,cwe_id,source,target 0, ,"public boolean update(Context context, KvPairs pairs, AnyKey anyKey){ LOGGER.trace(""update: "" + pairs.getPair().getId() + (pairs.size() > 1 ? "" ... "" : "" "") + anyKey.getAny().toString()); String table = anyKey.getKey().getTable(); if (table == null) { if (!kvSave(context, pairs, anyKey)) { LOGGER.debug(""update kvSave failed: "" + pairs.getPair().getId() + (pairs.size() > 1 ? "" ... "" : "" "")); return false; } else { LOGGER.debug(""updated kvSave Ok: "" + pairs.getPair().getId() + (pairs.size() > 1 ? "" ... "" : "" "")); } } else { Query query = new Query(context, jdbcTemplate, pairs, anyKey); if (!query.prepareUpdate() || !query.executeUpdate()) { if (enableDbFallback) { if (!kvSave(context, pairs, anyKey)) { LOGGER.debug(""update fallback to kvSave failed - "" + pairs.getPair().getId() + (pairs.size() > 1 ? "" ... "" : "" "")); return false; } else { String msg = ""updated fallbacked to kvSave OK: "" + pairs.getPair().getId() + (pairs.size() > 1 ? "" ... "" : "" ""); context.logTraceMessage(msg); LOGGER.warn(msg); } } else { LOGGER.debug(""update failed - "" + pairs.getPair().getId() + (pairs.size() > 1 ? "" ... "" : "" "")); return false; } } else { LOGGER.debug(""updated Ok: "" + anyKey.size() + "" record(s) from "" + table); } } AppCtx.getKeyInfoRepo().save(context, pairs, anyKey); return true; }","public boolean update(Context context, KvPairs pairs, AnyKey anyKey){ LOGGER.trace(""update: "" + pairs.getPair().getId() + (pairs.size() > 1 ? "" ... "" : "" "") + anyKey.getAny().toString()); String table = anyKey.getKey().getTable(); if (table == null) { if (!kvSave(context, pairs, anyKey)) { LOGGER.debug(""update kvSave failed: "" + pairs.getPair().getId() + (pairs.size() > 1 ? "" ... "" : "" "")); return false; } else { LOGGER.debug(""updated kvSave Ok: "" + pairs.getPair().getId() + (pairs.size() > 1 ? "" ... "" : "" "")); } } else { Query query = new Query(context, jdbcTemplate, pairs, anyKey); if (!query.ifUpdateOk() || !query.executeUpdate()) { if (enableDbFallback) { if (!kvSave(context, pairs, anyKey)) { LOGGER.debug(""update fallback to kvSave failed - "" + pairs.getPair().getId() + (pairs.size() > 1 ? "" ... "" : "" "")); return false; } else { String msg = ""updated fallbacked to kvSave OK: "" + pairs.getPair().getId() + (pairs.size() > 1 ? "" ... "" : "" ""); context.logTraceMessage(msg); LOGGER.warn(msg); } } else { LOGGER.debug(""update failed - "" + pairs.getPair().getId() + (pairs.size() > 1 ? "" ... "" : "" "")); return false; } } else { LOGGER.debug(""updated Ok: "" + anyKey.size() + "" record(s) from "" + table); } } return true; }" 1, ,"private static String internalDecode(ProtonBuffer buffer, final int length, CharsetDecoder decoder){ final char[] chars = new char[length]; final int bufferInitialPosition = buffer.getReadIndex(); int offset; for (offset = 0; offset < length; offset++) { final byte b = buffer.getByte(bufferInitialPosition + offset); if (b < 0) { break; } chars[offset] = (char) b; } buffer.setReadIndex(bufferInitialPosition + offset); if (offset == length) { return new String(chars, 0, length); } else { return internalDecodeUTF8(buffer, length, chars, offset, decoder); } }","private static String internalDecode(ProtonBuffer buffer, final int length, CharsetDecoder decoder, char[] scratch){ final int bufferInitialPosition = buffer.getReadIndex(); int offset; for (offset = 0; offset < length; offset++) { final byte b = buffer.getByte(bufferInitialPosition + offset); if (b < 0) { break; } scratch[offset] = (char) b; } buffer.setReadIndex(bufferInitialPosition + offset); if (offset == length) { return new String(scratch, 0, length); } else { return internalDecodeUTF8(buffer, length, scratch, offset, decoder); } }" 2, ,"public PartyDTO getPartyByPartyCode(String partyCode){ if (Strings.isNullOrEmpty(partyCode)) throw new InvalidDataException(""Party Code is required""); final TMsParty tMsParty = partyRepository.findByPrtyCodeAndPrtyStatus(partyCode, Constants.STATUS_ACTIVE.getShortValue()); if (tMsParty == null) throw new DataNotFoundException(""Party not found for the Code : "" + partyCode); PartyDTO partyDTO = PartyMapper.INSTANCE.entityToDTO(tMsParty); final List contactDTOList = partyContactService.getContactsByPartyCode(partyDTO.getPartyCode(), true); partyDTO.setContactList(contactDTOList); return partyDTO; }","public PartyDTO getPartyByPartyCode(String partyCode){ final TMsParty tMsParty = validateByPartyCode(partyCode); PartyDTO partyDTO = PartyMapper.INSTANCE.entityToDTO(tMsParty); setReferenceData(tMsParty, partyDTO); final List contactDTOList = partyContactService.getContactsByPartyCode(partyDTO.getPartyCode(), true); partyDTO.setContactList(contactDTOList); return partyDTO; }" 3, ,"public static long findMyBoardingPass(String fileName){ List passes = readInBoardingPasses(fileName); List seatIds = passes.stream().map(boardingPass -> getBoardingPassSeatId(boardingPass)).sorted().collect(Collectors.toList()); long mySeatId = -1; for (Long seatId : seatIds) { if (mySeatId == -1) { mySeatId = seatId; continue; } if (seatId > mySeatId + 1) { mySeatId++; break; } mySeatId = seatId; } return mySeatId; }","public static long findMyBoardingPass(String fileName){ List passes = readInBoardingPasses(fileName); return passes.stream().map(boardingPass -> getBoardingPassSeatId(boardingPass)).sorted().collect(Collectors.reducing(-1, (mySeatId, seatId) -> (mySeatId.longValue() == -1L || seatId.longValue() <= mySeatId.longValue() + 1) ? seatId : mySeatId)).longValue() + 1L; }" 4, ,"public Set findAllByOwnerId(long id) throws SQLException, NamingException{ Context ctx = new InitialContext(); Context envContext = (Context) ctx.lookup(""java:comp/env""); DataSource dataSource = (DataSource) envContext.lookup(""jdbc/TestDB""); Connection con = null; try { con = dataSource.getConnection(); PreparedStatement findAllCarsByOwnerIdStatement = con.prepareStatement(""SELECT * FROM cars WHERE owner_id = ?""); findAllCarsByOwnerIdStatement.setLong(1, id); ResultSet cars = findAllCarsByOwnerIdStatement.executeQuery(); Set carSet = new HashSet(); while (cars.next()) { Car car = CarUtils.initializeCar(cars); carSet.add(car); } findAllCarsByOwnerIdStatement.close(); cars.close(); return carSet; } finally { if (con != null) try { con.close(); } catch (Exception ignore) { } } }","public Set findAllByOwnerId(long id) throws SQLException, NamingException{ Connection con = null; try { con = dataSource.getConnection(); PreparedStatement findAllCarsByOwnerIdStatement = con.prepareStatement(""SELECT * FROM cars WHERE owner_id = ?""); findAllCarsByOwnerIdStatement.setLong(1, id); ResultSet cars = findAllCarsByOwnerIdStatement.executeQuery(); Set carSet = new HashSet(); while (cars.next()) { Car car = CarUtils.initializeCar(cars); carSet.add(car); } findAllCarsByOwnerIdStatement.close(); cars.close(); return carSet; } finally { if (con != null) try { con.close(); } catch (Exception ignore) { } } }" 5, ,"public String getEncryptedData(String alias){ if (alias == null || """".equals(alias)) { return alias; } if (!initialize || encryptedData.isEmpty()) { if (log.isDebugEnabled()) { log.debug(""There is no secret found for alias '"" + alias + ""' returning itself""); } return alias; } StringBuffer sb = new StringBuffer(); sb.append(alias); String encryptedValue = encryptedData.get(sb.toString()); if (encryptedValue == null || """".equals(encryptedValue)) { if (log.isDebugEnabled()) { log.debug(""There is no secret found for alias '"" + alias + ""' returning itself""); } return alias; } return encryptedValue; }","public String getEncryptedData(String alias){ if (alias == null || """".equals(alias)) { return alias; } if (!initialize || encryptedData.isEmpty()) { if (log.isDebugEnabled()) { log.debug(""There is no secret found for alias '"" + alias + ""' returning itself""); } return alias; } String encryptedValue = encryptedData.get(alias); if (encryptedValue == null || """".equals(encryptedValue)) { if (log.isDebugEnabled()) { log.debug(""There is no secret found for alias '"" + alias + ""' returning itself""); } return alias; } return encryptedValue; }" 6, ,"public List apply(Object beforeObject, Object afterObject, String description){ List diffs = new LinkedList<>(); Collection before = (Collection) beforeObject; Collection after = (Collection) afterObject; if (!isNullOrEmpty(before) && isNullOrEmpty(after)) { for (Object object : before) { diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, null, description)); } } else if (isNullOrEmpty(before) && !isNullOrEmpty(after)) { for (Object object : after) { diffs.addAll(getDiffComputeEngine().evaluateAndExecute(null, object, description)); } } else { for (Object object : before) { if (ReflectionUtil.isBaseClass(object.getClass())) { diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, findCorrespondingObject(object, after), description)); } else { diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, getCorrespondingObject(object, after), description)); } } List temp; for (Object object : after) { if (ReflectionUtil.isBaseClass(object.getClass())) { temp = getDiffComputeEngine().evaluateAndExecute(findCorrespondingObject(object, before), object, description); } else { temp = getDiffComputeEngine().evaluateAndExecute(getCorrespondingObject(object, before), object, description); } if (temp != null && temp.size() > 0) { temp.removeIf(delta -> delta.getChangeType().equals(ChangeType.NO_CHANGE) || delta.getChangeType().equals(ChangeType.UPDATED)); diffs.addAll(temp); } } } return diffs; }","public List apply(Object beforeObject, Object afterObject, String description){ List diffs = new LinkedList<>(); Collection before = (Collection) beforeObject; Collection after = (Collection) afterObject; if (!isNullOrEmpty(before) && isNullOrEmpty(after)) { before.forEach(object -> diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, null, description))); } else if (isNullOrEmpty(before) && !isNullOrEmpty(after)) { after.forEach(object -> diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, null, description))); } else { for (Object object : before) { if (ReflectionUtil.isBaseClass(object.getClass())) { diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, findCorrespondingObject(object, after), description)); } else { diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, getCorrespondingObject(object, after), description)); } } List temp = new LinkedList<>(); for (Object object : after) { if (ReflectionUtil.isBaseClass(object.getClass())) { temp.addAll(getDiffComputeEngine().evaluateAndExecute(findCorrespondingObject(object, before), object, description)); } else { temp.addAll(getDiffComputeEngine().evaluateAndExecute(getCorrespondingObject(object, before), object, description)); } } if (temp != null && temp.size() > 0) { temp.removeIf(delta -> delta.getChangeType().equals(ChangeType.NO_CHANGE) || delta.getChangeType().equals(ChangeType.UPDATED)); diffs.addAll(temp); } } return diffs; }" 7, ,"public final ASTNode visitExpr(final ExprContext ctx){ if (null != ctx.booleanPrimary()) { return visit(ctx.booleanPrimary()); } if (null != ctx.LP_()) { return visit(ctx.expr(0)); } if (null != ctx.logicalOperator()) { BinaryOperationExpression result = new BinaryOperationExpression(); result.setStartIndex(ctx.start.getStartIndex()); result.setStopIndex(ctx.stop.getStopIndex()); result.setLeft((ExpressionSegment) visit(ctx.expr(0))); result.setRight((ExpressionSegment) visit(ctx.expr(1))); result.setOperator(ctx.logicalOperator().getText()); String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex())); result.setText(text); return result; } NotExpression result = new NotExpression(); result.setStartIndex(ctx.start.getStartIndex()); result.setStopIndex(ctx.stop.getStopIndex()); result.setExpression((ExpressionSegment) visit(ctx.expr(0))); String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex())); result.setText(text); return result; }","public final ASTNode visitExpr(final ExprContext ctx){ if (null != ctx.booleanPrimary()) { return visit(ctx.booleanPrimary()); } if (null != ctx.LP_()) { return visit(ctx.expr(0)); } if (null != ctx.logicalOperator()) { BinaryOperationExpression result = new BinaryOperationExpression(); result.setStartIndex(ctx.start.getStartIndex()); result.setStopIndex(ctx.stop.getStopIndex()); result.setLeft((ExpressionSegment) visit(ctx.expr(0))); result.setRight((ExpressionSegment) visit(ctx.expr(1))); result.setOperator(ctx.logicalOperator().getText()); String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex())); result.setText(text); return result; } NotExpression result = new NotExpression(); result.setStartIndex(ctx.start.getStartIndex()); result.setStopIndex(ctx.stop.getStopIndex()); result.setExpression((ExpressionSegment) visit(ctx.expr(0))); return result; }" 8, ,"public void createPatients(Table table) throws Exception{ Patient patient = transformTableToPatient(table); registrationFirstPage.registerPatient(patient); waitForAppReady(); String path = driver.getCurrentUrl(); String uuid = path.substring(path.lastIndexOf('/') + 1); if (!Objects.equals(uuid, ""new"")) { patient.setUuid(uuid); registrationFirstPage.storePatientInSpecStore(patient); } }","public void createPatients(Table table) throws Exception{ registrationFirstPage.createPatients(table); }" 9, ,"public Set findAll() throws SQLException, NamingException{ Context ctx = new InitialContext(); Context envContext = (Context) ctx.lookup(""java:comp/env""); DataSource dataSource = (javax.sql.DataSource) envContext.lookup(""jdbc/TestDB""); Connection con = null; try { con = dataSource.getConnection(); PreparedStatement findAllDriversStatement = con.prepareStatement(""SELECT * FROM drivers ORDER BY id""); ResultSet drivers = findAllDriversStatement.executeQuery(); Set driverSet = new HashSet(); while (drivers.next()) { Driver driver = new Driver(); driver.setId(drivers.getInt(""id"")); driver.setName(drivers.getString(""name"")); driver.setPassportSerialNumbers(drivers.getString(""passport_serial_numbers"")); driver.setPhoneNumber(drivers.getString(""phone_number"")); driverSet.add(driver); } findAllDriversStatement.close(); drivers.close(); return driverSet; } finally { if (con != null) try { con.close(); } catch (Exception ignore) { } } }","public Set findAll() throws SQLException, NamingException{ Connection con = null; try { con = dataSource.getConnection(); PreparedStatement findAllDriversStatement = con.prepareStatement(""SELECT * FROM drivers ORDER BY id""); ResultSet drivers = findAllDriversStatement.executeQuery(); Set driverSet = new HashSet(); while (drivers.next()) { Driver driver = new Driver(); driver.setId(drivers.getInt(""id"")); driver.setName(drivers.getString(""name"")); driver.setPassportSerialNumbers(drivers.getString(""passport_serial_numbers"")); driver.setPhoneNumber(drivers.getString(""phone_number"")); driverSet.add(driver); } findAllDriversStatement.close(); drivers.close(); return driverSet; } finally { if (con != null) try { con.close(); } catch (Exception ignore) { } } }" 10, ," String transform(){ final String specialCharactersRegex = ""[^a-zA-Z0-9\\s+]""; final String inputCharacters = ""abcdefghijklmnopqrstuvwxyz""; Map> letterOccurenceMap = new LinkedHashMap>(); if (input.equals("""")) { return input; } input = input.toLowerCase(); input = input.replaceAll(specialCharactersRegex, """"); String[] words = input.split("" ""); for (Character letter : inputCharacters.toCharArray()) { for (String word : words) { if (word.contains(letter.toString())) { ArrayList letterWordsList = letterOccurenceMap.get(letter); if (letterWordsList == null) { letterWordsList = new ArrayList(); } if (!letterWordsList.contains(word)) { letterWordsList.add(word); Collections.sort(letterWordsList); } letterOccurenceMap.put(letter, letterWordsList); } } } return buildResult(letterOccurenceMap); }"," String transform(){ Map> letterOccurrenceMap = new LinkedHashMap>(); if (input.equals("""")) { return input; } input = input.toLowerCase(); input = input.replaceAll(specialCharactersRegex, """"); String[] words = input.split("" ""); for (Character letter : inputCharacters.toCharArray()) { for (String word : words) { if (word.contains(letter.toString())) { ArrayList letterWordsList = letterOccurrenceMap.get(letter); if (letterWordsList == null) { letterWordsList = new ArrayList(); } if (!letterWordsList.contains(word)) { letterWordsList.add(word); Collections.sort(letterWordsList); } letterOccurrenceMap.put(letter, letterWordsList); } } } return buildResult(letterOccurrenceMap); }" 11, ,"public Response simpleSearchWithSchemaName(@PathParam(""index"") final String index, @PathParam(""schemaName"") final String schemaName, @QueryParam(""q"") final String queryString, @QueryParam(""f"") final Integer from, @Context final UriInfo uriInfo){ final SearchResult results = dox.searchWithSchemaName(index, schemaName, queryString, 50, from); final JsonArrayBuilder hitsBuilder = Json.createArrayBuilder(); for (final IndexView hit : results.getHits()) { final JsonObjectBuilder hitBuilder = Json.createObjectBuilder(); final String id = hit.getDoxID().toString(); for (final Entry entry : hit.getNumbers()) { hitBuilder.add(entry.getKey(), entry.getValue()); } for (final Entry entry : hit.getStrings()) { hitBuilder.add(entry.getKey(), entry.getValue()); } hitBuilder.add(""_collection"", hit.getCollection()); if (!hit.isMasked()) { hitBuilder.add(""_id"", id); hitBuilder.add(""_url"", uriInfo.getBaseUriBuilder().path(hit.getCollection()).path(id).build().toString()); } hitsBuilder.add(hitBuilder); } final JsonObjectBuilder jsonBuilder = Json.createObjectBuilder().add(""totalHits"", results.getTotalHits()).add(""hits"", hitsBuilder); if (results.getBottomDoc() != null) { final String nextPage = uriInfo.getBaseUriBuilder().path(""search"").path(index).queryParam(""q"", queryString).queryParam(""f"", results.getBottomDoc()).build().toASCIIString(); jsonBuilder.add(""bottomDoc"", results.getBottomDoc()).add(""next"", nextPage); } final JsonObject resultJson = jsonBuilder.build(); return Response.ok(resultJson).cacheControl(NO_CACHE).build(); }","public Response simpleSearchWithSchemaName(@PathParam(""index"") final String index, @PathParam(""schemaName"") final String schemaName, @QueryParam(""q"") final String queryString, @QueryParam(""f"") final Integer from, @Context final UriInfo uriInfo){ final SearchResult results = dox.searchWithSchemaName(index, schemaName, queryString, 50, from); final JsonObjectBuilder resultBuilder = searchResultBuilder(uriInfo, results); if (results.getBottomDoc() != null) { final String nextPage = uriInfo.getBaseUriBuilder().path(""search"").path(index).path(schemaName).queryParam(""q"", queryString).queryParam(""f"", results.getBottomDoc()).build().toASCIIString(); resultBuilder.add(""bottomDoc"", results.getBottomDoc()).add(""next"", nextPage); } final JsonObject resultJson = resultBuilder.build(); return Response.ok(resultJson).cacheControl(NO_CACHE).build(); }" 12, ,"public boolean checkLoginExistInDB(String login) throws LoginExistException{ boolean isLoginExists = UserDB.Request.Create.checkLoginExist(login); if (isLoginExists) { throw new LoginExistException(); } return false; }","public boolean checkLoginExistInDB(String login){ return UserDB.Request.checkLoginExist(login); }" 13, ,"public List> items(@PathVariable String table){ LOGGER.info(""Getting items for "" + table); List> items = new ArrayList<>(); ScanRequest scanRequest = new ScanRequest().withTableName(table); try { List> list = amazonDynamoDBClient.scan(scanRequest).getItems(); LOGGER.info(""raw items "", list); for (Map item : list) { items.add(InternalUtils.toSimpleMapValue(item)); } } catch (AmazonClientException ex) { LOGGER.error(ex.getMessage()); } return items; }","public List> items(@PathVariable String table){ LOGGER.info(""Getting items for "" + table); List> items = new ArrayList<>(); scanRequest.withTableName(table); List> list = amazonDynamoDBClient.scan(scanRequest).getItems(); LOGGER.info(""raw items "", list); for (Map item : list) { items.add(InternalUtils.toSimpleMapValue(item)); } return items; }" 14, ,"public ExtractedFileSet extract(DownloadConfig runtime, File source, FilesToExtract toExtract) throws IOException{ Builder builder = ExtractedFileSet.builder(toExtract.baseDir()).baseDirIsGenerated(toExtract.baseDirIsGenerated()); ProgressListener progressListener = runtime.getProgressListener(); String progressLabel = ""Extract (not really) "" + source; progressListener.start(progressLabel); IExtractionMatch match = toExtract.find(new FileAsArchiveEntry(source)); if (match != null) { FileInputStream fin = new FileInputStream(source); try { BufferedInputStream in = new BufferedInputStream(fin); File file = match.write(in, source.length()); FileType type = match.type(); if (type == FileType.Executable) { builder.executable(file); } else { builder.addLibraryFiles(file); } if (!toExtract.nothingLeft()) { progressListener.info(progressLabel, ""Something went a little wrong. Listener say something is left, but we dont have anything""); } progressListener.done(progressLabel); } finally { fin.close(); } } return builder.build(); }","public ExtractedFileSet extract(DownloadConfig runtime, File source, FilesToExtract toExtract) throws IOException{ Builder builder = ExtractedFileSet.builder(toExtract.baseDir()).baseDirIsGenerated(toExtract.baseDirIsGenerated()); ProgressListener progressListener = runtime.getProgressListener(); String progressLabel = ""Extract (not really) "" + source; progressListener.start(progressLabel); IExtractionMatch match = toExtract.find(new FileAsArchiveEntry(source)); if (match != null) { try (FileInputStream fin = new FileInputStream(source); BufferedInputStream in = new BufferedInputStream(fin)) { File file = match.write(in, source.length()); FileType type = match.type(); if (type == FileType.Executable) { builder.executable(file); } else { builder.addLibraryFiles(file); } if (!toExtract.nothingLeft()) { progressListener.info(progressLabel, ""Something went a little wrong. Listener say something is left, but we dont have anything""); } progressListener.done(progressLabel); } } return builder.build(); }" 15, ,"private void processData(ByteBuffer data) throws IOException, InterruptedException{ int firstPacketElement = data.getInt(); int seqNum = firstPacketElement & ~LAST_MESSAGE_FLAG_BIT_MASK; boolean isEndOfStream = ((firstPacketElement & LAST_MESSAGE_FLAG_BIT_MASK) != 0); if (seqNum > maxSeqNum || seqNum < 0) { throw new IllegalStateException(""got insane sequence number""); } int offset = seqNum * DATA_PER_FULL_PACKET_WITH_SEQUENCE_NUM * WORD_SIZE; int trueDataLength = offset + data.limit() - SEQUENCE_NUMBER_SIZE; if (trueDataLength > dataReceiver.capacity()) { throw new IllegalStateException(""received more data than expected""); } if (!isEndOfStream || data.limit() != END_FLAG_SIZE) { data.position(SEQUENCE_NUMBER_SIZE); data.get(dataReceiver.array(), offset, trueDataLength - offset); } receivedSeqNums.set(seqNum); if (isEndOfStream) { if (!checkAllReceived()) { finished |= retransmitMissingSequences(); } else { finished = true; } } }","private void processData(ByteBuffer data) throws IOException, InterruptedException{ int firstPacketElement = data.getInt(); int seqNum = firstPacketElement & ~LAST_MESSAGE_FLAG_BIT_MASK; boolean isEndOfStream = ((firstPacketElement & LAST_MESSAGE_FLAG_BIT_MASK) != 0); if (seqNum > maxSeqNum || seqNum < 0) { throw new IllegalStateException(""got insane sequence number""); } int offset = seqNum * DATA_WORDS_PER_PACKET * WORD_SIZE; int trueDataLength = offset + data.limit() - SEQUENCE_NUMBER_SIZE; if (trueDataLength > dataReceiver.capacity()) { throw new IllegalStateException(""received more data than expected""); } if (!isEndOfStream || data.limit() != END_FLAG_SIZE) { data.position(SEQUENCE_NUMBER_SIZE); data.get(dataReceiver.array(), offset, trueDataLength - offset); } receivedSeqNums.set(seqNum); if (isEndOfStream) { finished = retransmitMissingSequences(); } }" 16, ,"public DistributionQueue getQueue(@NotNull String queueName) throws DistributionException{ String key = getKey(queueName); return queueMap.computeIfAbsent(key, k -> { statusMap.put(key, new ConcurrentHashMap<>()); if (isActive) { return new ActiveResourceQueue(resolverFactory, serviceName, queueName, agentRootPath); } else { return new ResourceQueue(resolverFactory, serviceName, queueName, agentRootPath); } }); }","public DistributionQueue getQueue(@NotNull String queueName) throws DistributionException{ return queueMap.computeIfAbsent(queueName, name -> { if (isActive) { return new ActiveResourceQueue(resolverFactory, serviceName, name, agentRootPath); } else { return new ResourceQueue(resolverFactory, serviceName, name, agentRootPath); } }); }" 17, ,"public Object clone() throws CloneNotSupportedException{ StatementTree v = (StatementTree) super.clone(); HashMap cloned_map = new HashMap(); v.map = cloned_map; Iterator i = map.keySet().iterator(); while (i.hasNext()) { Object key = i.next(); Object entry = map.get(key); entry = cloneSingleObject(entry); cloned_map.put(key, entry); } return v; }","public Object clone() throws CloneNotSupportedException{ StatementTree v = (StatementTree) super.clone(); HashMap cloned_map = new HashMap(); v.map = cloned_map; for (Object key : map.keySet()) { Object entry = map.get(key); entry = cloneSingleObject(entry); cloned_map.put(key, entry); } return v; }" 18, ,"private Document getDocument(String xml){ try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); return parser.parse(new InputSource(new StringReader(xml))); } catch (ParserConfigurationException | SAXException | IOException e) { e.printStackTrace(); } return null; }","private Document getDocument(String xml){ try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); return parser.parse(new InputSource(new StringReader(xml))); } catch (ParserConfigurationException | SAXException | IOException e) { throw new RuntimeException(e); } }" 19, ,"public SCCCiphertext encryptAsymmetric(AbstractSCCKey key, PlaintextContainerInterface plaintext) throws SCCException{ if (key.getKeyType() == KeyType.Asymmetric) { if (usedAlgorithm == null) { ArrayList algorithms = currentSCCInstance.getUsage().getAsymmetricEncryption(); for (int i = 0; i < algorithms.size(); i++) { SCCAlgorithm sccalgorithmID = algorithms.get(i); if (getEnums().contains(sccalgorithmID)) { switch(sccalgorithmID) { case RSA_SHA_512: return SecureCryptoConfig.createAsymMessage(plaintext, AlgorithmID.RSA_OAEP_SHA_512, key); case RSA_SHA_256: return SecureCryptoConfig.createAsymMessage(plaintext, AlgorithmID.RSA_OAEP_SHA_256, key); case RSA_ECB: return SecureCryptoConfig.createAsymMessage(plaintext, AlgorithmID.RSA_ECB, key); default: break; } } } } else { switch(usedAlgorithm) { case RSA_SHA_512: return SecureCryptoConfig.createAsymMessage(plaintext, AlgorithmID.RSA_OAEP_SHA_512, key); case RSA_SHA_256: return SecureCryptoConfig.createAsymMessage(plaintext, AlgorithmID.RSA_OAEP_SHA_256, key); case RSA_ECB: return SecureCryptoConfig.createAsymMessage(plaintext, AlgorithmID.RSA_ECB, key); default: break; } } } else { throw new SCCException(""The used SCCKey has the wrong KeyType for this use case."", new InvalidKeyException()); } throw new SCCException(""No supported algorithm"", new CoseException(null)); }","public SCCCiphertext encryptAsymmetric(AbstractSCCKey key, PlaintextContainerInterface plaintext) throws SCCException{ if (key.getKeyType() == KeyType.Asymmetric) { if (usedAlgorithm == null) { ArrayList algorithms = currentSCCInstance.getUsage().getAsymmetricEncryption(); for (int i = 0; i < algorithms.size(); i++) { SCCAlgorithm sccalgorithmID = algorithms.get(i); if (getEnums().contains(sccalgorithmID)) { return decideForAlgoAsymmetric(sccalgorithmID, key, plaintext); } } } else { return decideForAlgoAsymmetric(usedAlgorithm, key, plaintext); } } else { throw new SCCException(""The used SCCKey has the wrong KeyType for this use case."", new InvalidKeyException()); } throw new SCCException(""No supported algorithm"", new CoseException(null)); }" 20, ,"public List getRelationships(final String relationshipName){ List myrelationships = relationships.get(relationshipName.toLowerCase()); ArrayList retRels = new ArrayList(myrelationships); return retRels; }","public List getRelationships(final String relationshipName){ List myrelationships = relationships.get(relationshipName.toLowerCase()); return new ArrayList<>(myrelationships); }" 21, ,"public void openSecureChannel(EnumSet securityLevel) throws IOException, JavaCardException{ if (securityLevel.contains(SecurityLevel.C_DECRYPTION) && !securityLevel.contains(SecurityLevel.C_MAC)) { throw new IllegalArgumentException(""C_DECRYPTION must be combined with C_MAC""); } if (securityLevel.contains(SecurityLevel.R_DECRYPTION) && !securityLevel.contains(SecurityLevel.R_MAC)) { throw new IllegalArgumentException(""R_DECRYPTION must be combined with R_MAC""); } byte hostKeyVersionNumber = context.getCardProperties().getKeyVersionNumber(); Scp02Context scp02Context = initializeUpdate(hostKeyVersionNumber); byte[] icv = externalAuthenticate(scp02Context, securityLevel); channel = new Scp02ApduChannel(context, securityLevel, icv); channel.setRicv(icv); }","public void openSecureChannel(EnumSet securityLevel) throws IOException, JavaCardException{ if (securityLevel.contains(SecurityLevel.C_DECRYPTION) && !securityLevel.contains(SecurityLevel.C_MAC)) { throw new IllegalArgumentException(""C_DECRYPTION must be combined with C_MAC""); } byte hostKeyVersionNumber = context.getCardProperties().getKeyVersionNumber(); Scp02Context scp02Context = initializeUpdate(hostKeyVersionNumber); byte[] icv = externalAuthenticate(scp02Context, securityLevel); channel = new Scp02ApduChannel(context, securityLevel, icv); channel.setRicv(icv); }" 22, ,"public void run(){ LOGGER_RECEIVER.info(""Start the datagramm receiver.""); byte[] receiveBuffer = new byte[512]; while (!exit) { try { DatagramPacket packet = new DatagramPacket(receiveBuffer, receiveBuffer.length); LOGGER_RECEIVER.info(""Wait for packet ...""); socket.receive(packet); LOGGER_RECEIVER.info(""Received a packet: {}"", packet); if (PacketConverter.responseFromPacket(packet) != null) { Z21Response response = PacketConverter.responseFromPacket(packet); for (Z21ResponseListener listener : responseListeners) { for (ResponseTypes type : listener.getListenerTypes()) { if (type == response.boundType) { listener.responseReceived(type, response); } } } } else { Z21Broadcast broadcast = PacketConverter.broadcastFromPacket(packet); if (broadcast != null) { for (Z21BroadcastListener listener : broadcastListeners) { for (BroadcastTypes type : listener.getListenerTypes()) { if (type == broadcast.boundType) { listener.onBroadCast(type, broadcast); } } } } } } catch (IOException e) { if (!exit) LOGGER_RECEIVER.warn(""Failed to get a message from z21... "", e); } } LOGGER_RECEIVER.info(""The receiver has terminated.""); }","public void run(){ LOGGER_RECEIVER.info(""Start the datagramm receiver.""); byte[] receiveBuffer = new byte[512]; while (!exit) { try { DatagramPacket packet = new DatagramPacket(receiveBuffer, receiveBuffer.length); LOGGER_RECEIVER.info(""Wait for packet ...""); socket.receive(packet); z21Drive.record.Z21Record z21Record = Z21RecordFactory.fromPacket(packet); if (z21Record != null) { LOGGER_RECEIVER.info(""Received '{}'"", z21Record); if (z21Record.isResponse()) { for (Z21ResponseListener listener : responseListeners) { for (Z21RecordType type : listener.getListenerTypes()) { if (type == z21Record.getRecordType()) { listener.responseReceived(type, z21Record); } } } } else if (z21Record.isBroadCast()) { for (Z21BroadcastListener listener : broadcastListeners) { for (Z21RecordType type : listener.getListenerTypes()) { if (type == z21Record.getRecordType()) { listener.onBroadCast(type, z21Record); } } } } } } catch (IOException e) { if (!exit) LOGGER_RECEIVER.warn(""Failed to get a message from z21... "", e); } } LOGGER_RECEIVER.info(""The receiver has terminated.""); }" 23, ,"public void processAnnotation(final JNDIProperty jndiPropertyAnnotation, final Field field, final Object object) throws AnnotationProcessingException{ if (context == null) { try { context = new InitialContext(); } catch (NamingException e) { throw new AnnotationProcessingException(""Unable to initialize JNDI context"", e); } } String name = jndiPropertyAnnotation.value().trim(); if (name.isEmpty()) { throw new AnnotationProcessingException(missingAttributeValue(""name"", ""@JNDIProperty"", field, object)); } Object value; try { value = context.lookup(name); } catch (NamingException e) { throw new AnnotationProcessingException(String.format(""Unable to lookup object %s from JNDI context"", name), e); } if (value == null) { throw new AnnotationProcessingException(""JNDI object "" + name + "" not found in JNDI context.""); } processAnnotation(object, field, name, value); }","public void processAnnotation(final JNDIProperty jndiPropertyAnnotation, final Field field, final Object object) throws AnnotationProcessingException{ if (context == null) { try { context = new InitialContext(); } catch (NamingException e) { throw new AnnotationProcessingException(""Unable to initialize JNDI context"", e); } } String name = jndiPropertyAnnotation.value().trim(); checkIfEmpty(name, missingAttributeValue(""name"", ""@JNDIProperty"", field, object)); Object value; try { value = context.lookup(name); } catch (NamingException e) { throw new AnnotationProcessingException(format(""Unable to lookup object %s from JNDI context"", name), e); } if (value == null) { throw new AnnotationProcessingException(String.format(""JNDI object %s not found in JNDI context."", name)); } processAnnotation(object, field, name, value); }" 24, ,"public void add(T value, int index){ if (index < 0 || index > size) { throw new ArrayListIndexOutOfBoundsException(""Index are not exist, your index is "" + index + "" last index is "" + size); } else if (index == size && ensureCapacity()) { arrayData[index] = value; size++; } else if (indexCapacity(index) && ensureCapacity()) { arrayCopyAdd(index); arrayData[index] = value; size++; } else { grow(); arrayCopyAdd(index); arrayData[index] = value; size++; } }","public void add(T value, int index){ if (index < 0 || index > size) { throw new ArrayListIndexOutOfBoundsException(""Index are not exist, your index is "" + index + "" last index is "" + size); } else if (index == size && ensureCapacity()) { arrayData[index] = value; size++; } else if (indexCapacity(index) && ensureCapacity()) { arrayCopyAdd(index); arrayData[index] = value; } else { grow(); arrayCopyAdd(index); arrayData[index] = value; } }" 25, ,"public void testInsert(){ GeneratedAlwaysRecord record = new GeneratedAlwaysRecord(); record.setId(100); record.setFirstName(""Bob""); record.setLastName(""Jones""); InsertStatementProvider insertStatement = insert(record).into(generatedAlways).map(id).toProperty(""id"").map(firstName).toProperty(""firstName"").map(lastName).toProperty(""lastName"").build().render(RenderingStrategy.SPRING_NAMED_PARAMETER); SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(insertStatement.getRecord()); KeyHolder keyHolder = new GeneratedKeyHolder(); int rows = template.update(insertStatement.getInsertStatement(), parameterSource, keyHolder); String generatedKey = (String) keyHolder.getKeys().get(""FULL_NAME""); assertThat(rows).isEqualTo(1); assertThat(generatedKey).isEqualTo(""Bob Jones""); }","public void testInsert(){ GeneratedAlwaysRecord record = new GeneratedAlwaysRecord(); record.setId(100); record.setFirstName(""Bob""); record.setLastName(""Jones""); InsertStatementProvider insertStatement = insert(record).into(generatedAlways).map(id).toProperty(""id"").map(firstName).toProperty(""firstName"").map(lastName).toProperty(""lastName"").build().render(RenderingStrategy.SPRING_NAMED_PARAMETER); SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(insertStatement.getRecord()); KeyHolder keyHolder = new GeneratedKeyHolder(); }" 26, ,"public static void addRecipe(Recipe recipe){ String recipeJSON = gson.toJson(recipe); try { java.util.Properties config = new java.util.Properties(); config.put(""StrictHostKeyChecking"", ""no""); JSch jsch = new JSch(); jsch.addIdentity(DBUtils.ENV_SSH_KEY); ssh = null; ssh = jsch.getSession(""ubuntu"", DBUtils.ENV_DB_ADDRESS, DBUtils.SSH_PORT); ssh.setConfig(config); ssh.connect(); ssh.setPortForwardingL(6666, DBUtils.ENV_DB_ADDRESS, DBUtils.ENV_DB_PORT); MongoClient mongo = new MongoClient(""localhost"", 6666); MongoDatabase database = mongo.getDatabase(DBUtils.ENV_DB_NAME); MongoCollection recipes = database.getCollection(""recipes""); recipes.insertOne(Document.parse(recipeJSON)); } catch (JSchException ex) { Logger.getLogger(VirtualRefrigerator.class.getName()).log(Level.SEVERE, null, ex); } finally { try { ssh.delPortForwardingL(6666); } catch (JSchException ex) { Logger.getLogger(VirtualRefrigerator.class.getName()).log(Level.SEVERE, null, ex); } ssh.disconnect(); } }","public static void addRecipe(Recipe recipe){ String recipeJSON = gson.toJson(recipe); try { java.util.Properties config = new java.util.Properties(); config.put(""StrictHostKeyChecking"", ""no""); JSch jsch = new JSch(); jsch.addIdentity(DBUtils.ENV_SSH_KEY); ssh = jsch.getSession(""ubuntu"", DBUtils.ENV_DB_ADDRESS, DBUtils.SSH_PORT); ssh.setConfig(config); ssh.connect(); ssh.setPortForwardingL(DBUtils.DB_PORT_FORWARDING, DBUtils.ENV_DB_ADDRESS, DBUtils.ENV_DB_PORT); MongoClient mongo = new MongoClient(""localhost"", DBUtils.DB_PORT_FORWARDING); MongoDatabase database = mongo.getDatabase(DBUtils.ENV_DB_NAME); MongoCollection recipes = database.getCollection(""recipes""); recipes.insertOne(Document.parse(recipeJSON)); } catch (JSchException ex) { Logger.getLogger(VirtualRefrigerator.class.getName()).log(Level.SEVERE, null, ex); } finally { try { ssh.delPortForwardingL(DBUtils.DB_PORT_FORWARDING); } catch (JSchException ex) { Logger.getLogger(VirtualRefrigerator.class.getName()).log(Level.SEVERE, null, ex); } ssh.disconnect(); } }" 27, ,"public List getAll(@RequestParam(value = ""page"", defaultValue = ""0"") int page, @RequestParam(value = ""limit"", defaultValue = ""25"") int limit){ if (page > 0) page = page - 1; return mealService.getAll(page, limit); }","public List getAll(@RequestParam(value = ""page"", defaultValue = ""0"") int page, @RequestParam(value = ""limit"", defaultValue = ""25"") int limit){ return mealService.getAll(page, limit); }" 28, ,"public double GetExchangeRate(Currency currency) throws IOException{ double rate = 0; CloseableHttpResponse response = null; try { response = this.httpclient.execute(httpget); switch(response.getStatusLine().getStatusCode()) { case 200: HttpEntity entity = response.getEntity(); InputStream inputStream = response.getEntity().getContent(); var json = new BufferedReader(new InputStreamReader(inputStream)); @SuppressWarnings(""deprecation"") JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject(); String n = jsonObject.get(""bpi"").getAsJsonObject().get(currency.toString()).getAsJsonObject().get(""rate"").getAsString(); NumberFormat nf = NumberFormat.getInstance(); rate = nf.parse(n).doubleValue(); break; default: rate = -1; } } catch (Exception ex) { rate = -1; } finally { response.close(); } return rate; }","public double GetExchangeRate(Currency currency){ double rate = 0; try (CloseableHttpResponse response = this.httpclient.execute(httpget)) { switch(response.getStatusLine().getStatusCode()) { case 200: HttpEntity entity = response.getEntity(); InputStream inputStream = response.getEntity().getContent(); var json = new BufferedReader(new InputStreamReader(inputStream)); @SuppressWarnings(""deprecation"") JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject(); String n = jsonObject.get(""bpi"").getAsJsonObject().get(currency.toString()).getAsJsonObject().get(""rate"").getAsString(); NumberFormat nf = NumberFormat.getInstance(); rate = nf.parse(n).doubleValue(); break; default: rate = -1; } response.close(); } catch (Exception ex) { rate = -1; } return rate; }" 29, ,"public boolean equals(Object obj){ if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final OAuth2AllowDomain other = (OAuth2AllowDomain) obj; if (!Objects.equals(this.id, other.id)) { return false; } return true; }","public boolean equals(Object obj){ return ObjectEquals.of(this).equals(obj, (origin, other) -> { return Objects.equals(origin.getId(), other.getId()); }); }" 30, ,"public Key max(){ if (isEmpty()) throw new NoSuchElementException(""calls max() with empty symbol table""); return st.lastKey(); }","public Key max(){ noSuchElement(isEmpty(), ""calls max() with empty symbol table""); return st.lastKey(); }" 31, ,"private static void triggerJenkinsJob(String token) throws IOException{ URL url = new URL(remoteUrl + token); String user = ""salahin""; String pass = ""11d062d7023e11765b4d8ee867b67904f9""; String authStr = user + "":"" + pass; String basicAuth = ""Basic "" + Base64.getEncoder().encodeToString(authStr.getBytes(""utf-8"")); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty(""Authorization"", basicAuth); connection.setRequestMethod(""POST""); connection.setDoOutput(true); connection.setRequestProperty(""User-Agent"", ""Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:27.0) Gecko/20100101 Firefox/27.0.2 Waterfox/27.0""); connection.setRequestProperty(""Content-Type"", ""application/x-www-form-urlencoded""); System.out.println(""Step Tiger Jenkins Jobs: "" + connection.getResponseCode()); connection.disconnect(); }","private void triggerJenkinsJob(URL url) throws IOException{ String authStr = userId + "":"" + jenkinsToken; String basicAuth = ""Basic "" + Base64.getEncoder().encodeToString(authStr.getBytes(""utf-8"")); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty(""Authorization"", basicAuth); connection.setRequestMethod(""POST""); connection.setDoOutput(true); connection.setRequestProperty(""User-Agent"", ""Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:27.0) Gecko/20100101 Firefox/27.0.2 Waterfox/27.0""); connection.setRequestProperty(""Content-Type"", ""application/x-www-form-urlencoded""); System.out.println(""Step Tiger Jenkins Jobs: "" + connection.getResponseCode()); connection.disconnect(); }" 32, ,"public void run(){ if (Sesnor2Data == true) { Sesnor2Data = false; } else if (Sesnor2Data == false) { Sesnor2Data = true; } sensorStates.setLaserSensor2data(Sesnor2Data); System.out.println(""fahim sesnor from laser2 = "" + sensorStates.isLaserSensor2data()); changed(); }","public void run(){ if (Sesnor2Data == true) { Sesnor2Data = false; } else if (Sesnor2Data == false) { Sesnor2Data = true; } sensorStates.setLaserSensor2data(Sesnor2Data); changed(); }" 33, ,"public ModelAndView process(ModelAndView mav, Locale locale){ mav.setViewName(""memoryleak""); mav.addObject(""title"", msg.getMessage(""title.heap.memory.usage"", null, locale)); mav.addObject(""note"", msg.getMessage(""msg.java.heap.space.leak.occur"", null, locale)); try { toDoRemove(); List heapPoolMXBeans = new ArrayList<>(); List memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans(); for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) { if (MemoryType.HEAP.equals(memoryPoolMXBean.getType())) { heapPoolMXBeans.add(memoryPoolMXBean); } } mav.addObject(""memoryPoolMXBeans"", heapPoolMXBeans); } catch (Exception e) { log.error(""Exception occurs: "", e); mav.addObject(""errmsg"", msg.getMessage(""msg.unknown.exception.occur"", new String[] { e.getMessage() }, null, locale)); } return mav; }","public ModelAndView process(ModelAndView mav, Locale locale){ mav.setViewName(""memoryleak""); mav.addObject(""title"", msg.getMessage(""title.heap.memory.usage"", null, locale)); mav.addObject(""note"", msg.getMessage(""msg.java.heap.space.leak.occur"", null, locale)); toDoRemove(); List heapPoolMXBeans = new ArrayList<>(); List memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans(); for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) { if (MemoryType.HEAP.equals(memoryPoolMXBean.getType())) { heapPoolMXBeans.add(memoryPoolMXBean); } } mav.addObject(""memoryPoolMXBeans"", heapPoolMXBeans); return mav; }" 34, ,"private BoundStatement buildStatementLatestVideoPage(String yyyymmdd, Optional pagingState, AtomicBoolean cassandraPagingStateUsed, Optional startingAddedDate, Optional startingVideoId, int recordNeeded){ BoundStatementBuilder statementBuilder; if (startingAddedDate.isPresent() && startingVideoId.isPresent()) { statementBuilder = latestVideoPreview_startingPointPrepared.boundStatementBuilder(yyyymmdd, startingAddedDate.get(), startingVideoId.get()); } else { statementBuilder = latestVideoPreview_noStartingPointPrepared.boundStatementBuilder(yyyymmdd); } statementBuilder.setPageSize(recordNeeded); pagingState.ifPresent(x -> { statementBuilder.setPagingState(Bytes.fromHexString(x)); cassandraPagingStateUsed.compareAndSet(false, true); }); statementBuilder.setConsistencyLevel(ConsistencyLevel.ONE); return statementBuilder.build(); }","private BoundStatement buildStatementLatestVideoPage(String yyyymmdd, Optional pagingState, AtomicBoolean cassandraPagingStateUsed, Optional startingAddedDate, Optional startingVideoId, int recordNeeded){ BoundStatementBuilder statementBuilder = getBoundStatementBuilder(yyyymmdd, startingAddedDate, startingVideoId); statementBuilder.setPageSize(recordNeeded); pagingState.ifPresent(x -> { statementBuilder.setPagingState(Bytes.fromHexString(x)); cassandraPagingStateUsed.compareAndSet(false, true); }); statementBuilder.setConsistencyLevel(ConsistencyLevel.ONE); return statementBuilder.build(); }" 35, ,"public void sendMessage(ChannelId id, ByteBuf message){ Channel channel = allChannels.find(id); if (channel != null) { WebSocketFrame frame = new BinaryWebSocketFrame(message); channel.writeAndFlush(frame); } }","public void sendMessage(ChannelId id, Message message){ Channel channel = allChannels.find(id); if (channel != null) { channel.writeAndFlush(message); } }" 36, ,"public void test_isTogglePatternAvailable() throws Exception{ when(element.getPropertyValue(anyInt())).thenReturn(1); IUIAutomation mocked_automation = Mockito.mock(IUIAutomation.class); UIAutomation instance = new UIAutomation(mocked_automation); AutomationWindow window = new AutomationWindow(new ElementBuilder(element).itemContainer(container).automation(instance).window(pattern)); boolean value = window.isTogglePatternAvailable(); assertTrue(value); }","public void test_isTogglePatternAvailable() throws Exception{ Toggle pattern = Mockito.mock(Toggle.class); when(pattern.isAvailable()).thenReturn(true); AutomationWindow window = new AutomationWindow(new ElementBuilder(element).addPattern(pattern)); boolean value = window.isTogglePatternAvailable(); assertTrue(value); }" 37, ," static EbicsBank sendHPB(final EbicsSession session) throws IOException, GeneralSecurityException, EbicsException{ final HPBRequestElement request = new HPBRequestElement(session); final EbicsNoPubKeyDigestsRequest ebicsNoPubKeyDigestsRequest = request.build(); final byte[] xml = XmlUtil.prettyPrint(EbicsNoPubKeyDigestsRequest.class, ebicsNoPubKeyDigestsRequest); session.getTraceManager().trace(EbicsNoPubKeyDigestsRequest.class, ebicsNoPubKeyDigestsRequest, session.getUser()); XmlUtil.validate(xml); final HttpEntity httpEntity = HttpUtil.sendAndReceive(session.getBank(), new ByteArrayContentFactory(xml), session.getMessageProvider()); final KeyManagementResponseElement response = new KeyManagementResponseElement(httpEntity, session.getMessageProvider()); final EbicsKeyManagementResponse keyManagementResponse = response.build(); session.getTraceManager().trace(XmlUtil.prettyPrint(EbicsKeyManagementResponse.class, keyManagementResponse), ""HBPResponse"", session.getUser()); final ContentFactory factory = new ByteArrayContentFactory(ZipUtil.uncompress(CryptoUtil.decrypt(response.getOrderData(), response.getTransactionKey(), session.getUser().getEncryptionKey().getPrivateKey()))); final HPBResponseOrderDataElement orderData = new HPBResponseOrderDataElement(factory); final HPBResponseOrderDataType orderDataResponse = orderData.build(); session.getTraceManager().trace(HPBResponseOrderDataType.class, orderDataResponse, session.getUser()); return session.getBank().withAuthenticationKey(orderData.getBankAuthenticationKey()).withEncryptionKey(orderData.getBankEncryptionKey()); }"," static EbicsBank sendHPB(final EbicsSession session) throws IOException, GeneralSecurityException, EbicsException{ final EbicsNoPubKeyDigestsRequest ebicsNoPubKeyDigestsRequest = HPBRequestElement.create(session); final byte[] xml = XmlUtil.prettyPrint(EbicsNoPubKeyDigestsRequest.class, ebicsNoPubKeyDigestsRequest); session.getTraceManager().trace(EbicsNoPubKeyDigestsRequest.class, ebicsNoPubKeyDigestsRequest, session.getUser()); XmlUtil.validate(xml); final HttpEntity httpEntity = HttpUtil.sendAndReceive(session.getBank(), new ByteArrayContentFactory(xml), session.getMessageProvider()); final KeyManagementResponseElement response = new KeyManagementResponseElement(httpEntity, session.getMessageProvider()); final EbicsKeyManagementResponse keyManagementResponse = response.build(); session.getTraceManager().trace(XmlUtil.prettyPrint(EbicsKeyManagementResponse.class, keyManagementResponse), ""HBPResponse"", session.getUser()); final ContentFactory factory = new ByteArrayContentFactory(ZipUtil.uncompress(CryptoUtil.decrypt(response.getOrderData(), response.getTransactionKey(), session.getUser().getEncryptionKey().getPrivateKey()))); final HPBResponseOrderDataElement orderData = HPBResponseOrderDataElement.parse(factory); session.getTraceManager().trace(IOUtil.read(factory.getContent()), ""HPBResponseOrderData"", session.getUser()); return session.getBank().withAuthenticationKey(orderData.getBankAuthenticationKey()).withEncryptionKey(orderData.getBankEncryptionKey()); }" 38, ,"public FxNode eval(FxChildWriter dest, FxEvalContext ctx, FxNode src){ FxObjNode srcObj = (FxObjNode) src; boolean expr = FxNodeValueUtils.getBooleanOrThrow(srcObj, ""expr""); FxNode templateNode; if (expr) { templateNode = srcObj.get(""then""); } else { templateNode = srcObj.get(""else""); } FxNode res = null; if (templateNode != null) { res = FxNodeCopyVisitor.copyTo(dest, templateNode); } return res; }","public void eval(FxChildWriter dest, FxEvalContext ctx, FxNode src){ FxObjNode srcObj = (FxObjNode) src; boolean expr = FxNodeValueUtils.getBooleanOrThrow(srcObj, ""expr""); FxNode templateNode; if (expr) { templateNode = srcObj.get(""then""); } else { templateNode = srcObj.get(""else""); } if (templateNode != null) { FxNodeCopyVisitor.copyTo(dest, templateNode); } }" 39, ,"public Election registerElection(final Election election){ try { jdbcTemplate.update(REGISTER_ELECTION_QUERY, new Object[] { election.getElectionTitle(), election.getElectionId(), election.getElectionDescription(), election.getAdminVoterId(), ""1"" }, new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR }); return election; } catch (DataAccessException ex) { ConsoleLogger.Log(ControllerOperations.DB_PUT_ELECTION, ex.getMessage(), election); throw new RestrictedActionException(""Error While Creating Entry in Election""); } }","public void registerElection(final Election election){ try { jdbcTemplate.update(REGISTER_ELECTION_QUERY, new Object[] { election.getElectionTitle(), election.getElectionId(), election.getElectionDescription(), election.getAdminVoterId(), ""1"" }, new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR }); } catch (DataAccessException ex) { ConsoleLogger.Log(ControllerOperations.DB_PUT_ELECTION, ex.getMessage(), election); throw new RestrictedActionException(""Error While Creating Entry in Election""); } }" 40, ,"public MappingJacksonValue lessons(){ MappingJacksonValue result = new MappingJacksonValue(this.lessonService.findAll()); return result; }","public MappingJacksonValue lessons(){ return new MappingJacksonValue(this.lessonService.findAll()); }" 41, ,"public String execute(HttpServletRequest request, HttpServletResponse response){ String email = (String) request.getParameter(""email""); String password = (String) request.getParameter(""password""); User user = userService.findByEmail(email); if (user == null) { return LOGIN_PAGE; } else if (!user.getPassword().equals(password)) { return LOGIN_PAGE; } request.getSession().setAttribute(X_AUTH_TOKEN, user.getId()); return INDEX_PAGE; }","public String execute(HttpServletRequest request, HttpServletResponse response){ String email = (String) request.getParameter(""email""); String password = (String) request.getParameter(""password""); User user = userService.findByEmail(email); if (user == null || !user.getPassword().equals(password)) { return Pages.LOGIN; } request.getSession().setAttribute(X_AUTH_TOKEN, user.getId()); return Pages.INDEX; }" 42, ,"public void takeDamage(int damageValue, Weapon weapon){ if (damageValue <= 0) return; if (equipment.canBlockHit()) { equipment.blockHitFrom(weapon); return; } int damageToTake = damageValue - equipment.calculateTotalDamageResistance(); damageToTake = Math.max(damageToTake, 0); hp -= damageToTake; }","public void takeDamage(int damageValue, Weapon weapon){ if (damageValue <= 0) return; if (equipment.canBlockHit()) { equipment.blockHitFrom(weapon); return; } int damageToTake = damageValue - equipment.calculateTotalDamageResistance(); hp -= damageToTake; }" 43, ,"public Object createFromResultSet(ResultSetHelper rs) throws SQLException{ Object object = newEntityInstance(); for (int i = 0; i < fieldColumnMappings.size(); i++) { FieldColumnMapping fieldColumnMapping = fieldColumnMappings.get(i); fieldColumnMapping.setFromResultSet(object, rs); if (i == lastPrimaryKeyIndex) { Object existing = objectCache.get(classRowMapping, object); if (existing != null) { return existing; } } } objectCache.add(classRowMapping, object); return object; }","public Object createFromResultSet(ResultSetHelper rs) throws SQLException{ Object object = newEntityInstance(); for (int i = 0; i < fieldColumnMappings.size(); i++) { fieldColumnMappings.get(i).setFromResultSet(object, rs, i + 1); if (i == lastPrimaryKeyIndex) { Object existing = objectCache.get(classRowMapping, object); if (existing != null) { return existing; } } } objectCache.add(classRowMapping, object); return object; }" 44, ,"private void getInstalledOs(SQLConnection connection, Handler>> next){ String query = ""SELECT * FROM app_installer""; connection.query(query, selectHandler -> { if (selectHandler.failed()) { handleFailure(logger, selectHandler); } else { logger.info(""Installed OS: "", Json.encodePrettily(selectHandler.result().getRows())); next.handle(Future.succeededFuture(selectHandler.result().getRows())); } }); }","private void getInstalledOs(SQLConnection connection, Handler>> next){ connection.query(SELECT_APP_INSTALLER_QUERY, selectHandler -> { if (selectHandler.failed()) { handleFailure(logger, selectHandler); } else { logger.info(""Installed OS: "", Json.encodePrettily(selectHandler.result().getRows())); next.handle(Future.succeededFuture(selectHandler.result().getRows())); } }); }" 45, ,"public Integer[] flattenArray(Object[] inputArray){ List flattenedIntegerList = new ArrayList(); for (Object element : inputArray) { if (element instanceof Integer[]) { Integer[] elementArray = (Integer[]) element; for (Integer currentElement : elementArray) { flattenedIntegerList.add(currentElement); } } else if (element instanceof Integer) { flattenedIntegerList.add((Integer) element); } } return flattenedIntegerList.toArray(new Integer[flattenedIntegerList.size()]); }","public Integer[] flattenArray(Object[] inputArray){ List flattenedIntegerList = new ArrayList(); for (Object element : inputArray) { if (element instanceof Integer[]) { Integer[] elementArray = (Integer[]) element; Collections.addAll(flattenedIntegerList, elementArray); } else if (element instanceof Integer) { flattenedIntegerList.add((Integer) element); } } return flattenedIntegerList.toArray(new Integer[flattenedIntegerList.size()]); }" 46, ,"public void process(UserDTO dto){ UserEntity entity = repository.findFirstByEmail(dto.getEmail()).orElseGet(UserEntity::new); entity.setOuterId(dto.getId()); entity.setEmail(dto.getEmail()); entity.setFirstName(dto.getFirstName()); entity.setLastName(dto.getLastName()); entity.setDateModified(dto.getDateModified()); if (isNull(entity.getId())) { entity.setRegisteredDate(dto.getRegisteredDate()); entity.setExportDate(LocalDateTime.now()); } List employment = dto.getEmployments().stream().map(eDto -> { EmploymentEntity employmentEntity = new EmploymentEntity(); employmentEntity.setStart(eDto.getStart()); employmentEntity.setEnd(eDto.getEnd()); employmentEntity.setDepartment(departmentRepository.findFirstByOuterId(eDto.getDepartment().getIdentifier()).orElseGet(() -> new DepartmentEntity(eDto.getDepartment().getIdentifier(), eDto.getDepartment().getName()))); return employmentEntity; }).collect(toList()); entity.setEmployments(employment); repository.save(entity); }","public void process(UserDTO dto){ UserEntity entity = repository.findFirstByEmail(dto.getEmail()).orElseGet(UserEntity::new); entity.setOuterId(dto.getId()); entity.setEmail(dto.getEmail()); entity.setFirstName(dto.getFirstName()); entity.setLastName(dto.getLastName()); entity.setDateModified(dto.getDateModified()); entity.setRegisteredDate(dto.getRegisteredDate()); repository.save(entity); }" 47, ,"public void testSetOverallPositionAndWaitTimePhysical(){ int position = 2; physicalQueueStatus.setPosition(position); int numStudents = 1; long timeSpent = 5L; employee.setTotalTimeSpent(timeSpent); employee.setNumRegisteredStudents(numStudents); int expectedWaitTime = (int) ((position - 1.) * timeSpent / numStudents); queueService.setOverallPositionAndWaitTime(physicalQueueStatus); assertEquals(physicalQueueStatus.getCompanyId(), ""c1""); assertEquals(physicalQueueStatus.getQueueId(), ""pq1""); assertEquals(physicalQueueStatus.getRole(), Role.SWE); assertEquals(physicalQueueStatus.getPosition(), position); assertEquals(physicalQueueStatus.getQueueType(), QueueType.PHYSICAL); assertEquals(physicalQueueStatus.getWaitTime(), expectedWaitTime); assertEquals(physicalQueueStatus.getEmployee(), employee); }","public void testSetOverallPositionAndWaitTimePhysical(){ int position = 2; physicalQueueStatus.setPosition(position); int numStudents = 1; long timeSpent = 5L; employee.setTotalTimeSpent(timeSpent); employee.setNumRegisteredStudents(numStudents); int expectedWaitTime = (int) ((position - 1.) * timeSpent / numStudents); queueService.setOverallPositionAndWaitTime(physicalQueueStatus); validatePhysicalQueueStatus(physicalQueueStatus, position, expectedWaitTime); }" 48, ,"public void returnOnePositionForOneItemInInvoice(){ bookKeeper = new BookKeeper(new InvoiceFactory()); when(productData.getType()).thenReturn(productType); InvoiceBuilderImpl invoiceBuilderImpl = new InvoiceBuilderImpl(); invoiceBuilderImpl.setItemsQuantity(1); invoiceBuilderImpl.setProductData(productData); invoiceBuilderImpl.setMoney(money); request = invoiceBuilderImpl.build(); when(taxPolicy.calculateTax(productType, money)).thenReturn(tax); invoice = bookKeeper.issuance(request, taxPolicy); invoiceLines = invoice.getItems(); assertThat(invoice, notNullValue()); assertThat(invoiceLines, notNullValue()); assertThat(invoiceLines.size(), Matchers.equalTo(1)); }","public void returnOnePositionForOneItemInInvoice(){ bookKeeper = new BookKeeper(new InvoiceFactory()); when(productData.getType()).thenReturn(productType); request = buildRequest(1); when(taxPolicy.calculateTax(productType, money)).thenReturn(tax); invoice = bookKeeper.issuance(request, taxPolicy); invoiceLines = invoice.getItems(); assertThat(invoice, notNullValue()); assertThat(invoiceLines, notNullValue()); assertThat(invoiceLines.size(), Matchers.equalTo(1)); }" 49, ,"public Double removeBetEventOnTicket(@RequestBody String json){ Long id = Long.parseLong(JSON.parseObject(json).get(""id"").toString()); Character type = JSON.parseObject(json).get(""type"").toString().charAt(0); BetEvent betEvent = betEventService.getBetEventById(id); playedEvents.removeIf((PlayedEvent event) -> event.getEvent().equals(betEvent)); return calculateQuotaService.decreaseSumQuota(type, betEvent); }","public Double removeBetEventOnTicket(@RequestBody String json){ Long id = Long.parseLong(JSON.parseObject(json).get(""id"").toString()); Character type = JSON.parseObject(json).get(""type"").toString().charAt(0); BetEvent betEvent = betEventService.getBetEventById(id); return calculateQuotaService.decreaseSumQuota(type, betEvent); }" 50, ,"public void testRemoveJavadoc() throws ParseException{ String code = ""public class B { /**\n* This class is awesome**/\npublic void foo(){} }""; DefaultJavaParser parser = new DefaultJavaParser(); CompilationUnit cu = parser.parse(code, false); CompilationUnit cu2 = parser.parse(code, false); MethodDeclaration md = (MethodDeclaration) cu.getTypes().get(0).getMembers().get(0); md.setJavaDoc(null); ChangeLogVisitor visitor = new ChangeLogVisitor(); VisitorContext ctx = new VisitorContext(); ctx.put(ChangeLogVisitor.NODE_TO_COMPARE_KEY, cu2); visitor.visit((CompilationUnit) cu, ctx); List actions = visitor.getActionsToApply(); Assert.assertEquals(1, actions.size()); assertCode(actions, code, ""public class B { public void foo(){} }""); }","public void testRemoveJavadoc() throws ParseException{ String code = ""public class B { /**\n* This class is awesome**/\npublic void foo(){} }""; DefaultJavaParser parser = new DefaultJavaParser(); CompilationUnit cu = parser.parse(code, false); CompilationUnit cu2 = parser.parse(code, false); MethodDeclaration md = (MethodDeclaration) cu.getTypes().get(0).getMembers().get(0); md.setJavaDoc(null); List actions = getActions(cu2, cu); Assert.assertEquals(1, actions.size()); assertCode(actions, code, ""public class B { public void foo(){} }""); }" 51, ,"public void addGrantToAllTablesInSchema(String schema, Privileges privs, String grantee, boolean grant_option, String granter) throws DatabaseException{ TableName[] list = connection.getTableList(); for (int i = 0; i < list.length; ++i) { TableName tname = list[i]; if (tname.getSchema().equals(schema)) { addGrant(privs, TABLE, tname.toString(), grantee, grant_option, granter); } } }","public void addGrantToAllTablesInSchema(String schema, Privileges privs, String grantee, boolean grant_option, String granter) throws DatabaseException{ TableName[] list = connection.getTableList(); for (TableName tname : list) { if (tname.getSchema().equals(schema)) { addGrant(privs, TABLE, tname.toString(), grantee, grant_option, granter); } } }" 52, ,"private static void setupPluginBootService(final Collection pluginConfigurations){ PluginServiceManager.setUpAllService(pluginConfigurations); PluginServiceManager.startAllService(pluginConfigurations); Runtime.getRuntime().addShutdownHook(new Thread(PluginServiceManager::cleanUpAllService)); }","private static void setupPluginBootService(final Map pluginConfigurationMap){ PluginServiceManager.startAllService(pluginConfigurationMap); Runtime.getRuntime().addShutdownHook(new Thread(PluginServiceManager::closeAllService)); }" 53, ,"public void testCreateListing6() throws CommandParseFailException, UnsupportCommandException{ List arg = new ArrayList(); arg = CommandPaser.parse(clistCommand6); createListingCommand.setCommands(arg); createListingCommand.execute(); ResponseObject ret = registerUserCommand.getRetObj(); System.out.println(ret.getMessage()); }","public void testCreateListing6() throws CommandParseFailException, UnsupportCommandException{ List arg = new ArrayList(); arg = CommandPaser.parse(clistCommand6); createListingCommand.setCommands(arg); ResponseObject ret = createListingCommand.execute(); System.out.println(ret.getMessage()); }" 54, ,"public String paymentSuccess(@QueryParam(""PayerID"") String payerID){ System.out.println(payerID); return payService.executePayment(payerID).toJSON(); }","public String paymentSuccess(@QueryParam(""PayerID"") String payerID, @QueryParam(""paymentId"") String paymentId){ return payService.executePayment(payerID, paymentId).toJSON(); }" 55, ,"public String getToken(){ JwtRequest jwtRequest = JwtRequest.builder().username(""javainuse"").password(""password"").build(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity entity = new HttpEntity(jwtRequest, headers); logger.info(""url: {}"", this.createURLWithPort(""/authenticate"")); ResponseEntity response = restTemplate.exchange(this.createURLWithPort(""/authenticate""), HttpMethod.POST, entity, JwtResponse.class); logger.info(""response: {}"", response); assertEquals(HttpStatus.OK, response.getStatusCode()); return response.getBody().getJwtToken(); }","public String getToken(){ JwtRequest jwtRequest = JwtRequest.builder().username(""javainuse"").password(""password"").build(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); logger.info(""url: {}"", this.createURLWithPort(""/authenticate"")); ResponseEntity response = restTemplate.exchange(this.createURLWithPort(""/authenticate""), HttpMethod.POST, new HttpEntity(jwtRequest, headers), JwtResponse.class); logger.info(""response: {}"", response); assertEquals(HttpStatus.OK, response.getStatusCode()); return response.getBody().getJwtToken(); }" 56, ,"public List getDonation(@QueryParam(""filters"") Optional filters){ if (filters.isPresent()) { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new ProtobufModule()); DonationsFilters donationFilters; try { donationFilters = mapper.readValue(URLDecoder.decode(filters.get(), ""UTF-8""), DonationsFilters.class); if (donationFilters.hasLimit()) { if (donationFilters.getLimit() > this.maxLimit) { donationFilters = donationFilters.toBuilder().setLimit(this.maxLimit).build(); } else { donationFilters = donationFilters.toBuilder().setLimit(this.defaultLimit).build(); } } return this.manager.getDonations(donationFilters); } catch (IOException e) { LOG.error(e.getMessage()); throw new BadRequestException(""Donations filters were malformed. Could not parse JSON content in query param"", ApiDocs.DONATIONS_FILTERS); } } else { return this.manager.getDonations(); } }","public List getDonation(@QueryParam(""limit"") Optional maybeLimit, @QueryParam(""filters"") Optional maybeFilters){ Integer limit = ResourcesHelper.limit(maybeLimit, defaultLimit, maxLimit); if (maybeFilters.isPresent()) { DonationsFilters filters = ResourcesHelper.decodeUrlEncodedJson(maybeFilters.get(), DonationsFilters.class); return this.manager.getDonations(limit, filters); } else { return this.manager.getDonations(); } }" 57, ,"private BetweenExpression createBetweenSegment(final PredicateContext ctx){ BetweenExpression result = new BetweenExpression(); result.setStartIndex(ctx.start.getStartIndex()); result.setStopIndex(ctx.stop.getStopIndex()); result.setLeft((ExpressionSegment) visit(ctx.bitExpr(0))); result.setBetweenExpr((ExpressionSegment) visit(ctx.bitExpr(1))); result.setAndExpr((ExpressionSegment) visit(ctx.predicate())); String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex())); result.setText(text); return result; }","private BetweenExpression createBetweenSegment(final PredicateContext ctx){ BetweenExpression result = new BetweenExpression(); result.setStartIndex(ctx.start.getStartIndex()); result.setStopIndex(ctx.stop.getStopIndex()); result.setLeft((ExpressionSegment) visit(ctx.bitExpr(0))); result.setBetweenExpr((ExpressionSegment) visit(ctx.bitExpr(1))); result.setAndExpr((ExpressionSegment) visit(ctx.predicate())); return result; }" 58, ,"public void generateBuildTree(){ System.out.println(""Starting optimization of blueprint '"" + blueprint.getName() + ""'""); BuildTreeBlueprintNode tree = generateBuildTree(1, blueprint); tree.updateTreePrices(); BuildTreePrinter printer = new BuildTreePrinter(System.out); printer.printTree(tree); Map shoppingList = new HashMap<>(); Map buildList = new HashMap<>(); tree.generateBuildBuyLists(shoppingList, buildList); String[] buyHeaders = { ""Buy"", ""Quantity"" }; String[] buildHeaders = { ""Build"", ""Quantity"" }; Class[] classes = new Class[] { String.class, String.class }; DecimalFormat decimalFormat = new DecimalFormat(""#""); decimalFormat.setGroupingUsed(true); decimalFormat.setGroupingSize(3); List buyData = new LinkedList<>(); for (Map.Entry entries : shoppingList.entrySet()) { buyData.add(new String[] { typeLoader.getType(entries.getKey()).getName(), decimalFormat.format(entries.getValue()) }); } List buildData = new LinkedList<>(); for (Map.Entry entries : buildList.entrySet()) { buildData.add(new String[] { typeLoader.getType(entries.getKey()).getName(), decimalFormat.format(entries.getValue()) }); } ColumnOutputPrinter buyPrinter = new ColumnOutputPrinter(buyHeaders, classes, buyData); ColumnOutputPrinter buildPrinter = new ColumnOutputPrinter(buyHeaders, classes, buildData); buyPrinter.output(); buildPrinter.output(); }","public BuildManifest generateBuildTree(){ System.out.println(""Starting optimization of blueprint '"" + blueprint.getName() + ""'""); BuildTreeBlueprintNode tree = generateBuildTree(1, blueprint); tree.updateTreePrices(); Map shoppingList = new HashMap<>(); Map buildList = new HashMap<>(); tree.generateBuildBuyLists(typeLoader, shoppingList, buildList); return BuildManifest.builder().tree(tree).shoppingList(shoppingList).buildList(buildList).build(); }" 59, ,"public Milestone getMilestone(String name) throws TracRpcException{ Object[] params = new Object[] { name }; HashMap result = (HashMap) this.call(""ticket.milestone.get"", params); Milestone m = new Milestone(); m.setAttribs(result); return m; }","public Milestone getMilestone(String name) throws TracRpcException{ return this.getBasicStruct(name, ""ticket.milestone.get"", Milestone.class); }" 60, ,"public List findDeletedUserReports() throws ServiceException{ try { List reports = dao.findUserReportsByAvailability(false); return reports; } catch (DaoException e) { throw new ServiceException(e); } }","public List findDeletedUserReports() throws ServiceException{ try { return dao.findUserReportsByAvailability(false); } catch (DaoException e) { throw new ServiceException(e); } }" 61, ,"public Set getParticipantOfTournament(@PathVariable Integer tournamentId){ Tournament tournament = tournamentService.getTournamenById(tournamentId); System.out.println(tournament.getUsers().size()); return tournament.getUsers(); }","public Set getParticipantOfTournament(@PathVariable Integer tournamentId){ Tournament tournament = tournamentService.getTournamenById(tournamentId); return tournament.getUsers(); }" 62, ,"public final void read(InputStream source) throws IOException{ checkNotNull(source); progressTimer = new Timer(true); progressTimer.schedule(new ProgressTimer(source), 10_000, 30_000); try { run(new BufferedInputStream(source)); } catch (Exception e) { throw new IOException(e); } finally { progressTimer.cancel(); BasicNamespace.Registry.getInstance().clean(); } }","public final void read(InputStream source) throws IOException{ checkNotNull(source); try { run(new BufferedInputStream(source)); } catch (Exception e) { throw new IOException(e); } finally { BasicNamespace.Registry.getInstance().clean(); } }" 63, ,"public static Optional minRule(String field, Integer value, int min){ Optional isNotNull = notNullRule(field, value); if (isNotNull.isPresent()) { return isNotNull; } if (value < min) { return Optional.of(Violation.of(field, ""validation.error.integer.value.smaller.than.min"", ""Value is smaller than min."", singletonMap(""min"", min))); } return Optional.empty(); }","public static Optional minRule(String field, Integer value, int min){ Optional isNotNull = notNullRule(field, value); if (isNotNull.isPresent()) { return isNotNull; } return isTrueRule(() -> value >= min, Violation.of(field, ""validation.error.integer.value.smaller.than.min"", ""Value is smaller than min."", singletonMap(""min"", min))); }" 64, ," static int maxSubArray(int[] nums){ int cf = 0; int maxSum = Integer.MIN_VALUE; for (int i = 0; i < nums.length; i++) { if (nums[i] >= cf + nums[i]) cf = nums[i]; else cf += nums[i]; if (maxSum < cf) maxSum = cf; } return maxSum; }"," static int maxSubArray(int[] nums){ int cf = nums[0]; int maxSum = nums[0]; for (int i = 1; i < nums.length; i++) { cf = cf + nums[i]; if (nums[i] > cf) cf = nums[i]; if (cf > maxSum) maxSum = cf; } return maxSum; }" 65, ,"public void positiveEvaluteEqualsToInteger() throws Exception{ Map attributes = new HashMap<>(); attributes.put(""age"", 25); String feature = ""Age Feature""; String expression = ""age == 25""; final GatingValidator validator = new GatingValidator(); Assert.assertTrue(validator.isAllowed(expression, feature, attributes)); }","public void positiveEvaluteEqualsToInteger() throws Exception{ Map attributes = new HashMap<>(); attributes.put(""age"", 25); String feature = ""Age Feature""; String expression = ""age == 25""; Assert.assertTrue(validator.isAllowed(expression, feature, attributes)); }" 66, ," void invalidate(List movieRatings){ Map newActualMovieRating = new HashMap<>(); for (MovieRating movieRating : movieRatings) { newActualMovieRating.put(movieRating.getMovie().getId(), movieRating); } Lock writeLock = LOCK.writeLock(); try { writeLock.lock(); actualMovieRating = newActualMovieRating; } finally { writeLock.unlock(); } }"," void invalidate(List movieRatings){ Map newActualMovieRating = new ConcurrentHashMap<>(); for (MovieRating movieRating : movieRatings) { newActualMovieRating.put(movieRating.getMovie().getId(), movieRating); } actualMovieRating = newActualMovieRating; }" 67, ,"private void resize(int capacity){ assert capacity > n; Key[] temp = (Key[]) new Object[capacity]; for (int i = 1; i <= n; i++) { temp[i] = pq[i]; } pq = temp; }","private void resize(int capacity){ assert capacity > n; pq = Arrays.copyOf(pq, capacity); }" 68, ,"public void returnTenPositionsForTenItemInInvoiceTaxCalculatedTenTimes(){ bookKeeper = new BookKeeper(new InvoiceFactory()); when(productData.getType()).thenReturn(productType); InvoiceBuilderImpl invoiceBuilderImpl = new InvoiceBuilderImpl(); invoiceBuilderImpl.setItemsQuantity(10); invoiceBuilderImpl.setProductData(productData); invoiceBuilderImpl.setMoney(money); request = invoiceBuilderImpl.build(); when(taxPolicy.calculateTax(productType, money)).thenReturn(tax); invoice = bookKeeper.issuance(request, taxPolicy); invoiceLines = invoice.getItems(); verify(taxPolicy, times(10)).calculateTax(productType, money); assertThat(invoiceLines, notNullValue()); assertThat(invoiceLines.size(), Matchers.equalTo(10)); }","public void returnTenPositionsForTenItemInInvoiceTaxCalculatedTenTimes(){ bookKeeper = new BookKeeper(new InvoiceFactory()); when(productData.getType()).thenReturn(productType); request = buildRequest(10); when(taxPolicy.calculateTax(productType, money)).thenReturn(tax); invoice = bookKeeper.issuance(request, taxPolicy); invoiceLines = invoice.getItems(); verify(taxPolicy, times(10)).calculateTax(productType, money); assertThat(invoiceLines, notNullValue()); assertThat(invoiceLines.size(), Matchers.equalTo(10)); }" 69, ,"public void test_isSelectionPatternAvailable() throws Exception{ when(element.getPropertyValue(anyInt())).thenReturn(1); IUIAutomation mocked_automation = Mockito.mock(IUIAutomation.class); UIAutomation instance = new UIAutomation(mocked_automation); AutomationWindow window = new AutomationWindow(new ElementBuilder(element).itemContainer(container).automation(instance).window(pattern)); boolean value = window.isSelectionPatternAvailable(); assertTrue(value); }","public void test_isSelectionPatternAvailable() throws Exception{ Selection pattern = Mockito.mock(Selection.class); when(pattern.isAvailable()).thenReturn(true); AutomationWindow window = new AutomationWindow(new ElementBuilder(element).addPattern(pattern)); boolean value = window.isSelectionPatternAvailable(); assertTrue(value); }" 70, ,"public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception{ if (doesCheckerAppy(context)) { if (!check(exchange, context)) { MongoClient client = MongoDBClientSingleton.getInstance().getClient(); MongoDatabase mdb = client.getDatabase(context.getDBName()); MongoCollection coll = mdb.getCollection(context.getCollectionName(), BsonDocument.class); StringBuilder sb = new StringBuilder(); sb.append(""request check failed""); List warnings = context.getWarnings(); if (warnings != null && !warnings.isEmpty()) { warnings.stream().forEach(w -> { sb.append("", "").append(w); }); } BsonDocument oldData = context.getDbOperationResult().getOldData(); Object newEtag = context.getDbOperationResult().getEtag(); if (oldData != null) { DAOUtils.restoreDocument(coll, oldData.get(""_id""), context.getShardKey(), oldData, newEtag); if (oldData.get(""$set"") != null && oldData.get(""$set"").isDocument() && oldData.get(""$set"").asDocument().get(""_etag"") != null) { exchange.getResponseHeaders().put(Headers.ETAG, oldData.get(""$set"").asDocument().get(""_etag"").asObjectId().getValue().toString()); } else { exchange.getResponseHeaders().remove(Headers.ETAG); } } else { Object newId = context.getDbOperationResult().getNewData().get(""_id""); coll.deleteOne(and(eq(""_id"", newId), eq(""_etag"", newEtag))); } ResponseHelper.endExchangeWithMessage(exchange, context, HttpStatus.SC_BAD_REQUEST, sb.toString()); next(exchange, context); return; } } next(exchange, context); }","public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception{ if (doesCheckerAppy(context)) { if (!check(exchange, context)) { MongoClient client = MongoDBClientSingleton.getInstance().getClient(); MongoDatabase mdb = client.getDatabase(context.getDBName()); MongoCollection coll = mdb.getCollection(context.getCollectionName(), BsonDocument.class); BsonDocument oldData = context.getDbOperationResult().getOldData(); Object newEtag = context.getDbOperationResult().getEtag(); if (oldData != null) { DAOUtils.restoreDocument(coll, oldData.get(""_id""), context.getShardKey(), oldData, newEtag); if (oldData.get(""$set"") != null && oldData.get(""$set"").isDocument() && oldData.get(""$set"").asDocument().get(""_etag"") != null) { exchange.getResponseHeaders().put(Headers.ETAG, oldData.get(""$set"").asDocument().get(""_etag"").asObjectId().getValue().toString()); } else { exchange.getResponseHeaders().remove(Headers.ETAG); } } else { Object newId = context.getDbOperationResult().getNewData().get(""_id""); coll.deleteOne(and(eq(""_id"", newId), eq(""_etag"", newEtag))); } ResponseHelper.endExchangeWithMessage(exchange, context, HttpStatus.SC_BAD_REQUEST, ""request check failed""); next(exchange, context); return; } } next(exchange, context); }" 71, ,"public List tables(){ List tables = new ArrayList<>(); for (DaoDescriptor descriptor : descriptorsSet) { tables.add(createRegularTableSql(descriptor)); } return tables; }","public List tables(){ return descriptorsSet.stream().map(this::tablesSql).collect(Collectors.toList()); }" 72, ,"private void init(){ MainPanel mainPanel = (MainPanel) parentPanel.getParentPanel().getParentPanel(); Properties uiStylesProperties = mainPanel.getUiStylesProperties(); Properties uiPositionProperties = mainPanel.getUiPositionProperties(); Properties generalProperties = mainPanel.getGeneralProperties(); setBackground(PropertyUtil.getColor(uiStylesProperties, UIConstants.Styles.VIDEOLIST_MAIN_PANEL_TOPICS_MAIN_BG_COLOR)); Panel headerPanel = new Panel(ChildName.VideoListPage.MainPanel.TOPICS_HEADING_PANEL.name(), getTopicsHeaderBounds(uiPositionProperties), this, mainPanel); headerPanel.setBackground(PropertyUtil.getColor(uiStylesProperties, UIConstants.Styles.VIDEOLIST_MAIN_PANEL_TOPICS_BG_COLOR)); Label topicsLabel = getTopicsLabel(headerPanel, uiPositionProperties, uiStylesProperties, generalProperties); headerPanel.addChild(ChildName.General.LABEL.name(), topicsLabel); addChild(ChildName.VideoListPage.MainPanel.TOPICS_HEADING_PANEL.name(), headerPanel); initTopics(); }","private void init(){ Properties uiStylesProperties = mainPanel.getUiStylesProperties(); Properties uiPositionProperties = mainPanel.getUiPositionProperties(); Properties generalProperties = mainPanel.getGeneralProperties(); setBackground(PropertyUtil.getColor(uiStylesProperties, UIConstants.Styles.VIDEOLIST_MAIN_PANEL_TOPICS_MAIN_BG_COLOR)); Panel headerPanel = new Panel(ChildName.VideoListPage.MainPanel.TOPICS_HEADING_PANEL.name(), getTopicsHeaderBounds(uiPositionProperties), this, mainPanel); headerPanel.setBackground(PropertyUtil.getColor(uiStylesProperties, UIConstants.Styles.VIDEOLIST_MAIN_PANEL_TOPICS_BG_COLOR)); Label topicsLabel = getTopicsLabel(headerPanel, uiPositionProperties, uiStylesProperties, generalProperties); headerPanel.addChild(ChildName.General.LABEL.name(), topicsLabel); addChild(headerPanel); initTopics(); }" 73, ,"public List get(@PathParam(""userID"") String userID, @PathParam(""itemID"") List pathSegmentsList) throws OryxServingException{ ALSServingModel model = getALSServingModel(); float[] userFeatures = model.getUserVector(userID); checkExists(userFeatures != null, userID); List results = new ArrayList<>(pathSegmentsList.size()); for (PathSegment pathSegment : pathSegmentsList) { float[] itemFeatures = model.getItemVector(pathSegment.getPath()); if (itemFeatures == null) { results.add(0.0); } else { double value = VectorMath.dot(itemFeatures, userFeatures); Preconditions.checkState(!(Double.isInfinite(value) || Double.isNaN(value)), ""Bad estimate""); results.add(value); } } return results; }","public List get(@PathParam(""userID"") String userID, @PathParam(""itemID"") List pathSegmentsList) throws OryxServingException{ ALSServingModel model = getALSServingModel(); float[] userFeatures = model.getUserVector(userID); checkExists(userFeatures != null, userID); return pathSegmentsList.stream().map(pathSegment -> { float[] itemFeatures = model.getItemVector(pathSegment.getPath()); if (itemFeatures == null) { return 0.0; } else { double value = VectorMath.dot(itemFeatures, userFeatures); Preconditions.checkState(!(Double.isInfinite(value) || Double.isNaN(value)), ""Bad estimate""); return value; } }).collect(Collectors.toList()); }" 74, ,"public void testRemoveParenthesesReturn() throws ParseException{ String code = ""public class B{ public boolean bar() { return(true); }}""; DefaultJavaParser parser = new DefaultJavaParser(); CompilationUnit cu = parser.parse(code, false); CompilationUnit cu2 = parser.parse(code, false); MethodDeclaration md = (MethodDeclaration) cu.getTypes().get(0).getMembers().get(0); ReturnStmt stmt = (ReturnStmt) md.getBody().getStmts().get(0); EnclosedExpr expr = (EnclosedExpr) stmt.getExpr(); stmt.replaceChildNode(expr, expr.getInner()); ChangeLogVisitor visitor = new ChangeLogVisitor(); VisitorContext ctx = new VisitorContext(); ctx.put(ChangeLogVisitor.NODE_TO_COMPARE_KEY, cu2); visitor.visit((CompilationUnit) cu, ctx); List actions = visitor.getActionsToApply(); Assert.assertEquals(1, actions.size()); assertCode(actions, code, ""public class B{ public boolean bar() { return true; }}""); }","public void testRemoveParenthesesReturn() throws ParseException{ String code = ""public class B{ public boolean bar() { return(true); }}""; DefaultJavaParser parser = new DefaultJavaParser(); CompilationUnit cu = parser.parse(code, false); CompilationUnit cu2 = parser.parse(code, false); MethodDeclaration md = (MethodDeclaration) cu.getTypes().get(0).getMembers().get(0); ReturnStmt stmt = (ReturnStmt) md.getBody().getStmts().get(0); EnclosedExpr expr = (EnclosedExpr) stmt.getExpr(); stmt.replaceChildNode(expr, expr.getInner()); List actions = getActions(cu2, cu); Assert.assertEquals(1, actions.size()); assertCode(actions, code, ""public class B{ public boolean bar() { return true; }}""); }" 75, ,"public int max(int first, int second, int third){ int temp = max(first, second); int result = max(temp, third); return result; }","public int max(int first, int second, int third){ return max(max(first, second), third); }" 76, ,"public long getTimeForProcessQueue() throws InterruptedException{ long startTime = System.currentTimeMillis(); for (int i = 0; i < countCashboxes; i++) { Cashbox cashbox = new Cashbox(queue, ""cashbox_"" + i); cashbox.start(); threadList.add(cashbox); } for (Customer customer : customerList) { queue.put(customer); } for (Cashbox cashbox : threadList) { cashbox.disable(); } for (Cashbox cashbox : threadList) { cashbox.join(); } return Math.round((System.currentTimeMillis() - startTime) / 1000); }","public long getTimeForProcessQueue() throws InterruptedException{ long startTime = System.currentTimeMillis(); for (int i = 0; i < countCashboxes; i++) { Cashbox cashbox = new Cashbox(queue, ""cashbox_"" + i); cashbox.start(); threadList.add(cashbox); } for (Customer customer : customerList) { queue.put(customer); } threadList.forEach(cb -> cb.disable()); for (Cashbox cashbox : threadList) { cashbox.join(); } return Math.round((System.currentTimeMillis() - startTime) / 1000f); }" 77, ,"public TypeSpec generateView(ViewDesc typeDesc){ final TypeSpec.Builder builder = viewInitialiser.create(typeDesc); for (final PropertyDesc propertyDesc : typeDesc.getProperties()) { final JavaDocMethodBuilder javaDocMethodBuilder = docMethod(); if (propertyDesc.getDescription() == null || """".equals(propertyDesc.getDescription())) { javaDocMethodBuilder.setMethodDescription(""Getter for the property $1L.\n""); } else { javaDocMethodBuilder.setMethodDescription(""Getter for the property $1L.\n

\n"" + propertyDesc.getDescription() + ""\n""); } builder.addMethod(methodBuilder(getAccessorName(propertyDesc.getName())).addJavadoc(javaDocMethodBuilder.setReturnsDescription(""the value of $1L"").toJavaDoc(), propertyDesc.getName()).addModifiers(ABSTRACT, PUBLIC).returns(getType(propertyDesc)).build()); } return builder.build(); }","public TypeSpec generateView(ViewDesc typeDesc){ final TypeSpec.Builder builder = viewInitialiser.create(typeDesc); for (final PropertyDesc propertyDesc : typeDesc.getProperties()) { builder.addMethod(methodBuilder(getAccessorName(propertyDesc.getName())).addJavadoc(accessorJavadocGenerator.generateJavaDoc(propertyDesc)).addModifiers(ABSTRACT, PUBLIC).returns(getType(propertyDesc)).build()); } return builder.build(); }" 78, ,"private static void add(ConfigObject config, String prefix, Map values){ for (Map.Entry e : config.entrySet()) { String nextPrefix = prefix + ""."" + e.getKey(); ConfigValue value = e.getValue(); switch(value.valueType()) { case OBJECT: add((ConfigObject) value, nextPrefix, values); break; case NULL: break; default: values.put(nextPrefix, String.valueOf(value.unwrapped())); } } }","private static void add(ConfigObject config, String prefix, Map values){ config.forEach((key, value) -> { String nextPrefix = prefix + ""."" + key; switch(value.valueType()) { case OBJECT: add((ConfigObject) value, nextPrefix, values); break; case NULL: break; default: values.put(nextPrefix, String.valueOf(value.unwrapped())); } }); }" 79, ,"public Integer decrypt(IntegerWrapper message){ Integer value = message.getEncryptedValue(); boolean isNegative = value < 0; int[] values = getInts(value, isNegative); NumberComposer composer = new NumberComposer(isNegative); Arrays.stream(values).map(new DigitDecryptor(message.getOneTimePad())).forEach(composer); return composer.getInteger(); }","public Integer decrypt(IntegerWrapper message){ Integer value = message.getEncryptedValue(); NumberComposer composer = digitStreamCipher.decrypt(value.toString(), message.getOneTimePad()); return composer.getInteger(); }" 80, ,"public String showInactiveBugs(Model theModel, @RequestParam(""page"") Optional page, @RequestParam(""size"") Optional size){ String myUserName; Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof UserDetails) { myUserName = ((UserDetails) principal).getUsername(); } else { myUserName = principal.toString(); } int currentPage = page.orElse(1); int pageSize = size.orElse(15); Page inactiveBugPage = bugService.findPaginatedUserInactiveBugs(PageRequest.of(currentPage - 1, pageSize), myUserName); theModel.addAttribute(""inactiveBugPage"", inactiveBugPage); int totalPages = inactiveBugPage.getTotalPages(); if (totalPages > 0) { List pageNumbers = IntStream.rangeClosed(1, totalPages).boxed().collect(Collectors.toList()); theModel.addAttribute(""pageNumbers"", pageNumbers); } List myBugList = bugService.getListOfInactiveBugsForUser(myUserName); List listOfApplicableProjectNames = new ArrayList<>(); for (Bug bug : myBugList) { Project project = projectService.getProjectById(bug.getProjectId()); String projectName = project.getProjectName(); listOfApplicableProjectNames.add(projectName); } theModel.addAttribute(""projectNames"", listOfApplicableProjectNames); return ""inactiveBugsPage""; }","public String showInactiveBugs(Model theModel, @RequestParam(""page"") Optional page, @RequestParam(""size"") Optional size){ UserUtility userUtility = new UserUtility(); int currentPage = page.orElse(1); int pageSize = size.orElse(15); Page inactiveBugPage = bugService.findPaginatedUserInactiveBugs(PageRequest.of(currentPage - 1, pageSize), userUtility.getMyUserName()); theModel.addAttribute(""inactiveBugPage"", inactiveBugPage); int totalPages = inactiveBugPage.getTotalPages(); if (totalPages > 0) { List pageNumbers = IntStream.rangeClosed(1, totalPages).boxed().collect(Collectors.toList()); theModel.addAttribute(""pageNumbers"", pageNumbers); } List myBugList = bugService.getListOfInactiveBugsForUser(userUtility.getMyUserName()); List listOfApplicableProjectNames = new ArrayList<>(); for (Bug bug : myBugList) { Project project = projectService.getProjectById(bug.getProjectId()); String projectName = project.getProjectName(); listOfApplicableProjectNames.add(projectName); } theModel.addAttribute(""projectNames"", listOfApplicableProjectNames); return ""inactiveBugsPage""; }" 81, ,"public Object getMethodValue(EntityBean bean, String fieldName){ try { Method m = bean.getClass().getMethod(getString + fieldName); return m.invoke(bean); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { log.error(ex.getMessage()); } return null; }","public Object getMethodValue(EntityBean bean, String fieldName){ try { Method m = bean.getClass().getMethod(getString + fieldName); return m.invoke(bean); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { } return null; }" 82, ," static int rob(int[] nums, int s, int e){ int p1 = nums[s]; int p2 = p1; if (0 < e - s) p2 = Math.max(p1, nums[s + 1]); for (int i = s + 2; i <= e; i++) { final int tmp = p1 + nums[i]; p1 = p2; p2 = Math.max(tmp, p2); } return p2; }"," static int rob(int[] nums, int s, int e){ int p1 = 0; int p2 = 0; for (int i = s; i <= e; i++) { final int tmp = p1 + nums[i]; p1 = p2; p2 = Math.max(tmp, p2); } return p2; }" 83, ,"public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{ if (!isExecution(method)) { return method.invoke(delegate, args); } Subsegment subsegment = createSubsegment(); if (subsegment == null) { try { return method.invoke(delegate, args); } catch (Throwable t) { if (t instanceof InvocationTargetException) { InvocationTargetException ite = (InvocationTargetException) t; if (ite.getTargetException() != null) { throw ite.getTargetException(); } if (ite.getCause() != null) { throw ite.getCause(); } } throw t; } } logger.debug(""Invoking statement execution with X-Ray tracing.""); try { return method.invoke(delegate, args); } catch (Throwable t) { if (t instanceof InvocationTargetException) { InvocationTargetException ite = (InvocationTargetException) t; if (ite.getTargetException() != null) { subsegment.addException(ite.getTargetException()); throw ite.getTargetException(); } if (ite.getCause() != null) { subsegment.addException(ite.getCause()); throw ite.getCause(); } subsegment.addException(ite); throw ite; } subsegment.addException(t); throw t; } finally { AWSXRay.endSubsegment(); } }","public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{ Subsegment subsegment = null; if (isExecution(method)) { subsegment = createSubsegment(); } logger.debug(String.format(""Invoking statement execution with X-Ray tracing. Tracing active: %s"", subsegment != null)); try { return method.invoke(delegate, args); } catch (Throwable t) { Throwable rootThrowable = t; if (t instanceof InvocationTargetException) { InvocationTargetException ite = (InvocationTargetException) t; if (ite.getTargetException() != null) { rootThrowable = ite.getTargetException(); } else if (ite.getCause() != null) { rootThrowable = ite.getCause(); } } if (subsegment != null) { subsegment.addException(rootThrowable); } throw rootThrowable; } finally { if (isExecution(method)) { AWSXRay.endSubsegment(); } } }" 84, ,"public int getDamageOutput(){ triggerValue = 0.3; if (fighter.getHp() <= fighter.getInitialHp() * triggerValue) return fighter.calculateEquipmentDamageOutput() * damageMultiplier; return fighter.calculateEquipmentDamageOutput(); }","public int getDamageOutput(){ if (fighter.getHp() <= fighter.getInitialHp() * triggerValue) return fighter.calculateEquipmentDamageOutput() * damageMultiplier; return fighter.calculateEquipmentDamageOutput(); }" 85, ,"private static void loadProperties(File propertiesFile, Properties properties) throws IOException{ InputStream inStream = new FileInputStream(propertiesFile); try { properties.load(inStream); } finally { inStream.close(); } }","private static void loadProperties(File propertiesFile, Properties properties) throws IOException{ try (InputStream inStream = new FileInputStream(propertiesFile)) { properties.load(inStream); } }" 86, ,"public void run() throws InterruptedException{ EventLoopGroup bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory(String.format(""%s-boss"", name))); EventLoopGroup workerGroup = new NioEventLoopGroup(10, new DefaultThreadFactory(String.format(""%s-worker"", name))); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(channelHandler); } }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture future = serverBootstrap.bind(port).sync(); future.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }","public void run() throws InterruptedException{ EventLoopGroup bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory(String.format(""%s-boss"", name))); EventLoopGroup workerGroup = new NioEventLoopGroup(10, new DefaultThreadFactory(String.format(""%s-worker"", name))); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(channelInitializer).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture future = serverBootstrap.bind(port).sync(); future.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }" 87, ,"public User getUser(Observer observer){ User user = (User) observer; return user; }","public User getUser(Observer observer){ return (User) observer; }" 88, ,"public void generate(Long shiftId, LocalDate from, LocalDate to, int offset){ logger.debug(""Starting schedule generation for shift id={} from={} to={} with offset={}"", shiftId, from, to, offset); var shift = shiftRepository.findById(shiftId).orElseThrow(); var pattern = shiftPatternRepository.findById(shift.getPatternId()).orElseThrow(); var holidays = holidayRepository.findAllByEnterpriseIdAndDateBetween(shift.getDepartmentId(), from, to); var compositions = shiftCompositionRepository.findAllByShiftIdAndToGreaterThanEqualAndFromLessThanEqual(shiftId, from, to); var extraWeekends = extraWeekendRepository.findAllByEnterpriseIdAndDateBetween(shift.getDepartmentId(), from, to); var extraWorkDays = extraWorkDayRepository.findAllByEnterpriseIdAndDateBetween(shift.getDepartmentId(), from, to); logger.debug(""Data for generation:\r\n"" + ""Shift: {}\r\n"" + ""Pattern: {}\r\n"" + ""Compositions: {}\r\n"" + ""Holidays: {}\r\n"" + ""ExtraWeekends: {}\r\n"" + ""ExtraWorkDays: {}"", shift, pattern, compositions, holidays, extraWeekends, extraWorkDays); var workDays = generateSchedule(from, to, offset, pattern, holidays, compositions, extraWeekends, extraWorkDays); logger.debug(""Saving generated schedule to database...""); scheduleRepository.saveAll(workDays); }","public void generate(Long shiftId, LocalDate from, LocalDate to, int offset){ logger.debug(""Starting schedule generation for shift id={} from={} to={} with offset={}"", shiftId, from, to, offset); var shift = shiftRepository.findById(shiftId).orElseThrow(); var holidays = holidayRepository.findAllByEnterpriseIdAndDateBetween(shift.getDepartmentId(), from, to); var compositions = shiftCompositionRepository.findAllByShiftIdAndToGreaterThanEqualAndFromLessThanEqual(shiftId, from, to); var extraWeekends = extraWeekendRepository.findAllByEnterpriseIdAndDateBetween(shift.getDepartmentId(), from, to); var extraWorkDays = extraWorkDayRepository.findAllByEnterpriseIdAndDateBetween(shift.getDepartmentId(), from, to); logger.debug(""Data for generation:\r\n"" + ""Shift: {}\r\n"" + ""Compositions: {}\r\n"" + ""Holidays: {}\r\n"" + ""ExtraWeekends: {}\r\n"" + ""ExtraWorkDays: {}"", shift, compositions, holidays, extraWeekends, extraWorkDays); var workDays = generateSchedule(from, to, offset, shift, holidays, compositions, extraWeekends, extraWorkDays); logger.debug(""Saving generated schedule to database...""); scheduleRepository.saveAll(workDays); }" 89, ,"public void testSelectRequest_Query_Filter(){ @SuppressWarnings(""unchecked"") MultivaluedMap params = mock(MultivaluedMap.class); when(params.getFirst(""query"")).thenReturn(""Bla""); when(params.getFirst(SenchaRequestParser.FILTER)).thenReturn(""[{\""property\"":\""name\"",\""value\"":\""xyz\""}]""); UriInfo uriInfo = mock(UriInfo.class); when(uriInfo.getQueryParameters()).thenReturn(params); ResourceEntity resourceEntity = parser.parseSelect(getLrEntity(E2.class), uriInfo, E2.NAME.getName()); assertNotNull(resourceEntity.getQualifier()); assertEquals(exp(""name likeIgnoreCase 'Bla%' and name likeIgnoreCase 'xyz%'""), resourceEntity.getQualifier()); }","public void testSelectRequest_Query_Filter(){ @SuppressWarnings(""unchecked"") MultivaluedMap params = mock(MultivaluedMap.class); when(params.get(""query"")).thenReturn(Collections.singletonList(""Bla"")); when(params.get(SenchaRequestParser.FILTER)).thenReturn(Collections.singletonList(""[{\""property\"":\""name\"",\""value\"":\""xyz\""}]"")); ResourceEntity resourceEntity = parser.parseSelect(getLrEntity(E2.class), params, E2.NAME.getName()); assertNotNull(resourceEntity.getQualifier()); assertEquals(exp(""name likeIgnoreCase 'Bla%' and name likeIgnoreCase 'xyz%'""), resourceEntity.getQualifier()); }" 90, ,"public boolean estDansUnGarage(){ if (myStationnements.size() != 0) { Stationnement dernierStationnement = myStationnements.get(myStationnements.size() - 1); return dernierStationnement.estEnCours(); } else { return false; } }","public boolean estDansUnGarage(){ if (myStationnements.size() != 0) { Stationnement dernierStationnement = myStationnements.get(myStationnements.size() - 1); return dernierStationnement.estEnCours(); } return false; }" 91, ,"public static int fib(int n){ if (n < 2) return n; final int[] fibSeries = new int[2]; fibSeries[0] = 0; fibSeries[1] = 1; for (int i = 2; i <= n; i++) { final int f = fibSeries[0] + fibSeries[1]; fibSeries[0] = fibSeries[1]; fibSeries[1] = f; } return fibSeries[1]; }","public static int fib(int n){ if (n < 2) return n; int beforePrev = 0; int prev = 1; for (int i = 2; i <= n; i++) { final int tmp = beforePrev + prev; beforePrev = prev; prev = tmp; } return prev; }" 92, ,"public int getProductOfTwo(){ Map map = numbers.stream().collect(Collectors.toMap(n -> n, n -> n)); for (int i = 0; i < numbers.size(); i++) { Integer currentNum = numbers.get(i); Integer otherNum = map.get(2020 - currentNum); if (otherNum != null) { System.out.println(""this num = "" + currentNum); System.out.println(""other num = "" + otherNum); int result = otherNum * currentNum; System.out.println(""result = "" + result); return result; } } return -1; }","public int getProductOfTwo(){ Map map = numbers.stream().collect(Collectors.toMap(n -> n, n -> n)); for (Integer currentNum : numbers) { Integer otherNum = map.get(2020 - currentNum); if (otherNum != null) { System.out.println(""this num = "" + currentNum); System.out.println(""other num = "" + otherNum); int result = otherNum * currentNum; System.out.println(""result = "" + result); return result; } } return -1; }" 93, ,"public void encodeJson(StringBuffer sb){ sb.append(""{""); sb.append(""\""code\"": \""""); sb.append(getCode()); sb.append(""\"", ""); sb.append(""\""color\"": \""""); sb.append(getColor()); sb.append(""\"", ""); if (getSize() != null) { sb.append(""\""size\"": \""""); sb.append(getSize()); sb.append(""\"", ""); } sb.append(""\""price\"": ""); sb.append(getPrice()); sb.append("", ""); sb.append(""\""currency\"": \""""); sb.append(getCurrency()); sb.append(""\""}""); }","public void encodeJson(StringBuffer sb){ sb.append(""{""); ToJson.appendFieldTo(sb, ""code"", getCode()); ToJson.appendFieldTo(sb, ""color"", getColor().toString()); if (getSize() != null) { ToJson.appendFieldTo(sb, ""size"", getSize().toString()); } sb.append(""\""price\"": ""); sb.append(getPrice()); sb.append("", ""); ToJson.appendFieldTo(sb, ""currency"", getCurrency()); sb.delete(sb.length() - 2, sb.length()); sb.append(""}""); }" 94, ,"public String toString(){ if (html == null || html.isEmpty()) { return ""No data parsed yet""; } else { return getHtml(); } }","public String toString(){ return (html == null || html.isEmpty()) ? ""No data parsed yet"" : getHtml(); }" 95, ,"private PlaceArmy generatePlaceArmyOrder(Adjutant adjutant, Game game){ _log.info("" ----- generate place army order -----""); if (_placementsToMake == null) { _log.info("" computing placements ""); _placementsToMake = computePlacements(game); } Map.Entry entry = new ArrayList<>(_placementsToMake.entrySet()).get(0); PlaceArmy order = new PlaceArmy(adjutant, entry.getKey(), entry.getValue()); _placementsToMake.remove(entry.getKey()); return order; }","private PlaceArmy generatePlaceArmyOrder(Adjutant adjutant, Game game){ if (_placementsToMake == null) { _placementsToMake = computePlacements(game); } Map.Entry entry = new ArrayList<>(_placementsToMake.entrySet()).get(0); PlaceArmy order = new PlaceArmy(adjutant, entry.getKey(), entry.getValue()); _placementsToMake.remove(entry.getKey()); return order; }" 96, ,"public void add(TransactionBean transactionBean){ Date transactionTime = transactionBean.getTimestamp(); Calendar calendar = Calendar.getInstance(); calendar.setTime(transactionTime); int transactionSecond = calendar.get(Calendar.SECOND); StatisticBean statistic = statistics.get(transactionSecond); Date currentDate = new Date(); long diff = getDateDiffInSeconds(currentDate, statistic.getLastAddedTime()); if (diff <= TRANSACTION_SECONDS) { double sum = statistic.getSum() + transactionBean.getAmount(); double min = Math.min(statistic.getMin(), transactionBean.getAmount()); double max = Math.max(statistic.getMax(), transactionBean.getAmount()); int count = statistic.getCount() + 1; statistic.setSum(sum); statistic.setMin(min); statistic.setMax(max); statistic.setCount(count); } else { double amount = transactionBean.getAmount(); StatisticBean statisticBean = statistics.get(transactionSecond); statisticBean.setMax(amount); statisticBean.setMin(amount); statisticBean.setSum(amount); statisticBean.setCount(1); statisticBean.setLastAddedTime(currentDate); } }","public void add(TransactionBean transactionBean){ Date transactionTime = transactionBean.getTimestamp(); Calendar calendar = Calendar.getInstance(); calendar.setTime(transactionTime); int transactionSecond = calendar.get(Calendar.SECOND); StatisticBean statisticBean = statistics.get(transactionSecond); Date currentDate = new Date(); long diff = getDateDiffInSeconds(currentDate, statisticBean.getLastAddedTime()); if (diff <= TRANSACTION_SECONDS) { updateStatisticData(statisticBean, transactionBean); } else { initStatisticData(transactionSecond, transactionBean); } }" 97, ,"private static int decodeTuple(TupleType tupleType, byte[] buffer, final int idx_, int end, Object[] parentElements, int pei){ final ABIType[] elementTypes = tupleType.elementTypes; final int len = elementTypes.length; final Object[] elements = new Object[len]; int idx = end; Integer mark = null; for (int i = len - 1; i >= 0; i--) { final ABIType type = elementTypes[i]; if (type.dynamic) { mark = i; break; } if (type.typeCode() == TYPE_CODE_ARRAY) { final ArrayType, ?> arrayType = (ArrayType, ?>) type; end = idx -= (arrayType.elementType.byteLengthPacked(null) * arrayType.length); decodeArray(arrayType, buffer, idx, end, elements, i); } else if (type.typeCode() == TYPE_CODE_TUPLE) { TupleType inner = (TupleType) type; int innerLen = inner.byteLengthPacked(null); end = idx -= decodeTupleStatic(inner, buffer, idx - innerLen, end, elements, i); } else { end = idx -= decode(elementTypes[i], buffer, idx - type.byteLengthPacked(null), end, elements, i); } } if (mark != null) { final int m = mark; idx = idx_; for (int i = 0; i <= m; i++) { idx += decode(elementTypes[i], buffer, idx, end, elements, i); } } Tuple t = new Tuple(elements); parentElements[pei] = t; return tupleType.byteLengthPacked(t); }","private static int decodeTuple(TupleType tupleType, byte[] buffer, final int idx_, int end, Object[] parentElements, int pei){ final ABIType[] elementTypes = tupleType.elementTypes; final int len = elementTypes.length; final Object[] elements = new Object[len]; int mark = -1; for (int i = len - 1; i >= 0; i--) { final ABIType type = elementTypes[i]; if (type.dynamic) { mark = i; break; } final int typeCode = type.typeCode(); if (TYPE_CODE_ARRAY == typeCode) { final ArrayType, ?> arrayType = (ArrayType, ?>) type; end -= (arrayType.elementType.byteLengthPacked(null) * arrayType.length); decodeArray(arrayType, buffer, end, end, elements, i); } else if (TYPE_CODE_TUPLE == typeCode) { TupleType inner = (TupleType) type; int innerLen = inner.byteLengthPacked(null); end -= decodeTupleStatic(inner, buffer, end - innerLen, end, elements, i); } else { end -= decode(elementTypes[i], buffer, end - type.byteLengthPacked(null), end, elements, i); } } if (mark > -1) { int idx = idx_; for (int i = 0; i <= mark; i++) { idx += decode(elementTypes[i], buffer, idx, end, elements, i); } } Tuple t = new Tuple(elements); parentElements[pei] = t; return tupleType.byteLengthPacked(t); }" 98, ,"public BookRecord createBookRecord(BookRecord bookRecord, String isbn, Integer userCode){ Book book = bookRepository.findBookByIsbn(isbn); User user = userRepository.findByUserCode(userCode); if (book == null) { throw new ResourceNotFoundException(""Book with ISBN "" + isbn + "" does not exist""); } else if (user == null) { throw new ResourceNotFoundException(""User with code #"" + userCode + "" does not exist""); } else if (!book.getIsAvailable()) { throw new ResourceNotCreatedException(""Book is not available""); } else if (user.getBorrowedBooks() >= Constants.MAX_RENEWALS) { throw new ResourceNotCreatedException(""User has already borrow 3 books""); } DateFormat dateFormat = new SimpleDateFormat(""yyyy/MM/dd""); Date currentDate = new Date(); dateFormat.format(currentDate); Calendar c = Calendar.getInstance(); c.setTime(currentDate); c.add(Calendar.DATE, 7); Date currentDataPlusSeven = c.getTime(); bookRecord.setDueDate(currentDataPlusSeven); bookRecord.setRenewalCont(0); bookRecord.setIsReturned(false); bookRecord.setUser(user); bookRecord.setBook(book); book.setIsAvailable(false); user.setBorrowedBooks(user.getBorrowedBooks() + 1); try { return bookRecordRepository.save(bookRecord); } catch (Exception e) { throw new ResourceNotCreatedException(""Invoice #"" + bookRecord.getTransaction() + "" already exists""); } }","public BookRecord createBookRecord(BookRecord bookRecord, String isbn, Integer userCode){ Book book = bookRepository.findBookByIsbn(isbn); User user = userRepository.findByUserCode(userCode); if (book == null) { throw new ResourceNotFoundException(""Book with ISBN "" + isbn + "" does not exist""); } else if (user == null) { throw new ResourceNotFoundException(""User with code #"" + userCode + "" does not exist""); } else if (!book.getIsAvailable()) { throw new ResourceNotCreatedException(""Book is not available""); } else if (user.getBorrowedBooks() >= Constants.MAX_RENEWALS) { throw new ResourceNotCreatedException(""User has already borrow 3 books""); } Date currentDataPlusSeven = sumSevenDays(new Date()); bookRecord.setDueDate(currentDataPlusSeven); bookRecord.setRenewalCont(0); bookRecord.setIsReturned(false); bookRecord.setUser(user); bookRecord.setBook(book); book.setIsAvailable(false); user.setBorrowedBooks(user.getBorrowedBooks() + 1); try { return bookRecordRepository.save(bookRecord); } catch (Exception e) { throw new ResourceNotCreatedException(""Invoice #"" + bookRecord.getTransaction() + "" already exists""); } }" 99, ,"public void deleteCinemaHall(long id) throws SQLException, NotFoundException{ projectionDAO.deleteProjectionsByHallId(id); try (Connection connection = jdbcTemplate.getDataSource().getConnection(); PreparedStatement ps = connection.prepareStatement(DELETE_CINEMA_HALL_SQL)) { ps.setLong(1, id); if (ps.executeUpdate() == 0) { throw new NotFoundException(""Cinema hall was not found.""); } } }","public void deleteCinemaHall(long id) throws SQLException, NotFoundException{ projectionDAO.deleteProjectionsByHallId(id); try (Connection connection = jdbcTemplate.getDataSource().getConnection(); PreparedStatement ps = connection.prepareStatement(DELETE_CINEMA_HALL_SQL)) { ps.setLong(1, id); ps.executeUpdate(); } }" 100, ,"public void adjustResolution(){ int w = canvas.getClientWidth(); int h = canvas.getClientHeight(); double pixelRatio = Browser.getWindow().getDevicePixelRatio(); mouseToCanvasRescale = pixelRatio; canvas.setWidth((int) (w * pixelRatio)); canvas.setHeight((int) (h * pixelRatio)); margin = (int) (1 + Math.ceil(pixelRatio)); stitchXSpacing = (int) ((canvas.getWidth() - 2 * margin) / (data.width + STITCH_X_OVERLAP)); stitchYSpacing = (int) ((canvas.getHeight() - 2 * margin) / data.height + STITCH_Y_OVERLAP); stitchWidth = (int) (stitchXSpacing / (1 - STITCH_X_OVERLAP)); stitchHeight = (int) (stitchYSpacing / (1 - STITCH_Y_OVERLAP)); stitchXSpacing = (int) Math.min(stitchXSpacing, stitchHeight * STITCH_SIZE_RATIO * (1 - STITCH_X_OVERLAP)); stitchWidth = (int) (stitchXSpacing / (1 - STITCH_X_OVERLAP)); stitchHeight = (int) (stitchWidth / STITCH_SIZE_RATIO); stitchYSpacing = (int) (stitchHeight * (1 - STITCH_Y_OVERLAP)); colorZoneX = (data.width + 1) * stitchXSpacing; }","public void adjustResolution(){ int w = canvas.getClientWidth(); int h = canvas.getClientHeight(); double pixelRatio = Browser.getWindow().getDevicePixelRatio(); mouseToCanvasRescale = pixelRatio; canvas.setWidth((int) (w * pixelRatio)); canvas.setHeight((int) (h * pixelRatio)); margin = (int) (1 + Math.ceil(pixelRatio)); }" 101, ,"public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ String path = PATH_COMMAND_ERROR; RegistrationInfo info = new RegistrationInfo(request); request.getSession(true).setAttribute(SESSION_PATH, PATH_COMMAND_AUTHORIZATION); try { if (info.getEnteredPassword().equals("""") || info.getEmail().equals("""")) { response.sendRedirect(INCORRECT_DATA); return; } User user = USER_SERVICE.authorization(info); request.getSession(true).setAttribute(SESSION_PATH, PATH_COMMAND_AFTER_AUTHORIZATION); request.getSession(true).setAttribute(""user"", user); if (user == null) { path = USER_NOT_FOUND; } else { request.getSession(true).setAttribute(""user"", user); path = PATH_COMMAND_AFTER_AUTHORIZATION; logger.info(user.getName() + MESSAGE_AFTER_AUTHORIZATION); } } catch (ServiceException e) { logger.error(""Error in the application"", e); request.getSession(true).setAttribute(SESSION_PATH, PATH_COMMAND_ERROR); } response.sendRedirect(""Controller?command="" + path); }","public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ RegistrationInfo info = new RegistrationInfo(request); try { if (info.getEnteredPassword().equals("""") || info.getEmail().equals("""")) { response.sendRedirect(INCORRECT_DATA); return; } User user = USER_SERVICE.authorization(info); request.getSession(true).setAttribute(SESSION_PATH, AFTER_AUTHORIZATION); if (user == null) { response.sendRedirect(USER_NOT_FOUND); } else { request.getSession().setAttribute(ATTRIBUTE_USER, user); logger.info(user.getName() + MESSAGE_AFTER_AUTHORIZATION); response.sendRedirect(PATH_COMMAND_AFTER_AUTHORIZATION); } } catch (ServiceException e) { logger.error(""Error in the application"", e); response.sendRedirect(PATH_COMMAND_ERROR); } }" 102, ,"public void testConfiguration(){ ElasticSearchOutputConfig c = new ElasticSearchOutputConfig().withHost(""localhost"").withPort(8080).withTransportClientPort(9301).withAutomaticClientClose(true).withPrintElasticSearchLog(true); Assert.assertEquals(""localhost"", c.getHost()); Assert.assertEquals(8080, c.getPort()); Assert.assertEquals(9301, c.getTransportClientPort()); Assert.assertTrue(c.isAutomaticClientClose()); Assert.assertTrue(c.isPrintElasticSearchLog()); }","public void testConfiguration(){ ElasticSearchOutputConfig c = new ElasticSearchOutputConfig().withHost(""localhost"").withPort(8080).withTransportClientPort(9301).withPrintElasticSearchLog(true); Assert.assertEquals(""localhost"", c.getHost()); Assert.assertEquals(8080, c.getPort()); Assert.assertEquals(9301, c.getTransportClientPort()); Assert.assertTrue(c.isPrintElasticSearchLog()); }" 103, ,"public Car fetch(ParkingTicket parkingTicket) throws PleaseProvideTickerException, UnrecognizedParkingTicketException{ if (parkingTicket == null) { throw new PleaseProvideTickerException(); } ParkingLot parkingLot = parkingTicket.getParkingLot(); if (!parkingLots.contains(parkingLot)) { ; throw new UnrecognizedParkingTicketException(); } Car fetchedCar = parkingLot.fetch(parkingTicket); if (fetchedCar == null) { return null; } return fetchedCar; }","public Car fetch(ParkingTicket parkingTicket) throws PleaseProvideTickerException, UnrecognizedParkingTicketException{ if (parkingTicket == null) { throw new PleaseProvideTickerException(); } ParkingLot parkingLot = parkingTicket.getParkingLot(); if (!parkingLots.contains(parkingLot)) { throw new UnrecognizedParkingTicketException(); } Car fetchedCar = parkingLot.fetch(parkingTicket); if (fetchedCar == null) { return null; } return fetchedCar; }" 104, ," void removeBuilda(int i){ final BuildaVater bV = myBuilderz.get(i); for (int j = 0; j < bV.getChooserAnzahl(); j++) { final ChooserGruppe cg = bV.getChooserGruppe(j); while (cg.getmC().size() > 0) { if (cg.getmC().get(0).getEintrag() != null) { cg.getmC().get(0).aktuellenEintragLöschen(); cg.getmC().remove(0); } else { break; } } } myBuilderTextArea.removeBuildaVater(myBuilderz.get(i)); buildaPanelz.remove(i); myBuilderz.remove(i); RefreshListener.fireRefresh(); }"," void removeBuilda(int i){ final BuildaVater bV = myBuilderz.get(i); for (int j = 0; j < bV.getChooserAnzahl(); j++) { final ChooserGruppe cg = bV.getChooserGruppe(j); while (cg.getmC().size() > 0) { if (cg.getmC().get(0).getEintrag() != null) { cg.getmC().get(0).aktuellenEintragLöschen(); cg.getmC().remove(0); } else { break; } } } myBuilderTextArea.removeBuildaVater(myBuilderz.get(i)); myBuilderz.remove(i); RefreshListener.fireRefresh(); }" 105, ,"public T populate(){ if (getBeanTransformerSpi() != null) { getBeanTransformerSpi().getClonedMap().put(fromBean, toBean); } for (Method m : baseConfig.getSetterMethodCollector().collect(toBean)) { processSetterMethod(m); } @SuppressWarnings(""unchecked"") T ret = (T) toBean; return ret; }","public T populate(){ if (getBeanTransformerSpi() != null) { getBeanTransformerSpi().getClonedMap().put(fromBean, toBean); } for (Method m : baseConfig.getSetterMethodCollector().collect(toBean)) { processSetterMethod(m); } return (T) toBean; }" 106, ,"public void initSchema(AppEngineConfiguration appEngineConfiguration, String databaseSchemaUpdate){ Liquibase liquibase = null; try { if (AppEngineConfiguration.DB_SCHEMA_UPDATE_CREATE_DROP.equals(databaseSchemaUpdate)) { schemaCreate(); } else if (AppEngineConfiguration.DB_SCHEMA_UPDATE_DROP_CREATE.equals(databaseSchemaUpdate)) { schemaDrop(); schemaCreate(); } else if (AppEngineConfiguration.DB_SCHEMA_UPDATE_TRUE.equals(databaseSchemaUpdate)) { schemaUpdate(); } else if (AppEngineConfiguration.DB_SCHEMA_UPDATE_FALSE.equals(databaseSchemaUpdate)) { schemaCheckVersion(); } } catch (Exception e) { throw new FlowableException(""Error initialising app data model"", e); } finally { closeDatabase(liquibase); } }","public void initSchema(AppEngineConfiguration appEngineConfiguration, String databaseSchemaUpdate){ try { if (AppEngineConfiguration.DB_SCHEMA_UPDATE_CREATE_DROP.equals(databaseSchemaUpdate)) { schemaCreate(); } else if (AppEngineConfiguration.DB_SCHEMA_UPDATE_DROP_CREATE.equals(databaseSchemaUpdate)) { schemaDrop(); schemaCreate(); } else if (AppEngineConfiguration.DB_SCHEMA_UPDATE_TRUE.equals(databaseSchemaUpdate)) { schemaUpdate(); } else if (AppEngineConfiguration.DB_SCHEMA_UPDATE_FALSE.equals(databaseSchemaUpdate)) { schemaCheckVersion(); } } catch (Exception e) { throw new FlowableException(""Error initialising app data model"", e); } }" 107, ,"public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception{ if (doesCheckerAppy(context)) { if (check(exchange, context)) { next(exchange, context); } else { StringBuilder sb = new StringBuilder(); sb.append(""request check failed""); List warnings = context.getWarnings(); if (warnings != null && !warnings.isEmpty()) { warnings.stream().forEach(w -> { sb.append("", "").append(w); }); } ResponseHelper.endExchangeWithMessage(exchange, context, HttpStatus.SC_BAD_REQUEST, sb.toString()); next(exchange, context); return; } } else { next(exchange, context); } }","public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception{ if (doesCheckerAppy(context)) { if (check(exchange, context)) { next(exchange, context); } else { ResponseHelper.endExchangeWithMessage(exchange, context, HttpStatus.SC_BAD_REQUEST, ""request check failed""); next(exchange, context); return; } } else { next(exchange, context); } }" 108, ,"public Item peek(){ if (isEmpty()) throw new NoSuchElementException(""Queue underflow""); return q[first]; }","public Item peek(){ noSuchElement(isEmpty(), ""Queue underflow""); return q[first]; }" 109, ,"public Customer getCustomerById(@PathVariable(""id"") int customerId){ logger.info(""Entering getCustomerById""); logger.debug(""customerId: "" + customerId); Customer customerInfo = customerDao.getCustomerDetailById(customerId); return customerInfo; }","public Customer getCustomerById(@PathVariable(""id"") int customerId){ logger.info(""Entering getCustomerById""); logger.debug(""customerId: "" + customerId); return customerDao.getCustomerDetailById(customerId); }" 110, ,"private static void writeToFile(String contents, File file) throws IOException{ BufferedWriter bw = null; try { FileWriter fw = new FileWriter(file.getAbsoluteFile()); bw = new BufferedWriter(fw); bw.write(contents); } catch (IOException e) { throw e; } finally { IOUtils.closeQuietly(bw); } }","private static void writeToFile(String contents, File file) throws IOException{ BufferedWriter bw = null; try { FileWriter fw = new FileWriter(file.getAbsoluteFile()); bw = new BufferedWriter(fw); bw.write(contents); } finally { IOUtils.closeQuietly(bw); } }" 111, ,"public byte[] register(String email){ if (StringUtils.isBlank(email) || email.indexOf('&') > -1 || email.indexOf('=') > -1) { throw new IllegalArgumentException(""Invalid email""); } SimpleUserProfile profile = new SimpleUserProfile(email); byte[] encrypted = AesInEcb.encrypt(profile.toString().getBytes(), AES_KEY, true); return encrypted; }","public byte[] register(String email){ if (StringUtils.isBlank(email) || email.indexOf('&') > -1 || email.indexOf('=') > -1) { throw new IllegalArgumentException(""Invalid email""); } SimpleUserProfile profile = new SimpleUserProfile(email); return AesInEcb.encrypt(profile.toString().getBytes(), AES_KEY, true); }" 112, ,"public void testGetUsername(){ Student s; s = new Student(""Oluchi"", 20, new DateTime(), 900990, null, null, null); assertEquals(s.getUsername(), ""Oluchi20""); }","public void testGetUsername(){ Student s = new Student(""Oluchi"", 20, new DateTime(), ""12345000""); assertEquals(s.getUsername(), ""Oluchi20""); }" 113, ,"private boolean createLocalFile(ResolvedPath resolvedPath, boolean directory){ boolean absolute; String currentDirectory = filePanel.getCurrentWorkingDirectory(); String path = resolvedPath.getResolvedPath(); absolute = resolvedPath.isPathAlreadyAbsolute(); String parentPath = UI.getParentPath(path); boolean existsAsDir = new LocalFile(parentPath).isDirectory(); if (!existsAsDir) { UI.doError(""Directory does not exist"", ""Cannot create directory as path: "" + parentPath + "" does not exist""); return false; } else { boolean succeeds; if (directory) { succeeds = createLocalDirectory(path); } else { succeeds = createLocalNormalFile(path); } if (!succeeds) return false; boolean parentPathMatchesPanelsPath = currentDirectory.equals(parentPath); if (!absolute && parentPathMatchesPanelsPath) { filePanel.refresh(); } else if (parentPathMatchesPanelsPath) { filePanel.refresh(); } return true; } }","private boolean createLocalFile(String resolvedPath, boolean directory){ String currentDirectory = filePanel.getCurrentWorkingDirectory(); String parentPath = UI.getParentPath(resolvedPath); boolean existsAsDir = new LocalFile(parentPath).isDirectory(); if (!existsAsDir) { UI.doError(""Directory does not exist"", ""Cannot create directory as path: "" + parentPath + "" does not exist""); return false; } else { boolean succeeds; if (directory) { succeeds = createLocalDirectory(resolvedPath); } else { succeeds = createLocalNormalFile(resolvedPath); } if (!succeeds) return false; boolean parentPathMatchesPanelsPath = currentDirectory.equals(parentPath); if (parentPathMatchesPanelsPath) { filePanel.refresh(); } return true; } }" 114, ,"private static ServerBootstrap getServerBootstrap(NioEventLoopGroup boosGroup, NioEventLoopGroup workerGroup){ ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boosGroup, workerGroup); bootstrap.channel(NioServerSocketChannel.class); bootstrap.childHandler(new ChannelInitializer() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new LengthFieldBasedFrameDecoder(MAX_FRAME_LENGTH, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH)); pipeline.addLast(new SoundRecordMessageDecoder()); pipeline.addLast(new SoundRecordMessageResponseEncoder()); pipeline.addLast(new ServerHandler()); } }); return bootstrap; }","private static ServerBootstrap getServerBootstrap(NioEventLoopGroup boosGroup, NioEventLoopGroup workerGroup){ ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boosGroup, workerGroup); bootstrap.channel(NioServerSocketChannel.class); bootstrap.childHandler(new ServerChannelInitializer()); return bootstrap; }" 115, ,"private void handleSaslHeader(TransportHandlerContext context, HeaderFrame header){ if (!headerWritten) { context.fireWrite(header.getBody()); headerWritten = true; } if (headerReceived) { context.fireFailed(new IllegalStateException(""Unexpected second SASL Header read before SASL Authentication completed."")); } else { headerReceived = true; } listener.onSaslHeader(this, header.getBody()); if (serverMechanisms == null || serverMechanisms.length == 0) { context.fireFailed(new IllegalStateException(""SASL Server has no configured mechanisms"")); } SaslMechanisms mechanisms = new SaslMechanisms(); mechanisms.setSaslServerMechanisms(serverMechanisms); context.fireWrite(mechanisms); mechanismsSent = true; state = SaslStates.PN_SASL_STEP; header.release(); }","private void handleSaslHeader(TransportHandlerContext context, HeaderFrame header){ if (!headerWritten) { context.fireWrite(header.getBody()); headerWritten = true; } if (headerReceived) { context.fireFailed(new IllegalStateException(""Unexpected second SASL Header read before SASL Authentication completed."")); } else { headerReceived = true; } listener.onSaslHeader(this, header.getBody()); if (serverMechanisms == null || serverMechanisms.length == 0) { context.fireFailed(new IllegalStateException(""SASL Server has no configured mechanisms"")); } SaslMechanisms mechanisms = new SaslMechanisms(); mechanisms.setSaslServerMechanisms(serverMechanisms); context.fireWrite(mechanisms); mechanismsSent = true; state = SaslStates.PN_SASL_STEP; }" 116, ,"public void onLoad(final Device device, Date from, Date to, boolean filter, final ArchiveStyle style){ if (device != null && from != null && to != null) { Application.getDataService().getPositions(device, from, to, filter, new BaseAsyncCallback>(i18n) { @Override public void onSuccess(List result) { positionStore.clear(); if (result.isEmpty()) { new AlertMessageBox(i18n.error(), i18n.errNoResults()).show(); } else { for (Position position : result) { position.setStatus(Position.Status.ARCHIVE); if (style.getIconType() != null) { position.setIconType(style.getIconType()); } else { position.setIconType(device.getIconType().getPositionIconType(position.getStatus())); } position.setTrackColor(style.getTrackColor()); } positionStore.addAll(result); } } }); } else { new AlertMessageBox(i18n.error(), i18n.errFillFields()).show(); } }","public void onLoad(final Device device, Date from, Date to, boolean filter, final ArchiveStyle style){ if (device != null && from != null && to != null) { Application.getDataService().getPositions(device, from, to, filter, new BaseAsyncCallback>(i18n) { @Override public void onSuccess(List result) { positionStore.clear(); if (result.isEmpty()) { new AlertMessageBox(i18n.error(), i18n.errNoResults()).show(); } else { for (Position position : result) { position.setStatus(Position.Status.ARCHIVE); if (style.getIconType() != null) { position.setIconType(style.getIconType()); } else { position.setIconType(device.getIconType().getPositionIconType(position.getStatus())); } } positionStore.addAll(result); } } }); } else { new AlertMessageBox(i18n.error(), i18n.errFillFields()).show(); } }" 117, ,"public void doSomething() throws InterruptedException{ long _$metricStart = System.nanoTime(); try { System.out.println(""123""); int opCode = 100; _$metric_1.operationEnd(opCode, _$metricStart, false); } catch (RuntimeException e) { _$metric_1.operationEnd(191, _$metricStart, false); } }","public void doSomething() throws InterruptedException{ long _$metricStart = System.nanoTime(); try { System.out.println(""123""); _$metric_1.operationEnd(_$metricStart); } catch (RuntimeException e) { _$metric_1.operationErr(_$metricStart); } }" 118, ,"private void writeBuilderFile(final TypeElement typeElement, Map mapFieldName2Type){ final String className = typeElement.getQualifiedName().toString(); final String simpleClassName = typeElement.getSimpleName().toString(); final String packageName = JavaModelHelper.computePackageName(className); final String newInstanceName = simpleClassName.substring(0, 1).toLowerCase() + simpleClassName.substring(1); final String builderClassName = className + ""Builder""; final String builderSimpleClassName = simpleClassName + ""Builder""; final Filer filer = processingEnv.getFiler(); try (final JavaSrcFileCreator javaSrcFileCreator = javaModelService.getJavaSrcFileCreator(filer, builderClassName)) { javaSrcFileCreator.getNowAsISOString(); if (packageName != null) { javaSrcFileCreator.writePackage(packageName); } javaSrcFileCreator.writeImports(); javaSrcFileCreator.writeClassAnnotations(className); javaSrcFileCreator.writeClassDeclaration(builderSimpleClassName); javaSrcFileCreator.writeFieldDefinition(simpleClassName, newInstanceName); javaSrcFileCreator.writeConstructors(simpleClassName, newInstanceName, builderSimpleClassName); javaSrcFileCreator.writeBuildMethod(simpleClassName, newInstanceName); mapFieldName2Type.entrySet().forEach(fields -> { final String fieldName = fields.getKey().toString(); final String setterName = ""with"" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); final String argumentType = getFullQualifiedClassName(fields.getValue()); javaSrcFileCreator.writeSetterMethod(newInstanceName, builderSimpleClassName, fieldName, setterName, argumentType); }); javaSrcFileCreator.writeClassFinal(); } catch (IOException e) { System.out.println(e.getLocalizedMessage()); } catch (Exception e) { System.out.println(e.getLocalizedMessage()); } }","private void writeBuilderFile(final TypeElement typeElement, Map mapFieldName2Type){ final String className = typeElement.getQualifiedName().toString(); final String simpleClassName = typeElement.getSimpleName().toString(); final String packageName = JavaModelHelper.computePackageName(className); final String newInstanceName = simpleClassName.substring(0, 1).toLowerCase() + simpleClassName.substring(1); final String builderClassName = className + ""Builder""; final String builderSimpleClassName = simpleClassName + ""Builder""; final Filer filer = processingEnv.getFiler(); try (final JavaSrcFileCreator javaSrcFileCreator = javaModelService.getJavaSrcFileCreator(filer, builderClassName)) { javaSrcFileCreator.init(); javaSrcFileCreator.getNowAsISOString(); if (packageName != null) { javaSrcFileCreator.writePackage(packageName); } javaSrcFileCreator.writeImports(); javaSrcFileCreator.writeClassAnnotations(className); javaSrcFileCreator.writeClassDeclaration(builderSimpleClassName); javaSrcFileCreator.writeFieldDefinition(simpleClassName, newInstanceName); javaSrcFileCreator.writeConstructors(simpleClassName, newInstanceName, builderSimpleClassName); javaSrcFileCreator.writeBuildMethod(simpleClassName, newInstanceName); mapFieldName2Type.entrySet().forEach(fields -> { final String fieldName = fields.getKey().toString(); final String setterName = ""with"" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); final String argumentType = getFullQualifiedClassName(fields.getValue()); javaSrcFileCreator.writeSetterMethod(newInstanceName, builderSimpleClassName, fieldName, setterName, argumentType); }); javaSrcFileCreator.writeClassFinal(); } catch (Exception e) { System.out.println(e.getLocalizedMessage()); } }" 119, ,"public List isValid(){ List errorMsgs = new ArrayList(); for (String dataItem : _dataFileArray) { if (UtilHelper.match(dataItem, Constants.mediaRegex)) { String type = UtilHelper.parseStringAttr(dataItem, Constants.typeRegex); if (type == null || !Constants.ValidTypes.contains(type)) { errorMsgs.add(new ValidationReport(Constants.EXTXMEDIA, _fileName, ""Invalid media type attribute is detected."")); } String uri = UtilHelper.parseStringAttr(dataItem, Constants.uriRegex); if (uri != null && type != null && type.equals(""CLOSED-CAPTION"") && !uri.isEmpty()) { errorMsgs.add(new ValidationReport(Constants.EXTXMEDIA, _fileName, ""If the media type is 'CLOSED-CAPTION' URI attribute should not be present."")); } else { if (uri != null && !UtilHelper.isUrl(uri)) { errorMsgs.add(new ValidationReport(Constants.EXTXMEDIA, _fileName, ""Uri path is invalid."")); } } String groupId = UtilHelper.parseStringAttr(dataItem, Constants.groupRegex); if (groupId == null) { errorMsgs.add(new ValidationReport(Constants.EXTXMEDIA, _fileName, ""Group id is required and its missing from the menifest file."")); } } } return errorMsgs; }","public List isValid(){ List errorMsgs = new ArrayList(); String dataItem = UtilHelper.dataItemByTag(_dataFileArray, Constants.mediaRegex); String type = UtilHelper.parseStringAttr(dataItem, Constants.typeRegex); if (type == null || !Constants.ValidTypes.contains(type)) { errorMsgs.add(new ValidationReport(Constants.EXTXMEDIA, _fileName, ""Invalid media type attribute is detected."")); } String uri = UtilHelper.parseStringAttr(dataItem, Constants.uriRegex); if (uri != null && type != null && type.equals(""CLOSED-CAPTION"") && !uri.isEmpty()) { errorMsgs.add(new ValidationReport(Constants.EXTXMEDIA, _fileName, ""If the media type is 'CLOSED-CAPTION' URI attribute should not be present."")); } else { if (uri != null && !UtilHelper.isUrl(uri)) { errorMsgs.add(new ValidationReport(Constants.EXTXMEDIA, _fileName, ""Uri path is invalid."")); } } String groupId = UtilHelper.parseStringAttr(dataItem, Constants.groupRegex); if (groupId == null) { errorMsgs.add(new ValidationReport(Constants.EXTXMEDIA, _fileName, ""Group id is required and its missing from the menifest file."")); } return errorMsgs; }" 120, ,"public static int[] copyInt(int[] array, int bin, int end){ if (end < bin) { return new int[0]; } int len = end - bin + 1; int[] copy = new int[len]; for (int i = 0; i < len; ++i) { copy[i] = array[bin + i]; } return copy; }","public static int[] copyInt(int[] array, int bin, int end){ if (end < bin) { return new int[0]; } int len = end - bin + 1; int[] copy = new int[len]; System.arraycopy(array, bin, copy, 0, len); return copy; }" 121, ,"public void testEqualsOk(){ String expectedURL = ""https://github.com/javaeeeee/DropBookmarks""; Bookmark bookmark = new Bookmark(expectedURL, ""Project Repository URL""); Bookmark other = new Bookmark(expectedURL, ""Project Repository URL""); ; assertTrue(bookmark.equals(other)); }","public void testEqualsOk(){ String expectedURL = ""https://github.com/javaeeeee/DropBookmarks""; Bookmark bookmark = new Bookmark(expectedURL, ""Project Repository URL""); Bookmark other = new Bookmark(expectedURL, ""Project Repository URL""); assertTrue(bookmark.equals(other)); }" 122, ,"public String getDirectoryObjects(ModelMap model, HttpServletRequest httpRequest){ HttpSession session = httpRequest.getSession(); AuthenticationResult result = (AuthenticationResult) session.getAttribute(AuthHelper.PRINCIPAL_SESSION_NAME); System.out.println(result.getAccessToken()); if (result == null) { model.addAttribute(""error"", new Exception(""AuthenticationResult not found in session."")); return ""/error""; } else { String data; try { data = this.getUserDetailsFromGraph(result.getAccessToken(), session.getServletContext().getInitParameter(""tenant"")); model.addAttribute(""user"", data); } catch (Exception e) { model.addAttribute(""error"", e); return ""/error""; } } return ""/hello""; }","public String getDirectoryObjects(ModelMap model, HttpServletRequest httpRequest){ HttpSession session = httpRequest.getSession(); AuthenticationResult result = (AuthenticationResult) session.getAttribute(AuthHelper.PRINCIPAL_SESSION_NAME); if (result == null) { model.addAttribute(""error"", new Exception(""AuthenticationResult not found in session."")); return ""/error""; } else { String data; try { data = this.getUserDetailsFromGraph(result.getAccessToken(), session.getServletContext().getInitParameter(""tenant"")); model.addAttribute(""user"", data); } catch (Exception e) { model.addAttribute(""error"", e); return ""/error""; } } return ""/hello""; }" 123, ,"public Collection getAuditUserAccessLogs(){ Collection newList = repository.findAll(); return newList; }","public Collection getAuditUserAccessLogs(){ return repository.findAll(); }" 124, ,"public void testOpenSecureChannel(){ ApduChannel channel = request -> new ResponseAPDU(Hexs.hex().toByteArray(""9000"")); CardChannelContext context = createContext(channel); Scp02Session session = new Scp02Session(context); try { session.openSecureChannel(EnumSet.of(SecurityLevel.C_DECRYPTION)); Assert.fail(""must throw IllegalArgumentException""); } catch (Exception ex) { Assert.assertEquals(""C_DECRYPTION must be combined with C_MAC"", ex.getMessage()); } try { session.openSecureChannel(EnumSet.of(SecurityLevel.R_DECRYPTION)); Assert.fail(""must throw IllegalArgumentException""); } catch (Exception ex) { Assert.assertEquals(""R_DECRYPTION must be combined with R_MAC"", ex.getMessage()); } }","public void testOpenSecureChannel(){ ApduChannel channel = request -> new ResponseAPDU(Hexs.hex().toByteArray(""9000"")); CardChannelContext context = createContext(channel); Scp02Session session = new Scp02Session(context); try { session.openSecureChannel(EnumSet.of(SecurityLevel.C_DECRYPTION)); Assert.fail(""must throw IllegalArgumentException""); } catch (Exception ex) { Assert.assertEquals(""C_DECRYPTION must be combined with C_MAC"", ex.getMessage()); } }" 125, ,"public void checkByCharacter(String text, char character, int index, NodePatternIdentifier nodePatternIdentifier){ if (startIndex == INVALID_INDEX && character == nodeBreakLinePattern.characterTrigger() && isFoundStart(text, index)) { startIndex = index; } else if (startIndex != INVALID_INDEX && endIndex == INVALID_INDEX && isFoundEnd(text, index)) { endIndex = index + 1; } if (startIndex != INVALID_INDEX && endIndex != INVALID_INDEX) { nodePatternIdentifier.found(startIndex, endIndex, null); reset(); } }","public void checkByCharacter(String text, char character, int index, NodePatternIdentifier nodePatternIdentifier){ if (startIndex == INVALID_INDEX && character == nodeBreakLinePattern.characterTrigger() && isFoundStart(text, index)) { startIndex = index; } else if (startIndex != INVALID_INDEX && endIndex == INVALID_INDEX && isFoundEnd(text, index)) { endIndex = index + 1; nodePatternIdentifier.found(startIndex, endIndex, null); reset(); } }" 126, ,"public String toRomanNumber(int valueToConvert){ StringBuilder stringBuilder = new StringBuilder(); int restToProcess = valueToConvert; for (RomanNumber romanNumber : RomanNumber.values()) { restToProcess = createRomanString(stringBuilder, romanNumber.getRomanNumber(), romanNumber.getArabicNumber(), restToProcess); } for (int i = 0; i < restToProcess; i++) { stringBuilder.append(""I""); } return stringBuilder.toString(); }","public String toRomanNumber(int valueToConvert){ StringBuilder stringBuilder = new StringBuilder(); int restToProcess = valueToConvert; for (RomanNumber romanNumber : RomanNumber.values()) { restToProcess = createRomanString(stringBuilder, romanNumber.getRomanNumber(), romanNumber.getArabicNumber(), restToProcess); } return stringBuilder.toString(); }" 127, ,"public final int update(QueryContext context, Table table, Assignment[] assign_list, int limit) throws DatabaseException{ checkReadWriteLock(); IntegerVector row_set = new IntegerVector(); RowEnumeration e = table.rowEnumeration(); while (e.hasMoreRows()) { row_set.addInt(e.nextRowIndex()); } e = null; int first_column = table.findFieldName(getResolvedVariable(0)); if (first_column == -1) { throw new DatabaseException(""Search table does not contain any "" + ""reference to table being updated from""); } table.setToRowTableDomain(first_column, row_set, this); RowData original_data = createRowDataObject(context); RowData row_data = createRowDataObject(context); if (limit < 0) { limit = Integer.MAX_VALUE; } int len = Math.min(row_set.size(), limit); int update_count = 0; for (int i = 0; i < len; ++i) { int to_update = row_set.intAt(i); original_data.setFromRow(to_update); row_data.setFromRow(to_update); for (int n = 0; n < assign_list.length; ++n) { Assignment assignment = assign_list[n]; row_data.evaluate(assignment, context); } updateRow(to_update, row_data); ++update_count; } if (update_count > 0) { data_source.constraintIntegrityCheck(); } return update_count; }","public final int update(QueryContext context, Table table, Assignment[] assign_list, int limit) throws DatabaseException{ checkReadWriteLock(); IntegerVector row_set = new IntegerVector(); RowEnumeration e = table.rowEnumeration(); while (e.hasMoreRows()) { row_set.addInt(e.nextRowIndex()); } e = null; int first_column = table.findFieldName(getResolvedVariable(0)); if (first_column == -1) { throw new DatabaseException(""Search table does not contain any "" + ""reference to table being updated from""); } table.setToRowTableDomain(first_column, row_set, this); RowData original_data = createRowDataObject(context); RowData row_data = createRowDataObject(context); if (limit < 0) { limit = Integer.MAX_VALUE; } int len = Math.min(row_set.size(), limit); int update_count = 0; for (int i = 0; i < len; ++i) { int to_update = row_set.intAt(i); original_data.setFromRow(to_update); row_data.setFromRow(to_update); for (Assignment assignment : assign_list) { row_data.evaluate(assignment, context); } updateRow(to_update, row_data); ++update_count; } if (update_count > 0) { data_source.constraintIntegrityCheck(); } return update_count; }" 128, ,"public int add(String numbers){ int sum = 0; String[] result; ArrayList negativeNumbers = new ArrayList<>(); String[] delimiters; StringBuilder stringBuilder = new StringBuilder(); if (numbers == null || numbers.isEmpty()) { return 0; } if (numbers.startsWith(""//"")) { String delimiter = StringUtils.substringBetween(numbers, ""//"", ""\n""); if (delimiter.contains(""["")) { delimiters = StringUtils.substringsBetween(numbers, ""["", ""]""); for (String s : delimiters) { stringBuilder.append(s).append(""|""); } stringBuilder.deleteCharAt(stringBuilder.length() - 1); delimiter = stringBuilder.toString(); } numbers = numbers.substring(numbers.lastIndexOf(""\n"") + 1); result = numbers.split(delimiter); } else { result = numbers.split(""[,\n]""); } for (int i = 0; i < result.length; i++) { result[i] = result[i].trim(); } if (result.length == 1) { return Integer.parseInt(result[0]); } for (String value : result) { int parsedValue = Integer.parseInt(value); if (parsedValue < 0) { negativeNumbers.add(parsedValue); } if (parsedValue <= 1000) { sum += parsedValue; } } for (Integer number : negativeNumbers) { if (number < 0) { throw new NegativesNotAllowedException(""Negatives not allowed "" + negativeNumbers); } } return sum; }","public int add(String numbers){ String[] result; if (numbers == null || numbers.isEmpty()) { return 0; } if (numbers.startsWith(""//"")) { String delimiter = retrieveDelimiter(numbers); numbers = numbers.substring(numbers.lastIndexOf(""\n"") + 1); result = numbers.split(delimiter); } else { result = numbers.split(""[,\n]""); } for (int i = 0; i < result.length; i++) { result[i] = result[i].trim(); } checkIfNegativesOccur(result); if (result.length == 1) { return Integer.parseInt(result[0]); } return makeCalculations(result); }" 129, ,"public Builder playlist_id(final String playlist_id){ assert (playlist_id != null); assert (!playlist_id.equals("""")); return setPathParameter(""playlist_id"", playlist_id); }","public Builder playlist_id(final String playlist_id){ assertHasAndNotNull(playlist_id); return setPathParameter(""playlist_id"", playlist_id); }" 130, ,"private void updateQuality(final Item item){ if (toVO(item).isAgedBrie()) { increaseQuality(item); decreaseSellIn(item); if (isExpired(item)) { increaseQuality(item); } return; } if (toVO(item).isAgedBrie()) { } else if (toVO(item).isABackstagePass()) { increaseQuality(item); if (item.sellIn < 11) { increaseQuality(item); } if (item.sellIn < 6) { increaseQuality(item); } } else if (!toVO(item).isASulfuras()) { decreaseQuality(item); } if (!toVO(item).isASulfuras()) { decreaseSellIn(item); } if (isExpired(item)) { if (toVO(item).isAgedBrie()) { increaseQuality(item); } else if (toVO(item).isABackstagePass()) { item.quality = 0; } else if (!toVO(item).isASulfuras()) { decreaseQuality(item); } } }","private void updateQuality(final Item item){ if (toVO(item).isAgedBrie()) { increaseQuality(item); decreaseSellIn(item); if (isExpired(item)) { increaseQuality(item); } return; } if (toVO(item).isAgedBrie()) { } else if (toVO(item).isABackstagePass()) { increaseQuality(item); if (item.sellIn < 11) { increaseQuality(item); } if (item.sellIn < 6) { increaseQuality(item); } } else if (!toVO(item).isASulfuras()) { decreaseQuality(item); } if (!toVO(item).isASulfuras()) { decreaseSellIn(item); } if (isExpired(item)) { if (toVO(item).isAgedBrie()) { } else if (toVO(item).isABackstagePass()) { item.quality = 0; } else if (!toVO(item).isASulfuras()) { decreaseQuality(item); } } }" 131, ,"private void addConflict(ArchiveInfo archive, ArchiveInfo candidate, ResourceInfo resource, boolean isDuplicate){ final ConflictCheckResponse.ArchiveConflict ac = conflictCollector.addConflict(candidate, archive, resource); if (isDuplicate) { ac.addDuplicate(resource); } else { ac.addConflict(resource); } }","private void addConflict(ArchiveInfo archive, ArchiveInfo candidate, ResourceInfo resource, boolean isDuplicate){ final ConflictCheckResponse.ArchiveConflict ac = conflictCollector.addOverlap(candidate, archive, resource, isDuplicate); }" 132, ,"private void addKeyPointIfDifferentHeight(List skyline, PointAndBuilding pointAndBuilding){ if (!skyline.isEmpty()) { if (skyline.get(skyline.size() - 1)[1] != pointAndBuilding.building.height) { addKeyPoint(skyline, pointAndBuilding.point, pointAndBuilding.building.height); } } else { addKeyPoint(skyline, pointAndBuilding.point, pointAndBuilding.building.height); } }","private void addKeyPointIfDifferentHeight(List skyline, PointAndBuilding pointAndBuilding){ if (skyline.isEmpty() || skyline.get(skyline.size() - 1)[1] != pointAndBuilding.building.height) { addKeyPoint(skyline, pointAndBuilding.point, pointAndBuilding.building.height); } }" 133, ," void init(){ System.out.println(""=== ConfigurationService =====""); if (configurationService.getDemoNumberMap() != null) { configurationService.getDemoNumberMap().forEach((k, v) -> System.out.println(""Key : "" + k + "" Value : "" + v)); } System.out.println(""=================""); System.out.println(""=== @Value =====""); System.out.println(configImageUrl); System.out.println(mySecret); System.out.println(""=================""); System.out.println(""=== MyConfig =====""); System.out.println(myConfig.getNumber()); System.out.println(myConfig.getUuid()); System.out.println(""==================""); }"," void init(){ System.out.println(""=== ConfigurationService =====""); Optional.ofNullable(configurationService.getDemoNumberMap()).ifPresent(demoNumbers -> demoNumbers.forEach((k, v) -> System.out.println(""Key : "" + k + "" Value : "" + v))); System.out.println(""=================""); System.out.println(""=== @Value =====""); System.out.println(configImageUrl); System.out.println(mySecret); System.out.println(""=================""); System.out.println(""=== MyConfig =====""); System.out.println(myConfig.getNumber()); System.out.println(myConfig.getUuid()); System.out.println(""==================""); }" 134, ,"private static String convertDatePatternToClientPattern(DatePattern pattern){ if (pattern == null) return null; else { final String dayPart = pattern.isZeroPrefixedDay() ? ""0d"" : ""_d""; final String monthPart; switch(pattern.getMonthDisplayMode()) { case NAME: monthPart = ""mM""; break; case NUMBER: monthPart = ""_M""; break; default: monthPart = ""0M""; break; } final String yearPart = pattern.isShortYear() ? ""0y"" : ""_y""; StringBuilder builder = new StringBuilder(); if (pattern.hasSeparator()) builder.append(pattern.getSeparator()); switch(pattern.getDisplayOrder()) { case DAY_MONTH_YEAR: builder.append(dayPart).append(monthPart).append(yearPart); break; case MONTH_DAY_YEAR: builder.append(monthPart).append(dayPart).append(yearPart); break; default: builder.append(yearPart).append(monthPart).append(dayPart); break; } if (pattern.isShortYear() || pattern.isShortYearAlwaysAccepted()) { builder.append(pattern.isPreviousCenturyBelowBoundary() ? '+' : '-'); builder.append(String.format(""%02d"", pattern.getBaseCentury() % 100)); builder.append(String.format(""%02d"", pattern.getCenturyBoundaryYear() % 100)); } return builder.toString(); } }","private static String convertDatePatternToClientPattern(DatePattern pattern){ if (pattern == null) return null; else { final String dayPart = pattern.isZeroPrefixedDay() ? ""0d"" : ""_d""; final String monthPart = MONTH_DISPLAY_PATTERNS.get(pattern.getMonthDisplayMode()); final String yearPart = pattern.isShortYear() ? ""0y"" : ""_y""; StringBuilder builder = new StringBuilder(); if (pattern.hasSeparator()) builder.append(pattern.getSeparator()); ORDER_BUILDERS.get(pattern.getDisplayOrder()).accept(builder, new String[] { yearPart, monthPart, dayPart }); if (pattern.isShortYear() || pattern.isShortYearAlwaysAccepted()) { builder.append(pattern.isPreviousCenturyBelowBoundary() ? '+' : '-'); builder.append(String.format(""%02d"", pattern.getBaseCentury() % 100)); builder.append(String.format(""%02d"", pattern.getCenturyBoundaryYear() % 100)); } return builder.toString(); } }" 135, ,"public void handleRequest(HttpServerExchange exchange) throws Exception{ var response = Response.wrap(exchange); if (!exchange.isResponseStarted()) { exchange.setStatusCode(response.getStatusCode()); } if (response.getContentAsJson() != null) { exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, ""application/json""); exchange.getResponseSender().send(response.getContentAsJson().toString()); } else if (response.getContent() != null) { if (response.getContentType() != null) { exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, response.getContentType()); } exchange.getResponseSender().send(BuffersUtils.toByteBuffer(response.getContent())); } exchange.endExchange(); next(exchange); }","public void handleRequest(HttpServerExchange exchange) throws Exception{ var response = Response.wrap(exchange); if (!exchange.isResponseStarted()) { exchange.setStatusCode(response.getStatusCode()); } if (response.isContentAvailable()) { exchange.getResponseSender().send(BuffersUtils.toByteBuffer(response.getContent())); } exchange.endExchange(); next(exchange); }" 136, ,"public void cureDiseaseTest(){ GrapeCureDTO grapeCureDto1 = beanMappingService.mapTo(testGrape1, GrapeCureDTO.class); grapeFacade.cureDisease(grapeCureDto1); verify(grapeService).cureDisease(any(), any()); }","public void cureDiseaseTest(){ grapeFacade.cureDisease(grapeCureDto1); verify(grapeService).cureDisease(any(), any()); }" 137, ,"public MetaData mapToData(final MetaDataDTO metaDataDTO){ return Optional.ofNullable(metaDataDTO).map(v -> { MetaData.Builder metaData = MetaData.builder(); metaData.id(v.getId()); metaData.appName(v.getAppName()); metaData.contextPath(v.getContextPath()); metaData.path(v.getPath()); metaData.rpcType(v.getRpcType()); metaData.serviceName(v.getServiceName()); metaData.methodName(v.getMethodName()); metaData.parameterTypes(v.getParameterTypes()); metaData.rpcExt(v.getRpcExt()); metaData.enabled(v.getEnabled()); return metaData.build(); }).orElse(null); }","public MetaData mapToData(final MetaDataDTO metaDataDTO){ return Optional.ofNullable(metaDataDTO).map(v -> MetaData.builder().id(v.getId()).appName(v.getAppName()).contextPath(v.getContextPath()).path(v.getPath()).rpcType(v.getRpcType()).serviceName(v.getServiceName()).methodName(v.getMethodName()).parameterTypes(v.getParameterTypes()).rpcExt(v.getRpcExt()).enabled(v.getEnabled()).build()).orElse(null); }" 138, ,"public PaymentUrlDto postPreparePayment(KpRequest kpRequest){ LOGGER.info(""Handling KP request.""); PaymentUrlDto paymentUrlDto = new PaymentUrlDto(); PreparedPaymentDto preparedPaymentDto = paymentService.preparePayment(kpRequest); ResponseEntity response = postOrder(preparedPaymentDto); String paymentUrl = Objects.requireNonNull(response.getBody()).getPaymentUrl(); LOGGER.info(""Payment URL: "" + paymentUrl); paymentService.persist(response.getBody(), preparedPaymentDto); paymentUrlDto.setPaymentUrl(paymentUrl); return paymentUrlDto; }","public PaymentUrlDto postPreparePayment(KpRequest kpRequest){ LOGGER.info(""Handling KP request.""); return paymentService.sendOrder(kpRequest); }" 139, ,"private T populate(T backend) throws BackendServiceException{ String id = backend.getId(); if (!StringUtils.isEmpty(id)) { Backend backendFromDB = backendRepository.get(id); } if (backend.getId() == null) { backend.setId(generateUniqueBackendId()); } switch(backend.getType()) { case RABBIT_MQ: if (((BackendRabbitMQ) backend).getBackendConfiguration() == null) { String backendExchange = TransportConfigRabbitMQ.getBackendExchange(configuration); String backendExchangeType = TransportConfigRabbitMQ.getBackendExchangeType(configuration); String backendReceiveRoutingKey = TransportConfigRabbitMQ.getBackendReceiveRoutingKey(configuration); String backendReceiveControlRoutingKey = TransportConfigRabbitMQ.getBackendReceiveControlRoutingKey(configuration); Long heartbeatPeriodMills = TransportConfigRabbitMQ.getBackendHeartbeatTimeMills(configuration); backendExchange = backendExchange + ""_"" + backend.getId(); BackendConfiguration backendConfiguration = new BackendConfiguration(backendExchange, backendExchangeType, backendReceiveRoutingKey, backendReceiveControlRoutingKey, heartbeatPeriodMills); ((BackendRabbitMQ) backend).setBackendConfiguration(backendConfiguration); return backend; } break; case LOCAL: break; default: throw new BackendServiceException(""Unknown backend type "" + backend.getType()); } return backend; }","private T populate(T backend) throws BackendServiceException{ if (backend.getId() == null) { backend.setId(generateUniqueBackendId()); } switch(backend.getType()) { case RABBIT_MQ: if (((BackendRabbitMQ) backend).getBackendConfiguration() == null) { String backendExchange = TransportConfigRabbitMQ.getBackendExchange(configuration); String backendExchangeType = TransportConfigRabbitMQ.getBackendExchangeType(configuration); String backendReceiveRoutingKey = TransportConfigRabbitMQ.getBackendReceiveRoutingKey(configuration); String backendReceiveControlRoutingKey = TransportConfigRabbitMQ.getBackendReceiveControlRoutingKey(configuration); Long heartbeatPeriodMills = TransportConfigRabbitMQ.getBackendHeartbeatTimeMills(configuration); backendExchange = backendExchange + ""_"" + backend.getId(); BackendConfiguration backendConfiguration = new BackendConfiguration(backendExchange, backendExchangeType, backendReceiveRoutingKey, backendReceiveControlRoutingKey, heartbeatPeriodMills); ((BackendRabbitMQ) backend).setBackendConfiguration(backendConfiguration); return backend; } break; case LOCAL: break; default: throw new BackendServiceException(""Unknown backend type "" + backend.getType()); } return backend; }" 140, ,"protected void registerValue(CDateRange v){ if (onlyQuarters && !v.isSingleQuarter()) { onlyQuarters = false; } if (onlyClosed && v.isOpen()) { onlyClosed = false; } if (v.getMaxValue() > maxValue) { maxValue = v.getMaxValue(); } if (v.getMinValue() < minValue) { minValue = v.getMinValue(); } }","protected void registerValue(CDateRange v){ onlyQuarters = onlyQuarters && !v.isSingleQuarter(); onlyClosed = onlyClosed && v.isOpen(); maxValue = Math.max(maxValue, v.getMaxValue()); minValue = Math.min(minValue, v.getMinValue()); }" 141, ,"private void processTypeSafeName(TypeElement typeElement, RoundEnvironment roundEnv){ final Set elementsAnnotatedWith = roundEnv.getElementsAnnotatedWith(typeElement); final Map>> elementsMap = elementsAnnotatedWith.stream().filter(x -> !(x instanceof ExecutableElement) || ((ExecutableElement) x).getTypeParameters().isEmpty()).map(x -> new Pair(x, -1)).collect(groupingBy(k -> { String className = ""****""; final Element element = k.first(); if (element instanceof VariableElement) { className = element.getEnclosingElement().getEnclosingElement().toString(); } else if (element instanceof ExecutableElement) { className = element.getEnclosingElement().toString(); } return className; }, toList())); if (elementsMap.isEmpty()) { return; } elementsMap.forEach(this::writeTypeSafeNameFile); }","private void processTypeSafeName(TypeElement typeElement, RoundEnvironment roundEnv){ final Set elementsAnnotatedWith = roundEnv.getElementsAnnotatedWith(typeElement); final Map>> elementsMap = elementsAnnotatedWith.stream().filter(x -> !(x instanceof ExecutableElement) || ((ExecutableElement) x).getTypeParameters().isEmpty()).map(x -> new Pair(x, -1)).collect(groupingBy(k -> { final Element element = k.first(); return element.getEnclosingElement().toString(); }, toList())); if (elementsMap.isEmpty()) { return; } elementsMap.forEach(this::writeTypeSafeNameFile); }" 142, ,"public static BigInteger countOnes(long left, long right){ if (left == 0 && right == 0) { return BigInteger.valueOf(0L); } if (left == 2 && right == 2) { return BigInteger.valueOf(0L); } return BigInteger.valueOf(1L); }","public static BigInteger countOnes(long left, long right){ if (left == right && left % 2 == 0) { return BigInteger.valueOf(0L); } return BigInteger.valueOf(1L); }" 143, ,"public void exportSmells(ReportController.ReportOutput data) throws IOException{ List entries = new ArrayList<>(); entries.add(data.getName()); entries.addAll(data.getData().values()); data.getSmellsPresence().values().forEach(e -> entries.add(e.toString())); writeCSV(entries); }","public void exportSmells(Report data) throws IOException{ List entries = data.getEntryValues(); writeCSV(entries); }" 144, ,"public void testWithoutBlankHeadRowsAndCols(){ @Cleanup val workbook = getClassPathWorkbook(""member.xlsx""); val excelToBeans = new ExcelToBeans(workbook); val beans = excelToBeans.convert(MemberImportBean.class); assertThat(beans).hasSize(4); assertThat(beans.get(0).getRowNum()).isEqualTo(6); assertThat(beans.get(1).getRowNum()).isEqualTo(7); assertThat(beans.get(2).getRowNum()).isEqualTo(8); assertThat(beans.get(3).getRowNum()).isEqualTo(9); beans.get(0).setError(""error 000""); beans.get(1).setError(""error 000""); excelToBeans.writeError(MemberImportBean.class, beans); excelToBeans.removeOkRows(MemberImportBean.class, beans); excelToBeans.getWorkbookBytes(); }","public void testWithoutBlankHeadRowsAndCols(){ @Cleanup val workbook = getClassPathWorkbook(""member.xlsx""); val excelToBeans = new ExcelToBeans(workbook); val beans = excelToBeans.convert(MemberImportBean.class); assertThat(beans).hasSize(4); assertThat(beans.get(0).getRowNum()).isEqualTo(6); assertThat(beans.get(1).getRowNum()).isEqualTo(7); assertThat(beans.get(2).getRowNum()).isEqualTo(8); assertThat(beans.get(3).getRowNum()).isEqualTo(9); beans.get(0).setError(""error 000""); beans.get(1).setError(""error 000""); excelToBeans.writeError(MemberImportBean.class, beans); excelToBeans.removeOkRows(MemberImportBean.class, beans); }" 145, ,"public String findNextStep(GameBoard gameBoard){ Vertex me = gameBoard.getMe().getHead(); return findNextMovement(gameBoard, me); }","public String findNextStep(GameBoard gameBoard){ return findNextMovement(gameBoard, gameBoard.getMe().getHead()); }" 146, ,"public static Graph eulerianPath(int V, int E){ if (E < 0) throw new IllegalArgumentException(""negative number of edges""); if (V <= 0) throw new IllegalArgumentException(""An Eulerian path must have at least one vertex""); Graph G = new GraphImpl(V); int[] vertices = new int[E + 1]; for (int i = 0; i < E + 1; i++) vertices[i] = StdRandom.uniform(V); for (int i = 0; i < E; i++) { G.addEdge(vertices[i], vertices[i + 1]); } return G; }","public static Graph eulerianPath(int V, int E){ checkArgument(E >= 0, ""negative number of edges""); checkArgument(V > 0, ""An Eulerian path must have at least one vertex""); Graph G = new GraphImpl(V); int[] vertices = new int[E + 1]; for (int i = 0; i < E + 1; i++) vertices[i] = StdRandom.uniform(V); for (int i = 0; i < E; i++) { G.addEdge(vertices[i], vertices[i + 1]); } return G; }" 147, ,"public void testThreadSyncByCodeBlockLock() throws InterruptedException{ threadSyncThread.workersCaller(); LOGGER.info(""Synchronized worker 1 size {}"", threadSyncThread.getWorker1().size()); LOGGER.info(""Synchronized worker 2 size {}"", threadSyncThread.getWorker2().size()); Assert.assertEquals(expectedCounter, threadSyncThread.getWorker1().size()); }","public void testThreadSyncByCodeBlockLock() throws InterruptedException{ threadSyncThread.threadsRunByCodeBlockLock(); LOGGER.info(""Synchronized thread, counter = {}"", threadSyncThread.getCounter()); Assert.assertEquals(expectedCounter, threadSyncThread.getCounter().intValue()); }" 148, ,"private boolean skipping(RoutingContext ctx){ MultiMap headers = ctx.request().headers(); String method = headers.get(HTTP_HEADER_REQUEST_METHOD); if (headers.contains(AUDIT_FILTER_ID)) { auditFilterIds.remove(headers.get(AUDIT_FILTER_ID)); return true; } if (""GET"".equals(method) || ""200"".equals(headers.get(HTTP_HEADER_MODULE_RES))) { return true; } return false; }","private boolean skipping(RoutingContext ctx){ MultiMap headers = ctx.request().headers(); String method = headers.get(HTTP_HEADER_REQUEST_METHOD); if (headers.contains(AUDIT_FILTER_ID)) { auditFilterIds.remove(headers.get(AUDIT_FILTER_ID)); return true; } return (""GET"".equals(method) || ""200"".equals(headers.get(HTTP_HEADER_MODULE_RES))); }" 149, ,"public void testAnonymousClassesDontHoldRefs(){ final AtomicReference>> stringProvider = new AtomicReference>>(); final AtomicReference>> intProvider = new AtomicReference>>(); final Object foo = new Object() { @SuppressWarnings(""unused"") @Inject List list; }; Module module = new AbstractModule() { @Override protected void configure() { bind(new Key>() { }).toInstance(new ArrayList()); bind(new TypeLiteral>() { }).toInstance(new ArrayList()); stringProvider.set(getProvider(new Key>() { })); intProvider.set(binder().getProvider(Dependency.get(new Key>() { }))); binder().requestInjection(new TypeLiteral() { }, foo); } }; WeakReference moduleRef = new WeakReference<>(module); final Injector injector = Guice.createInjector(module); module = null; awaitClear(moduleRef); Runnable runner = new Runnable() { @Override public void run() { injector.getInstance(new Key>() { }); injector.getInstance(Key.get(new TypeLiteral>() { })); } }; WeakReference runnerRef = new WeakReference<>(runner); runner.run(); runner = null; awaitClear(runnerRef); }","public void testAnonymousClassesDontHoldRefs(){ final AtomicReference>> stringProvider = new AtomicReference>>(); final AtomicReference>> intProvider = new AtomicReference>>(); final Object foo = new Object() { @SuppressWarnings(""unused"") @Inject List list; }; Module module = new AbstractModule() { @Override protected void configure() { bind(new Key>() { }).toInstance(new ArrayList()); bind(new TypeLiteral>() { }).toInstance(new ArrayList()); stringProvider.set(getProvider(new Key>() { })); intProvider.set(binder().getProvider(Dependency.get(new Key>() { }))); binder().requestInjection(new TypeLiteral() { }, foo); } }; WeakReference moduleRef = new WeakReference<>(module); final Injector injector = Guice.createInjector(module); module = null; awaitClear(moduleRef); Runnable runner = () -> { injector.getInstance(new Key>() { }); injector.getInstance(Key.get(new TypeLiteral>() { })); }; WeakReference runnerRef = new WeakReference<>(runner); runner.run(); runner = null; awaitClear(runnerRef); }" 150, ,"public static boolean isCommonEnglishChar(char c){ if (Character.isUpperCase(c)) { return true; } else if (Character.isLowerCase(c)) { return true; } else if (Character.isWhitespace(c)) { return true; } else if (c == ',' || c == '.') { return true; } return false; }","public static boolean isCommonEnglishChar(char c){ if (Character.isUpperCase(c)) { return true; } else if (Character.isLowerCase(c)) { return true; } else if (Character.isWhitespace(c)) { return true; } else return c == ',' || c == '.'; }" 151, ,"public Strategy save(Strategy entity) throws ClientException, ParseException{ Strategy strategy = null; JsonResponse finalJsonResponse = null; if (entity != null) { StringBuilder uri = getUri(entity); if (entity.getId() > 0) { uri.append(""/""); uri.append(entity.getId()); } if (entity.getId() > 0 && !entity.getStrategyDomainRestrictions().isEmpty()) { uri.append(""/domain_restrictions""); } if (entity.getId() > 0 && !entity.getAudienceSegments().isEmpty() && entity.getAudienceSegmentExcludeOp() != null && entity.getAudienceSegmentIncludeOp() != null) { uri.append(""/audience_segments""); } String path = t1Service.constructUrl(uri); Response responseObj = this.connection.post(path, StrategyHelper.getForm(entity), this.user); String response = responseObj.readEntity(String.class); T1JsonToObjParser parser = new T1JsonToObjParser(); if (response.isEmpty()) return null; JsonPostErrorResponse error = jsonPostErrorResponseParser(response, responseObj); if (error != null) throwExceptions(error); finalJsonResponse = parsePostData(response, parser, entity); if (finalJsonResponse == null) return null; if (finalJsonResponse.getData() == null) return null; if (finalJsonResponse.getData() instanceof ArrayList) { List dataList = (ArrayList) finalJsonResponse.getData(); if (dataList.get(0) != null && dataList.get(0) instanceof StrategyAudienceSegment) { strategy = entity; strategy.setStrategyAudienceSegments(dataList); } } else { strategy = (Strategy) finalJsonResponse.getData(); } } return strategy; }","public Strategy save(Strategy entity) throws ClientException, ParseException{ Strategy strategy = null; JsonResponse finalJsonResponse = null; if (entity != null) { StringBuilder uri = getUri(entity); if (entity.getId() > 0) { uri.append(""/""); uri.append(entity.getId()); } if (entity.getId() > 0 && !entity.getStrategyDomainRestrictions().isEmpty()) { uri.append(""/domain_restrictions""); } if (entity.getId() > 0 && !entity.getAudienceSegments().isEmpty() && entity.getAudienceSegmentExcludeOp() != null && entity.getAudienceSegmentIncludeOp() != null) { uri.append(""/audience_segments""); } String path = t1Service.constructUrl(uri); Response responseObj = this.connection.post(path, StrategyHelper.getForm(entity), this.user); finalJsonResponse = getJsonResponse(entity, responseObj); if (finalJsonResponse == null) return null; if (finalJsonResponse.getData() == null) return null; if (finalJsonResponse.getData() instanceof ArrayList) { List dataList = (ArrayList) finalJsonResponse.getData(); if (dataList.get(0) != null && dataList.get(0) instanceof StrategyAudienceSegment) { strategy = entity; strategy.setStrategyAudienceSegments(dataList); } } else { strategy = (Strategy) finalJsonResponse.getData(); } } return strategy; }" 152, ,"public void createProcess(CreateProcessRequest request) throws UserNotFoundException{ UserEntity userEntity = userRepository.findById(request.getUserId()).orElseThrow(() -> new UserNotFoundException(request.getUserId())); ProcessEntity processEntity = CreateProcessRequestConverter.convert(request); processEntity.setUserEntity(userEntity); processRepository.save(processEntity); }","public void createProcess(CreateProcessRequest request) throws UserNotFoundException{ ProcessEntity processEntity = CreateProcessRequestConverter.convert(request); processRepository.save(processEntity); }" 153, ,"public static void addReservation(Reservation reservation) throws IOException{ GsonBuilder builder = new GsonBuilder(); Gson gson = builder.setPrettyPrinting().create(); reservations = readReservation(); try { reservations.add(reservation); Reservation[] reservationArray = new Reservation[reservations.size()]; reservations.toArray(reservationArray); Path file = Path.of(""src/main/resources/data/reservation.json""); Files.writeString(file, gson.toJson(reservationArray), StandardOpenOption.WRITE); } catch (JsonIOException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }","public static void addReservation(Reservation reservation) throws IOException{ GsonBuilder builder = new GsonBuilder(); Gson gson = builder.setPrettyPrinting().create(); reservations = readReservation(); try { reservations.add(reservation); Reservation[] reservationArray = new Reservation[reservations.size()]; reservations.toArray(reservationArray); Path file = Path.of(""src/main/resources/data/reservation.json""); Files.writeString(file, gson.toJson(reservationArray), StandardOpenOption.WRITE); } catch (JsonIOException | IOException e) { e.printStackTrace(); } }" 154, ,"public Builder id(final String id){ assert (id != null); assert (!id.equals("""")); return setPathParameter(""id"", id); }","public Builder id(final String id){ assertHasAndNotNull(id); return setPathParameter(""id"", id); }" 155, ,"public void doubleDown(Context context, Game g){ g.playerHit(); g.dPlay(); }","public void doubleDown(Context context, Game g){ }" 156, ,"public void updateCache(String userId, String query, Gif gif){ log.error(cache); var userCache = cache.getOrDefault(userId, new ArrayList<>()); var maybeCache = userCache.stream().filter(c -> Objects.equals(c.getQuery(), query)).findFirst(); if (maybeCache.isPresent()) { var oldCache = maybeCache.get(); var gifs = oldCache.getGifs(); if (!gifs.contains(gif.getPath())) { gifs.add(gif.getPath()); var newCache = new Cache(query, gifs); userCache.replaceAll(c -> { if (Objects.equals(c.getQuery(), query)) { return newCache; } return c; }); cache.put(userId, userCache); } } else { var gifs = new ArrayList(); gifs.add(gif.getPath()); userCache.add(new Cache(query, gifs)); cache.put(userId, userCache); } }","public void updateCache(String userId, String query, Gif gif){ var userCache = cache.getOrDefault(userId, new ArrayList<>()); var maybeCache = userCache.stream().filter(c -> Objects.equals(c.getQuery(), query)).findFirst(); if (maybeCache.isPresent()) { var oldCache = maybeCache.get(); var gifs = oldCache.getGifs(); if (!gifs.contains(gif.getPath())) { gifs.add(gif.getPath()); var newCache = new Cache(query, gifs); userCache.replaceAll(c -> { if (Objects.equals(c.getQuery(), query)) { return newCache; } return c; }); cache.put(userId, userCache); } } else { var gifs = new ArrayList(); gifs.add(gif.getPath()); userCache.add(new Cache(query, gifs)); cache.put(userId, userCache); } }" 157, ,"public String create(@Valid @RequestBody AddStackRequest addStackRequest){ String svn_url = addStackRequest.getSvn_url(); String stack_name = addStackRequest.getStack_name(); List images = addStackRequest.getImages(); String inputmessage = "" svn_url:"" + svn_url + "" stack_name:"" + stack_name; log.debug(""POST /stack "" + inputmessage); Map docker_compose_template_yaml = retrieveDockercomposeTemplate.doGet(svn_url); Lock lock = new ReentrantLock(); lock.lock(); List not_occupied_ports = retrieveNotOccupiedPort.getPorts(); createDabCompose.doCreate(docker_compose_template_yaml, images, not_occupied_ports); String dab = createDabCompose.getDab(); String result = """"; try { result = shurenyunApiRequestForward2.createStack(stack_name, dab); } catch (Exception e) { result = e.getMessage(); } lock.unlock(); return result; }","public String create(@Valid @RequestBody AddStackRequest addStackRequest){ String svn_url = addStackRequest.getSvn_url(); String stack_name = addStackRequest.getStack_name(); List images = addStackRequest.getImages(); String inputmessage = "" svn_url:"" + svn_url + "" stack_name:"" + stack_name; log.debug(""POST /stack "" + inputmessage); Map services = dockerComposeTemplate.doGet(svn_url); Lock lock = new ReentrantLock(); lock.lock(); List notOccupiedPorts = dynamicResource.getPorts(); String dab = dabCompose.doCreate(services, images, notOccupiedPorts); String result = """"; try { result = DMApiRequestForward.createStack(stack_name, dab); } catch (Exception e) { result = e.getMessage(); } lock.unlock(); return result; }" 158, ,"public void increaseKey(int i, Key key){ validateIndex(i); if (!contains(i)) throw new NoSuchElementException(""index is not in the priority queue""); if (keys[i].compareTo(key) == 0) throw new IllegalArgumentException(""Calling increaseKey() with a key equal to the key in the priority queue""); if (keys[i].compareTo(key) > 0) throw new IllegalArgumentException(""Calling increaseKey() with a key that is strictly less than the key in the priority queue""); keys[i] = key; swim(qp[i]); }","public void increaseKey(int i, Key key){ validateIndex(i); checkArgument(contains(i), ""index is not in the priority queue""); checkArgument(keys[i].compareTo(key) != 0, ""Calling increaseKey() with a key equal to the key in the priority queue""); checkArgument(keys[i].compareTo(key) <= 0, ""Calling increaseKey() with a key that is strictly less than the key in the priority queue""); keys[i] = key; swim(qp[i]); }" 159, ,"public Map countByStatus(String namespace, long createdAfter, long createdBefore) throws StoreException{ logger.debug(""Received request to count all tasks by status under namespace {},"" + ""created after {}, created before {}"", namespace, createdAfter, createdBefore); try { MongoCollection mongoCollection = mongoClient.getDatabase(namespace).getCollection(COLLECTION_NAME); List pipelines = new ArrayList<>(); pipelines.add(Aggregates.match(and(eq(""namespace"", namespace), lt(""createdAt"", createdBefore), gt(""createdAt"", createdAfter)))); pipelines.add(Aggregates.group(""$status"", Accumulators.sum(""count"", 1))); AggregateIterable tasks = mongoCollection.aggregate(pipelines); Map statusMap = new HashMap<>(); for (Document task : tasks) { Task.Status status = Task.Status.valueOf(task.get(""_id"").toString()); statusMap.put(status, task.getInteger(""count"")); } return statusMap; } catch (Exception e) { logger.error(""Error loading all tasks under namespace {}, created after {}, created before {}"", namespace, createdAfter, createdBefore, e); throw new StoreException(e.getMessage(), e.getCause()); } }","public Map countByStatus(String namespace, long createdAfter, long createdBefore) throws StoreException{ logger.debug(""Received request to count all tasks by status under namespace {},"" + ""created after {}, created before {}"", namespace, createdAfter, createdBefore); try { MongoCollection taskCollection = mongoClient.getDatabase(namespace).getCollection(COLLECTION_NAME); Bson filter = Aggregates.match(and(eq(""namespace"", namespace), lt(""createdAt"", createdBefore), gt(""createdAt"", createdAfter))); return aggregateByStatus(taskCollection, filter); } catch (Exception e) { logger.error(""Error loading all tasks under namespace {}, created after {}, created before {}"", namespace, createdAfter, createdBefore, e); throw new StoreException(e.getMessage(), e.getCause()); } }" 160, ,"public T get(String tenantCode){ val list = threadList.get(); for (int i = list.size() - 1; i >= 0; i--) { val entry = list.remove(i); val bagEntry = entry.get(); if (bagEntry != null && bagEntry.stateFreeToUsing()) { bagEntry.setTenantCode(tenantCode); return bagEntry; } } return null; }","public T get(){ val list = threadList.get(); for (int i = list.size() - 1; i >= 0; i--) { val entry = list.remove(i); val bagEntry = entry.get(); if (bagEntry != null && bagEntry.stateFreeToUsing()) { return bagEntry; } } return null; }" 161, ,"public static List process(String filename) throws IOException, URISyntaxException{ List input = readLinesFromInputFile(filename); List output = new ArrayList(); List coordinates = new ArrayList<>(); coordinates = parseLine(input.get(0), false); List lostPositions = new ArrayList(); for (int i = 1; i < input.size(); i = i + 3) { List initialPosition = parseLine(input.get(i), true); String orientation = input.get(i).charAt(input.get(i).length() - 1) + """"; char[] instructions = input.get(i + 1).toCharArray(); String res = processRobot(coordinates, initialPosition, orientation, instructions, lostPositions); System.out.println(res); output.add(res); } return output; }","public static List process(String filename) throws IOException, URISyntaxException{ List input = readLinesFromInputFile(filename); List output = new ArrayList(); List coordinates = parseLine(input.get(0), false); List lostPositions = new ArrayList(); for (int i = 1; i < input.size(); i = i + 3) { List initialPosition = parseLine(input.get(i), true); String orientation = input.get(i).charAt(input.get(i).length() - 1) + """"; char[] instructions = input.get(i + 1).toCharArray(); String res = processRobot(coordinates, initialPosition, orientation, instructions, lostPositions); System.out.println(res); output.add(res); } return output; }" 162, ,"private String buildSelectSQL(ArrayList> paramAppenders){ SQLSelectRecognizer recognizer = (SQLSelectRecognizer) sqlRecognizer; StringBuffer selectSQLAppender = new StringBuffer(""SELECT ""); selectSQLAppender.append(getColumnNameInSQL(getTableMeta().getPkName())); selectSQLAppender.append("" FROM "" + getFromTableInSQL()); String whereCondition = null; if (statementProxy instanceof ParametersHolder) { whereCondition = recognizer.getWhereCondition((ParametersHolder) statementProxy, paramAppenders); } else { whereCondition = recognizer.getWhereCondition(); } if (!StringUtils.isNullOrEmpty(whereCondition)) { selectSQLAppender.append("" WHERE "" + whereCondition); } selectSQLAppender.append("" FOR UPDATE""); String selectSQL = selectSQLAppender.toString(); if (!paramAppenders.isEmpty() && paramAppenders.size() > 1) { StringBuffer stringBuffer = new StringBuffer(selectSQL); for (int i = 1; i < paramAppenders.size(); i++) { stringBuffer.append("" UNION "").append(selectSQL); } selectSQL = stringBuffer.toString(); } return selectSQL; }","private String buildSelectSQL(ArrayList> paramAppenderList){ SQLSelectRecognizer recognizer = (SQLSelectRecognizer) sqlRecognizer; StringBuffer selectSQLAppender = new StringBuffer(""SELECT ""); selectSQLAppender.append(getColumnNameInSQL(getTableMeta().getPkName())); selectSQLAppender.append("" FROM "" + getFromTableInSQL()); String whereCondition = buildWhereCondition(recognizer, paramAppenderList); if (!StringUtils.isNullOrEmpty(whereCondition)) { selectSQLAppender.append("" WHERE "" + whereCondition); } selectSQLAppender.append("" FOR UPDATE""); return buildParamsAppenderSQL(selectSQLAppender.toString(), paramAppenderList); }" 163, ,"public RenderPart toRenderPart(){ List children = stream().map(e -> e.toRenderPart()).collect(Collectors.toList()); return new ParallelRenderPart(this, children); }","public RenderPart toRenderPart(){ return new ParallelRenderPart(this, getChildRenderParts()); }" 164, ,"public void run(){ Application app = new Application(""2d jobs Visio""); DrawerFeature.setupDrawerPlugin(app); setupDefaultDrawerVisibilityManagement(app); DriverFeature.setupDriverPlugin(app); setupDrivers(app); setupPresetTests(app); setupLogger(app); app.setVisibility(true); }","public void run(){ Application app = new Application(""2d jobs Visio""); DrawerFeature.setupDrawerPlugin(app); DriverFeature.setupDriverPlugin(app); setupDrivers(app); setupPresetTests(app); setupLogger(app); app.setVisibility(true); }" 165, ,"public JImmutableSet intersection(@Nonnull Cursor values){ if (isEmpty()) { return this; } JImmutableMap newMap = emptyMap(); for (Cursor c = values.start(); c.hasValue(); c = c.next()) { final T value = c.getValue(); if ((value != null) && map.getValueOr(value, Boolean.FALSE)) { newMap = newMap.assign(value, Boolean.TRUE); } } return create(newMap); }","public JImmutableSet intersection(@Nonnull Cursor values){ return intersection(values.iterator()); }" 166, ," void underscoreSeparators_shouldIndexUnderscoreSeparatedFiles(){ System.setProperty(FilenamePropertyIndexSupplier.SEPARATOR_PROPERTY, ""_""); ConfigurableEnvironment environment = new StandardEnvironment(); FilenamePropertyIndexSupplier supplier = new FilenamePropertyIndexSupplier(Supplier::get, environment); Map index = supplier.get(); assertNotNull(index); assertEquals(2, index.size()); assertTrue(index.containsKey(""spring.datasource.password"")); assertEquals(fromFile(""spring_datasource_password""), index.get(""spring.datasource.password"")); assertTrue(index.containsKey(""spring.mail.host"")); assertEquals(fromFile(""spring_mail_host""), index.get(""spring.mail.host"")); }"," void underscoreSeparators_shouldIndexUnderscoreSeparatedFiles(){ setUpSupplier(""_""); Map index = supplier.get(); assertNotNull(index); assertEquals(2, index.size()); assertTrue(index.containsKey(""spring.datasource.password"")); assertEquals(fromFile(""spring_datasource_password""), index.get(""spring.datasource.password"")); assertTrue(index.containsKey(""spring.mail.host"")); assertEquals(fromFile(""spring_mail_host""), index.get(""spring.mail.host"")); }" 167, ,"public void saveAll(List tasks){ status.incrementValue(SAVE_ALL_CALLS); log.debug(""Saving "" + tasks.size() + "" tasks""); tasks.forEach(task -> { taskDispatcher.addTask(super.save(task)); }); }","public void saveAll(List tasks){ status.incrementValue(SAVE_ALL_CALLS); log.debug(""Saving "" + tasks.size() + "" tasks""); tasks.forEach(task -> taskDispatcher.addTask(super.save(task))); }" 168, ,"public void run(String... args) throws Exception{ Owner owner1 = new Owner(); owner1.setFirstName(""Jimmy""); owner1.setLastName(""Wilson""); owner1.setId(1L); Owner owner2 = new Owner(); owner2.setFirstName(""Jimmy""); owner2.setLastName(""Neutron""); owner2.setId(2L); Owner owner3 = new Owner(); owner3.setFirstName(""Jimmy""); owner3.setLastName(""Shimy-o""); owner3.setId(3L); List owners = new ArrayList<>(); owners.add(owner1); owners.add(owner2); owners.add(owner3); Vet vet1 = new Vet(); vet1.setFirstName(""Dr""); vet1.setLastName(""Larson""); vet1.setId(1L); vetService.save(vet1); ownerService.save(owners); System.out.println(""Data Loaded...""); }","public void run(String... args) throws Exception{ Owner owner1 = new Owner(); owner1.setFirstName(""Jimmy""); owner1.setLastName(""Wilson""); Owner owner2 = new Owner(); owner2.setFirstName(""Jimmy""); owner2.setLastName(""Neutron""); Owner owner3 = new Owner(); owner3.setFirstName(""Jimmy""); owner3.setLastName(""Shimy-o""); List owners = new ArrayList<>(); owners.add(owner1); owners.add(owner2); owners.add(owner3); Vet vet1 = new Vet(); vet1.setFirstName(""Dr""); vet1.setLastName(""Larson""); vetService.save(vet1); ownerService.save(owners); System.out.println(""Data Loaded...""); }" 169, ,"public void updateCar(Car car) throws NamingException, SQLException{ Context ctx = new InitialContext(); Context envContext = (Context) ctx.lookup(""java:comp/env""); DataSource dataSource = (DataSource) envContext.lookup(""jdbc/TestDB""); Connection con = null; try { con = dataSource.getConnection(); PreparedStatement updateCar = con.prepareStatement(""UPDATE cars SET registration_number = ?, model = ?,"" + "" type_id = ?, condition_type_id = ?, number_of_seats = ?, color = ? WHERE id = ?""); updateCar.setString(1, car.getRegistrationNumber()); updateCar.setString(2, car.getModel()); updateCar.setInt(3, CarUtils.typeToInt(car.getType())); updateCar.setInt(4, CarUtils.conditionTypeToInt(car.getCondition())); updateCar.setInt(5, car.getNumberOfSeats()); updateCar.setString(6, car.getColor()); updateCar.setLong(7, car.getId()); updateCar.execute(); updateCar.close(); } finally { if (con != null) try { con.close(); } catch (Exception ignore) { } } }","public void updateCar(Car car) throws NamingException, SQLException{ Connection con = null; try { con = dataSource.getConnection(); PreparedStatement updateCar = con.prepareStatement(""UPDATE cars SET registration_number = ?, model = ?,"" + "" type_id = ?, condition_type_id = ?, number_of_seats = ?, color = ? WHERE id = ?""); updateCar.setString(1, car.getRegistrationNumber()); updateCar.setString(2, car.getModel()); updateCar.setInt(3, CarUtils.typeToInt(car.getType())); updateCar.setInt(4, CarUtils.conditionTypeToInt(car.getCondition())); updateCar.setInt(5, car.getNumberOfSeats()); updateCar.setString(6, car.getColor()); updateCar.setLong(7, car.getId()); updateCar.execute(); updateCar.close(); } finally { if (con != null) try { con.close(); } catch (Exception ignore) { } } }" 170, ,"public Span startPropagation(final HttpServerRequestAdapter httpRequest){ final String honeycombHeaderValue = httpRequest.getFirstHeader(HONEYCOMB_TRACE_HEADER).orElse(null); final PropagationContext decoded = propagationCodec.decode(honeycombHeaderValue); final String spanName = requestToSpanName.apply(httpRequest); final Span rootSpan = beeline.startTrace(spanName, decoded, serviceName); spanCustomizer.customize(rootSpan, httpRequest); return rootSpan; }","public Span startPropagation(final HttpServerRequestAdapter httpRequest){ final PropagationContext decoded = propagationCodec.decode(httpRequest.getHeaders()); final String spanName = requestToSpanName.apply(httpRequest); final Span rootSpan = beeline.startTrace(spanName, decoded, serviceName); spanCustomizer.customize(rootSpan, httpRequest); return rootSpan; }" 171, ,"public void testNodesMappedMemoryOptionWithNegative() throws IOException{ Map options = BlueprintsNeo4jOptions.newBuilder().nodesMappedBuffer(-64).asMap(); Throwable thrown = catchThrowable(() -> resource.save(options)); assertThat(thrown).isInstanceOf(InvalidDataStoreException.class); }","public void testNodesMappedMemoryOptionWithNegative() throws IOException{ Map options = BlueprintsNeo4jOptions.builder().nodesMappedBuffer(-64).asMap(); assertThat(catchThrowable(() -> resource.save(options))).isInstanceOf(InvalidDataStoreException.class); }" 172, ," double evaluate(JavaRDD evalData){ Map clusterMetricsByID = fetchClusterMetrics(evalData).collectAsMap(); double totalDBIndex = 0.0; Map clustersByID = getClustersByID(); DistanceFn distanceFn = getDistanceFn(); for (Map.Entry entryI : clustersByID.entrySet()) { double maxDBIndex = 0.0; Integer idI = entryI.getKey(); double[] centerI = entryI.getValue().getCenter(); double clusterScatter1 = clusterMetricsByID.get(idI).getMeanDist(); for (Map.Entry entryJ : clustersByID.entrySet()) { Integer idJ = entryJ.getKey(); if (!idI.equals(idJ)) { double[] centerJ = entryJ.getValue().getCenter(); double clusterScatter2 = clusterMetricsByID.get(idJ).getMeanDist(); double dbIndex = (clusterScatter1 + clusterScatter2) / distanceFn.applyAsDouble(centerI, centerJ); maxDBIndex = Math.max(maxDBIndex, dbIndex); } } totalDBIndex += maxDBIndex; } return totalDBIndex / clustersByID.size(); }"," double evaluate(JavaRDD evalData){ Map clusterMetricsByID = fetchClusterMetrics(evalData).collectAsMap(); Map clustersByID = getClustersByID(); DistanceFn distanceFn = getDistanceFn(); return clustersByID.entrySet().stream().mapToDouble(entryI -> { Integer idI = entryI.getKey(); double[] centerI = entryI.getValue().getCenter(); double clusterScatter1 = clusterMetricsByID.get(idI).getMeanDist(); return clustersByID.entrySet().stream().mapToDouble(entryJ -> { Integer idJ = entryJ.getKey(); if (idI.equals(idJ)) { return 0.0; } double[] centerJ = entryJ.getValue().getCenter(); double clusterScatter2 = clusterMetricsByID.get(idJ).getMeanDist(); return (clusterScatter1 + clusterScatter2) / distanceFn.applyAsDouble(centerI, centerJ); }).max().orElse(0.0); }).average().orElse(0.0); }" 173, ,"public void testUpdate(){ UpdateStatementProvider updateStatement = update(generatedAlways).set(firstName).equalToStringConstant(""Rob"").where(id, isIn(1, 5, 22)).build().render(RenderingStrategy.SPRING_NAMED_PARAMETER); SqlParameterSource parameterSource = new MapSqlParameterSource(updateStatement.getParameters()); int rows = template.update(updateStatement.getUpdateStatement(), parameterSource); assertThat(rows).isEqualTo(2); }","public void testUpdate(){ UpdateStatementProvider updateStatement = update(generatedAlways).set(firstName).equalToStringConstant(""Rob"").where(id, isIn(1, 5, 22)).build().render(RenderingStrategy.SPRING_NAMED_PARAMETER); SqlParameterSource parameterSource = new MapSqlParameterSource(updateStatement.getParameters()); }" 174, ,"public ServerResponse getProductDetail(HttpServletRequest request, Integer productId){ String loginToken = CookieUtil.readLoginLoken(request); if (StringUtils.isBlank(loginToken)) { return ServerResponse.createByErrorMessage(""用户未登录""); } String userStr = ShardedRedisPoolUtil.get(loginToken); User existUser = JsonUtil.Json2Obj(userStr, User.class); if (existUser == null) { return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ""用户未登录""); } if (iUserService.checkAdmin(existUser).isSuccess()) { return iProductService.getProductDetail(productId); } return ServerResponse.createByErrorMessage(""该用户没有权限""); }","public ServerResponse getProductDetail(HttpServletRequest request, Integer productId){ return iProductService.getProductDetail(productId); }" 175, ,"public Builder user_id(final String user_id){ assert (user_id != null); assert (!user_id.equals("""")); return setPathParameter(""user_id"", user_id); }","public Builder user_id(final String user_id){ assertHasAndNotNull(user_id); return setPathParameter(""user_id"", user_id); }" 176, ,"public static List read(PMML pmml){ List models = pmml.getModels(); Model model = models.get(0); Preconditions.checkArgument(model instanceof ClusteringModel); ClusteringModel clusteringModel = (ClusteringModel) model; List clusters = clusteringModel.getClusters(); List clusterInfoList = new ArrayList<>(clusters.size()); for (Cluster cluster : clusters) { String[] tokens = TextUtils.parseDelimited(cluster.getArray().getValue(), ' '); ClusterInfo clusterInfo = new ClusterInfo(Integer.parseInt(cluster.getId()), VectorMath.parseVector(tokens), cluster.getSize()); clusterInfoList.add(clusterInfo); } return clusterInfoList; }","public static List read(PMML pmml){ Model model = pmml.getModels().get(0); Preconditions.checkArgument(model instanceof ClusteringModel); ClusteringModel clusteringModel = (ClusteringModel) model; return clusteringModel.getClusters().stream().map(cluster -> new ClusterInfo(Integer.parseInt(cluster.getId()), VectorMath.parseVector(TextUtils.parseDelimited(cluster.getArray().getValue(), ' ')), cluster.getSize())).collect(Collectors.toList()); }" 177, ,"public QueryData business(@RequestParam(value = ""businessID"", defaultValue = ""0"") Integer business_ID, @RequestParam(value = ""name"", defaultValue = """") String name, @RequestParam(value = ""address"", defaultValue = """") String address){ String businessCall = ""select * from business""; LinkedHashMap arguments = new LinkedHashMap<>(); if (business_ID > 0) arguments.put(""business_ID"", business_ID.toString()); if (!name.equals("""")) arguments.put(""name"", name); if (!address.equals("""")) arguments.put(""address"", address); businessCall = h2.buildQuery(businessCall, arguments); QueryData results = new QueryData(); try { ResultSet businesses = h2.query(businessCall); while (businesses.next()) { results.addData(new Business(businesses.getInt(""business_ID""), businesses.getString(""name""), businesses.getString(""address""))); } } catch (SQLException se) { System.out.println(""Error parsing results of query '"" + businessCall + ""'""); results.setData(new ArrayList() { { add(new Exception(""Could not complete request"")); } }); results.setCount(-1); } return results; }","public QueryData business(@RequestParam(value = ""businessID"", defaultValue = ""0"") Integer business_ID, @RequestParam(value = ""name"", defaultValue = """") String name, @RequestParam(value = ""address"", defaultValue = """") String address){ String businessCall = ""select * from business""; LinkedHashMap arguments = new LinkedHashMap<>(); if (business_ID > 0) arguments.put(""business_ID"", business_ID.toString()); if (!name.equals("""")) arguments.put(""name"", name); if (!address.equals("""")) arguments.put(""address"", address); businessCall = h2.buildQuery(businessCall, arguments); QueryData results = new QueryData(); try { ResultSet businesses = h2.query(businessCall); while (businesses.next()) { results.addData(new Business(businesses.getInt(""business_ID""), businesses.getString(""name""), businesses.getString(""address""))); } } catch (SQLException se) { results = h2.errorCall(results, businessCall); } return results; }" 178, ,"public int compute(int num1, int num2, char symbol){ switch(symbol) { case '+': return num1 + num2; case '-': return num1 - num2; default: throw new IllegalArgumentException(); } }","public int compute(int num1, int num2, char symbol){ Computable computable = ComputeFactory.getCompute(symbol); return computable.compute(num1, num2); }" 179, ,"public void testCloseOrderBookWhenInvalidInstrumentIdThenReturnInstrumentIdNotFound() throws Exception{ instrumentId = 10; when(service.changeOrderBookStatus(anyInt(), anyString())).thenReturn(OrderBookConstants.INSTRUMENT_ID_NOT_FOUND); requestBuilder = MockMvcRequestBuilders.put(""/orderbook/"" + instrumentId).characterEncoding(OrderBookConstants.UTF_8).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON); response = mockMvc.perform(requestBuilder).andExpect(status().isNotFound()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)).andReturn(); context = JsonPath.parse(response.getResponse().getContentAsString()); Assertions.assertThat(context.read(""$.error"").toString()).isNotNull(); Assertions.assertThat(context.read(""$.error.errorMessage"").toString()).isNotNull(); Assertions.assertThat(context.read(""$.error.errorMessage"").toString()).isEqualTo(OrderBookConstants.INSTRUMENT_ID_NOT_FOUND); }","public void testCloseOrderBookWhenInvalidInstrumentIdThenReturnInstrumentIdNotFound() throws Exception{ instrumentId = 10; when(service.closeOrderBook(anyInt())).thenReturn(OrderBookConstants.INSTRUMENT_ID_NOT_FOUND); requestBuilder = MockMvcRequestBuilders.put(""/orderbook/"" + instrumentId).characterEncoding(OrderBookConstants.UTF_8).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON); response = mockMvc.perform(requestBuilder).andExpect(status().isNotFound()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)).andReturn(); context = JsonPath.parse(response.getResponse().getContentAsString()); Assertions.assertThat(context.read(""$.bookStatus"").toString()).isNotNull(); Assertions.assertThat(context.read(""$.bookStatus"").toString()).isEqualTo(OrderBookConstants.INSTRUMENT_ID_NOT_FOUND); }" 180, ,"public List getAllUsers(@RequestParam(""countryId"") Integer countryId){ List cityList = citySevice.findCitiesByCountryId(countryId); return cityList; }","public List getAllUsers(@RequestParam(""countryId"") Integer countryId){ return citySevice.findCitiesByCountryId(countryId); }" 181, ,"public void isAnagrams_whenStringsAreNotValid_returnError() throws Exception{ String string1 = ""cinema""; String string2 = ""iceman4""; String uri = ANAGRAM_URI + ""/"" + string1 + ""/"" + string2; mockMvc.perform(get(uri)).andExpect(status().isBadRequest()); }","public void isAnagrams_whenStringsAreNotValid_returnError() throws Exception{ String uri = String.format(""%s/%s/%s"", ANAGRAM_URI, ""cinema"", ""iceman4""); mockMvc.perform(get(uri)).andExpect(status().isBadRequest()); }" 182, ,"public void EnterBookingResourceDetails(String startTime, String endTime, String description) throws InterruptedException{ click(""cssSelector"", ""#starttime""); WebElement calStarttime = webElementId(""cssSelector"", ""#starttime""); if (driver.findElement(By.cssSelector(""#starttime"")).getText().equalsIgnoreCase(startTime)) { click(""cssSelector"", ""#starttime""); } Thread.sleep(2000); click(""cssSelector"", ""#endtime""); List elements = driver.findElements(By.cssSelector(""#endtime"")); System.out.println(elements.size()); for (WebElement element : elements) { System.out.println(element.getText()); } if (driver.findElement(By.cssSelector(""#endtime"")).getText().equalsIgnoreCase(endTime)) { click(""cssSelector"", ""#endtime""); } driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); WebElement btndescription = webElementId(""xpath"", "".//*[@id='RRB']/section/table/tbody/tr/td/table[2]/tbody/tr[3]/td[1]/table/tbody/tr[6]/td[2]/textarea""); btndescription.sendKeys(description); }","public void EnterBookingResourceDetails(String startTime, String endTime, String description) throws InterruptedException{ click(""cssSelector"", ""#starttime""); WebElement calStarttime = webElementId(""cssSelector"", ""#starttime""); if (driver.findElement(By.cssSelector(""#starttime"")).getText().equalsIgnoreCase(startTime)) { click(""cssSelector"", ""#starttime""); } Thread.sleep(2000); if (driver.findElement(By.cssSelector(""#endtime"")).getText().equalsIgnoreCase(endTime)) { click(""cssSelector"", ""#endtime""); } driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); WebElement btndescription = webElementId(""xpath"", "".//*[@id='RRB']/section/table/tbody/tr/td/table[2]/tbody/tr[3]/td[1]/table/tbody/tr[6]/td[2]/textarea""); btndescription.sendKeys(description); }" 183, ,"public boolean keyDown(InputEvent event, int keycode){ super.keyDown(event, keycode); switch(keycode) { case Input.Keys.ESCAPE: parent.changeScreen(RoboRallyApplication.MAIN_MENU); return super.keyDown(event, keycode); case Input.Keys.UP: MovementCard movementCardUp = new MovementCard(0, MovementType.ONE_FORWARD); board.execute(player, movementCardUp); parent.getGameScreen().updateGraphics(); break; case Input.Keys.DOWN: MovementCard movementCardDown = new MovementCard(0, MovementType.ONE_BACKWARD); board.execute(player, movementCardDown); parent.getGameScreen().updateGraphics(); break; case Input.Keys.RIGHT: Direction oldDirectionR = player.getDirection(); RotationCard rotationCardRight = new RotationCard(0, RotationType.CLOCKWISE); board.execute(player, rotationCardRight); parent.getGameScreen().updateGraphics(); break; case Input.Keys.LEFT: Direction oldDirectionL = player.getDirection(); RotationCard rotationCardLeft = new RotationCard(0, RotationType.COUNTER_CLOCKWISE); board.execute(player, rotationCardLeft); parent.getGameScreen().updateGraphics(); break; } return true; }","public boolean keyDown(InputEvent event, int keycode){ super.keyDown(event, keycode); switch(keycode) { case Input.Keys.ESCAPE: parent.changeScreen(RoboRallyApplication.MAIN_MENU); return super.keyDown(event, keycode); case Input.Keys.UP: MovementCard movementCardUp = new MovementCard(0, MovementType.ONE_FORWARD); board.execute(player, movementCardUp); break; case Input.Keys.DOWN: MovementCard movementCardDown = new MovementCard(0, MovementType.ONE_BACKWARD); board.execute(player, movementCardDown); break; case Input.Keys.RIGHT: RotationCard rotationCardRight = new RotationCard(0, RotationType.CLOCKWISE); board.execute(player, rotationCardRight); break; case Input.Keys.LEFT: RotationCard rotationCardLeft = new RotationCard(0, RotationType.COUNTER_CLOCKWISE); board.execute(player, rotationCardLeft); break; } return true; }" 184, ,"protected Mono doExecute(final ServerWebExchange exchange, final SoulPluginChain chain, final SelectorData selector, final RuleData rule){ WafConfig wafConfig = Singleton.INST.get(WafConfig.class); if (Objects.isNull(selector) && Objects.isNull(rule)) { if (WafModelEnum.BLACK.getName().equals(wafConfig.getModel())) { return chain.execute(exchange); } else { exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN); Object error = SoulResultWrap.error(403, Constants.REJECT_MSG, null); return WebFluxResultUtils.result(exchange, error); } } String handle = rule.getHandle(); WafHandle wafHandle = GsonUtils.getInstance().fromJson(handle, WafHandle.class); if (Objects.isNull(wafHandle) || StringUtils.isBlank(wafHandle.getPermission())) { log.error(""waf handler can not configuration:{}"", handle); return chain.execute(exchange); } if (WafEnum.REJECT.getName().equals(wafHandle.getPermission())) { exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN); Object error = SoulResultWrap.error(Integer.parseInt(wafHandle.getStatusCode()), Constants.REJECT_MSG, null); return WebFluxResultUtils.result(exchange, error); } return chain.execute(exchange); }","protected Mono doExecute(final ServerWebExchange exchange, final SoulPluginChain chain, final SelectorData selector, final RuleData rule){ WafConfig wafConfig = Singleton.INST.get(WafConfig.class); if (Objects.isNull(selector) && Objects.isNull(rule)) { if (WafModelEnum.BLACK.getName().equals(wafConfig.getModel())) { return chain.execute(exchange); } exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN); Object error = SoulResultWrap.error(403, Constants.REJECT_MSG, null); return WebFluxResultUtils.result(exchange, error); } String handle = rule.getHandle(); WafHandle wafHandle = GsonUtils.getInstance().fromJson(handle, WafHandle.class); if (Objects.isNull(wafHandle) || StringUtils.isBlank(wafHandle.getPermission())) { log.error(""waf handler can not configuration:{}"", handle); return chain.execute(exchange); } if (WafEnum.REJECT.getName().equals(wafHandle.getPermission())) { exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN); Object error = SoulResultWrap.error(Integer.parseInt(wafHandle.getStatusCode()), Constants.REJECT_MSG, null); return WebFluxResultUtils.result(exchange, error); } return chain.execute(exchange); }" 185, ,"private void validateIndex(int i){ if (i < 0) throw new IllegalArgumentException(""index is negative: "" + i); if (i >= maxN) throw new IllegalArgumentException(""index >= capacity: "" + i); }","private void validateIndex(int i){ checkArgument(i >= 0, ""index is negative: "" + i); checkArgument(i < maxN, ""index >= capacity: "" + i); }" 186, ,"public String process(@RequestBody MultiValueMap formData, Model model, HttpSession session){ String trxId = UUID.randomUUID().toString(); session.setAttribute(""TRX_ID"", trxId); log.info(""Session Id: "" + trxId + "" Starting""); int querySize = lexicalDataRepository.getSize(trxId, formData.get(""field""), formData.get(""constraints"")); log.info(""Session Id: "" + trxId + "" Pre Size Check: "" + querySize); if (querySize >= 100000) { model.addAttribute(""errorMessage"", ""You query generated "" + querySize + "" results! Please add constraints...""); model.addAttribute(""errorBackLink"", ""/query17/query17.html""); return ""errorback""; } List> query = lexicalDataRepository.get(trxId, formData.get(""field""), formData.get(""constraints"")); log.info(""Session Id: "" + trxId + "" QuerySize: "" + query.size()); session.setAttribute(""expData"", query); model.addAttribute(""dist"", formData.get(""dist"")); model.addAttribute(""constraints"", formData.get(""constraints"")); model.addAttribute(""field"", formData.get(""field"")); model.addAttribute(""expData"", query); model.addAttribute(""expDataCount"", query.size()); addButtonFlags(formData, model); if (query.isEmpty()) { model.addAttribute(""errorMessage"", ""You query generated no results!""); model.addAttribute(""errorBackLink"", ""/query17/query17.html""); return ""errorback""; } if (query.size() > maxHtmlResultSet || formData.get(""dist"").contains(""email"")) { return ""query17/emailresponse""; } return ""query17/query17do""; }","public String process(@RequestBody MultiValueMap formData, Model model, HttpSession session){ String trxId = initializeSession(log, session); int querySize = lexicalDataRepository.getSize(trxId, formData.get(""field""), formData.get(""constraints"")); log.info(""Session Id: "" + trxId + "" Pre Size Check: "" + querySize); if (querySize >= 100000) { model.addAttribute(""errorMessage"", ""You query generated "" + querySize + "" results! Please add constraints...""); model.addAttribute(""errorBackLink"", ""/query17/query17.html""); return ""errorback""; } List> query = lexicalDataRepository.get(trxId, formData.get(""field""), formData.get(""constraints"")); log.info(""Session Id: "" + trxId + "" QuerySize: "" + query.size()); session.setAttribute(""expData"", query); model.addAttribute(""dist"", formData.get(""dist"")); model.addAttribute(""constraints"", formData.get(""constraints"")); model.addAttribute(""field"", formData.get(""field"")); model.addAttribute(""expData"", query); model.addAttribute(""expDataCount"", query.size()); addButtonsFlags(formData, model); if (query.isEmpty()) { model.addAttribute(""errorMessage"", ""You query generated no results!""); model.addAttribute(""errorBackLink"", ""/query17/query17.html""); return ""errorback""; } if (query.size() > maxHtmlResultSet || formData.get(""dist"").contains(""email"")) { return ""query17/emailresponse""; } return ""query17/query17do""; }" 187, ,"public void testTypeParameters() throws ParseException{ String code = ""public class B { public void foo(){} }""; DefaultJavaParser parser = new DefaultJavaParser(); CompilationUnit cu = parser.parse(code, false); CompilationUnit cu2 = parser.parse(code, false); ClassOrInterfaceDeclaration dec = (ClassOrInterfaceDeclaration) cu.getTypes().get(0); List types = dec.getTypeParameters(); types.add(new TypeParameter(""D"", null)); ChangeLogVisitor visitor = new ChangeLogVisitor(); VisitorContext ctx = new VisitorContext(); ctx.put(ChangeLogVisitor.NODE_TO_COMPARE_KEY, cu2); visitor.visit((CompilationUnit) cu, ctx); List actions = visitor.getActionsToApply(); Assert.assertEquals(1, actions.size()); Assert.assertEquals(ActionType.REPLACE, actions.get(0).getType()); assertCode(actions, code, ""public class B {public void foo() {}}""); cu = parser.parse(code, false); dec = (ClassOrInterfaceDeclaration) cu.getTypes().get(0); types = dec.getTypeParameters(); types.remove(0); types.add(new TypeParameter(""D"", null)); visitor = new ChangeLogVisitor(); ctx = new VisitorContext(); ctx.put(ChangeLogVisitor.NODE_TO_COMPARE_KEY, cu2); visitor.visit((CompilationUnit) cu, ctx); actions = visitor.getActionsToApply(); Assert.assertEquals(1, actions.size()); Assert.assertEquals(ActionType.REPLACE, actions.get(0).getType()); assertCode(actions, code, ""public class B {public void foo() {}}""); }","public void testTypeParameters() throws ParseException{ String code = ""public class B { public void foo(){} }""; DefaultJavaParser parser = new DefaultJavaParser(); CompilationUnit cu = parser.parse(code, false); CompilationUnit cu2 = parser.parse(code, false); ClassOrInterfaceDeclaration dec = (ClassOrInterfaceDeclaration) cu.getTypes().get(0); List types = dec.getTypeParameters(); types.add(new TypeParameter(""D"", null)); List actions = getActions(cu2, cu); Assert.assertEquals(1, actions.size()); Assert.assertEquals(ActionType.REPLACE, actions.get(0).getType()); assertCode(actions, code, ""public class B {public void foo() {}}""); cu = parser.parse(code, false); dec = (ClassOrInterfaceDeclaration) cu.getTypes().get(0); types = dec.getTypeParameters(); types.remove(0); types.add(new TypeParameter(""D"", null)); actions = getActions(cu2, cu); Assert.assertEquals(1, actions.size()); Assert.assertEquals(ActionType.REPLACE, actions.get(0).getType()); assertCode(actions, code, ""public class B {public void foo() {}}""); }" 188, ,"public String removeElement(OrderPlaceHolder orderPlaceHolder, Model model){ log.info(""before removeElement: "" + this.order); if (order.getOrderList().size() > 0) this.order.getOrderList().remove(orderPlaceHolder.getIndexToRemove()); List items = itemRepository.findAll(); Type[] types = Type.values(); for (Type type : types) { List tmpList = new ArrayList<>(); for (Item tmpItem : items) { if (tmpItem.getType() == type) { tmpList.add(tmpItem); } } if (tmpList.size() == 0) continue; log.info(""continue for "" + type.toString()); model.addAttribute(type.toString(), tmpList); } model.addAttribute(""orderedItem"", this.order.getOrderList()); log.info(""after removeElement: "" + this.order); log.info(""calling remove element!""); return ""order""; }","public String removeElement(OrderPlaceHolder orderPlaceHolder, Model model){ log.info(""before removeElement: "" + this.order); if (order.getOrderList().size() > 0) this.order.getOrderList().remove(orderPlaceHolder.getIndexToRemove()); itemServiceForSpringModel.addAllItemsToModel(model); orderServiceForSpringModel.addOrderedItemsToModel(model); log.info(""after removeElement: "" + this.order); log.info(""calling remove element!""); return ""order""; }" 189, ,"public AutomationApplication launchOrAttach(String... command) throws Exception{ File file = new File(command[0]); String filename = file.getName(); Kernel32 kernel32 = (Kernel32) Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS); final Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference(); WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0)); boolean found = false; try { while (kernel32.Process32Next(snapshot, processEntry)) { String fname = Native.toString(processEntry.szExeFile); if (fname.equals(filename)) { found = true; break; } } } finally { kernel32.CloseHandle(snapshot); } if (!found) { return this.launch(command); } else { WinNT.HANDLE handle = Kernel32.INSTANCE.OpenProcess(0x0400 | 0x0800 | 0x0001 | 0x00100000, false, processEntry.th32ProcessID.intValue()); if (handle == null) { throw new Exception(Kernel32Util.formatMessageFromLastErrorCode(Kernel32.INSTANCE.GetLastError())); } return new AutomationApplication(new AutomationElement(rootElement), uiAuto, handle); } }","public AutomationApplication launchOrAttach(String... command) throws Exception{ final Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference(); boolean found = Utils.findProcessEntry(processEntry, command); if (!found) { return this.launch(command); } else { WinNT.HANDLE handle = Utils.getHandleFromProcessEntry(processEntry); return new AutomationApplication(new AutomationElement(rootElement), uiAuto, handle); } }" 190, ,"public void assignParkingSlotForMultipleVehicles() throws Exception{ ParkingService instance = new ParkingServiceImpl(); String output = instance.createParkingLot(6); assertTrue(""Createdparkingof6slots"".equalsIgnoreCase(output.trim().replace("" "", """"))); VehicleDetails vehicleDetails1 = new CarDetails(""KA-01-HH-1234""); DriverDetails driverDetails1 = new DriverDetails(21L); String parkingVehicleOutput = instance.parkVehicle(vehicleDetails1, driverDetails1); assertTrue(""CarwithvehicleregistrationNumberKA-01-HH-1234hasbeenparkedatslotnumber1"".equalsIgnoreCase(parkingVehicleOutput.trim().replace("" "", """"))); VehicleDetails vehicleDetails2 = new CarDetails(""KA-02-HH-1234""); DriverDetails driverDetails2 = new DriverDetails(22L); parkingVehicleOutput = instance.parkVehicle(vehicleDetails2, driverDetails2); assertTrue(""CarwithvehicleregistrationNumberKA-02-HH-1234hasbeenparkedatslotnumber2"".equalsIgnoreCase(parkingVehicleOutput.trim().replace("" "", """"))); instance.destroy(); }","public void assignParkingSlotForMultipleVehicles() throws Exception{ ParkingService instance = new ParkingServiceImpl(); String output = instance.createParkingLot(6); assertTrue(""Createdparkingof6slots"".equalsIgnoreCase(output.trim().replace("" "", """"))); VehicleDetails vehicleDetails1 = new CarDetails(""KA-01-HH-1234""); DriverDetails driverDetails1 = new DriverDetails(21L); String parkingVehicleOutput = instance.parkVehicle(vehicleDetails1, driverDetails1); assertTrue(""CarwithvehicleregistrationNumberKA-01-HH-1234hasbeenparkedatslotnumber1"".equalsIgnoreCase(parkingVehicleOutput.trim().replace("" "", """"))); VehicleDetails vehicleDetails2 = new CarDetails(""KA-02-HH-1234""); DriverDetails driverDetails2 = new DriverDetails(22L); parkingVehicleOutput = instance.parkVehicle(vehicleDetails2, driverDetails2); assertTrue(""CarwithvehicleregistrationNumberKA-02-HH-1234hasbeenparkedatslotnumber2"".equalsIgnoreCase(parkingVehicleOutput.trim().replace("" "", """"))); }" 191, ,"public BookingDto cancelBooking(Long bookingId){ String loggedInUser = loggedInUserService.getLoggedInUserDetails().getDisplayName(); Booking bookingDetails = bookingRepository.findById(bookingId).get(); if (bookingDetails.getChangedBy().equalsIgnoreCase(loggedInUser) && bookingDetails.getApprovalStatus().getApprovalName().equalsIgnoreCase(""Draft"")) { bookingRepository.delete(bookingDetails); } else if (bookingDetails.getChangedBy().equalsIgnoreCase(loggedInUser)) { BookingRevision bookingRevision = new BookingRevision(); BookingRevision latestBookingRevision = getLatestRevision(bookingDetails); Long revisionNumber = latestBookingRevision.getRevisionNumber(); ModelMapper modelMapper = new ModelMapper(); modelMapper.map(latestBookingRevision, bookingRevision); ApprovalStatusDm cancelledStatusDetails = approvalStatusDmRepository.findByApprovalName(""Cancelled""); bookingRevision.setRevisionNumber(revisionNumber + 1); bookingRevision.setChangedBy(loggedInUser); bookingRevision.setApprovalStatus(cancelledStatusDetails); bookingRevision.setChangedDate(new Timestamp(System.currentTimeMillis())); bookingRevision.setBookingRevisionId(null); bookingDetails.setApprovalStatus(cancelledStatusDetails); bookingDetails.setChangedBy(loggedInUser); bookingDetails.setChangedDate(new Timestamp(System.currentTimeMillis())); bookingDetails.addBookingRevision(bookingRevision); Booking savedBooking = bookingRepository.save(bookingDetails); return retrieveBookingDetails(savedBooking.getBookingId()); } return new BookingDto(); }","public BookingDto cancelBooking(Long bookingId){ String loggedInUser = loggedInUserService.getLoggedInUserDetails().getDisplayName(); Booking booking = bookingRepository.findById(bookingId).get(); if (booking.getChangedBy().equalsIgnoreCase(loggedInUser) && ApprovalStatusConstant.APPROVAL_DRAFT.getApprovalStatusId().equals(booking.getApprovalStatus().getApprovalStatusId())) { bookingRepository.delete(booking); } else if (booking.getChangedBy().equalsIgnoreCase(loggedInUser)) { BookingRevision latestBookingRevision = getLatestRevision(booking); saveBooking(booking, latestBookingRevision, ApprovalStatusConstant.APPROVAL_CANCELLED.getApprovalStatusId(), loggedInUserService.getLoggedInUserDetails()); return retrieveBookingDetails(bookingId); } return new BookingDto(); }" 192, ,"private Supplier wrapTry(CacheFactory supplier){ if (supplier == null) { return null; } return () -> { try { return supplier.get(); } catch (Throwable e) { logger.error(""fail to create obj."", e); ; return null; } }; }","private Supplier wrapTry(CacheFactory supplier){ if (supplier == null) { return null; } return () -> { try { return supplier.get(); } catch (Throwable e) { logger.error(""fail to create obj."", e); return null; } }; }" 193, ,"public void calculate(){ Arithmetic arithmetic = new Arithmetic(); Number result = arithmetic.calculate(6l, 3l, Operator.ADD); assertThat(result instanceof Long); assertThat(result.longValue() == 9); result = arithmetic.calculate(6l, 3l, Operator.ADD); assertThat(result instanceof Long); assertThat(result.longValue() == 3); result = arithmetic.calculate(6l, 3l, Operator.ADD); assertThat(result instanceof Long); assertThat(result.longValue() == 18); result = arithmetic.calculate(6l, 3l, Operator.DIV); assertThat(result instanceof Long); assertThat(result.longValue() == 2); }","public void calculate(){ Arithmetic arithmetic = new Arithmetic(); Number result = arithmetic.calculate(6l, 3l, Operator.ADD); assertThat(result.longValue()).isEqualTo(9); result = arithmetic.calculate(6l, 3l, Operator.SUB); assertThat(result.longValue() == 3); result = arithmetic.calculate(6l, 3l, Operator.MUL); assertThat(result.longValue() == 18); result = arithmetic.calculate(6l, 3l, Operator.DIV); assertThat(result.longValue() == 2); }" 194, ,"public RDFPatch fetch(Id key){ String s3Key = idToKey(key); try { S3Object x = client.getObject(bucketName, s3Key); x.getObjectMetadata(); S3ObjectInputStream input = x.getObjectContent(); RDFPatch patch = RDFPatchOps.read(input); return patch; } catch (AmazonServiceException awsEx) { switch(awsEx.getStatusCode()) { case HttpSC.NOT_FOUND_404: case HttpSC.FORBIDDEN_403: return null; case HttpSC.MOVED_PERMANENTLY_301: { System.err.println(""301 Location: "" + awsEx.getHttpHeaders().get(HttpNames.hLocation)); return null; } } throw awsEx; } }","public RDFPatch fetch(final Id key){ String s3Key = idToKey(key); try { S3Object x = client.getObject(bucketName, s3Key); x.getObjectMetadata(); S3ObjectInputStream input = x.getObjectContent(); return RDFPatchOps.read(input); } catch (AmazonServiceException awsEx) { switch(awsEx.getStatusCode()) { case HttpSC.NOT_FOUND_404: case HttpSC.FORBIDDEN_403: return null; case HttpSC.MOVED_PERMANENTLY_301: { System.err.println(""301 Location: "" + awsEx.getHttpHeaders().get(HttpNames.hLocation)); return null; } } throw awsEx; } }" 195, ,"public void onDirectory(FsImageProto.INodeSection.INode inode, String path){ FsImageProto.INodeSection.INodeDirectory d = inode.getDirectory(); PermissionStatus p = loader.getPermissionStatus(d.getPermission()); if (LOG.isDebugEnabled()) { LOG.debug(""Visiting directory {}"", path + (""/"".equals(path) ? """" : ""/"") + inode.getName().toStringUtf8()); } final String groupName = p.getGroupName(); final GroupStats groupStat = report.groupStats.computeIfAbsent(groupName, report.createGroupStats); synchronized (groupStat) { groupStat.sumDirectories++; } final String userName = p.getUserName(); final UserStats userStat = report.userStats.computeIfAbsent(userName, report.createUserStat); synchronized (userStat) { userStat.sumDirectories++; } synchronized (overallStats) { overallStats.sumDirectories++; } }","public void onDirectory(FsImageProto.INodeSection.INode inode, String path){ FsImageProto.INodeSection.INodeDirectory d = inode.getDirectory(); PermissionStatus p = loader.getPermissionStatus(d.getPermission()); if (LOG.isDebugEnabled()) { LOG.debug(""Visiting directory {}"", path + (""/"".equals(path) ? """" : ""/"") + inode.getName().toStringUtf8()); } final String groupName = p.getGroupName(); final GroupStats groupStat = report.groupStats.computeIfAbsent(groupName, report.createGroupStats); groupStat.sumDirectories.increment(); final String userName = p.getUserName(); final UserStats userStat = report.userStats.computeIfAbsent(userName, report.createUserStat); userStat.sumDirectories.increment(); overallStats.sumDirectories.increment(); }" 196, ,"public boolean equals(final Object obj){ if (this == obj) { return true; } if (!(obj instanceof ModuleEffectiveStatementImpl)) { return false; } ModuleEffectiveStatementImpl other = (ModuleEffectiveStatementImpl) obj; if (!Objects.equals(getName(), other.getName())) { return false; } if (!qnameModule.equals(other.qnameModule)) { return false; } if (!Objects.equals(getYangVersion(), other.getYangVersion())) { return false; } return true; }","public boolean equals(final Object obj){ if (this == obj) { return true; } if (!(obj instanceof ModuleEffectiveStatementImpl)) { return false; } ModuleEffectiveStatementImpl other = (ModuleEffectiveStatementImpl) obj; return Objects.equals(getName(), other.getName()) && qnameModule.equals(other.qnameModule) && Objects.equals(getYangVersion(), other.getYangVersion()); }" 197, ,"public static void writeTestDecodingAndEncoding(List cities, List vehicles, Depot depot, Map> routes){ Decoder decoder = new Decoder(cities); Integer[][] array = decoder.decodeResult(routes); buildTitleOnConsole(""Decoding""); for (int i = 0; i < vehicles.size(); i++) { System.out.println(""Vehicle = "" + routes.keySet().toArray()[i].toString()); for (int j = 0; j < cities.size(); j++) { System.out.print(array[i][j] + "";""); } System.out.println(); } buildTitleOnConsole(""Encoding""); Encoder encoder = new Encoder(cities, array); Result result = encoder.encodeResult(vehicles, Utils.getDepotByCity(depot)); for (Map.Entry> entry : result.getRoutes().entrySet()) { System.out.println(""Vehicle = "" + entry.getKey()); entry.getValue().forEach(city -> System.out.print(city.getName() + "" "")); System.out.println(); System.out.println(); } }","public static void writeTestDecodingAndEncoding(List cities, List vehicles, Depot depot, Map> routes){ Decoder decoder = new Decoder(cities); Integer[][] array = decoder.decodeResult(routes); buildTitleOnConsole(""Decoding""); for (int i = 0; i < vehicles.size(); i++) { System.out.println(""Vehicle = "" + routes.keySet().toArray()[i].toString()); for (int j = 0; j < cities.size(); j++) { System.out.print(array[i][j] + "";""); } System.out.println(); } buildTitleOnConsole(""Encoding""); Result result = new Encoder(vehicles, cities, Utils.getDepotByCity(depot), array).encodeResult(); for (Map.Entry> entry : result.getRoutes().entrySet()) { System.out.println(""Vehicle = "" + entry.getKey()); entry.getValue().forEach(city -> System.out.print(city.getName() + "" "")); System.out.println(); System.out.println(); } }" 198, ,"public Key max(){ if (isEmpty()) throw new NoSuchElementException(""called max() with empty set""); return set.last(); }","public Key max(){ noSuchElement(isEmpty(), ""called max() with empty set""); return set.last(); }" 199, ,"protected boolean setOtherFields(Variant variant, String fileId, String studyId, Set ids, float quality, String filter, String info, String format, int numAllele, String[] alternateAlleles, String line) throws NonVariantException{ variant.setIds(ids); VariantSourceEntry sourceEntry = variant.getSourceEntry(fileId, studyId); if (quality > -1) { sourceEntry.addAttribute(""QUAL"", String.valueOf(quality)); } if (!filter.isEmpty()) { sourceEntry.addAttribute(""FILTER"", filter); } boolean hasCountsOrFrequenciesInInfoField = false; if (!info.isEmpty()) { hasCountsOrFrequenciesInInfoField = parseInfo(variant, fileId, studyId, info, numAllele); } sourceEntry.setFormat(format); sourceEntry.addAttribute(""src"", line); boolean hasGTCInfoTag = false; if (tagMap == null) { hasGTCInfoTag = parseEVSAttributes(variant, fileId, studyId, numAllele, alternateAlleles); } else { hasGTCInfoTag = parseCohortEVSInfo(variant, sourceEntry, numAllele, alternateAlleles); } return hasCountsOrFrequenciesInInfoField || hasGTCInfoTag; }","protected void setOtherFields(Variant variant, String fileId, String studyId, Set ids, float quality, String filter, String info, String format, int numAllele, String[] alternateAlleles, String line){ variant.setIds(ids); VariantSourceEntry sourceEntry = variant.getSourceEntry(fileId, studyId); if (quality > -1) { sourceEntry.addAttribute(""QUAL"", String.valueOf(quality)); } if (!filter.isEmpty()) { sourceEntry.addAttribute(""FILTER"", filter); } if (!info.isEmpty()) { parseInfo(variant, fileId, studyId, info, numAllele); } sourceEntry.setFormat(format); sourceEntry.addAttribute(""src"", line); if (tagMap == null) { parseEVSAttributes(variant, fileId, studyId, numAllele, alternateAlleles); } else { parseCohortEVSInfo(variant, sourceEntry, numAllele, alternateAlleles); } }" 200, ,"public String addOrder(@ModelAttribute(""orderDTO"") @Valid final OrderDTO orderDTO, final BindingResult bindingResult, final RedirectAttributes redirectAttributes, final Locale locale){ java.sql.Date startSqlDate = StringToSqlDateParser(orderDTO.getStartDate()); if (orderDTO.getStartDate() != null && !orderDTO.getStartDate().isEmpty() && startSqlDate == null) { bindingResult.rejectValue(""startDate"", ""typeMismatch.order.start"", null); } if (orderDTO.getOrderStatusId() != 0 && orderDTO.getManager().contentEquals(""-"") && !orderStatusSvc.getOrderStatusById(orderDTO.getOrderStatusId()).getOrderStatusName().contentEquals(""pending"")) { bindingResult.rejectValue(""manager"", ""error.adminpage.managerRequired"", null); } if (bindingResult.hasErrors()) { redirectAttributes.addFlashAttribute(""org.springframework.validation.BindingResult.orderDTO"", bindingResult); redirectAttributes.addFlashAttribute(""orderDTO"", orderDTO); return ""redirect:/adminpageorders#add_new_order""; } Order newOrder = new Order(); newOrder.setStart(startSqlDate); newOrder.setManager(orderDTO.getManager()); if (orderSvc.add(newOrder, orderDTO.getClientId(), orderDTO.getRepairTypeId(), orderDTO.getMachineId(), orderDTO.getOrderStatusId())) { changeSessionScopeAddingInfo(messageSource.getMessage(""popup.adminpage.orderAdded"", null, locale), """"); } else { changeSessionScopeAddingInfo("""", messageSource.getMessage(""popup.adminpage.orderNotAdded"", null, locale)); } return ""redirect:/adminpageorders""; }","public String addOrder(@ModelAttribute(""dataObject"") @Valid final OrderDTO orderDTO, final BindingResult bindingResult, final RedirectAttributes redirectAttributes, final Locale locale){ java.sql.Date startSqlDate = StringToSqlDateParser(orderDTO.getStartDate()); if (orderDTO.getStartDate() != null && !orderDTO.getStartDate().isEmpty() && startSqlDate == null) { bindingResult.rejectValue(""startDate"", ""typeMismatch.order.start"", null); } if (orderDTO.getOrderStatusId() != 0 && orderDTO.getManager().contentEquals(""-"") && !orderStatusSvc.getOrderStatusById(orderDTO.getOrderStatusId()).getOrderStatusName().contentEquals(""pending"")) { bindingResult.rejectValue(""manager"", ""error.adminpage.managerRequired"", null); } if (bindingResult.hasErrors()) { redirectAttributes.addFlashAttribute(""org.springframework.validation.BindingResult.dataObject"", bindingResult); redirectAttributes.addFlashAttribute(""dataObject"", orderDTO); return ""redirect:/adminpageorders#add_new_order""; } Order newOrder = new Order(); newOrder.setStart(startSqlDate); newOrder.setManager(orderDTO.getManager()); addMessages(orderSvc.add(newOrder, orderDTO.getClientId(), orderDTO.getRepairTypeId(), orderDTO.getMachineId(), orderDTO.getOrderStatusId()), ""popup.adminpage.orderAdded"", ""popup.adminpage.orderNotAdded"", locale); return ""redirect:/adminpageorders""; }" 201, ,"private void validateIndex(int i){ checkArgument(i >= 0, ""index is negative: "" + i); checkArgument(i < maxN, ""index >= capacity: "" + i); }","private void validateIndex(int i){ checkIndexInRange(i, 0, maxN); }" 202, ,"public boolean isValidComponentSelector1ForDataset(String cs1, String dataset){ String datasetPath = String.format(""/DatasetSelectors/DatasetSelector/Datasets/Dataset[text()='%s']/../.."", dataset); String csAttrPath = String.format(""ComponentSelector[@kind='%s'] | ComponentSelector[@minimum <= '%s' and @maximum >= '%s']"", cs1, cs1, cs1); XPath xPath = XPathFactory.newInstance().newXPath(); XPathExpression datasetExp = null; NodeList selector = null; try { datasetExp = xPath.compile(datasetPath); selector = (NodeList) datasetExp.evaluate(doc, XPathConstants.NODESET); } catch (XPathExpressionException e) { return false; } if (selector.getLength() == 0) { return false; } XPathExpression csAttrExp = null; NodeList csNodes = null; try { csAttrExp = xPath.compile(csAttrPath); csNodes = (NodeList) csAttrExp.evaluate(selector.item(0), XPathConstants.NODESET); } catch (XPathExpressionException e) { return false; } if (csNodes.getLength() > 0) { return true; } return false; }","public boolean isValidComponentSelector1ForDataset(String cs1, String dataset){ String datasetPath = String.format(DATASETS_QUERY, dataset); String csAttrPath = String.format(""ComponentSelector[@kind='%s'] | ComponentSelector[@minimum <= '%s' and @maximum >= '%s']"", cs1, cs1, cs1); NodeList selector = null; try { selector = compileAndEvaluate(datasetPath, doc); } catch (XPathExpressionException e) { return false; } if (selector.getLength() == 0) { return false; } NodeList csNodes = null; try { csNodes = compileAndEvaluate(csAttrPath, selector.item(0)); } catch (XPathExpressionException e) { return false; } if (csNodes.getLength() > 0) { return true; } return false; }" 203, ,"private void print(int x, int y, String text, Ansi.Color colour){ if (chess.side != PieceColour.WHITE) { System.out.println(Ansi.ansi().cursor(19 - y, 38 - x).fg(colour).a(text)); System.out.println(Ansi.ansi().cursor(19 - y, 38 - x).fg(colour).a(text)); } else { System.out.println(Ansi.ansi().cursor(1 + y, x).fg(colour).a(text)); System.out.println(Ansi.ansi().cursor(1 + y, x).fg(colour).a(text)); } }","private void print(int x, int y, String text, Ansi.Color colour){ if (chess.side != PieceColour.WHITE) { System.out.println(Ansi.ansi().cursor(19 - y, 38 - x).fg(colour).a(text)); } else { System.out.println(Ansi.ansi().cursor(1 + y, x).fg(colour).a(text)); } }" 204, ,"public void requestDistributedSuggestions(long splitId, ModelAggregator modelAggrProc){ this.isSplitting = true; this.suggestionCtr = 0; this.thrownAwayInstance = 0; ComputeContentEvent cce = new ComputeContentEvent(splitId, this.id, this.getObservedClassDistribution()); cce.setEnsembleId(this.ensembleId); modelAggrProc.sendToControlStream(cce); }","public void requestDistributedSuggestions(long splitId, ModelAggregatorProcessor modelAggrProc){ this.isSplitting = true; this.suggestionCtr = 0; this.thrownAwayInstance = 0; ComputeContentEvent cce = new ComputeContentEvent(splitId, this.id, this.getObservedClassDistribution()); modelAggrProc.sendToControlStream(cce); }" 205, ,"public void testSelectRequest_Filter_CayenneExp(){ @SuppressWarnings(""unchecked"") MultivaluedMap params = mock(MultivaluedMap.class); when(params.getFirst(""cayenneExp"")).thenReturn(""{\""exp\"" : \""address = '1 Main Street'\""}""); when(params.getFirst(SenchaRequestParser.FILTER)).thenReturn(""[{\""property\"":\""name\"",\""value\"":\""xyz\""}]""); UriInfo uriInfo = mock(UriInfo.class); when(uriInfo.getQueryParameters()).thenReturn(params); ResourceEntity resourceEntity = parser.parseSelect(getLrEntity(E2.class), uriInfo, null); assertNotNull(resourceEntity.getQualifier()); assertEquals(exp(""address = '1 Main Street' and name likeIgnoreCase 'xyz%'""), resourceEntity.getQualifier()); }","public void testSelectRequest_Filter_CayenneExp(){ @SuppressWarnings(""unchecked"") MultivaluedMap params = mock(MultivaluedMap.class); when(params.get(""cayenneExp"")).thenReturn(Collections.singletonList(""{\""exp\"" : \""address = '1 Main Street'\""}"")); when(params.get(SenchaRequestParser.FILTER)).thenReturn(Collections.singletonList(""[{\""property\"":\""name\"",\""value\"":\""xyz\""}]"")); ResourceEntity resourceEntity = parser.parseSelect(getLrEntity(E2.class), params, null); assertNotNull(resourceEntity.getQualifier()); assertEquals(exp(""address = '1 Main Street' and name likeIgnoreCase 'xyz%'""), resourceEntity.getQualifier()); }" 206, ,"public void testContactFilterForNo(){ profiles = ProfileUtility.getProfiles(); criteria = new MatchSearchCriteria(); criteria.setPhoto(MatchConstants.NO); List filteredProfiles = photoFilter.filter(profiles, criteria); assertEquals(0, filteredProfiles.size()); }","public void testContactFilterForNo(){ criteria = new MatchSearchCriteria(); criteria.setPhoto(MatchConstants.NO); List filteredProfiles = photoFilter.filter(profiles, criteria); assertEquals(0, filteredProfiles.size()); }" 207, ,"public void addPage(IPage page){ Connection conn = null; try { conn = this.getConnection(); conn.setAutoCommit(false); String pageCode = page.getCode(); this.addPageRecord(page, conn); Date now = new Date(); PageMetadata draftMetadata = page.getMetadata(); if (draftMetadata == null) { draftMetadata = new PageMetadata(); } draftMetadata.setUpdatedAt(now); this.addDraftPageMetadata(pageCode, draftMetadata, conn); this.addWidgetForPage(page, WidgetConfigDest.DRAFT, conn); conn.commit(); } catch (Throwable t) { this.executeRollback(conn); _logger.error(""Error while adding a new page"", t); throw new RuntimeException(""Error while adding a new page"", t); } finally { closeConnection(conn); } }","public void addPage(IPage page){ Connection conn = null; try { conn = this.getConnection(); conn.setAutoCommit(false); String pageCode = page.getCode(); this.addPageRecord(page, conn); PageMetadata draftMetadata = page.getMetadata(); if (draftMetadata == null) { draftMetadata = new PageMetadata(); } draftMetadata.setUpdatedAt(new Date()); this.addDraftPageMetadata(pageCode, draftMetadata, conn); this.addWidgetForPage(page, WidgetConfigDest.DRAFT, conn); conn.commit(); } catch (Throwable t) { this.executeRollback(conn); _logger.error(""Error while adding a new page"", t); throw new RuntimeException(""Error while adding a new page"", t); } finally { closeConnection(conn); } }" 208, ,"public User createUser(User newUser){ Connection newConnection = DbConnection.getDbConnection(); try { String sql = ""insert into \""user\""(person_id, user_name,"" + "" password, role) values (?,?,?,?) returning user_id;""; PreparedStatement createUserStatement = newConnection.prepareStatement(sql); createUserStatement.setInt(1, newUser.getPersonId()); createUserStatement.setString(2, newUser.getUserName()); createUserStatement.setString(3, newUser.getPassword()); createUserStatement.setString(4, newUser.getRole()); ResultSet result = createUserStatement.executeQuery(); if (result.next()) { newUser.setPersonId(result.getInt(""user_Id"")); } } catch (SQLException e) { BankAppLauncher.appLogger.catching(e); BankAppLauncher.appLogger.error(""Internal error occured in the database""); } return newUser; }","public User createUser(User newUser){ Connection newConnection = DbConnection.getDbConnection(); try { String sql = ""insert into \""user\""(person_id, user_name,"" + "" password, role) values (?,?,?,?) returning user_id;""; PreparedStatement createUserStatement = newConnection.prepareStatement(sql); createUserStatement.setInt(1, newUser.getPersonId()); createUserStatement.setString(2, newUser.getUserName()); createUserStatement.setString(3, newUser.getPassword()); createUserStatement.setString(4, newUser.getRole()); ResultSet result = createUserStatement.executeQuery(); if (result.next()) { newUser.setPersonId(result.getInt(""user_Id"")); } } catch (SQLException e) { BankAppLauncher.appLogger.error(""Internal error occured in the database""); } return newUser; }" 209, ,"public Parking createParking(ParkingData parkingData){ ParkingBuilder parkingBuilder = new ParkingBuilder().withSquareSize(parkingData.getSize()); for (Integer i : parkingData.getPedestrianExits()) { parkingBuilder.withPedestrianExit(i); } Parking parking = parkingBuilder.build(); parkingRepository.save(parking); return parking; }","public Parking createParking(ParkingData parkingData){ ParkingBuilder parkingBuilder = new ParkingBuilder().withSquareSize(parkingData.getSize()); parkingData.getPedestrianExits().forEach(parkingBuilder::withPedestrianExit); Parking parking = parkingBuilder.build(); parkingRepository.save(parking); return parking; }" 210, ,"private static Future> grabLocksInThread(final CycleDetectingLock lock1, final CycleDetectingLock lock2, final CyclicBarrier barrier){ FutureTask> future = new FutureTask>(new Callable>() { @Override public ListMultimap call() throws Exception { assertTrue(lock1.lockOrDetectPotentialLocksCycle().isEmpty()); barrier.await(); ListMultimap cycle = lock2.lockOrDetectPotentialLocksCycle(); if (cycle == null) { lock2.unlock(); } lock1.unlock(); return cycle; } }); Thread thread = new Thread(future); thread.start(); return future; }","private static Future> grabLocksInThread(final CycleDetectingLock lock1, final CycleDetectingLock lock2, final CyclicBarrier barrier){ FutureTask> future = new FutureTask>(() -> { assertTrue(lock1.lockOrDetectPotentialLocksCycle().isEmpty()); barrier.await(); ListMultimap cycle = lock2.lockOrDetectPotentialLocksCycle(); if (cycle == null) { lock2.unlock(); } lock1.unlock(); return cycle; }); Thread thread = new Thread(future); thread.start(); return future; }" 211, ,"public Builder user_id(final String user_id){ assert (user_id != null); assert (!user_id.equals("""")); return setPathParameter(""user_id"", user_id); }","public Builder user_id(final String user_id){ assertHasAndNotNull(user_id); return setPathParameter(""user_id"", user_id); }" 212, ,"public GetShortUrlsResponse getExistingShortenedUrls(@ParameterObject Pageable pageable){ log.info(""Received request to get existing shortened URLs with pageable {}"", pageable); GetShortUrlsResponse getShortUrlsResponse = urlShortenerService.getShortUrls(pageable); log.info(""Successfully retrieved existing shortened URLs: {}"", getShortUrlsResponse); return getShortUrlsResponse; }","public GetShortUrlsResponse getExistingShortenedUrls(@ParameterObject Pageable pageable){ return shortUrlRetrievalService.getShortUrls(pageable); }" 213, ,"public void testArgumentList() throws ParseException{ String code = ""public class B{ public void foo(){ print(3); } }""; DefaultJavaParser parser = new DefaultJavaParser(); CompilationUnit cu = parser.parse(code, false); CompilationUnit cu2 = parser.parse(code, false); MethodDeclaration md = (MethodDeclaration) cu.getTypes().get(0).getMembers().get(0); ExpressionStmt stmt = (ExpressionStmt) md.getBody().getStmts().get(0); MethodCallExpr expr = (MethodCallExpr) stmt.getExpression(); expr.getArgs().add(new IntegerLiteralExpr(""4"")); ChangeLogVisitor visitor = new ChangeLogVisitor(); VisitorContext ctx = new VisitorContext(); ctx.put(ChangeLogVisitor.NODE_TO_COMPARE_KEY, cu2); visitor.visit((CompilationUnit) cu, ctx); List actions = visitor.getActionsToApply(); Assert.assertEquals(1, actions.size()); Assert.assertEquals(ActionType.REPLACE, actions.get(0).getType()); assertCode(actions, code, ""public class B{ public void foo(){ print(3, 4); } }""); }","public void testArgumentList() throws ParseException{ String code = ""public class B{ public void foo(){ print(3); } }""; DefaultJavaParser parser = new DefaultJavaParser(); CompilationUnit cu = parser.parse(code, false); CompilationUnit cu2 = parser.parse(code, false); MethodDeclaration md = (MethodDeclaration) cu.getTypes().get(0).getMembers().get(0); ExpressionStmt stmt = (ExpressionStmt) md.getBody().getStmts().get(0); MethodCallExpr expr = (MethodCallExpr) stmt.getExpression(); expr.getArgs().add(new IntegerLiteralExpr(""4"")); List actions = getActions(cu2, cu); Assert.assertEquals(1, actions.size()); Assert.assertEquals(ActionType.REPLACE, actions.get(0).getType()); assertCode(actions, code, ""public class B{ public void foo(){ print(3, 4); } }""); }" 214, ,"public OSService[] getServices(){ OSProcess[] process = getChildProcesses(1, 0, OperatingSystem.ProcessSort.PID); File etc = new File(""/etc/inittab""); try { File[] files = etc.listFiles(); OSService[] svcArray = new OSService[files.length]; for (int i = 0; i < files.length; i++) { svcArray[i].setName(files[i].getName()); for (int j = 0; j < process.length; j++) { if (process[j].getName().equals(files[i].getName())) { svcArray[i].setProcessID(process[j].getProcessID()); svcArray[i].setState(OSService.State.RUNNING); } else { svcArray[i].setState(OSService.State.STOPPED); } } } return svcArray; } catch (NullPointerException ex) { LOG.error(""Directory: /etc/inittab does not exist""); return new OSService[0]; } }","public OSService[] getServices(){ OSProcess[] process = getChildProcesses(1, 0, OperatingSystem.ProcessSort.PID); File etc = new File(""/etc/inittab""); if (etc.exists()) { File[] files = etc.listFiles(); OSService[] svcArray = new OSService[files.length]; for (int i = 0; i < files.length; i++) { for (int j = 0; j < process.length; j++) { if (process[j].getName().equals(files[i].getName())) { svcArray[i] = new OSService(process[j].getName(), process[j].getProcessID(), RUNNING); } else { svcArray[i] = new OSService(files[i].getName(), 0, STOPPED); } } } return svcArray; } LOG.error(""Directory: /etc/inittab does not exist""); return new OSService[0]; }" 215, ," static int subarraySum(int[] nums, int k){ final int n = nums.length; final Map m = new HashMap<>(); m.put(0, 1); int sum = 0; int c = 0; for (int i = 0; i < n; i++) { sum = sum + nums[i]; if (m.containsKey(sum - k)) c = c + m.getOrDefault(sum - k, 0); m.merge(sum, 1, Integer::sum); } return c; }"," static int subarraySum(int[] nums, int k){ final int n = nums.length; final Map m = new HashMap<>(); m.put(0, 1); int sum = 0; int c = 0; for (int i = 0; i < n; i++) { sum = sum + nums[i]; c = c + m.getOrDefault(sum - k, 0); m.merge(sum, 1, Integer::sum); } return c; }" 216, ,"public FxNode eval(FxChildWriter dest, FxEvalContext ctx, FxNode src){ FxObjNode srcObj = (FxObjNode) src; String message = FxNodeValueUtils.getStringOrThrow(srcObj, ""message""); String level = FxNodeValueUtils.getOrDefault(srcObj, ""level"", ""info""); level = level.toLowerCase(); switch(level) { case ""trace"": logger.trace(message); break; case ""debug"": logger.debug(message); break; case ""info"": logger.info(message); break; case ""warn"": case ""warning"": logger.warn(message); break; case ""error"": logger.error(message); break; default: logger.info(message); break; } return null; }","public void eval(FxChildWriter dest, FxEvalContext ctx, FxNode src){ FxObjNode srcObj = (FxObjNode) src; String message = FxNodeValueUtils.getStringOrThrow(srcObj, ""message""); String level = FxNodeValueUtils.getOrDefault(srcObj, ""level"", ""info""); level = level.toLowerCase(); switch(level) { case ""trace"": logger.trace(message); break; case ""debug"": logger.debug(message); break; case ""info"": logger.info(message); break; case ""warn"": case ""warning"": logger.warn(message); break; case ""error"": logger.error(message); break; default: logger.info(message); break; } }" 217, ,"private void calculateBrowsers(String logLine, Context context){ if (logLine.contains(""Mozilla"")) { context.getCounter(""browser"", ""Mozilla"").increment(1); } else if (logLine.contains(""MSIE"")) { context.getCounter(""browser"", ""MSIE"").increment(1); } else if (logLine.contains(""Opera"")) { context.getCounter(""browser"", ""Opera"").increment(1); } else { context.getCounter(""browser"", ""Other"").increment(1); } }","private void calculateBrowsers(String logLine, Context context){ if (logLine.contains(""Mozilla"")) { context.getCounter(""browser"", ""Mozilla"").increment(1); } else if (logLine.contains(""Opera"")) { context.getCounter(""browser"", ""Opera"").increment(1); } else { context.getCounter(""browser"", ""Other"").increment(1); } }" 218, ,"public void execute() throws MojoExecutionException{ if (project.isExecutionRoot()) { String finalSuffix = null; if (backup) { LocalDateTime localDateTime = LocalDateTime.now(); if (suffix == null || suffix.isEmpty()) { finalSuffix = Common.getFormattedTimestamp(localDateTime); } else { finalSuffix = suffix; } } if (mainClass == null || mainClass.isEmpty()) { getLog().error(""Unknown main class: use -DmainClass=com.mycompany.app.App\n""); System.exit(1); } else { if (binName == null || binName.isEmpty()) { binName = mainClass; getLog().warn(""binary name is set to main class: -DbinName="" + binName); } try { Common.generateBinary(getLog(), project.getBasedir().getAbsolutePath(), mainClass, binName, finalSuffix); } catch (MojoExecutionException e) { getLog().error(e.getMessage()); } } } else { getLog().info(""skipping""); } }","public void execute() throws MojoExecutionException{ if (project.isExecutionRoot()) { String finalSuffix = null; if (backup) { finalSuffix = Common.getBackupSuffix(suffix); } if (mainClass == null || mainClass.isEmpty()) { getLog().error(""Unknown main class: use -DmainClass=com.mycompany.app.App\n""); System.exit(1); } else { if (binName == null || binName.isEmpty()) { binName = mainClass; getLog().warn(""binary name is set to main class: -DbinName="" + binName); } try { Common.generateBinary(getLog(), project.getBasedir().getAbsolutePath(), mainClass, binName, finalSuffix); } catch (MojoExecutionException e) { getLog().error(e.getMessage()); } } } else { getLog().info(""skipping""); } }" 219, ,"private boolean validate(){ final Optional command = this.arguments.getCommand(); boolean ok = false; if (!command.isPresent()) { this.error = ""Missing command""; this.suggestion = ""Add one of "" + listCommands(); } else if (TraceCommand.COMMAND_NAME.equals(command.get())) { ok = validateTraceCommand(); } else if (ConvertCommand.COMMAND_NAME.equals(command.get())) { ok = validateConvertCommand(); } else { final String nullableCommand = command.isPresent() ? command.get() : null; this.error = ""'"" + nullableCommand + ""' is not an OFT command.""; this.suggestion = ""Choose one of "" + listCommands() + "".""; } return ok; }","private boolean validate(){ final Optional command = this.arguments.getCommand(); boolean ok = false; if (!command.isPresent()) { this.error = ""Missing command""; this.suggestion = ""Add one of "" + listCommands(); } else if (TraceCommand.COMMAND_NAME.equals(command.get())) { ok = validateTraceCommand(); } else if (ConvertCommand.COMMAND_NAME.equals(command.get())) { ok = validateConvertCommand(); } else { this.error = ""'"" + command.orElse(null) + ""' is not an OFT command.""; this.suggestion = ""Choose one of "" + listCommands() + "".""; } return ok; }" 220, ,"public GreenHouse parseXml(String path){ XMLInputFactory factory = XMLInputFactory.newInstance(); FlowerStack flowerStack = new FlowerStack(); GreenHouse greenHouse = new GreenHouse(); flowerStack.push(new AliveFlower()); try { XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(path)); while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); switch(event.getEventType()) { case XMLStreamConstants.START_ELEMENT: StartElement startElement = event.asStartElement(); String qName = startElement.getName().getLocalPart(); elementStart(flowerStack, qName); break; case XMLStreamConstants.CHARACTERS: Characters characters = event.asCharacters(); chars(characters.getData()); break; case XMLStreamConstants.END_ELEMENT: EndElement endElement = event.asEndElement(); elementEnd(flowerStack, endElement.getName().getLocalPart(), greenHouse); break; } } } catch (XMLStreamException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; }","public GreenHouse parseXml(String path){ XMLInputFactory factory = XMLInputFactory.newInstance(); GreenHouse greenHouse = new GreenHouse(); try { XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(path)); while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); switch(event.getEventType()) { case XMLStreamConstants.START_ELEMENT: StartElement startElement = event.asStartElement(); String qName = startElement.getName().getLocalPart(); elementStart(qName); break; case XMLStreamConstants.CHARACTERS: Characters characters = event.asCharacters(); chars(characters.getData()); break; case XMLStreamConstants.END_ELEMENT: EndElement endElement = event.asEndElement(); elementEnd(endElement.getName().getLocalPart(), greenHouse); break; } } } catch (XMLStreamException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } return greenHouse; }" 221, ,"public void removeBannedDependencies(Collection artifacts){ if (!bannedArtifacts.isEmpty() && artifacts != null) { for (Iterator it = artifacts.iterator(); it.hasNext(); ) { Artifact artifact = it.next(); if (bannedArtifacts.containsKey(artifact)) { it.remove(); } } } }","public void removeBannedDependencies(Collection artifacts){ if (!bannedArtifacts.isEmpty() && artifacts != null) { artifacts.removeIf(artifact -> bannedArtifacts.containsKey(artifact)); } }" 222, ,"public void test_getServiceUserID(){ ServiceUserMapperImpl.Config config = mock(ServiceUserMapperImpl.Config.class); when(config.user_mapping()).thenReturn(new String[] { BUNDLE_SYMBOLIC1 + ""="" + SAMPLE, BUNDLE_SYMBOLIC2 + ""="" + ANOTHER, BUNDLE_SYMBOLIC1 + "":"" + SUB + ""="" + SAMPLE_SUB, BUNDLE_SYMBOLIC2 + "":"" + SUB + ""="" + ANOTHER_SUB }); when(config.user_default()).thenReturn(NONE); when(config.user_enable_default_mapping()).thenReturn(false); final ServiceUserMapperImpl sum = new ServiceUserMapperImpl(); sum.configure(null, config); TestCase.assertEquals(SAMPLE, sum.getServiceUserID(BUNDLE1, null)); TestCase.assertEquals(ANOTHER, sum.getServiceUserID(BUNDLE2, null)); TestCase.assertEquals(SAMPLE, sum.getServiceUserID(BUNDLE1, """")); TestCase.assertEquals(ANOTHER, sum.getServiceUserID(BUNDLE2, """")); TestCase.assertEquals(SAMPLE_SUB, sum.getServiceUserID(BUNDLE1, SUB)); TestCase.assertEquals(ANOTHER_SUB, sum.getServiceUserID(BUNDLE2, SUB)); TestCase.assertEquals(NONE, sum.getServiceUserID(BUNDLE3, null)); TestCase.assertEquals(NONE, sum.getServiceUserID(BUNDLE3, SUB)); }","public void test_getServiceUserID(){ ServiceUserMapperImpl.Config config = mock(ServiceUserMapperImpl.Config.class); when(config.user_mapping()).thenReturn(new String[] { BUNDLE_SYMBOLIC1 + ""="" + SAMPLE, BUNDLE_SYMBOLIC2 + ""="" + ANOTHER, BUNDLE_SYMBOLIC1 + "":"" + SUB + ""="" + SAMPLE_SUB, BUNDLE_SYMBOLIC2 + "":"" + SUB + ""="" + ANOTHER_SUB }); when(config.user_default()).thenReturn(NONE); when(config.user_enable_default_mapping()).thenReturn(false); final ServiceUserMapperImpl sum = new ServiceUserMapperImpl(null, config); TestCase.assertEquals(SAMPLE, sum.getServiceUserID(BUNDLE1, null)); TestCase.assertEquals(ANOTHER, sum.getServiceUserID(BUNDLE2, null)); TestCase.assertEquals(SAMPLE, sum.getServiceUserID(BUNDLE1, """")); TestCase.assertEquals(ANOTHER, sum.getServiceUserID(BUNDLE2, """")); TestCase.assertEquals(SAMPLE_SUB, sum.getServiceUserID(BUNDLE1, SUB)); TestCase.assertEquals(ANOTHER_SUB, sum.getServiceUserID(BUNDLE2, SUB)); TestCase.assertEquals(NONE, sum.getServiceUserID(BUNDLE3, null)); TestCase.assertEquals(NONE, sum.getServiceUserID(BUNDLE3, SUB)); }" 223, ,"public List calendarByPin(String pincode, String date){ ResponseEntity res = restTemplate.exchange(vaccineServiceHelper.calendarByPinUri(pincode, date), HttpMethod.GET, VaccineServiceHelper.buildHttpEntity(), CenterData.class); System.out.println(res.getBody()); List list = vaccineServiceHelper.vaccineInfoByCenter(res.getBody().getCenters()); return list; }","public List calendarByPin(String pincode, String date){ ResponseEntity res = restTemplate.exchange(vaccineServiceHelper.calendarByPinUri(pincode, date), HttpMethod.GET, VaccineServiceHelper.buildHttpEntity(), CenterData.class); List list = vaccineServiceHelper.vaccineInfoByCenter(res.getBody().getCenters()); return list; }" 224, ,"public void reduce(Text docMetaData, Iterator documentPayloads, OutputCollector output, Reporter reporter) throws IOException{ String[] pieces = StringUtils.split(docMetaData.toString(), TUPLE_SEPARATOR); String indexName = pieces[0]; String routing = pieces[1]; init(indexName); BulkRequestBuilder bulkRequestBuilder = esEmbededContainer.getNode().client().prepareBulk(); int count = 0; while (documentPayloads.hasNext()) { count++; Text line = documentPayloads.next(); if (line == null) { continue; } pieces = StringUtils.split(line.toString(), TUPLE_SEPARATOR); indexType = pieces[0]; docId = pieces[1]; pre = indexType + TUPLE_SEPARATOR + docId + TUPLE_SEPARATOR; json = line.toString().substring(pre.length()); bulkRequestBuilder.add(esEmbededContainer.getNode().client().prepareIndex(indexName, indexType).setId(docId).setRouting(routing).setSource(json)); if (count % esBatchCommitSize == 0) { bulkRequestBuilder.execute().actionGet(); bulkRequestBuilder = esEmbededContainer.getNode().client().prepareBulk(); count = 0; } } if (count > 0) { long start = System.currentTimeMillis(); bulkRequestBuilder.execute().actionGet(); reporter.incrCounter(JOB_COUNTER.TIME_SPENT_INDEXING_MS, System.currentTimeMillis() - start); } snapshot(indexName, reporter); output.collect(NullWritable.get(), new Text(indexName)); }","public void reduce(Text docMetaData, Iterator documentPayloads, OutputCollector output, final Reporter reporter) throws IOException{ String[] pieces = StringUtils.split(docMetaData.toString(), TUPLE_SEPARATOR); String indexName = pieces[0]; String routing = pieces[1]; init(indexName); long start = System.currentTimeMillis(); int count = 0; while (documentPayloads.hasNext()) { count++; Text line = documentPayloads.next(); if (line == null) { continue; } pieces = StringUtils.split(line.toString(), TUPLE_SEPARATOR); indexType = pieces[0]; docId = pieces[1]; pre = indexType + TUPLE_SEPARATOR + docId + TUPLE_SEPARATOR; json = line.toString().substring(pre.length()); IndexResponse response = esEmbededContainer.getNode().client().prepareIndex(indexName, indexType).setId(docId).setRouting(routing).setSource(json).execute().actionGet(); if (response.isCreated()) { reporter.incrCounter(JOB_COUNTER.INDEX_DOC_CREATED, 1l); } else { reporter.incrCounter(JOB_COUNTER.INDEX_DOC_NOT_CREATED, 1l); } } reporter.incrCounter(JOB_COUNTER.TIME_SPENT_INDEXING_MS, System.currentTimeMillis() - start); snapshot(indexName, reporter); output.collect(NullWritable.get(), new Text(indexName)); }" 225, ,"public void onSubscribe(final MetaData metaData){ if (RpcTypeEnum.DUBBO.getName().equals(metaData.getRpcType())) { MetaData exist = META_DATA.get(metaData.getPath()); if (Objects.isNull(exist)) { ApacheDubboConfigCache.getInstance().initRef(metaData); } else { ApacheDubboConfigCache.getInstance().get(metaData.getPath()); if (!Objects.equals(metaData.getServiceName(), exist.getServiceName()) || !Objects.equals(metaData.getRpcExt(), exist.getRpcExt()) || !Objects.equals(metaData.getParameterTypes(), exist.getParameterTypes()) || !Objects.equals(metaData.getMethodName(), exist.getMethodName())) { ApacheDubboConfigCache.getInstance().build(metaData); } } META_DATA.put(metaData.getPath(), metaData); } }","public void onSubscribe(final MetaData metaData){ if (RpcTypeEnum.DUBBO.getName().equals(metaData.getRpcType())) { MetaData exist = META_DATA.get(metaData.getPath()); if (Objects.isNull(exist) || Objects.isNull(ApacheDubboConfigCache.getInstance().get(metaData.getPath()))) { ApacheDubboConfigCache.getInstance().initRef(metaData); } else { if (!Objects.equals(metaData.getServiceName(), exist.getServiceName()) || !Objects.equals(metaData.getRpcExt(), exist.getRpcExt()) || !Objects.equals(metaData.getParameterTypes(), exist.getParameterTypes()) || !Objects.equals(metaData.getMethodName(), exist.getMethodName())) { ApacheDubboConfigCache.getInstance().build(metaData); } } META_DATA.put(metaData.getPath(), metaData); } }" 226, ,"public String addClient(@ModelAttribute(""clientDTO"") @Valid final ClientDTO clientDTO, final BindingResult bindingResult, final RedirectAttributes redirectAttributes, final Locale locale){ if (bindingResult.hasErrors()) { redirectAttributes.addFlashAttribute(""org.springframework.validation.BindingResult.clientDTO"", bindingResult); redirectAttributes.addFlashAttribute(""clientDTO"", clientDTO); return ""redirect:/adminpageclients#add_new_client""; } if (clientSvc.add(new Client(clientDTO.getClientName()), clientDTO.getUserId())) { changeSessionScopeAddingInfo(messageSource.getMessage(""popup.adminpage.clientAdded"", null, locale), """"); } else { changeSessionScopeAddingInfo("""", messageSource.getMessage(""popup.adminpage.clientNotAdded"", null, locale)); } return ""redirect:/adminpageclients""; }","public String addClient(@ModelAttribute(""dataObject"") @Valid final ClientDTO clientDTO, final BindingResult bindingResult, final RedirectAttributes redirectAttributes, final Locale locale){ if (bindingResult.hasErrors()) { redirectAttributes.addFlashAttribute(""org.springframework.validation.BindingResult.dataObject"", bindingResult); redirectAttributes.addFlashAttribute(""dataObject"", clientDTO); return ""redirect:/adminpageclients#add_new_client""; } addMessages(clientSvc.add(new Client(clientDTO.getClientName()), clientDTO.getUserId()), ""popup.adminpage.clientAdded"", ""popup.adminpage.clientNotAdded"", locale); return ""redirect:/adminpageclients""; }" 227, ," void viewAnIngredient() throws Exception{ IngredientCommand ingredientCommand = new IngredientCommand(); when(ingredientService.findCommandByIdWithRecipeId(anyString(), anyString())).thenReturn(ingredientCommand); mockMvc.perform(get(""/recipe/1L/ingredient/1L/show"")).andExpect(status().isOk()).andExpect(view().name(""recipe/ingredient/view"")).andExpect(model().attributeExists(""ingredient"")); }"," void viewAnIngredient() throws Exception{ when(ingredientService.findCommandByIdWithRecipeId(anyString(), anyString())).thenReturn(Mono.just(new IngredientCommand())); mockMvc.perform(get(""/recipe/1L/ingredient/1L/show"")).andExpect(status().isOk()).andExpect(view().name(""recipe/ingredient/view"")).andExpect(model().attributeExists(""ingredient"")); }" 228, ,"public ServerResponse productUpOrDown(HttpServletRequest request, Integer status, Integer productId){ String loginToken = CookieUtil.readLoginLoken(request); if (StringUtils.isBlank(loginToken)) { return ServerResponse.createByErrorMessage(""用户未登录""); } String userStr = ShardedRedisPoolUtil.get(loginToken); User existUser = JsonUtil.Json2Obj(userStr, User.class); if (existUser == null) { return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ""用户未登录""); } if (iUserService.checkAdmin(existUser).isSuccess()) { return iProductService.productUpOrDown(status, productId); } return ServerResponse.createByErrorMessage(""该用户没有权限""); }","public ServerResponse productUpOrDown(HttpServletRequest request, Integer status, Integer productId){ return iProductService.productUpOrDown(status, productId); }" 229, ,"private Object convertCellValue(ExcelBeanField beanField, Cell cell, String cellValue, int rowNum){ if (beanField.isCellDataType()) { val cellData = CellData.builder().value(cellValue).row(rowNum).col(cell.getColumnIndex()).sheetIndex(workbook.getSheetIndex(sheet)); applyComment(cell, cellData); return cellData.build(); } else { val type = beanField.getField().getType(); if (type == int.class || type == Integer.class) { return Integer.parseInt(cellValue); } } return cellValue; }","private Object convertCellValue(ExcelBeanField beanField, Cell cell, String cellValue, int rowNum){ if (beanField.isCellDataType()) { val cellData = CellData.builder().value(cellValue).row(rowNum).col(cell.getColumnIndex()).sheetIndex(workbook.getSheetIndex(sheet)); applyComment(cell, cellData); return cellData.build(); } else { return beanField.convert(cellValue); } }" 230, ," void is_rover_moved_right(int posX, int posY, Direction direction, String stringCommands, int expectedPosX, int expectedPosY, Direction expectedDirection){ Rover rover = new Rover(generatePosition(posX, posY, direction, mars), mars); char[] commands = stringCommands.toCharArray(); rover.move(commands); assertThat(rover.getPositionRover().getX()).isEqualTo(expectedPosX); assertThat(rover.getPositionRover().getY()).isEqualTo(expectedPosY); assertThat(rover.getPositionRover().getDirection()).isEqualTo(expectedDirection); }"," void is_rover_moved_right(int posX, int posY, Direction direction, String stringCommands, int expectedPosX, int expectedPosY, Direction expectedDirection){ Rover rover = new Rover(generatePosition(posX, posY, direction, mars), mars); rover.move(stringCommands); assertThat(rover.getPositionRover().getX()).isEqualTo(expectedPosX); assertThat(rover.getPositionRover().getY()).isEqualTo(expectedPosY); assertThat(rover.getPositionRover().getDirection()).isEqualTo(expectedDirection); }" 231, ,"public ServerResponse updateCategoryName(HttpServletRequest request, String categoryName, Integer categoryId){ String loginToken = CookieUtil.readLoginLoken(request); if (StringUtils.isBlank(loginToken)) { return ServerResponse.createByErrorMessage(""用户未登录""); } String userStr = ShardedRedisPoolUtil.get(loginToken); User existUser = JsonUtil.Json2Obj(userStr, User.class); if (existUser == null) { return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ""用户未登录""); } if (iUserService.checkAdmin(existUser).isSuccess()) { return iCategoryService.updateCategoryName(categoryName, categoryId); } return ServerResponse.createByErrorMessage(""该用户没有权限""); }","public ServerResponse updateCategoryName(HttpServletRequest request, String categoryName, Integer categoryId){ return iCategoryService.updateCategoryName(categoryName, categoryId); }" 232, ,"public String action(HttpServletRequest request, HttpServletResponse response) throws RuntimeException{ DataSource dataSource = DataSourceFactory.getInstance().getDataSource(); Connection connection = null; try { connection = dataSource.getConnection(); DaoFactory daoFactory = DaoFactory.getDaoFactory(connection); BeverageOrderDao beverageOrderDao = daoFactory.createBeverageOrderDao(); BeverageOrder one = beverageOrderDao.findOne(5L); Beverage beverage = one.getBeverage(); Order order = one.getOrder(); Integer amount = one.getAmount(); one.getId(); } catch (SQLException e) { e.printStackTrace(); } Long authToken = (Long) request.getSession().getAttribute(X_AUTH_TOKEN); String commandName = request.getParameter(COMMAND); if (commandName != null && ADMIN.equals(commandName.split(""/"")[0])) { List roles = serviceFactory.createUserService().getCurrentUser(request).getRoles(); boolean isAdmin = false; for (Role role : roles) { if (ADMIN_ROLE.equals(role.getName())) { isAdmin = true; break; } } if (!isAdmin) { return ERROR; } commandName = commandName.split(""/"")[1]; } Command command = commandMap.get(commandName); if (authToken == null && !LOGIN_COMMAND.equals(commandName) && !REGISTRATION_PAGE_COMMAND.equals(commandName) && !REGISTRATION_COMMAND.equals(commandName)) { command = commandMap.get(LOGIN_PAGE_COMMAND); } else if (authToken != null && commandName == null) { command = commandMap.get(INDEX_COMMAND); } return command.execute(request, response); }","public String action(HttpServletRequest request, HttpServletResponse response) throws RuntimeException{ Long authToken = (Long) request.getSession().getAttribute(X_AUTH_TOKEN); String commandName = request.getParameter(COMMAND); if (commandName != null && ADMIN.equals(commandName.split(""/"")[0])) { List roles = serviceFactory.createUserService().getCurrentUser(request).getRoles(); boolean isAdmin = false; for (Role role : roles) { if (ADMIN_ROLE.equals(role.getName())) { isAdmin = true; break; } } if (!isAdmin) { return Pages.ERROR; } commandName = commandName.split(""/"")[1]; } Command command = commandMap.get(commandName); if (authToken == null && !LOGIN_COMMAND.equals(commandName) && !REGISTRATION_PAGE_COMMAND.equals(commandName) && !REGISTRATION_COMMAND.equals(commandName)) { command = commandMap.get(LOGIN_PAGE_COMMAND); } else if (authToken != null && commandName == null) { command = commandMap.get(INDEX_COMMAND); } return command.execute(request, response); }" 233, ," int[] maxSlidingWindowHeap(int[] nums, int k){ if (nums == null || nums.length == 0 || k < 0) return nums; if (k > nums.length) { Arrays.sort(nums); return new int[] { nums[nums.length - 1] }; } int[] result = new int[nums.length - k + 1]; PriorityQueue priorityQueue = new PriorityQueue<>(k, Collections.reverseOrder()); for (int i = 0; i < k; i++) { priorityQueue.offer(nums[i]); } result[0] = Objects.requireNonNull(priorityQueue.peek()); priorityQueue.size(); for (int j = k; j < nums.length; j++) { priorityQueue.offer(nums[j]); priorityQueue.remove(nums[j - k]); result[j - k + 1] = Objects.requireNonNull(priorityQueue.peek()); } return result; }"," int[] maxSlidingWindowHeap(int[] nums, int k){ if (nums == null || nums.length == 0 || k < 0) return nums; if (k > nums.length) { Arrays.sort(nums); return new int[] { nums[nums.length - 1] }; } int[] result = new int[nums.length - k + 1]; PriorityQueue priorityQueue = new PriorityQueue<>(k, Collections.reverseOrder()); for (int i = 0; i < k; i++) { priorityQueue.offer(nums[i]); } result[0] = Objects.requireNonNull(priorityQueue.peek()); for (int j = k; j < nums.length; j++) { priorityQueue.offer(nums[j]); priorityQueue.remove(nums[j - k]); result[j - k + 1] = Objects.requireNonNull(priorityQueue.peek()); } return result; }" 234, ,"public UserEntity createUser(UserEntity userEntity){ RouteEntity routeToAdd = routeRepository.findByRouteName(""Gbg-Sthlm""); userEntity.addRoute(routeToAdd); return userEntity; }","public UserEntity createUser(UserEntity userEntity){ return userEntity; }" 235, ," Set generateNeighbours(Ship ship){ Set neighbours = new HashSet<>(); List occupiedFields = new ArrayList<>(); occupiedFields.addAll(ship.toHit); occupiedFields.addAll(ship.hit); for (Integer field : occupiedFields) { if (field != (((field / COLUMNS) * COLUMNS) + COLUMNS - 1)) { generateNeighboursFromRightSideOfAField(field, neighbours, ship.hit); } if (field != ((field / COLUMNS) * COLUMNS)) { generateNeighboursFromLeftSideOfAField(field, neighbours, ship.hit); } generateNeighboursAboveAndUnderAField(field, neighbours, ship.hit); } return neighbours; }"," Set generateNeighbours(Ship ship){ Set neighbours = new HashSet<>(); List occupiedFields = getOccupiedFields(ship); for (Integer field : occupiedFields) { if (field != (((field / COLUMNS) * COLUMNS) + COLUMNS - 1)) { generateNeighboursFromRightSideOfAField(field, neighbours, ship.hit); } if (field != ((field / COLUMNS) * COLUMNS)) { generateNeighboursFromLeftSideOfAField(field, neighbours, ship.hit); } generateNeighboursAboveAndUnderAField(field, neighbours, ship.hit); } return neighbours; }" 236, ,"private void clearNotSelectedGrains(){ for (int i = 0; i < space.getSizeY(); i++) { for (int j = 0; j < space.getSizeX(); j++) { Cell cell = space.getCells()[i][j]; if (selectedGrainsById.containsKey(cell.getId())) { continue; } cell.setGrowable(true); cell.setId(0); } } selectedGrainsById.remove(-1); }","private void clearNotSelectedGrains(){ space.getCellsByCoords().values().stream().filter(cell -> !selectedGrainsById.containsKey(cell.getId())).forEach(cell -> { cell.setId(0); cell.setGrowable(true); }); selectedGrainsById.remove(-1); }" 237, ,"public boolean equals(Object o){ if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PlaceBetRequestDTO betDTO = (PlaceBetRequestDTO) o; if (Double.compare(betDTO.coefficient, coefficient) != 0) return false; if (betAmount != null ? !betAmount.equals(betDTO.betAmount) : betDTO.betAmount != null) return false; if (betType != betDTO.betType) return false; if (sportsMatchName != null ? !sportsMatchName.equals(betDTO.sportsMatchName) : betDTO.sportsMatchName != null) return false; return true; }","public boolean equals(Object o){ if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PlaceBetRequestDTO betDTO = (PlaceBetRequestDTO) o; if (Double.compare(betDTO.coefficient, coefficient) != 0) return false; if (betAmount != null ? !betAmount.equals(betDTO.betAmount) : betDTO.betAmount != null) return false; if (betType != betDTO.betType) return false; return !(sportsMatchName != null ? !sportsMatchName.equals(betDTO.sportsMatchName) : betDTO.sportsMatchName != null); }" 238, ,"public void initVariabls(){ player = new Player(""Jozek""); size = input.getIntInputWithMessage(""Podaj rozmiar planszy : ""); board = new Board(size); board = board.putFoodOnCoreBoard(); snake = new Snake(size); board.putSnakeOnBoard(snake); printer.printBoard(board); counter = new Counter(); mover = new Mover(); }","public void initVariabls(){ player = new Player(""Jozek""); size = input.getIntInputWithMessage(""Podaj rozmiar planszy : ""); board = new Board(size).putFoodOnCoreBoard().putTrapOnCoreBoard(); snake = new Snake(size); board.putSnakeOnBoard(snake); printer.printBoard(board); counter = new Counter(); mover = new Mover(); }" 239, ,"public CurrentOfferResult calculateCurrentOffer(RequestAndOffers requestAndOffers){ if (requestAndOffers.getOffers().isEmpty()) { return NO_OFFER; } BigDecimal remainderFromRequest = requestAndOffers.getRequest().getAmount(); BigDecimal weightedInterest = BigDecimal.ZERO; for (LoanOffer offer : requestAndOffers.getOffers()) { if (remainderFromRequest.compareTo(BigDecimal.ZERO) > 0) { BigDecimal availableToTake = remainderFromRequest.min(offer.getAmount()); remainderFromRequest = remainderFromRequest.subtract(availableToTake); weightedInterest = weightedInterest.add(availableToTake.multiply(offer.getInterestRate())); } else break; } BigDecimal amountSatisfied = requestAndOffers.getRequest().getAmount().subtract(remainderFromRequest); return new CurrentOfferResult(amountSatisfied, weightedInterest.divide(amountSatisfied)); }","public CurrentOfferResult calculateCurrentOffer(RequestAndOffers requestAndOffers){ if (requestAndOffers.getOffers().isEmpty()) { return NO_OFFER; } BigDecimal remainderFromRequest = requestAndOffers.getRequest().getAmount(); BigDecimal weightedInterest = BigDecimal.ZERO; Iterator offerIt = requestAndOffers.getOffers().iterator(); while (offerIt.hasNext() && remainderFromRequest.compareTo(BigDecimal.ZERO) > 0) { LoanOffer offer = offerIt.next(); BigDecimal availableToTake = remainderFromRequest.min(offer.getAmount()); remainderFromRequest = remainderFromRequest.subtract(availableToTake); weightedInterest = weightedInterest.add(availableToTake.multiply(offer.getInterestRate())); } BigDecimal amountSatisfied = requestAndOffers.getRequest().getAmount().subtract(remainderFromRequest); return new CurrentOfferResult(amountSatisfied, weightedInterest.divide(amountSatisfied)); }" 240, ,"public boolean process(Set annotations, RoundEnvironment roundEnv){ if (annotations.isEmpty()) { return true; } Element ce = null; HashMap> modelMap = new HashMap<>(); try { DeltaBuilderTypeModel model = null; for (Element elem : roundEnv.getElementsAnnotatedWith(DeltaForceBuilder.class)) { ce = elem; if (elem.getKind() == ElementKind.CLASS) { createBuilderModel(modelMap, elem); } } if (modelMap.size() > 0) { for (DeltaBuilderTypeModel tm : modelMap.keySet()) { writeBuilder(tm, modelMap.get(tm)); } } } catch (ResourceNotFoundException rnfe) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, rnfe.getLocalizedMessage()); } catch (ParseErrorException pee) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, pee.getLocalizedMessage()); } catch (IOException ioe) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, ioe.getLocalizedMessage()); } catch (Exception e) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getLocalizedMessage(), ce); } return true; }","public boolean process(Set annotations, RoundEnvironment roundEnv){ if (annotations.isEmpty()) { return true; } Element ce = null; HashMap> modelMap = new HashMap<>(); try { for (Element elem : roundEnv.getElementsAnnotatedWith(DeltaForceBuilder.class)) { ce = elem; if (elem.getKind() == ElementKind.CLASS) { createBuilderModel(modelMap, elem); } } if (modelMap.size() > 0) { for (DeltaBuilderTypeModel tm : modelMap.keySet()) { writeBuilder(tm, modelMap.get(tm)); } } } catch (Exception e) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getLocalizedMessage(), ce); } return true; }" 241, ,"public TranslationResult visit(final SubstantiveSelection node, final EoVisitorArgument argument){ final TranslationResult result = new TranslationResult(node); final ConceptBookEntry conceptBookEntry = this.eoTranslator.getConceptBook().get(node.getSubstantive().getConcept()); List defaultTargets = conceptBookEntry.getDefaultTargets(Language.EO); if (defaultTargets.isEmpty()) { result.setTranslation(conceptBookEntry.getConceptPhrase()); } else if (argument.getArticle() != null) { final TranslationTarget substantiveTarget = defaultTargets.get(0); result.setTranslation(""la"", EoUtils.getCasedSubstantive(substantiveTarget, argument.getCaseAttribute())); } else { final TranslationTarget substantiveTarget = defaultTargets.get(0); result.setTranslation(EoUtils.getCasedSubstantive(substantiveTarget, argument.getCaseAttribute())); } return result; }","public TranslationResult visit(final SubstantiveSelection node, final EoVisitorArgument argument){ final TranslationResult result = new TranslationResult(node); final TranslationTarget substantiveTarget = this.eoTranslator.getFirstDefaultTarget(node.getSubstantive().getConcept()); if (argument.getArticle() != null) { result.setTranslation(""la"", EoUtils.getCasedSubstantive(substantiveTarget, argument.getCaseAttribute())); } else { result.setTranslation(EoUtils.getCasedSubstantive(substantiveTarget, argument.getCaseAttribute())); } return result; }" 242, ,"public void checkIfRestIsBackwardCompatibleFilteredSpecs() throws Exception{ setProps(); CommandExecutor cmdIss = new MockCommandExecutor(); RESTClient restClient = BDDMockito.mock(RESTClient.class); HttpMethod getHTTPMethod = BDDMockito.mock(HttpMethod.class); RESTSpecLRValidator restSpecLRValidator = new RESTSpecLRValidator(cmdIss, restClient, FILTER_URL); given(restClient.executeMethod(any(HttpMethod.class))).willReturn(RESTSpecLRValidator.HTTP_OK); given(restClient.createGetMethod(anyString())).willReturn(getHTTPMethod); given(getHTTPMethod.getResponseBodyAsString()).willReturn(""swagger: 2.0""); restSpecLRValidator.checkIfRestIsBackwardCompatible(); final Collection execs = ((MockCommandExecutor) cmdIss).getExecs(); final String processedFilesPaths = execs.stream().collect(Collectors.joining()); assertThat(execs).hasSize(SPECS_THAT_MATCH_COUNT); assertThat(processedFilesPaths).contains(""/spec0_1.json""); assertThat(processedFilesPaths).contains(""/spec1_1.json""); assertThat(processedFilesPaths).contains(""/spec2_1.json""); }","public void checkIfRestIsBackwardCompatibleFilteredSpecs() throws Exception{ CommandExecutor cmdIss = new MockCommandExecutor(); RESTClient restClient = BDDMockito.mock(RESTClient.class); HttpMethod getHTTPMethod = BDDMockito.mock(HttpMethod.class); RESTSpecLRValidator restSpecLRValidator = new RESTSpecLRValidator(cmdIss, restClient, FILTER_URL); given(restClient.executeMethod(any(HttpMethod.class))).willReturn(RESTSpecLRValidator.HTTP_OK); given(restClient.createGetMethod(anyString())).willReturn(getHTTPMethod); given(getHTTPMethod.getResponseBodyAsString()).willReturn(""swagger: 2.0""); restSpecLRValidator.checkIfRestIsBackwardCompatible(); final Collection execs = ((MockCommandExecutor) cmdIss).getExecs(); final String processedFilesPaths = execs.stream().collect(Collectors.joining()); assertThat(execs).hasSize(SPECS_THAT_MATCH_COUNT); assertThat(processedFilesPaths).contains(""/spec0_1.json""); assertThat(processedFilesPaths).contains(""/spec1_1.json""); assertThat(processedFilesPaths).contains(""/spec2_1.json""); }" 243, ,"public void run(){ while (true) { moveType = input.getMoveType(input.getIntInput()); snake = mover.moveSnake(snake, moveType, board, counter); board = board.clearBoard(); board = board.putFoodOnCoreBoard(); board = board.putSnakeOnBoard(snake); printer.printBoard(board); printer.printMessage(""Counter : "" + String.valueOf(counter.getAmount())); printer.goNextLine(); } }","public void run(){ while (true) { moveType = input.getMoveType(input.getIntInput()); snake = mover.moveSnake(snake, moveType, board, counter); printer.printBoard(board.clearBoard().putFoodOnCoreBoard().putSnakeOnBoard(snake)); printer.printMessage(""Counter : "" + String.valueOf(counter.getAmount())); printer.goNextLine(); } }" 244, ,"public SubmissionList getSubmissionByDate(UserSubmissionByDateRequest userSubmissionByDateRequest){ String uri = String.format(""https://codeforces.com/api/user.status?handle=%s&from=1&count=100"", userSubmissionByDateRequest.getHandle()); SubmissionList result = restTemplate.getForObject(uri, SubmissionList.class); Instant now = Instant.now(); Instant yesterday = now.minus(userSubmissionByDateRequest.getNoOfDays(), ChronoUnit.DAYS); Long epochSecond = yesterday.getEpochSecond(); SubmissionList filteredResult = new SubmissionList(); for (Submission submission : result.getResult()) { if (submission.getCreationTimeSeconds() > epochSecond) { filteredResult.getResult().add(submission); } else { break; } } return filteredResult; }","public SubmissionList getSubmissionByDate(UserSubmissionByDateRequest userSubmissionByDateRequest){ String uri = String.format(""https://codeforces.com/api/user.status?handle=%s&from=1&count=100"", userSubmissionByDateRequest.getHandle()); SubmissionList result = restTemplate.getForObject(uri, SubmissionList.class); Long epochSecond = TimeUtil.getEpochBeforeNDays(userSubmissionByDateRequest.getNoOfDays()); SubmissionList filteredResult = new SubmissionList(); for (Submission submission : result.getResult()) { if (submission.getCreationTimeSeconds() > epochSecond) { filteredResult.getResult().add(submission); } else { break; } } return filteredResult; }" 245, ,"public static int poisson(double lambda){ if (!(lambda > 0.0)) throw new IllegalArgumentException(""lambda must be positive: "" + lambda); if (Double.isInfinite(lambda)) throw new IllegalArgumentException(""lambda must not be infinite: "" + lambda); int k = 0; double p = 1.0; double expLambda = Math.exp(-lambda); do { k++; p *= uniform(); } while (p >= expLambda); return k - 1; }","public static int poisson(double lambda){ checkArgument(lambda > 0.0, ""lambda must be positive: "" + lambda); checkArgument(!Double.isInfinite(lambda), ""lambda must not be infinite: "" + lambda); int k = 0; double p = 1.0; double expLambda = Math.exp(-lambda); do { k++; p *= uniform(); } while (p >= expLambda); return k - 1; }" 246, ,"public static void write(InputStream in, long size, File output) throws IOException{ FileOutputStream out = new FileOutputStream(output); try { byte[] buf = new byte[BYTE_BUFFER_LENGTH]; int read; int left = buf.length; if (left > size) left = (int) size; while ((read = in.read(buf, 0, left)) > 0) { out.write(buf, 0, read); size = size - read; if (left > size) left = (int) size; } } finally { out.close(); } }","public static void write(InputStream in, long size, File output) throws IOException{ try (FileOutputStream out = new FileOutputStream(output)) { byte[] buf = new byte[BYTE_BUFFER_LENGTH]; int read; int left = buf.length; if (left > size) left = (int) size; while ((read = in.read(buf, 0, left)) > 0) { out.write(buf, 0, read); size = size - read; if (left > size) left = (int) size; } } }" 247, ,"public PDAppearanceEntry getNormalAppearance(){ COSBase entry = dictionary.getDictionaryObject(COSName.N); if (entry == null) { return null; } else { return new PDAppearanceEntry(entry); } }","public PDAppearanceEntry getNormalAppearance(){ COSBase entry = dictionary.getDictionaryObject(COSName.N); if (nonNull(entry)) { return new PDAppearanceEntry(entry); } return null; }" 248, ,"private JSONObject compactConvert(JSONObject jsonObject){ val compactJsonObject = new JSONObject(); for (val entry : jsonObject.entrySet()) { Object value = entry.getValue(); String key = entry.getKey(); if (value instanceof JSONArray) { value = compactConvert((JSONArray) value); } else if (value instanceof JSONObject) { value = compactConvert((JSONObject) value); } compactJsonObject.put(key, value); } return compactJsonObject; }","private JSONObject compactConvert(JSONObject jsonObject){ val compactJsonObject = new JSONObject(); for (val entry : jsonObject.entrySet()) { Object value = entry.getValue(); if (value instanceof JSONArray) { value = compactConvert((JSONArray) value); } else if (value instanceof JSONObject) { value = compactConvert((JSONObject) value); } compactJsonObject.put(entry.getKey(), value); } return compactJsonObject; }" 249, ,"public static T newInstance(T obj){ SoapServiceProxy proxy = new SoapServiceProxy(obj); Class clazz = obj.getClass(); T res = (T) Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), proxy); return res; }","public static T newInstance(T obj){ SoapServiceProxy proxy = new SoapServiceProxy(obj); Class clazz = obj.getClass(); return (T) Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), proxy); }" 250, ,"public static byte[] generateIV(){ Random r = new Random(); byte[] iv = new byte[16]; r.nextBytes(iv); return iv; }","public static byte[] generateIV(){ return generatePasswordSalt(16); }" 251, ,"public String myProducts(Model model, Principal principal){ getLoggedUser(principal); List products = productService.getProducts().stream().filter(product -> product.getUser().getId().equals(getLoggedUser(principal).getId())).collect(Collectors.toList()); model.addAttribute(""products"", products); return ""my-products-page""; }","public String myProducts(Model model, Principal principal){ model.addAttribute(""products"", productService.getProductByUserId(getLoggedUser(principal).getId())); return ""my-products-page""; }" 252, ,"public void positiveEvaluateGreaterThanEqualsToOperatorTest() throws Exception{ Map attributes = new HashMap<>(); attributes.put(""age"", 25); String feature = ""Age Greater than EqualsTo Feature""; String expression = ""age >= 25""; final GatingValidator validator = new GatingValidator(); Assert.assertTrue(validator.isAllowed(expression, feature, attributes)); }","public void positiveEvaluateGreaterThanEqualsToOperatorTest() throws Exception{ Map attributes = new HashMap<>(); attributes.put(""age"", 25); String feature = ""Age Greater than EqualsTo Feature""; String expression = ""age >= 25""; Assert.assertTrue(validator.isAllowed(expression, feature, attributes)); }" 253, ,"public void addIdentifier(NodeIdentifier pNode){ LOGGER.trace(""Method addIdentifier("" + pNode + "") called.""); if (!mMapNode.containsKey(pNode)) { PText vText = new PText(mIdentifierInformationStrategy.getText(pNode.getIdentifier())); vText.setHorizontalAlignment(Component.CENTER_ALIGNMENT); vText.setTextPaint(getColorIdentifierText(pNode)); vText.setFont(new Font(null, Font.PLAIN, mFontSize)); vText.setOffset(-0.5F * (float) vText.getWidth(), -0.5F * (float) vText.getHeight()); final PPath vNode = PPath.createRoundRectangle(-5 - 0.5F * (float) vText.getWidth(), -5 - 0.5F * (float) vText.getHeight(), (float) vText.getWidth() + 10, (float) vText.getHeight() + 10, 20.0f, 20.0f); vNode.setPaint(getColor(vNode, pNode)); vNode.setStrokePaint(getColorIdentifierStroke(pNode)); final PComposite vCom = new PComposite(); vCom.addChild(vNode); vCom.addChild(vText); vCom.setOffset(mAreaOffsetX + pNode.getX() * mAreaWidth, mAreaOffsetY + pNode.getY() * mAreaHeight); vCom.addAttribute(""type"", NodeType.IDENTIFIER); vCom.addAttribute(""position"", pNode); vCom.addAttribute(""edges"", new ArrayList>()); mMapNode.put(pNode, vCom); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { mLayerNode.addChild(vCom); } }); } }","public void addIdentifier(NodeIdentifier pNode){ LOGGER.trace(""Method addIdentifier("" + pNode + "") called.""); if (!mMapNode.containsKey(pNode)) { PText vText = new PText(mIdentifierInformationStrategy.getText(pNode.getIdentifier())); vText.setHorizontalAlignment(Component.CENTER_ALIGNMENT); vText.setTextPaint(getColorIdentifierText(pNode)); vText.setFont(new Font(null, Font.PLAIN, mFontSize)); vText.setOffset(-0.5F * (float) vText.getWidth(), -0.5F * (float) vText.getHeight()); final PPath vNode = PPath.createRoundRectangle(-5 - 0.5F * (float) vText.getWidth(), -5 - 0.5F * (float) vText.getHeight(), (float) vText.getWidth() + 10, (float) vText.getHeight() + 10, 20.0f, 20.0f); final PComposite vCom = new PComposite(); vCom.addChild(vNode); vCom.addChild(vText); vCom.setOffset(mAreaOffsetX + pNode.getX() * mAreaWidth, mAreaOffsetY + pNode.getY() * mAreaHeight); vCom.addAttribute(""type"", NodeType.IDENTIFIER); vCom.addAttribute(""position"", pNode); vCom.addAttribute(""edges"", new ArrayList>()); paintIdentifierNode(pNode.getIdentifier(), pNode, vNode, vText); mMapNode.put(pNode, vCom); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { mLayerNode.addChild(vCom); } }); } }" 254, ,"public void testingLeavingTheVehicleWhenSlotIdIsNull() throws Exception{ ParkingService instance = new ParkingServiceImpl(); String output = instance.createParkingLot(1); assertTrue(""Createdparkingof1slots"".equalsIgnoreCase(output.trim().replace("" "", """"))); VehicleDetails vehicleDetails1 = new CarDetails(""KA-01-HH-1234""); DriverDetails driverDetails1 = new DriverDetails(21L); String parkingVehicleOutput = instance.parkVehicle(vehicleDetails1, driverDetails1); assertTrue(""CarwithvehicleregistrationNumberKA-01-HH-1234hasbeenparkedatslotnumber1"".equalsIgnoreCase(parkingVehicleOutput.trim().replace("" "", """"))); thrownExpectedException.expect(ParkingLotException.class); thrownExpectedException.expectMessage(is(""slotId cannot be null or empty"")); instance.leaveVehicle(null); instance.destroy(); }","public void testingLeavingTheVehicleWhenSlotIdIsNull() throws Exception{ ParkingService instance = new ParkingServiceImpl(); String output = instance.createParkingLot(1); assertTrue(""Createdparkingof1slots"".equalsIgnoreCase(output.trim().replace("" "", """"))); VehicleDetails vehicleDetails1 = new CarDetails(""KA-01-HH-1234""); DriverDetails driverDetails1 = new DriverDetails(21L); String parkingVehicleOutput = instance.parkVehicle(vehicleDetails1, driverDetails1); assertTrue(""CarwithvehicleregistrationNumberKA-01-HH-1234hasbeenparkedatslotnumber1"".equalsIgnoreCase(parkingVehicleOutput.trim().replace("" "", """"))); thrownExpectedException.expect(ParkingLotException.class); thrownExpectedException.expectMessage(is(""slotId cannot be null or empty"")); instance.leaveVehicle(null); }" 255, ,"public ASTNode visitExprList(final ExprListContext ctx){ ListExpression result = new ListExpression(); result.setStartIndex(ctx.start.getStartIndex()); result.setStopIndex(ctx.stop.getStopIndex()); if (null != ctx.exprList()) { result.getItems().addAll(((ListExpression) visitExprList(ctx.exprList())).getItems()); } result.getItems().add((ExpressionSegment) visit(ctx.aExpr())); String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex())); result.setText(text); return result; }","public ASTNode visitExprList(final ExprListContext ctx){ ListExpression result = new ListExpression(); result.setStartIndex(ctx.start.getStartIndex()); result.setStopIndex(ctx.stop.getStopIndex()); if (null != ctx.exprList()) { result.getItems().addAll(((ListExpression) visitExprList(ctx.exprList())).getItems()); } result.getItems().add((ExpressionSegment) visit(ctx.aExpr())); return result; }" 256, ,"private String formatOrder(Order order){ StringBuffer sb = new StringBuffer(); sb.append(""{""); sb.append(""\""id\"": ""); sb.append(order.getOrderId()); sb.append("", ""); sb.append(""\""products\"": [""); for (int j = 0; j < order.getProductsCount(); j++) { Product product = order.getProduct(j); sb.append(""{""); sb.append(""\""code\"": \""""); sb.append(product.getCode()); sb.append(""\"", ""); sb.append(""\""color\"": \""""); sb.append(getColorFor(product)); sb.append(""\"", ""); if (product.getSize() != Product.SIZE_NOT_APPLICABLE) { sb.append(""\""size\"": \""""); sb.append(getSizeFor(product)); sb.append(""\"", ""); } sb.append(""\""price\"": ""); sb.append(product.getPrice()); sb.append("", ""); sb.append(""\""currency\"": \""""); sb.append(product.getCurrency()); sb.append(""\""}, ""); } if (order.getProductsCount() > 0) { sb.delete(sb.length() - 2, sb.length()); } sb.append(""]""); sb.append(""}, ""); return sb.toString(); }","private String formatOrder(Order order){ StringBuffer sb = new StringBuffer(); sb.append(""{""); sb.append(formatField(""id"", order.getOrderId())); sb.append("", ""); sb.append(""\""products\"": [""); for (int j = 0; j < order.getProductsCount(); j++) { Product product = order.getProduct(j); sb.append(""{""); sb.append(formatField(""code"", product.getCode())); sb.append("", ""); sb.append(formatField(""color"", getColorFor(product))); sb.append("", ""); if (product.getSize() != Product.SIZE_NOT_APPLICABLE) { sb.append(formatField(""size"", getSizeFor(product))); sb.append("", ""); } sb.append(formatField(""price"", product.getPrice())); sb.append("", ""); sb.append(formatField(""currency"", product.getCurrency())); sb.append(""}, ""); } if (order.getProductsCount() > 0) { sb.delete(sb.length() - 2, sb.length()); } sb.append(""]""); sb.append(""}, ""); return sb.toString(); }" 257, ," void requestBuildRIDList(){ if (!isBuilt()) { if (!request_processing) { request_processing = true; system.postEvent(10000, system.createEvent(new Runnable() { public void run() { createRIDCache(); } })); } } }"," void requestBuildRIDList(){ if (!isBuilt()) { if (!request_processing) { request_processing = true; system.postEvent(10000, system.createEvent(() -> createRIDCache())); } } }" 258, ,"public Mono send(final HttpRequest request){ Objects.requireNonNull(request.httpMethod()); Objects.requireNonNull(request.url()); Objects.requireNonNull(request.url().getProtocol()); Objects.requireNonNull(this.httpClientConfig); return this.httpClient.port(request.port()).request(HttpMethod.valueOf(request.httpMethod().toString())).uri(request.url().toString()).send(bodySendDelegate(request)).responseConnection(responseDelegate(request)).single(); }","public Mono send(final HttpRequest request){ Objects.requireNonNull(request.httpMethod()); Objects.requireNonNull(request.uri()); Objects.requireNonNull(this.httpClientConfig); return this.httpClient.port(request.port()).request(HttpMethod.valueOf(request.httpMethod().toString())).uri(request.uri().toString()).send(bodySendDelegate(request)).responseConnection(responseDelegate(request)).single(); }" 259, ,"public static Graph bipartite(int V1, int V2, double p){ if (p < 0.0 || p > 1.0) throw new IllegalArgumentException(""Probability must be between 0 and 1""); int[] vertices = new int[V1 + V2]; for (int i = 0; i < V1 + V2; i++) vertices[i] = i; StdRandom.shuffle(vertices); Graph G = new GraphImpl(V1 + V2); for (int i = 0; i < V1; i++) for (int j = 0; j < V2; j++) if (StdRandom.bernoulli(p)) G.addEdge(vertices[i], vertices[V1 + j]); return G; }","public static Graph bipartite(int V1, int V2, double p){ checkArgument(p >= 0.0 && p <= 1.0, ""Probability must be between 0 and 1""); int[] vertices = new int[V1 + V2]; for (int i = 0; i < V1 + V2; i++) vertices[i] = i; StdRandom.shuffle(vertices); Graph G = new GraphImpl(V1 + V2); for (int i = 0; i < V1; i++) for (int j = 0; j < V2; j++) if (StdRandom.bernoulli(p)) G.addEdge(vertices[i], vertices[V1 + j]); return G; }" 260, ,"private List> fillBookLists(List books){ List> qttByBook = new ArrayList<>(); for (HarryPotterBook book : books) { boolean added = false; int i = 0; while (!added && i < qttByBook.size()) { added = addIfNotExists(book, qttByBook.get(i)); i++; } if (i == qttByBook.size() && !added) { qttByBook.add(createNewList(book)); } } return qttByBook; }","private List> fillBookLists(List books){ List> qttByBook = new ArrayList<>(); for (HarryPotterBook book : books) { boolean added = false; for (int i = 0; !added && i < qttByBook.size(); i++) { added = addIfNotExists(book, qttByBook.get(i)); } if (!added) { qttByBook.add(createNewList(book)); } } return qttByBook; }" 261, ,"public static void setup() throws InterruptedException{ chain = new BlockchainImpl(MemoryDB.FACTORY); ChannelManager channelMgr = new ChannelManager(); PendingManager pendingMgr = new PendingManager(chain, channelMgr); pendingMgr.start(); bft = SemuxBFT.getInstance(); coinbase = new EdDSA(); bft.init(chain, channelMgr, pendingMgr, coinbase); new Thread(() -> { bft.start(); }, ""cons"").start(); Thread.sleep(200); }","public static void setup() throws InterruptedException{ chain = new BlockchainImpl(MemoryDB.FACTORY); ChannelManager channelMgr = new ChannelManager(); PendingManager pendingMgr = new PendingManager(chain, channelMgr); pendingMgr.start(); bft = SemuxBFT.getInstance(); coinbase = new EdDSA(); bft.init(chain, channelMgr, pendingMgr, coinbase); new Thread(() -> bft.start(), ""cons"").start(); Thread.sleep(200); }" 262, ,"private void setCell(SetCell setCell){ log().debug(""{}"", setCell); removeInRow(setCell); removeInCol(setCell); removeInBox(setCell); if (monitoredCells.isEmpty()) { monitoringComplete(); } else if (monitoredCells.size() == 1) { Cell cell = monitoredCells.get(0); String who = String.format(""Set by row (%d, %d) = %d"", cell.row, cell.col, cell.value); getSender().tell(new SetCell(cell.row, cell.col, monitoredValue, who), getSelf()); monitoringComplete(); } }","private void setCell(SetCell setCell){ removeInRow(setCell); removeInCol(setCell); removeInBox(setCell); if (monitoredCells.isEmpty()) { monitoringComplete(); } else if (monitoredCells.size() == 1) { Cell cell = monitoredCells.get(0); String who = String.format(""Set by row (%d, %d) = %d"", cell.row, cell.col, cell.value); getSender().tell(new SetCell(cell.row, cell.col, monitoredValue, who), getSelf()); monitoringComplete(); } }" 263, ,"public void analyzeWithClassVisitor(File pluginFile, ClassVisitor aClassVisitor) throws IOException{ final WarReader warReader = new WarReader(pluginFile, true); try { String fileName = warReader.nextClass(); while (fileName != null) { analyze(warReader.getInputStream(), aClassVisitor); fileName = warReader.nextClass(); } } finally { warReader.close(); } }","public void analyzeWithClassVisitor(File pluginFile, ClassVisitor aClassVisitor) throws IOException{ try (WarReader warReader = new WarReader(pluginFile, true)) { String fileName = warReader.nextClass(); while (fileName != null) { analyze(warReader.getInputStream(), aClassVisitor); fileName = warReader.nextClass(); } } }" 264, ,"public ChannelInstance getRoundRobinChannel(){ if (channelKeyList == null || channelKeyList.size() == 0) { return null; } Channel channel = null; InstanceDetails instanceDetails = null; String channelKey = null; while (channel == null) { try { if (channelKeyList.size() == 0) { return null; } int number = roundRobinLong.getAndIncrement(); int index = number % channelKeyList.size(); System.out.println(""index=number/size, ["" + number + ""/"" + channelKeyList.size() + ""]"" + "", index="" + index); channelKey = channelKeyList.get(index); instanceDetails = channelInstanceMap.get(channelKey); channel = channelMap.get(channelKey); } catch (Exception e) { channel = null; e.printStackTrace(); } } System.out.println(""use roundRobin algorithm to find an channel, channelKey="" + channelKey + "", instanceDetails="" + instanceDetails); return new ChannelInstance(channel, instanceDetails); }","public ChannelInstance getRoundRobinChannel(){ if (channelKeyList == null || channelKeyList.size() == 0) { return null; } String channelKey = null; ChannelInstance channelInstance = null; while (channelInstance == null) { try { if (channelKeyList.size() == 0) { return null; } int number = roundRobinLong.getAndIncrement(); int index = number % channelKeyList.size(); System.out.println(""index=number/size, ["" + number + ""/"" + channelKeyList.size() + ""]"" + "", index="" + index); channelKey = channelKeyList.get(index); channelInstance = channelInstanceMap.get(channelKey); } catch (Exception e) { channelInstance = null; e.printStackTrace(); } } System.out.println(""use roundRobin algorithm to find an channelInstance="" + channelInstance); return channelInstance; }" 265, ,"public Result encode(String sourceFilename, String destinationFilename){ log.info(""Start encoding "" + sourceFilename); Result res = new Result(); fileEncoder.encode(sourceFilename, destinationFilename, res); if (res.getInf().get(0).getCode() != -1) { log.info(""Stop encoding file "" + sourceFilename); } else { emailClient.sendFailedMessage(sourceFilename); } return res; }","public Result encode(String sourceFilename, String destinationFilename){ log.info(""Start encoding "" + sourceFilename); Result res = fileEncoder.encode(sourceFilename, destinationFilename); if (res.isSuccessful()) { log.info(""Stop encoding file "" + sourceFilename); } else { emailClient.sendFailedMessage(sourceFilename); } return res; }" 266, ,"public Optional findByProductIdAndAttributeDicId(String attributeValTableName, Long productId, Long attributeDicId){ final String sqlQuery = String.format(""select id, value, attribute_dic_id, attribute_link_id, product_id from %s where product_id = ? and attribute_dic_id = ?"", attributeValTableName); return jdbcTemplate.queryForObject(sqlQuery, (rs, rowNum) -> { DictionaryAttributeValDto dto = new DictionaryAttributeValDto(); dto.setAttributeId(rs.getLong(""id"")).setAttributeValue(rs.getString(""value"")).setAttributeDicId(rs.getLong(""attribute_dic_id"")).setAttributeLinkId(rs.getLong(""attribute_link_id"")).setProductId(rs.getLong(""product_id"")); return Optional.of(dto); }, productId, attributeDicId); }","public Optional findByProductIdAndAttributeDicId(String attributeValTableName, Long productId, Long attributeDicId){ final String sqlQuery = String.format(""select id, value, attribute_dic_id, attribute_link_id, product_id from %s where product_id = ? and attribute_dic_id = ?"", attributeValTableName); return jdbcTemplate.queryForObject(sqlQuery, (rs, rowNum) -> Optional.of(new DictionaryAttributeValDto().setAttributeId(rs.getLong(""id"")).setAttributeValue(rs.getString(""value"")).setAttributeDicId(rs.getLong(""attribute_dic_id"")).setAttributeLinkId(rs.getLong(""attribute_link_id"")).setProductId(rs.getLong(""product_id""))), productId, attributeDicId); }" 267, ,"private Single getDatabaseAccountAsync(URL serviceEndpoint){ HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.set(HttpConstants.HttpHeaders.VERSION, HttpConstants.Versions.CURRENT_VERSION); UserAgentContainer userAgentContainer = new UserAgentContainer(); String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix(); if (userAgentSuffix != null && userAgentSuffix.length() > 0) { userAgentContainer.setSuffix(userAgentSuffix); } httpHeaders.set(HttpConstants.HttpHeaders.USER_AGENT, userAgentContainer.getUserAgent()); httpHeaders.set(HttpConstants.HttpHeaders.API_TYPE, Constants.Properties.SQL_API_TYPE); String authorizationToken = StringUtils.EMPTY; if (this.hasAuthKeyResourceToken || baseAuthorizationTokenProvider == null) { authorizationToken = HttpUtils.urlEncode(this.authKeyResourceToken); } else { String xDate = Utils.nowAsRFC1123(); httpHeaders.set(HttpConstants.HttpHeaders.X_DATE, xDate); Map header = new HashMap<>(); header.put(HttpConstants.HttpHeaders.X_DATE, xDate); try { authorizationToken = baseAuthorizationTokenProvider.generateKeyAuthorizationSignature(HttpConstants.HttpMethods.GET, serviceEndpoint.toURI(), header); } catch (URISyntaxException e) { e.printStackTrace(); } } httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorizationToken); HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, serviceEndpoint, serviceEndpoint.getPort()).withHeaders(httpHeaders); Mono httpResponse = httpClient.send(httpRequest); return toDatabaseAccountObservable(httpResponse); }","private Single getDatabaseAccountAsync(URI serviceEndpoint){ HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.set(HttpConstants.HttpHeaders.VERSION, HttpConstants.Versions.CURRENT_VERSION); UserAgentContainer userAgentContainer = new UserAgentContainer(); String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix(); if (userAgentSuffix != null && userAgentSuffix.length() > 0) { userAgentContainer.setSuffix(userAgentSuffix); } httpHeaders.set(HttpConstants.HttpHeaders.USER_AGENT, userAgentContainer.getUserAgent()); httpHeaders.set(HttpConstants.HttpHeaders.API_TYPE, Constants.Properties.SQL_API_TYPE); String authorizationToken; if (this.hasAuthKeyResourceToken || baseAuthorizationTokenProvider == null) { authorizationToken = HttpUtils.urlEncode(this.authKeyResourceToken); } else { String xDate = Utils.nowAsRFC1123(); httpHeaders.set(HttpConstants.HttpHeaders.X_DATE, xDate); Map header = new HashMap<>(); header.put(HttpConstants.HttpHeaders.X_DATE, xDate); authorizationToken = baseAuthorizationTokenProvider.generateKeyAuthorizationSignature(HttpConstants.HttpMethods.GET, serviceEndpoint, header); } httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorizationToken); HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, serviceEndpoint, serviceEndpoint.getPort(), httpHeaders); Mono httpResponse = httpClient.send(httpRequest); return toDatabaseAccountObservable(httpResponse); }" 268, ,"private void setTooltip(final T component, final TooltipStateData state){ if (component == null) { throw new IllegalArgumentException(""Tooltips4Vaadin requires a non null component in order to set a tooltip""); } final boolean attached = component.getElement().getNode().isAttached(); final Page page = ui.getPage(); if (state.getCssClass() != null) { ensureCssClassIsSet(state); if (attached) { TooltipsUtil.securelyAccessUI(ui, () -> page.executeJs(JS_METHODS.UPDATE_TOOLTIP, state.getCssClass(), state.getTooltipConfig().toJson()).then(json -> setTippyId(state, json))); } } else { String uniqueClassName = CLASS_PREFIX + state.getTooltipId(); component.addClassName(uniqueClassName); state.setCssClass(uniqueClassName); Runnable register = () -> TooltipsUtil.securelyAccessUI(ui, () -> { ensureCssClassIsSet(state); page.executeJs(JS_METHODS.SET_TOOLTIP, state.getCssClass(), state.getTooltipConfig().toJson()).then(json -> setTippyId(state, json), err -> log.fine(() -> ""Tooltips: js error: "" + err)); }); if (attached) { register.run(); } Registration attachReg = component.addAttachListener(evt -> register.run()); state.setAttachReg(new WeakReference<>(attachReg)); Registration detachReg = component.addDetachListener(evt -> TooltipsUtil.securelyAccessUI(ui, () -> closeFrontendTooltip(state, Optional.empty()))); state.setDetachReg(new WeakReference<>(detachReg)); } }","private void setTooltip(final T component, final TooltipStateData tooltipState){ if (component == null) { throw new IllegalArgumentException(""Tooltips4Vaadin requires a non null component in order to set a tooltip""); } if (tooltipState.getCssClass() != null) { updateKnownComponent(component, tooltipState); } else { initiallySetupComponent(component, tooltipState); } }" 269, ," void setUp(){ vc = new VigenereCipher(key); ; }"," void setUp(){ vc = new VigenereCipher(key); }" 270, ,"public PowerHost findHostForVm(Vm vm, Set excludedHosts){ Comparator hostPowerConsumptionComparator = (h1, h2) -> { double h1PowerDiff = getPowerAfterAllocationDifference(h1, vm); double h2PowerDiff = getPowerAfterAllocationDifference(h2, vm); return (int) Math.ceil(h1PowerDiff - h2PowerDiff); }; return this.getHostList().stream().filter(h -> !excludedHosts.contains(h)).filter(h -> h.isSuitableForVm(vm)).filter(h -> !isHostOverUtilizedAfterAllocation(h, vm)).filter(h -> getPowerAfterAllocation(h, vm) > 0).min(hostPowerConsumptionComparator).orElse(PowerHost.NULL); }","public PowerHost findHostForVm(Vm vm, Set excludedHosts){ Comparator hostPowerConsumptionComparator = (h1, h2) -> Double.compare(getPowerAfterAllocationDifference(h1, vm), getPowerAfterAllocationDifference(h2, vm)); return this.getHostList().stream().filter(h -> !excludedHosts.contains(h)).filter(h -> h.isSuitableForVm(vm)).filter(h -> !isHostOverUtilizedAfterAllocation(h, vm)).filter(h -> getPowerAfterAllocation(h, vm) > 0).min(hostPowerConsumptionComparator).orElse(PowerHost.NULL); }" 271, ,"public void createMilestone(Milestone m) throws TracRpcException{ Object[] params = new Object[] { m.getName(), m.getAttribs() }; Integer result = (Integer) this.call(""ticket.milestone.create"", params); if (result > 0) { throw new TracRpcException(""ticket.milestone.create returned error "" + result.toString()); } }","public void createMilestone(Milestone m) throws TracRpcException{ this.sendBasicStruct(m, ""ticket.milestone.create""); }" 272, ,"public FxNode eval(FxChildWriter dest, FxEvalContext ctx, FxNode src){ FxObjNode srcObj = (FxObjNode) src; String name = FxNodeValueUtils.getStringOrThrow(srcObj, ""name""); FxNode template = FxNodeValueUtils.getOrThrow(srcObj, ""template""); FxNode templateCopy = FxNodeCopyVisitor.cloneMemNode(template); FxReplaceTemplateCopyFunc macroFunc = new FxReplaceTemplateCopyFunc(templateCopy); ctx.getFuncRegistry().registerFunc(name, macroFunc); return null; }","public void eval(FxChildWriter dest, FxEvalContext ctx, FxNode src){ FxObjNode srcObj = (FxObjNode) src; String name = FxNodeValueUtils.getStringOrThrow(srcObj, ""name""); FxNode template = FxNodeValueUtils.getOrThrow(srcObj, ""template""); FxNode templateCopy = FxNodeCopyVisitor.cloneMemNode(template); FxReplaceTemplateCopyFunc macroFunc = new FxReplaceTemplateCopyFunc(templateCopy); ctx.getFuncRegistry().registerFunc(name, macroFunc); }" 273, ,"public AppResponse getAccountByAccountNumber(String accountNumber){ Logger.debug(""Starting deleteAccountByAccountNumber() in AccountServiceImpl for [{}]"", accountNumber); AppResponse resp = null; if (StringUtils.isNullOrEmpty(accountNumber)) { Logger.error(""Failed to get the account as the account number is null/empty""); return new AppResponse(false, ""Failed to delete the account as the account number is null/empty"", new ErrorDetails(Constants.ERROR_CODE_VALIDATION, ""Account Number is found null/empty"")); } resp = accountDao.getAccountByAccountNumber(accountNumber); if (!resp.isStatus() || resp.getData() == null) { Logger.error(""Failed to get as the account is not found""); return new AppResponse(false, ""Failed to get as the account is not found"", new ErrorDetails(Constants.ERROR_CODE_VALIDATION, ""Account is not found in db for requested account number"")); } resp = accountDao.deleteAccountByAccountNumber(accountNumber); if (!resp.isStatus()) { return new AppResponse(false, ""Account not found in Db"", resp.getError()); } Logger.info(""Account deleted successfully having account number [{}]"", accountNumber); return resp; }","public AppResponse getAccountByAccountNumber(String accountNumber){ Logger.debug(""Starting getAccountByAccountNumber() in AccountServiceImpl for [{}]"", accountNumber); AppResponse resp = null; if (StringUtils.isNullOrEmpty(accountNumber)) { Logger.error(""Failed to get the account as the account number is null/empty""); return new AppResponse(false, ""Failed to delete the account as the account number is null/empty"", new ErrorDetails(Constants.ERROR_CODE_VALIDATION, ""Account Number is found null/empty"")); } resp = accountDao.getAccountByAccountNumber(accountNumber); if (!resp.isStatus() || resp.getData() == null) { Logger.error(""Failed to get as the account is not found""); return new AppResponse(false, ""Failed to get as the account is not found"", new ErrorDetails(Constants.ERROR_CODE_VALIDATION, ""Account is not found in db for requested account number"")); } Account acc = (Account) resp.getData(); Logger.info(""Account fetched successfully having account number [{}]"", acc); return resp; }" 274, ,"public void run(){ System.out.println(getName() + "" - start""); try { final String table = createTable(); final String path = getPath(); final Loader loader = new Loader(path, table); loader.write(); } catch (Exception ex) { ex.printStackTrace(); } System.out.println(getName() + "" - DONE""); }","public void run(){ System.out.println(getName() + "" - start""); try { final String table = createTable(); saveTable(table); } catch (Exception ex) { ex.printStackTrace(); } System.out.println(getName() + "" - DONE""); }" 275, ,"protected void processStop(){ terminating = true; if (sockets == 0) { sendDone(); poller.removeHandle(mailboxHandle); poller.stop(); } }","protected void processStop(){ terminating = true; if (socketsReaping == 0) { finishTerminating(); } }" 276, ,"public Builder id(final String id){ assert (id != null); assert (!id.equals("""")); return setPathParameter(""id"", id); }","public Builder id(final String id){ assertHasAndNotNull(id); return setPathParameter(""id"", id); }" 277, ,"private boolean checkUser(String username, String password){ User user = userDao.getUser(username, 0); if (user == null) { return false; } return BCrypt.checkpw(password, user.getPswd()); }","private boolean checkUser(String username, String password){ User user = userDao.getUser(username, 0); return user != null && BCrypt.checkpw(password, user.getPswd()); }" 278, ,"protected void validate(final Task entity) throws ServiceException{ try { Assert.notNull(entity, ""The class must not be null""); Assert.hasText(entity.getDescription(), ""'description' must not be empty""); Assert.hasText(entity.getType(), ""'type' must not be empty""); TaskType.validate(entity.getType()); if (entity.getHelper() != null) RenderType.validate(entity.getHelper().getRenderType()); } catch (final Exception e) { throw new ServiceException(e.getMessage(), e); } }","protected void validate(final Task entity) throws ServiceException{ try { Assert.notNull(entity, ""The class must not be null""); Assert.notNull(entity.getType(), ""'type' must not be empty""); Assert.hasText(entity.getDescription(), ""'description' must not be empty""); if (entity.getHelper() != null) RenderType.validate(entity.getHelper().getRenderType()); } catch (final Exception e) { throw new ServiceException(e.getMessage(), e); } }" 279, ,"public boolean mutate(TestCase test, TestFactory factory){ JsonElement oldVal = this.jsonElement; int lim = 4; int current = 0; while (this.jsonElement.equals(oldVal) && current < lim) { if (Randomness.nextDouble() <= Properties.RANDOM_PERTURBATION) { randomize(); } else { delta(); } current++; } this.value = gson.toJson(this.jsonElement); return true; }","public boolean mutate(TestCase test, TestFactory factory){ JsonElement oldVal = this.jsonElement; int current = 0; while (this.jsonElement.equals(oldVal) && current < Properties.GRAMMAR_JSON_MUTATION_RETRY_LIMIT) { if (Randomness.nextDouble() <= Properties.RANDOM_PERTURBATION) { this.randomize(); } else { this.delta(); } current++; } this.value = gson.toJson(this.jsonElement); return true; }" 280, ,"protected PStmtKey createKey(final String sql, final String[] columnNames){ String catalog = null; try { catalog = getCatalog(); } catch (final SQLException e) { } return new PStmtKey(normalizeSQL(sql), catalog, columnNames); }","protected PStmtKey createKey(final String sql, final String[] columnNames){ return new PStmtKey(normalizeSQL(sql), getCatalogOrNull(), columnNames); }" 281, ,"public Optional create(Map fields){ Optional result = Optional.empty(); if (isRegisterFormValid(fields)) { String email = fields.get(RequestParameter.EMAIL); String firstName = fields.get(RequestParameter.FIRST_NAME); String lastName = fields.get(RequestParameter.LAST_NAME); String dateOfBirth = fields.get(RequestParameter.DATE_OF_BIRTH); String phoneNumber = fields.get(RequestParameter.PHONE_NUMBER); User user = new User(DEFAULT_ROLE, DEFAULT_ACTIVE_VALUE, DEFAULT_PHOTO_NAME, firstName, lastName, LocalDate.parse(dateOfBirth), phoneNumber, email); result = Optional.of(user); } return result; }","public Optional create(Map fields){ Optional result = Optional.empty(); if (isRegisterFormValid(fields)) { String email = fields.get(RequestParameter.EMAIL); String firstName = fields.get(RequestParameter.FIRST_NAME); String lastName = fields.get(RequestParameter.LAST_NAME); String dateOfBirth = fields.get(RequestParameter.DATE_OF_BIRTH); String phoneNumber = fields.get(RequestParameter.PHONE_NUMBER); result = Optional.of(new User(DEFAULT_ROLE, DEFAULT_ACTIVE_VALUE, DEFAULT_PHOTO_NAME, firstName, lastName, LocalDate.parse(dateOfBirth), phoneNumber, email)); } return result; }" 282, ,"protected void addColumnValue(PrintWriter writer, DataTable table, List components, String tag, UIColumn column) throws IOException{ FacesContext context = FacesContext.getCurrentInstance(); writer.append(""\t\t<"" + tag + "">""); if (LangUtils.isNotBlank(column.getExportValue())) { writer.append(EscapeUtils.forXml(column.getExportValue())); } else if (column.getExportFunction() != null) { writer.append(EscapeUtils.forXml(exportColumnByFunction(context, column))); } else if (LangUtils.isNotBlank(column.getField())) { String value = table.getConvertedFieldValue(context, column); writer.append(EscapeUtils.forXml(Objects.toString(value, Constants.EMPTY_STRING))); } else { for (UIComponent component : components) { if (component.isRendered()) { String value = exportValue(context, component); if (value != null) { writer.append(EscapeUtils.forXml(value)); } } } } writer.append(""\n""); }","protected void addColumnValue(PrintWriter writer, DataTable table, List components, String tag, UIColumn column) throws IOException{ FacesContext context = FacesContext.getCurrentInstance(); writer.append(""\t\t<"" + tag + "">""); exportColumn(context, table, column, components, false, (s) -> writer.append(EscapeUtils.forXml(s))); writer.append(""\n""); }" 283, ,"public void testConstructor() throws Exception{ Constructor constructor = MoreIterables.class.getDeclaredConstructor(); assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue(); constructor.setAccessible(true); Throwable thrown = catchThrowable(constructor::newInstance); assertThat(thrown).isInstanceOf(InvocationTargetException.class); assertThat(thrown.getCause()).isExactlyInstanceOf(IllegalStateException.class).hasMessage(""This class should not be instantiated""); }","public void testConstructor() throws Exception{ Constructor constructor = MoreIterables.class.getDeclaredConstructor(); assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue(); constructor.setAccessible(true); assertThat(catchThrowable(constructor::newInstance)).isInstanceOf(InvocationTargetException.class).hasCauseExactlyInstanceOf(IllegalStateException.class); }" 284, ,"public void execute(){ vertx.runOnContext(action -> { Optional.ofNullable(excecuteEventBusAndReply).ifPresent(evFunction -> { try { evFunction.execute(vertx, t, errorMethodHandler, context, headers, encoder, errorHandler, onFailureRespond, httpStatusCode, retryCount); } catch (Exception e) { e.printStackTrace(); } }); Optional.ofNullable(byteSupplier).ifPresent(supplier -> { int retry = retryCount; byte[] result = new byte[0]; boolean errorHandling = false; while (retry >= 0) { try { result = supplier.get(); retry = -1; } catch (Throwable e) { retry--; if (retry < 0) { result = RESTExecutionUtil.handleError(result, errorHandler, onFailureRespond, errorMethodHandler, e); errorHandling = true; } else { RESTExecutionUtil.handleError(errorHandler, e); } } } if (errorHandling && result == null) return; repond(result); }); }); }","public void execute(){ vertx.runOnContext(action -> { Optional.ofNullable(excecuteEventBusAndReply).ifPresent(evFunction -> { try { evFunction.execute(vertx, t, errorMethodHandler, context, headers, encoder, errorHandler, onFailureRespond, httpStatusCode, retryCount); } catch (Exception e) { e.printStackTrace(); } }); Optional.ofNullable(byteSupplier).ifPresent(supplier -> { int retry = retryCount; byte[] result = null; Optional.ofNullable(ResponseUtil.createResponse(retry, result, supplier, errorHandler, onFailureRespond, errorMethodHandler)).ifPresent(res -> repond(res)); }); }); }" 285, ,"public FxNode eval(FxChildWriter dest, FxEvalContext ctx, FxNode src){ FxObjNode srcObj = (FxObjNode) src; int startIndex = FxNodeValueUtils.getOrDefault(srcObj, ""start"", 0); int incr = FxNodeValueUtils.getOrDefault(srcObj, ""incr"", 1); int endIndex = FxNodeValueUtils.getIntOrThrow(srcObj, ""end""); String iterIndexName = FxNodeValueUtils.getOrDefault(srcObj, ""indexName"", ""index""); FxNode templateNode = srcObj.get(""template""); if (incr == 0 || (incr > 0 && endIndex < startIndex) || (incr < 0 && endIndex > startIndex)) { throw new IllegalArgumentException(); } if (templateNode == null) { return null; } FxArrayNode res = dest.addArray(); FxChildWriter resChildAdder = res.insertBuilder(); FxMemRootDocument tmpDoc = new FxMemRootDocument(); FxObjNode tmpObj = tmpDoc.setContentObj(); FxIntNode tmpIndexNode = tmpObj.put(iterIndexName, 0); FxEvalContext childCtx = ctx.createChildContext(); Map replVars = new HashMap(); replVars.put(iterIndexName, tmpIndexNode); FxVarsReplaceFunc replaceVarsFunc = new FxVarsReplaceFunc(replVars); for (int index = startIndex; ((incr > 0) ? (index < endIndex) : (index > endIndex)); index += incr) { tmpIndexNode.setValue(index); childCtx.putVariable(iterIndexName, index); replaceVarsFunc.eval(resChildAdder, childCtx, templateNode); } return res; }","public void eval(FxChildWriter dest, FxEvalContext ctx, FxNode src){ FxObjNode srcObj = (FxObjNode) src; int startIndex = FxNodeValueUtils.getOrDefault(srcObj, ""start"", 0); int incr = FxNodeValueUtils.getOrDefault(srcObj, ""incr"", 1); int endIndex = FxNodeValueUtils.getIntOrThrow(srcObj, ""end""); String iterIndexName = FxNodeValueUtils.getOrDefault(srcObj, ""indexName"", ""index""); FxNode templateNode = srcObj.get(""template""); if (incr == 0 || (incr > 0 && endIndex < startIndex) || (incr < 0 && endIndex > startIndex)) { throw new IllegalArgumentException(); } if (templateNode == null) { return; } FxArrayNode res = dest.addArray(); FxChildWriter resChildAdder = res.insertBuilder(); FxMemRootDocument tmpDoc = new FxMemRootDocument(); FxObjNode tmpObj = tmpDoc.setContentObj(); FxIntNode tmpIndexNode = tmpObj.put(iterIndexName, 0); FxEvalContext childCtx = ctx.createChildContext(); Map replVars = new HashMap(); replVars.put(iterIndexName, tmpIndexNode); FxVarsReplaceFunc replaceVarsFunc = new FxVarsReplaceFunc(replVars); for (int index = startIndex; ((incr > 0) ? (index < endIndex) : (index > endIndex)); index += incr) { tmpIndexNode.setValue(index); childCtx.putVariable(iterIndexName, index); replaceVarsFunc.eval(resChildAdder, childCtx, templateNode); } }" 286, ,"public Builder id(final String id){ assert (id != null); assert (!id.equals("""")); return setPathParameter(""id"", id); }","public Builder id(final String id){ assertHasAndNotNull(id); return setPathParameter(""id"", id); }" 287, ,"private List> querySource(String query, int maxResults) throws InternalErrorException, FileNotFoundException, IOException{ List> subjects = new ArrayList<>(); int index = query.indexOf(""=""); int indexContains = query.indexOf(""contains""); if (index != -1) { String queryType = query.substring(0, index); String value = query.substring(index + 1); switch(queryType) { case ""id"": subjects = executeQueryTypeID(value, maxResults); break; case ""email"": subjects = executeQueryTypeEmail(value, maxResults); break; case ""group"": subjects = executeQueryTypeGroupSubjects(value, maxResults); break; default: throw new IllegalArgumentException(""Word before '=' symbol can be 'id' or 'email' or 'group', nothing else.""); } } else { if (indexContains != -1) { String queryType = query.substring(0, indexContains).trim(); String value = query.substring(indexContains + ""contains"".trim().length()); if (queryType.equals(""email"")) { subjects = executeQueryTypeContains(value.trim()); } else { throw new IllegalArgumentException(""Search for substrings is possible only for 'email' attribute.""); } } else { throw new InternalErrorException(""Wrong query!""); } } return subjects; }","private void querySource(String query, int maxResults, List> subjects) throws InternalErrorException, FileNotFoundException, IOException{ int index = query.indexOf(""=""); int indexContains = query.indexOf(""contains""); if (index != -1) { String queryType = query.substring(0, index); String value = query.substring(index + 1); switch(queryType) { case ""id"": executeQueryTypeID(value, maxResults, subjects); break; case ""email"": executeQueryTypeEmail(value, maxResults, subjects); break; case ""group"": executeQueryTypeGroupSubjects(value, maxResults, subjects); break; default: throw new IllegalArgumentException(""Word before '=' symbol can be 'id' or 'email' or 'group', nothing else.""); } } else { if (indexContains != -1) { String queryType = query.substring(0, indexContains).trim(); String value = query.substring(indexContains + ""contains"".trim().length()); if (queryType.equals(""email"")) { executeQueryTypeContains(value.trim(), subjects); } else { throw new IllegalArgumentException(""Search for substrings is possible only for 'email' attribute.""); } } else { throw new InternalErrorException(""Wrong query!""); } } }" 288, ,"public GithubUser getUser(String accessToken){ OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(""https://api.github.com/user?access_token="" + accessToken).build(); try { Response response = client.newCall(request).execute(); String string = response.body().string(); GithubUser githubUser = JSON.parseObject(string, GithubUser.class); return githubUser; } catch (IOException e) { } return null; }","public GithubUser getUser(String accessToken){ OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(""https://api.github.com/user?access_token="" + accessToken).build(); try { Response response = client.newCall(request).execute(); String string = response.body() != null ? response.body().string() : null; return JSON.parseObject(string, GithubUser.class); } catch (IOException ignored) { } return null; }" 289, ,"public void recordEvent(int dataId, byte value){ if (weaveStartDataId == -1 || weaveEndDataId == -1) { setDataId(); } if (dataId == weaveStartDataId) isRecord = true; if (isRecord) countOccurrence(dataId); if (dataId == weaveEndDataId) { isRecord = false; this.close(); } }","public void recordEvent(int dataId, byte value){ if (dataId == weaver.getFilteringStartDataId()) isRecord = true; if (isRecord) countOccurrence(dataId); if (dataId == weaver.getFilteringEndDataId()) { isRecord = false; this.close(); } }" 290, ,"private Map, Integer> getDistances(Graph graph){ DijkstraShortestPath dijkstra = new DijkstraShortestPath<>(graph); Map, Integer> distanceMap = new HashMap<>(); for (V vertex : graph.vertexSet()) { ShortestPathAlgorithm.SingleSourcePaths distances = dijkstra.getPaths(vertex); for (V n : graph.vertexSet()) { GraphPath graphPath = distances.getPath(n); if (graphPath == null) { continue; } Pair pair = Pair.of(vertex, n); if (distanceMap.containsKey(pair)) { log.trace(""about to replace {},{} with {},{},{}"", pair, distanceMap.get(pair), vertex, n, graphPath.getWeight()); } if (graphPath.getWeight() != 0) { distanceMap.put(Pair.of(vertex, n), (int) graphPath.getWeight()); } } } return distanceMap; }","private Map, Integer> getDistances(Graph graph){ DijkstraShortestPath dijkstra = new DijkstraShortestPath<>(graph); Map, Integer> distanceMap = new HashMap<>(); for (V vertex : graph.vertexSet()) { ShortestPathAlgorithm.SingleSourcePaths distances = dijkstra.getPaths(vertex); for (V n : graph.vertexSet()) { GraphPath graphPath = distances.getPath(n); if (graphPath != null && graphPath.getWeight() != 0) { distanceMap.put(Pair.of(vertex, n), (int) graphPath.getWeight()); } } } return distanceMap; }" 291, ,"public int[] returnSortedBallsWithSelectionSort(int[] baskets, SortOrder sortOrder){ int sortedIndexPosition = 0; int idx = 0; List basketsList = Arrays.stream(baskets).boxed().collect(Collectors.toList()); for (int k = sortedIndexPosition; k < baskets.length; k++) { if (sortOrder.name().equals(SortOrder.ASCENDING.name())) { idx = IntStream.range(sortedIndexPosition, basketsList.size()).reduce((i, j) -> basketsList.get(i) > basketsList.get(j) ? j : i).getAsInt(); } else { idx = IntStream.range(sortedIndexPosition, basketsList.size()).reduce((i, j) -> basketsList.get(i) < basketsList.get(j) ? j : i).getAsInt(); } Collections.swap(basketsList, sortedIndexPosition, idx); sortedIndexPosition++; } return basketsList.stream().mapToInt(Integer::intValue).toArray(); }","public int[] returnSortedBallsWithSelectionSort(int[] baskets, SortOrder sortOrder){ int idx = 0; List basketsList = Arrays.stream(baskets).boxed().collect(Collectors.toList()); for (int sortedIndexPosition = 0; sortedIndexPosition < basketsList.size(); sortedIndexPosition++) { if (sortOrder.name().equals(SortOrder.ASCENDING.name())) { idx = IntStream.range(sortedIndexPosition, basketsList.size()).reduce((i, j) -> basketsList.get(i) > basketsList.get(j) ? j : i).getAsInt(); } else { idx = IntStream.range(sortedIndexPosition, basketsList.size()).reduce((i, j) -> basketsList.get(i) < basketsList.get(j) ? j : i).getAsInt(); } Collections.swap(basketsList, sortedIndexPosition, idx); } return basketsList.stream().mapToInt(Integer::intValue).toArray(); }" 292, ,"public EbicsRequest buildEbicsRequest() throws EbicsException{ final DataTransferRequestType.OrderData orderData = OBJECT_FACTORY.createDataTransferRequestTypeOrderData(); try { orderData.setValue(IOUtil.read(contentFactory.getContent())); } catch (final IOException e) { throw new EbicsException(e); } final DataTransferRequestType dataTransfer = OBJECT_FACTORY.createDataTransferRequestType(); dataTransfer.setOrderData(orderData); final EbicsRequest.Body body = OBJECT_FACTORY.createEbicsRequestBody(); body.setDataTransfer(dataTransfer); return EbicsXmlFactory.request(session.getConfiguration(), EbicsXmlFactory.header(EbicsXmlFactory.mutableHeader(TransactionPhaseType.TRANSFER, segmentNumber, lastSegment), EbicsXmlFactory.staticHeader(session.getHostId(), transactionId)), body); }","public EbicsRequest buildEbicsRequest() throws EbicsException{ final DataTransferRequestType.OrderData orderData = OBJECT_FACTORY.createDataTransferRequestTypeOrderData(); try { orderData.setValue(IOUtil.read(contentFactory.getContent())); } catch (final IOException e) { throw new EbicsException(e); } final DataTransferRequestType dataTransfer = OBJECT_FACTORY.createDataTransferRequestType(); dataTransfer.setOrderData(orderData); return request(session.getConfiguration(), header(mutableHeader(TransactionPhaseType.TRANSFER, segmentNumber, lastSegment), staticHeader(session.getHostId(), transactionId)), body(dataTransfer)); }" 293, ,"private void displayLocalMap(Sprite background, List sprites){ if (sprites.size() > 0) { GraphicsContext gc = context.getLocalMapCanvas().getGraphicsContext2D(); background.draw(gc); List orderedSprites = calcRenderOrder(sprites); orderedSprites.forEach(s -> { s.draw(gc); }); } }","private void displayLocalMap(Sprite background, List sprites){ if (sprites.size() > 0) { GraphicsContext gc = context.getLocalMapCanvas().getGraphicsContext2D(); background.draw(gc); sprites.forEach(s -> s.draw(gc)); } }" 294, ,"private ValueNode parseCharacter(final String fieldName) throws SQLException{ final ScannerPosition position = this.token.getPosition(); this.expect(TokenType.CHARACTER); final String fieldAlias = getFieldAlias(fieldName); return new ValueNode(fieldName, fieldAlias, position, Types.VARCHAR); }","private ValueNode parseCharacter(final String fieldName) throws SQLException{ final ScannerPosition position = this.token.getPosition(); this.expect(TokenType.CHARACTER); return new ValueNode(fieldName, fieldName, position, Types.VARCHAR); }" 295, ,"public final ASTNode visitExpr(final ExprContext ctx){ if (null != ctx.booleanPrimary()) { return visit(ctx.booleanPrimary()); } if (null != ctx.LP_()) { return visit(ctx.expr(0)); } if (null != ctx.logicalOperator()) { BinaryOperationExpression result = new BinaryOperationExpression(); result.setStartIndex(ctx.start.getStartIndex()); result.setStopIndex(ctx.stop.getStopIndex()); result.setLeft((ExpressionSegment) visit(ctx.expr(0))); result.setRight((ExpressionSegment) visit(ctx.expr(1))); result.setOperator(ctx.logicalOperator().getText()); String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex())); result.setText(text); return result; } NotExpression result = new NotExpression(); result.setStartIndex(ctx.start.getStartIndex()); result.setStopIndex(ctx.stop.getStopIndex()); result.setExpression((ExpressionSegment) visit(ctx.expr(0))); String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex())); result.setText(text); return result; }","public final ASTNode visitExpr(final ExprContext ctx){ if (null != ctx.booleanPrimary()) { return visit(ctx.booleanPrimary()); } if (null != ctx.LP_()) { return visit(ctx.expr(0)); } if (null != ctx.logicalOperator()) { BinaryOperationExpression result = new BinaryOperationExpression(); result.setStartIndex(ctx.start.getStartIndex()); result.setStopIndex(ctx.stop.getStopIndex()); result.setLeft((ExpressionSegment) visit(ctx.expr(0))); result.setRight((ExpressionSegment) visit(ctx.expr(1))); result.setOperator(ctx.logicalOperator().getText()); String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex())); result.setText(text); return result; } NotExpression result = new NotExpression(); result.setStartIndex(ctx.start.getStartIndex()); result.setStopIndex(ctx.stop.getStopIndex()); result.setExpression((ExpressionSegment) visit(ctx.expr(0))); return result; }" 296, ,"private void checkCurrentConnections(){ int len = server_connections_list.size(); for (int i = len - 1; i >= 0; --i) { ServerConnectionState connection_state = (ServerConnectionState) server_connections_list.get(i); try { if (!connection_state.isProcessingRequest()) { ServerConnection connection = connection_state.getConnection(); if (connection_state.hasPendingCommand() || connection.requestPending()) { connection_state.setPendingCommand(); connection_state.setProcessingRequest(); final ServerConnectionState current_state = connection_state; database.execute(null, null, new Runnable() { public void run() { try { current_state.getConnection().processRequest(); } catch (IOException e) { Debug().writeException(Lvl.INFORMATION, e); } finally { current_state.clearInternal(); } } }); } } } catch (IOException e) { try { connection_state.getConnection().close(); } catch (IOException e2) { } server_connections_list.remove(i); Debug().write(Lvl.INFORMATION, this, ""IOException generated while checking connections, "" + ""removing provider.""); Debug().writeException(Lvl.INFORMATION, e); } } }","private void checkCurrentConnections(){ int len = server_connections_list.size(); for (int i = len - 1; i >= 0; --i) { ServerConnectionState connection_state = (ServerConnectionState) server_connections_list.get(i); try { if (!connection_state.isProcessingRequest()) { ServerConnection connection = connection_state.getConnection(); if (connection_state.hasPendingCommand() || connection.requestPending()) { connection_state.setPendingCommand(); connection_state.setProcessingRequest(); final ServerConnectionState current_state = connection_state; database.execute(null, null, () -> { try { current_state.getConnection().processRequest(); } catch (IOException e) { Debug().writeException(Lvl.INFORMATION, e); } finally { current_state.clearInternal(); } }); } } } catch (IOException e) { try { connection_state.getConnection().close(); } catch (IOException e2) { } server_connections_list.remove(i); Debug().write(Lvl.INFORMATION, this, ""IOException generated while checking connections, "" + ""removing provider.""); Debug().writeException(Lvl.INFORMATION, e); } } }" 297, ,"public synchronized String[] keysComparator(){ Set key_set = properties.keySet(); String[] keys = new String[key_set.size()]; int index = 0; Iterator it = key_set.iterator(); while (it.hasNext()) { keys[index] = (String) it.next(); ++index; } return keys; }","public synchronized String[] keysComparator(){ Set key_set = properties.keySet(); String[] keys = new String[key_set.size()]; int index = 0; for (Object o : key_set) { keys[index] = (String) o; ++index; } return keys; }" 298, ,"private String constructSQLInsertStatement(){ String sqlInsertStatement = ""INSERT INTO dbo.Role (Name) VALUES ""; String valueString = """"; for (String role : roleCollection.getRoles()) { valueString = ""(\'"" + role + ""\'), ""; sqlInsertStatement += valueString; } sqlInsertStatement = sqlInsertStatement.substring(0, sqlInsertStatement.length() - 2) + "";""; System.out.println(sqlInsertStatement); return sqlInsertStatement; }","private String constructSQLInsertStatement(){ StringBuilder sqlInsertStatement = new StringBuilder(""INSERT INTO dbo.Role (Name) VALUES ""); for (String role : roleCollection.getRoles()) { sqlInsertStatement.append(""('"").append(role).append(""'), ""); } return sqlInsertStatement.substring(0, sqlInsertStatement.length() - 2) + "";""; }" 299, ,"public Person createPerson(Person person){ Connection newConnection = DbConnection.getDbConnection(); try { String sql = ""insert into person (first_name, last_name, age, phone_number, email_address)"" + "" values(?,?,?,?,?) returning person_id;""; PreparedStatement createPersonStatement = newConnection.prepareStatement(sql); createPersonStatement.setString(1, person.getFirstName()); createPersonStatement.setString(2, person.getLastName()); createPersonStatement.setInt(3, person.getAge()); createPersonStatement.setString(4, person.getPhoneNumber()); createPersonStatement.setString(5, person.getEmailAddress()); ResultSet result = createPersonStatement.executeQuery(); if (result.next()) { person.setPersonId(result.getInt(""person_Id"")); } } catch (SQLException e) { BankAppLauncher.appLogger.catching(e); BankAppLauncher.appLogger.error(""Internal error occured in the database""); } return person; }","public Person createPerson(Person person){ Connection newConnection = DbConnection.getDbConnection(); try { String sql = ""insert into person (first_name, last_name, age, phone_number, email_address)"" + "" values(?,?,?,?,?) returning person_id;""; PreparedStatement createPersonStatement = newConnection.prepareStatement(sql); createPersonStatement.setString(1, person.getFirstName()); createPersonStatement.setString(2, person.getLastName()); createPersonStatement.setInt(3, person.getAge()); createPersonStatement.setString(4, person.getPhoneNumber()); createPersonStatement.setString(5, person.getEmailAddress()); ResultSet result = createPersonStatement.executeQuery(); if (result.next()) { person.setPersonId(result.getInt(""person_Id"")); } } catch (SQLException e) { BankAppLauncher.appLogger.error(""Internal error occured in the database""); } return person; }" 300, ,"protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception{ if (state() == State.HEADER) { int nLoc = in.bytesBefore((byte) '\n'); ByteBuf headerBuf = in.readBytes(nLoc + 1); String headerLine = headerBuf.toString(UTF8).trim(); nLoc = in.bytesBefore((byte) '\n'); in.readBytes(nLoc); in.readByte(); if (headerLine.startsWith(CONTENT_LENGTH)) { String lenStr = headerLine.substring(CONTENT_LENGTH.length()).trim(); this.length = Integer.parseInt(lenStr); state(State.BODY); } } if (this.length < 0) { System.err.println(""LEN LESS THAN 0""); } if (state() == State.BODY) { if (in.readableBytes() < this.length) { return; } ByteBuf jsonBuf = in.slice(in.readerIndex(), this.length); in.readerIndex(in.readerIndex() + this.length); this.length = -1; ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true); JsonNode node = mapper.readTree(new ByteBufInputStream((ByteBuf) jsonBuf)); String type = node.get(""type"").asText(); if (""request"".equals(type)) { String commandStr = node.get(""command"").asText(); AbstractCommand command = this.debugger.getCommand(commandStr); if (command != null) { ObjectReader reader = mapper.reader().withValueToUpdate(command.newRequest()); Request request = reader.readValue(node); out.add(request); } } state(State.HEADER); } }","protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception{ if (state() == State.HEADER) { int nLoc = in.bytesBefore((byte) '\n'); ByteBuf headerBuf = in.readBytes(nLoc + 1); String headerLine = headerBuf.toString(UTF8).trim(); nLoc = in.bytesBefore((byte) '\n'); in.readBytes(nLoc); in.readByte(); if (headerLine.startsWith(CONTENT_LENGTH)) { String lenStr = headerLine.substring(CONTENT_LENGTH.length()).trim(); this.length = Integer.parseInt(lenStr); state(State.BODY); return; } } if (state() == State.BODY) { ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true); JsonNode node = mapper.readTree(new ByteBufInputStream(in, this.length)); String type = node.get(""type"").asText(); if (""request"".equals(type)) { String commandStr = node.get(""command"").asText(); AbstractCommand command = this.debugger.getCommand(commandStr); if (command != null) { ObjectReader reader = mapper.reader().withValueToUpdate(command.newRequest()); Request request = reader.readValue(node); out.add(request); } } state(State.HEADER); this.length = -1; } }" 301, ,"public void checkAttributeValue(PerunSessionImpl perunSession, Resource resource, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException{ if (attribute.getValue() == null) { throw new WrongAttributeValueException(attribute); } Facility facility = perunSession.getPerunBl().getResourcesManagerBl().getFacility(perunSession, resource); Attribute facilityAttr = null; try { facilityAttr = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, facility, A_F_homeMountPoints); } catch (AttributeNotExistsException ex) { throw new InternalErrorException(ex); } if (facilityAttr.getValue() == null) throw new WrongReferenceAttributeValueException(attribute, facilityAttr, ""Reference attribute have null value.""); if (!((List) facilityAttr.getValue()).containsAll((List) attribute.getValue())) { throw new WrongAttributeValueException(attribute); } List homeMountPoints = (List) attribute.getValue(); if (!homeMountPoints.isEmpty()) { Pattern pattern = Pattern.compile(""^/[-a-zA-Z.0-9_/]*$""); for (String st : homeMountPoints) { Matcher match = pattern.matcher(st); if (!match.matches()) { throw new WrongAttributeValueException(attribute, ""Bad homeMountPoints attribute format "" + st); } } } }","public void checkAttributeValue(PerunSessionImpl perunSession, Resource resource, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException{ if (attribute.getValue() == null) { throw new WrongAttributeValueException(attribute); } Facility facility = perunSession.getPerunBl().getResourcesManagerBl().getFacility(perunSession, resource); Attribute facilityAttr = null; try { facilityAttr = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, facility, A_F_homeMountPoints); } catch (AttributeNotExistsException ex) { throw new InternalErrorException(ex); } if (facilityAttr.getValue() == null) throw new WrongReferenceAttributeValueException(attribute, facilityAttr, ""Reference attribute have null value.""); if (!((List) facilityAttr.getValue()).containsAll((List) attribute.getValue())) { throw new WrongAttributeValueException(attribute); } List homeMountPoints = (List) attribute.getValue(); if (!homeMountPoints.isEmpty()) { for (String st : homeMountPoints) { Matcher match = pattern.matcher(st); if (!match.matches()) { throw new WrongAttributeValueException(attribute, ""Bad homeMountPoints attribute format "" + st); } } } }" 302, ,"private ServiceSchedule parseDaySchedule(String strSchedule, TimeInterval timeInterval) throws ParseException{ DayOfWeek dayOfWeek = dayFormat.parse(strSchedule.substring(0, 3)).toInstant().atZone(ZoneId.systemDefault()).toLocalDate().getDayOfWeek(); ServiceSchedule serviceSchedule = new ServiceSchedule(); serviceSchedule.setOpenTime(LocalDateTime.of(LocalDate.of(1970, 1, 4), timeInterval.getInitialTime()).with(TemporalAdjusters.next(dayOfWeek))); LocalDateTime localEndTime = LocalDateTime.of(LocalDate.of(1970, 1, 4), timeInterval.getEndTime()).with(TemporalAdjusters.next(dayOfWeek)); if (timeInterval.getEndTime().isAfter(LocalTime.of(0, 0, 0)) && timeInterval.getEndTime().isBefore(timeInterval.getInitialTime())) { localEndTime = localEndTime.plusDays(1); } serviceSchedule.setCloseTime(localEndTime); return serviceSchedule; }","private ServiceSchedule parseDaySchedule(String strSchedule, TimeInterval timeInterval) throws ParseException{ DayOfWeek dayOfWeek = dayFormat.parse(strSchedule.substring(0, 3)).toInstant().atZone(ZoneId.systemDefault()).toLocalDate().getDayOfWeek(); ServiceSchedule serviceSchedule = setOpenAndCloseTime(timeInterval, dayOfWeek.getValue()); return serviceSchedule; }" 303, ,"private List getCrashedImage(BlockUml blockUml, Throwable t, SFile outputFile) throws IOException{ final GeneratedImage image = new GeneratedImageImpl(outputFile, ""Crash Error"", blockUml, FileImageData.CRASH); OutputStream os = null; try { os = outputFile.createBufferedOutputStream(); UmlDiagram.exportDiagramError(os, t, fileFormatOption, 42, null, blockUml.getFlashData(), UmlDiagram.getFailureText2(t, blockUml.getFlashData())); } finally { if (os != null) { os.close(); } } return Collections.singletonList(image); }","private List getCrashedImage(BlockUml blockUml, Throwable t, SFile outputFile) throws IOException{ final GeneratedImage image = new GeneratedImageImpl(outputFile, ""Crash Error"", blockUml, FileImageData.CRASH); try (OutputStream os = outputFile.createBufferedOutputStream()) { UmlDiagram.exportDiagramError(os, t, fileFormatOption, 42, null, blockUml.getFlashData(), UmlDiagram.getFailureText2(t, blockUml.getFlashData())); } return Collections.singletonList(image); }" 304, ,"public String addCommentForUserGame(@RequestBody CommentsForGameDTO commentsForGameDTO){ CommentsForGame commentsForGame = new CommentsForGame(); commentsForGame = CommentForGameMapper.toEntity(commentsForGameDTO); commentsForGame.setGameUser(gameUserService.getUserGamesById(commentsForGameDTO.getGameID())); commentsForGame.setUser(userService.getUser(WebUtil.getPrincipalUsername())); commentForGameService.addComment(commentsForGame); return """"; }","public void addCommentForUserGame(@RequestBody CommentsForGameDTO commentsForGameDTO){ CommentsForGame commentsForGame = new CommentsForGame(); commentsForGame = CommentForGameMapper.toEntity(commentsForGameDTO); commentsForGame.setGameUser(gameUserService.getUserGamesById(commentsForGameDTO.getGameID())); commentsForGame.setUser(userService.getUser(WebUtil.getPrincipalUsername())); commentForGameService.addComment(commentsForGame); }" 305, ,"public void execute(){ Profiler profiler = new Profiler(); profiler.start(); ConfigHelper.inputConfigValidation(this.configuration.getInputConfig()); ConfigHelper.outputConfigValidation(this.configuration.getOutputConfig()); logger.info(""Start execution for input type "" + this.configuration.getInputConfig().inputType()); long lastLine = this.dataIteration(); this.printLogToOutput(profiler, lastLine); }","public void execute(){ Profiler profiler = new Profiler(); profiler.start(); this.validation(); logger.info(""Start execution for input type "" + this.configuration.getInputConfig().inputType()); long lastLine = this.dataIteration(); this.printLogToOutput(profiler, lastLine); }" 306, ,"public void parse(ByteBuffer b, Data data){ int size = b.get() & 0xff; ByteBuffer buf = b.slice(); buf.limit(size); b.position(b.position() + size); int count = buf.get() & 0xff; data.putList(); parseChildren(data, buf, count); }","public void parse(ProtonBuffer buffer, Data data){ int size = buffer.readByte() & 0xff; ProtonBuffer buf = buffer.slice(buffer.getReadIndex(), size); buffer.skipBytes(size); int count = buf.readByte() & 0xff; data.putList(); parseChildren(data, buf, count); }" 307, ,"private void parseHtmlMarkup(Message resultMessage){ StringBuilder messageBuilder = new StringBuilder(resultMessage.text()); if (messageBuilder.indexOf(""-\n"") != -1) { MessageEntity[] entityArray = resultMessage.entities(); int globalOffset = 0; String preStart = ""
"";
        String preEnd = ""
""; for (int i = 0; i < entityArray.length; i++) { MessageEntity entity = entityArray[i]; switch(entity.type()) { case pre: { messageBuilder.insert(entity.offset() + globalOffset, preStart); globalOffset += preStart.length(); messageBuilder.insert(entity.offset() + entity.length() + globalOffset, preEnd); globalOffset += preEnd.length(); break; } default: break; } } int preStartIndex = messageBuilder.indexOf(preStart); int preEndIndex = messageBuilder.indexOf(preEnd); if (preStartIndex != -1 && preEndIndex != -1) { message = messageBuilder.substring(preStartIndex + preStart.length(), preEndIndex); } LOG.debug(""Parsed message: {}"", message); } }","private void parseHtmlMarkup(Message resultMessage){ StringBuilder messageBuilder = new StringBuilder(resultMessage.text()); if (messageBuilder.indexOf(""-\n"") != -1) { MessageEntity[] entityArray = resultMessage.entities(); int globalOffset = 0; String preStart = ""
"";
        String preEnd = ""
""; for (int i = 0; i < entityArray.length; i++) { MessageEntity entity = entityArray[i]; switch(entity.type()) { case pre: { messageBuilder.insert(entity.offset() + globalOffset, preStart); globalOffset += preStart.length(); messageBuilder.insert(entity.offset() + entity.length() + globalOffset, preEnd); globalOffset += preEnd.length(); break; } default: break; } } int preStartIndex = messageBuilder.indexOf(preStart); int preEndIndex = messageBuilder.indexOf(preEnd); if (preStartIndex != -1 && preEndIndex != -1) { message = messageBuilder.substring(preStartIndex + preStart.length(), preEndIndex); } } }" 308, ,"public String getGameScore(){ if (isDeuce()) score = String.valueOf(TennisPoints.Deuce); else if (isPlayerOneAdvantage()) score = playerOne.getName() + SPACE + TennisPoints.Advantage; else if (isPlayerTwoAdvantage()) score = playerTwo.getName() + SPACE + TennisPoints.Advantage; else if (playerOne.getPointScore() == playerTwo.getPointScore()) score = translateScore(playerOne.getPointScore()) + SPACE + ALL; else if (isPlayerTwoWinner()) score = playerTwo.getName() + SPACE + WINS; else score = translateScore(playerOne.getPointScore()) + SPACE + translateScore(playerTwo.getPointScore()); return score; }","public String getGameScore(){ if (isDeuce()) score = String.valueOf(TennisPoints.Deuce); else if (hasAdvantage()) return advantagePlayerName() + "" "" + TennisPoints.Advantage; else if (playerOne.getPointScore() == playerTwo.getPointScore()) score = translateScore(playerOne.getPointScore()) + SPACE + ALL; else if (isPlayerTwoWinner()) score = playerTwo.getName() + SPACE + WINS; else score = translateScore(playerOne.getPointScore()) + SPACE + translateScore(playerTwo.getPointScore()); return score; }" 309, ,"private void onOutcomeSubmitButtonClicked(){ boolean wasSubmitted = false; if (validationService.isNameValid(outcomeNameTextField.getText()) && validationService.isValueValid(outcomeValueTextField.getText()) && isCategorySelected(outcomeCategoryComboBox)) { outcomeService.getAllPositions().add(new Outcome(outcomeNameTextField.getText(), validationService.returnFormattedValue(outcomeValueTextField.getText()), outcomeCategoryComboBox.getSelectionModel().getSelectedItem())); outcomeObservableList.clear(); outcomeObservableList.addAll(outcomeService.getAllPositions()); outcomeCategoryComboBox.getSelectionModel().clearSelection(); outcomeNameTextField.clear(); outcomeValueTextField.clear(); summaryObservableList.clear(); summaryObservableList.addAll(outcomeObservableList); summaryObservableList.addAll(incomeObservableList); outcomeNameRequiredText.setVisible(false); outcomeWrongValueText.setVisible(false); outcomeSelectCategoryText.setVisible(false); wasSubmitted = true; outcomeTableView.sort(); } if (!wasSubmitted) { validAllMessagesUnderFields(outcomeNameTextField, outcomeNameRequiredText, outcomeValueTextField, outcomeWrongValueText, outcomeCategoryComboBox, outcomeSelectCategoryText); } }","private void onOutcomeSubmitButtonClicked(){ boolean wasSubmitted = false; if (validationService.isNameValid(outcomeNameTextField.getText()) && validationService.isValueValid(outcomeValueTextField.getText()) && isCategorySelected(outcomeCategoryComboBox)) { outcomeService.getAllPositions().add(new Outcome(outcomeNameTextField.getText(), validationService.returnFormattedValue(outcomeValueTextField.getText()), outcomeCategoryComboBox.getSelectionModel().getSelectedItem())); clearPositionAfterSubmitted(outcomeObservableList, outcomeService, outcomeTableView, outcomeCategoryComboBox, outcomeNameTextField, outcomeValueTextField, outcomeNameRequiredText, outcomeWrongValueText, outcomeSelectCategoryText); wasSubmitted = true; } if (!wasSubmitted) { validAllMessagesUnderFields(outcomeNameTextField, outcomeNameRequiredText, outcomeValueTextField, outcomeWrongValueText, outcomeCategoryComboBox, outcomeSelectCategoryText); } }" 310, ,"public void run(){ try { synchronized (this) { Starter.addToDb(employeeDAO, subList); } } catch (FileNotFoundException e) { e.printStackTrace(); } }","public void run(){ synchronized (this) { employeeDAO.insertEmployee(subList); } }" 311, ,"public T1Entity save(T1Entity entity) throws ClientException, ParseException{ if (entity == null) return null; JsonResponse finalJsonResponse; StringBuilder uri = getUri(entity); String uriPath = entity.getUri(); if (checkString(uriPath)) uri.append(uriPath); String path = t1Service.constructUrl(uri); Response responseObj = this.connection.post(path, entity.getForm(), this.user); String response = responseObj.readEntity(String.class); T1JsonToObjParser parser = new T1JsonToObjParser(); if (response.isEmpty()) return null; JsonPostErrorResponse error = jsonPostErrorResponseParser(response, responseObj); if (error != null) throwExceptions(error); finalJsonResponse = parsePostData(response, parser, entity); if (finalJsonResponse == null) return null; return finalJsonResponse.getData(); }","public T1Entity save(T1Entity entity) throws ClientException, ParseException{ if (entity == null) return null; JsonResponse finalJsonResponse; StringBuilder uri = getUri(entity); String uriPath = entity.getUri(); if (checkString(uriPath)) uri.append(uriPath); String path = t1Service.constructUrl(uri); Response responseObj = this.connection.post(path, entity.getForm(), this.user); finalJsonResponse = getJsonResponse(entity, responseObj); if (finalJsonResponse == null) return null; return finalJsonResponse.getData(); }" 312, ,"public void showCards(){ programCardsToChooseFrom = roboGame.localPlayer.getReceivedProgramCards(); for (ProgramCard c : programCardsToChooseFrom) { picked.add(c); } int xStart = 800; int yStart = 295; int width = 120; int height = 200; int deltaW = 125; int deltaH = 205; int i = 0; for (int x = xStart; x < xStart + 3 * deltaW; x += deltaW) { for (int y = yStart; y < yStart + 3 * deltaH; y += deltaH) { ProgramCard currentCard = roboGame.localPlayer.getReceivedProgramCards().remove(0); ImageButton imageButton = CardUI.createTextureButton((""/cards/"" + currentCard.getProgramCardType().toString())); imageButton.setPosition(x, y); imageButton.setSize(width, height); imageButton.addListener(new CardInputListener(imageButton, this, x, y, width, height, i)); startCardsStage.addActor(imageButton); i++; } } }","public void showCards(){ programCardsToChooseFrom = roboGame.localPlayer.getReceivedProgramCards(); picked.addAll(programCardsToChooseFrom); int xStart = 800; int yStart = 295; int width = 120; int height = 200; int deltaW = 125; int deltaH = 205; int i = 0; for (int x = xStart; x < xStart + 3 * deltaW; x += deltaW) { for (int y = yStart; y < yStart + 3 * deltaH; y += deltaH) { ProgramCard currentCard = roboGame.localPlayer.getReceivedProgramCards().remove(0); ImageButton imageButton = CardUI.createTextureButton((""/cards/"" + currentCard.getProgramCardType().toString())); imageButton.setPosition(x, y); imageButton.setSize(width, height); imageButton.addListener(new CardInputListener(imageButton, this, x, y, width, height, i)); startCardsStage.addActor(imageButton); i++; } } }" 313, ,"public FxNode eval(FxChildWriter dest, FxEvalContext ctx, FxNode src){ FxObjNode srcObj = (FxObjNode) src; FxObjNode params = (FxObjNode) srcObj.get(""params""); if (params != null) { Map varReplacements = params.fieldsHashMapCopy(); FxVarsReplaceFunc replFunc = new FxVarsReplaceFunc(varReplacements); replFunc.eval(dest, ctx, template); } else { FxNodeCopyVisitor.copyTo(dest, template); } return null; }","public void eval(FxChildWriter dest, FxEvalContext ctx, FxNode src){ FxObjNode srcObj = (FxObjNode) src; FxObjNode params = (FxObjNode) srcObj.get(""params""); if (params != null) { Map varReplacements = params.fieldsHashMapCopy(); FxVarsReplaceFunc replFunc = new FxVarsReplaceFunc(varReplacements); replFunc.eval(dest, ctx, template); } else { FxNodeCopyVisitor.copyTo(dest, template); } }" 314, ,"public static List evaluateCapturedArguments(final List statements, final List capturedArguments){ if (capturedArguments.isEmpty()) { return statements; } else { final List capturedArgValues = capturedArguments.stream().map(a -> a.getValue()).collect(Collectors.toList()); statements.stream().forEach(s -> s.accept(new StatementExpressionsDelegateVisitor(new CapturedArgumentsEvaluator(capturedArgValues)))); return statements; } }","public static List evaluateCapturedArguments(final List statements, final List capturedArguments){ if (capturedArguments.isEmpty()) { return statements; } final List capturedArgValues = capturedArguments.stream().map(a -> a.getValue()).collect(Collectors.toList()); statements.stream().forEach(s -> s.accept(new StatementExpressionsDelegateVisitor(new CapturedArgumentsEvaluator(capturedArgValues)))); return statements; }" 315, ,"private void generateMetaPropertyMapSetup(){ data.ensureImport(MetaProperty.class); data.ensureImport(DirectMetaPropertyMap.class); insertRegion.add(""\t\t/**""); insertRegion.add(""\t\t * The meta-properties.""); insertRegion.add(""\t\t */""); insertRegion.add(""\t\tprivate final Map> "" + config.getPrefix() + ""metaPropertyMap$ = new DirectMetaPropertyMap(""); if (data.isSubClass()) { insertRegion.add(""\t\t\t\tthis, (DirectMetaPropertyMap) super.metaPropertyMap()"" + (properties.size() == 0 ? "");"" : "","")); } else { insertRegion.add(""\t\t\t\tthis, null"" + (properties.size() == 0 ? "");"" : "","")); } for (int i = 0; i < properties.size(); i++) { String line = ""\t\t\t\t\"""" + properties.get(i).getData().getPropertyName() + ""\""""; line += (i + 1 == properties.size() ? "");"" : "",""); insertRegion.add(line); } insertRegion.add(""""); }","private void generateMetaPropertyMapSetup(){ data.ensureImport(MetaProperty.class); data.ensureImport(DirectMetaPropertyMap.class); insertRegion.add(""\t\t/**""); insertRegion.add(""\t\t * The meta-properties.""); insertRegion.add(""\t\t */""); insertRegion.add(""\t\tprivate final Map> "" + config.getPrefix() + ""metaPropertyMap$ = new DirectMetaPropertyMap(""); if (data.isSubClass()) { insertRegion.add(""\t\t\t\tthis, (DirectMetaPropertyMap) super.metaPropertyMap()"" + (properties.size() == 0 ? "");"" : "","")); } else { insertRegion.add(""\t\t\t\tthis, null"" + (properties.size() == 0 ? "");"" : "","")); } for (int i = 0; i < properties.size(); i++) { insertRegion.add(""\t\t\t\t\"""" + properties.get(i).getData().getPropertyName() + ""\"""" + joinComma(i, properties, "");"")); } insertRegion.add(""""); }" 316, ,"public LoanDetailDTO calculate() throws ResponseException{ if (loanRequestDTO.getNominalRate() == 0) { throw new ResponseException(""ERR-01"", ""Nominal rate can not be zero""); } if (loanRequestDTO.getDuration() == 0) { throw new ResponseException(""ERR-03"", ""Duration can not be zero""); } double rate = loanRequestDTO.getNominalRate() / (12 * 100); BigDecimal borrowerPaymentAmount = BigDecimal.valueOf(rate).multiply(loanRequestDTO.getLoanAmount()).divide(BigDecimal.valueOf((1 - Math.pow(1 + rate, -(loanRequestDTO.getDuration())))), 2, RoundingMode.HALF_UP); LoanDetailDTO loanDetailDTO = new LoanDetailDTO(loanRequestDTO.getLoanAmount(), loanRequestDTO.getNominalRate(), """"); loanDetailDTO.setBorrowerPaymentAmount(borrowerPaymentAmount); loanDetailDTO.setDuration(loanRequestDTO.getDuration()); loanDetailDTO.setStartDate(loanRequestDTO.getStartDate()); LOGGER.info(loanDetailDTO.toString()); return loanDetailDTO; }","public LoanDetailDTO calculate() throws ResponseException{ if (loanRequestDTO.getNominalRate() == 0) { throw new ResponseException(""ERR-01"", ""Nominal rate can not be zero""); } if (loanRequestDTO.getDuration() == 0) { throw new ResponseException(""ERR-03"", ""Duration can not be zero""); } double rate = loanRequestDTO.getNominalRate() / (12 * 100); BigDecimal borrowerPaymentAmount = BigDecimal.valueOf(rate).multiply(loanRequestDTO.getLoanAmount()).divide(BigDecimal.valueOf((1 - Math.pow(1 + rate, -(loanRequestDTO.getDuration())))), 2, RoundingMode.HALF_UP); LoanDetailDTO loanDetailDTO = new LoanDetailDTO(loanRequestDTO.getLoanAmount(), loanRequestDTO.getNominalRate(), loanRequestDTO.getStartDate()); loanDetailDTO.setBorrowerPaymentAmount(borrowerPaymentAmount); loanDetailDTO.setDuration(loanRequestDTO.getDuration()); LOGGER.info(loanDetailDTO.toString()); return loanDetailDTO; }" 317, ,"public void validateConformanceOperationAndResponse(TestPoint testPoint){ String testPointUri = new UriBuilder(testPoint).buildUrl(); Response response = null; try { response = init().baseUri(testPointUri).accept(JSON).when().request(GET); } catch (Exception e) { if (e.getMessage().contains(""dummydata"")) { throw new RuntimeException(""No conformance classes found at the /conformance path.""); } throw new RuntimeException(e); } validateConformanceOperationResponse(testPointUri, response); }","public void validateConformanceOperationAndResponse(TestPoint testPoint){ String testPointUri = new UriBuilder(testPoint).buildUrl(); if (testPointUri.contains(""dummydata"")) { throw new RuntimeException(""No conformance classes found at the /conformance path.""); } Response response = init().baseUri(testPointUri).accept(JSON).when().request(GET); validateConformanceOperationResponse(testPointUri, response); }" 318, ,"public Map getSubAliasProjectNames(String projectId){ Map aliasSubProjects = new LinkedHashMap(); jdbcTemplate = new JdbcTemplate(dataSource); String sql; List> rows; if ("""" != projectId) { sql = ""select SubProjId, AliasSubProjName from subproject where ProjId = ?""; rows = jdbcTemplate.queryForList(sql, new Object[] { projectId }); } else { sql = ""select SubProjId, AliasSubProjName from subproject""; rows = jdbcTemplate.queryForList(sql); } for (Map row : rows) { aliasSubProjects.put(String.valueOf(row.get(""SubProjId"")), (String) row.get(""AliasSubProjName"")); } return aliasSubProjects; }","public Map getSubAliasProjectNames(String projectId){ Map aliasSubProjects = new LinkedHashMap(); String sql; List> rows; if ("""" != projectId) { sql = ""select SubProjId, AliasSubProjName from subproject where ProjId = ?""; rows = jdbcTemplate.queryForList(sql, new Object[] { projectId }); } else { sql = ""select SubProjId, AliasSubProjName from subproject""; rows = jdbcTemplate.queryForList(sql); } for (Map row : rows) { aliasSubProjects.put(String.valueOf(row.get(""SubProjId"")), (String) row.get(""AliasSubProjName"")); } return aliasSubProjects; }" 319, ,"private void initFields(){ teamId_ = 0; sinceTime_ = 0L; limit_ = 0; type_ = org.jailbreak.api.representations.Representations.Donation.DonationType.OFFLINE; }","private void initFields(){ teamId_ = 0; sinceTime_ = 0L; type_ = org.jailbreak.api.representations.Representations.Donation.DonationType.OFFLINE; }" 320, ,"private void onHandshakeDone(Peer peer){ if (!isHandshakeDone) { consenus.onMessage(channel, new BFTNewHeightMessage(peer.getLatestBlockNumber() + 1)); getNodes = exec.scheduleAtFixedRate(() -> { msgQueue.sendMessage(new GetNodesMessage()); }, channel.isInbound() ? 2 : 0, 2, TimeUnit.MINUTES); pingPong = exec.scheduleAtFixedRate(() -> { msgQueue.sendMessage(new PingMessage()); }, channel.isInbound() ? 1 : 0, 1, TimeUnit.MINUTES); isHandshakeDone = true; } }","private void onHandshakeDone(Peer peer){ if (!isHandshakeDone) { consenus.onMessage(channel, new BFTNewHeightMessage(peer.getLatestBlockNumber() + 1)); getNodes = exec.scheduleAtFixedRate(() -> msgQueue.sendMessage(new GetNodesMessage()), channel.isInbound() ? 2 : 0, 2, TimeUnit.MINUTES); pingPong = exec.scheduleAtFixedRate(() -> msgQueue.sendMessage(new PingMessage()), channel.isInbound() ? 1 : 0, 1, TimeUnit.MINUTES); isHandshakeDone = true; } }" 321, ,"public static List getPostsDTOs(){ PostDTO postOne = new PostDTO(); postOne.setId(1L); postOne.setDateCreated(LocalDateTime.now()); postOne.setDateUpdated(LocalDateTime.now()); postOne.setPostTitle(""Test post one title""); postOne.setContent(""Test post one content""); postOne.setCover(""testPostOne.webp""); postOne.setReadTime(10); postOne.setSlug(""test-post-one""); postOne.setPublicationDate(LocalDateTime.now()); PostDTO postTwo = new PostDTO(); postTwo.setId(2L); postTwo.setDateCreated(LocalDateTime.now()); postTwo.setDateUpdated(LocalDateTime.now()); postTwo.setPostTitle(""Test post two title""); postTwo.setContent(""Test post two content""); postTwo.setCover(""testPostTwo.webp""); postTwo.setReadTime(25); postTwo.setSlug(""test-post-two""); postTwo.setPublicationDate(LocalDateTime.now()); PostDTO postThree = new PostDTO(); postThree.setId(3L); postThree.setDateCreated(LocalDateTime.now()); postThree.setDateUpdated(LocalDateTime.now()); postThree.setPostTitle(""Test post three title""); postThree.setContent(""Test post three content""); postThree.setCover(""testPostThree.webp""); postThree.setReadTime(5); postThree.setSlug(""post-three""); return Arrays.asList(postOne, postTwo, postThree); }","public static List getPostsDTOs(){ PostDTO postOne = new PostDTO(); postOne.setDateCreated(LocalDateTime.now()); postOne.setDateUpdated(LocalDateTime.now()); postOne.setTitle(""Test post one title""); postOne.setContent(""Test post one content""); postOne.setCover(""testPostOne.webp""); postOne.setReadTime(10); postOne.setSlug(""test-post-one""); postOne.setPublicationDate(LocalDateTime.now()); PostDTO postTwo = new PostDTO(); postTwo.setDateCreated(LocalDateTime.now()); postTwo.setDateUpdated(LocalDateTime.now()); postTwo.setTitle(""Test post two title""); postTwo.setContent(""Test post two content""); postTwo.setCover(""testPostTwo.webp""); postTwo.setReadTime(25); postTwo.setSlug(""test-post-two""); postTwo.setPublicationDate(LocalDateTime.now()); PostDTO postThree = new PostDTO(); postThree.setDateCreated(LocalDateTime.now()); postThree.setDateUpdated(LocalDateTime.now()); postThree.setTitle(""Test post three title""); postThree.setContent(""Test post three content""); postThree.setCover(""testPostThree.webp""); postThree.setReadTime(5); postThree.setSlug(""post-three""); return Arrays.asList(postOne, postTwo, postThree); }" 322, ,"public void newGame(){ text = scanner.nextLine(); hands = text.split(""\\s+""); for (int i = 0; i < 5; i++) { Card card = new Card(hands[i]); compCards[i] = card; } compHand = new Hand(compCards); for (int i = 5, j = 0; i < 10; i++, j++) { Card card = new Card(hands[i]); oppCards[j] = card; } oppHand = new Hand(oppCards); for (int i = 10, j = 0; i < 13; i++, j++) { Card card = new Card(hands[i]); swapCards[j] = card; System.out.println(card.toString()); } }","public void newGame(){ text = scanner.nextLine(); hands = text.split(""\\s+""); for (int i = 0; i < 5; i++) { Card card = new Card(hands[i]); compCards[i] = card; } compHand = new Hand(compCards); for (int i = 5, j = 0; i < 10; i++, j++) { Card card = new Card(hands[i]); oppCards[j] = card; } oppHand = new Hand(oppCards); for (int i = 10, j = 0; i < 13; i++, j++) { Card card = new Card(hands[i]); swapCards[j] = card; } }" 323, ,"private boolean isValidSPCFile() throws IOException{ raf.seek(0); final String fileHeader = readStuff(HEADER_OFFSET, HEADER_LENGTH).trim().substring(0, CORRECT_HEADER.length()); return (CORRECT_HEADER.equalsIgnoreCase(fileHeader)); }","private boolean isValidSPCFile() throws IOException{ final String fileHeader = readStuff(HEADER_OFFSET, HEADER_LENGTH).trim().substring(0, CORRECT_HEADER.length()); return (CORRECT_HEADER.equalsIgnoreCase(fileHeader)); }" 324, ,"public void setUp() throws Exception{ customerAccount = new CustomerAccount(new AccountRule() { public boolean withdrawPermitted(Double resultingAccountBalance) { return false; } }); }","public void setUp() throws Exception{ customerAccount = new CustomerAccount(new CustomerAccountRule()); }" 325, ,"public Mono saveRecipeCommand(RecipeCommand command){ if (command == null) return null; Recipe availableRecipe = recipeRepository.findById(command.getId()).block(); if (availableRecipe == null) { return recipeRepository.save(recipeCommandToRecipe.convert(command)).map(recipeToRecipeCommand::convert); } availableRecipe.setUrl(command.getUrl()); availableRecipe.setServings(command.getServings()); availableRecipe.setCookTime(command.getCookTime()); availableRecipe.setDescription(command.getDescription()); availableRecipe.setDifficulty(command.getDifficulty()); availableRecipe.setDirections(command.getDirections()); availableRecipe.setPrepTime(command.getPrepTime()); availableRecipe.setSource(command.getSource()); availableRecipe.setNotes(notesCommandToNotes.convert(command.getNotes())); command.getCategories().forEach(categoryCommand -> { availableRecipe.getCategories().add(categoryCommandToCategory.convert(categoryCommand)); }); return recipeRepository.save(availableRecipe).map(recipeToRecipeCommand::convert); }","public Mono saveRecipeCommand(RecipeCommand command){ if (command == null) return null; Recipe availableRecipe = recipeRepository.findById(command.getId()).block(); if (availableRecipe == null) { return recipeRepository.save(recipeCommandToRecipe.convert(command)).map(recipeToRecipeCommand::convert); } availableRecipe.setUrl(command.getUrl()); availableRecipe.setServings(command.getServings()); availableRecipe.setCookTime(command.getCookTime()); availableRecipe.setDescription(command.getDescription()); availableRecipe.setDifficulty(command.getDifficulty()); availableRecipe.setDirections(command.getDirections()); availableRecipe.setPrepTime(command.getPrepTime()); availableRecipe.setSource(command.getSource()); availableRecipe.setNotes(notesCommandToNotes.convert(command.getNotes())); availableRecipe.setCategories(command.getCategories().stream().map(categoryCommandToCategory::convert).collect(Collectors.toSet())); return recipeRepository.save(availableRecipe).map(recipeToRecipeCommand::convert); }" 326, ,"public T remove(int index){ if (!indexCapacity(index)) { throw new ArrayListIndexOutOfBoundsException(""Index are not exist,"" + "" please input right index""); } T value = arrayData[index]; if (indexCapacity(index) && ensureCapacity()) { arrayCopyRemove(index); size--; } else if ((index == size && !ensureCapacity()) || (indexCapacity(index) && !ensureCapacity())) { grow(); arrayCopyRemove(index); size--; } return value; }","public T remove(int index){ if (index < 0 || index >= size) { throw new ArrayListIndexOutOfBoundsException(""Index are not exist,"" + "" please input right index""); } T value = arrayData[index]; arrayCopyRemove(index); return value; }" 327, ,"public Student updateStudentDetails(Integer studentId, String name, String address, String gender, Date dob, Integer age){ Student student = new Student(); student.setStudentId(studentId); student.setName(name); student.setAge(age); student.setAddress(address); student.setGender(gender); student.setDob(dob); return studentRepository.updateStudentDetails(student); }","public Student updateStudentDetails(Student student){ Boolean isValid = validateStudent(student); if (isValid) { return studentRepository.updateStudentDetails(student); } return null; }" 328, ,"private void cleanupEncodeSlotIfNecessary(){ if (encodeSlot != NO_SLOT) { bufferPool.release(encodeSlot); encodeSlot = NO_SLOT; encodeSlotOffset = 0; encodeSlotMarkOffset = 0; if (Http2Configuration.DEBUG_HTTP2_BUDGETS) { System.out.format(""[%d] [cleanupEncodeSlotIfNecessary] [0x%016x] [0x%016x] encode encodeSlotOffset => %d\n"", System.nanoTime(), 0, budgetId, encodeSlotOffset); } } }","private void cleanupEncodeSlotIfNecessary(){ if (encodeSlot != NO_SLOT) { bufferPool.release(encodeSlot); encodeSlot = NO_SLOT; encodeSlotOffset = 0; if (Http2Configuration.DEBUG_HTTP2_BUDGETS) { System.out.format(""[%d] [cleanupEncodeSlotIfNecessary] [0x%016x] [0x%016x] encode encodeSlotOffset => %d\n"", System.nanoTime(), 0, budgetId, encodeSlotOffset); } } }" 329, ,"public ArrayList findAll(){ try { float randomDelay = mySqlDelay(); String query = ""select rooms.id,rooms.number,rooms.floor,rooms.price,rooms.description,rooms_type.roomType,rooms_type.maxCapacity,rooms_type.roomSize,SLEEP(?)"" + "" from rooms"" + "" left join rooms_type"" + "" on rooms.room_type = rooms_type.id""; ArrayList rooms = jdbcTemplate.query(query, new Object[] { randomDelay }, new ResultSetExtractor>() { public ArrayList extractData(ResultSet rs) throws SQLException, DataAccessException { ArrayList result = extractDataFromReultSet(rs); return result; } }); return rooms; } catch (Exception ex) { return null; } }","public ArrayList findAll(){ try { float randomDelay = mySqlDelay(); String query = ""select rooms.id,rooms.number,rooms.floor,rooms.price,rooms.description,rooms_type.roomType,rooms_type.maxCapacity,rooms_type.roomSize,SLEEP(?)"" + "" from rooms"" + "" left join rooms_type"" + "" on rooms.room_type = rooms_type.id""; return jdbcTemplate.query(query, new Object[] { randomDelay }, this::extractDataFromReultSet); } catch (Exception ex) { return null; } }" 330, ,"public Builder uris(final String uris){ assert (uris != null); assert (!uris.equals("""")); assert (uris.split("","").length <= 100); return setQueryParameter(""uris"", uris); }","public Builder uris(final String uris){ assertHasAndNotNull(uris); assert (uris.split("","").length <= 100); return setQueryParameter(""uris"", uris); }" 331, ,"public Map detachVariables(boolean deep){ Map detached = new HashMap(vars.size()); vars.forEach((k, v) -> { switch(v.type) { case JS_FUNCTION: JsFunction jf = new JsFunction(v.getValue()); v = new Variable(jf); break; case MAP: case LIST: if (deep) { Object o = recurseAndDetachAndDeepClone(v.getValue()); v = new Variable(o); } else { recurseAndDetach(v.getValue()); } break; default: } detached.put(k, v); }); return detached; }","protected Map detachVariables(){ Set seen = Collections.newSetFromMap(new IdentityHashMap()); Map detached = new HashMap(vars.size()); vars.forEach((k, v) -> { switch(v.type) { case JS_FUNCTION: JsFunction jf = new JsFunction(v.getValue()); v = new Variable(jf); break; case MAP: case LIST: Object o = recurseAndDetachAndDeepClone(v.getValue(), seen); v = new Variable(o); break; default: } detached.put(k, v); }); return detached; }" 332, ,"public CustomerBill generateBill(CustomerBill bill){ bill.setFinalBill(ds.getFinalDiscountPrice(bill)); return bill; }","public void generateBill(CustomerBill bill){ bill.setFinalBill(ds.getFinalPrice(bill.getBasicBill(), bill.getCustomer().getType())); }" 333, ,"public void run(String testName, boolean conformingMapping){ try { String directoryName = this.mapTestCaseName.get(testName); String configurationDirectory = mappingDirectory + File.separator; String configurationFile = testName + "".morph.properties""; MorphRDBRunnerFactory runnerFactory = new MorphRDBRunnerFactory(); MorphBaseRunner runner = runnerFactory.createRunner(configurationDirectory, configurationFile); runner.run(); System.out.println(""------"" + testName + "" DONE------""); assertTrue(conformingMapping); } catch (Exception e) { e.printStackTrace(); System.out.println(""Error : "" + e.getMessage()); System.out.println(""------"" + testName + "" FAILED------\n\n""); assertTrue(e.getMessage(), !conformingMapping); } }","public void run(String testName, boolean conformingMapping){ try { String configurationDirectory = mappingDirectory + File.separator; String configurationFile = testName + "".morph.properties""; MorphRDBRunnerFactory runnerFactory = new MorphRDBRunnerFactory(); MorphBaseRunner runner = runnerFactory.createRunner(configurationDirectory, configurationFile); runner.run(); System.out.println(""------"" + testName + "" DONE------""); assertTrue(conformingMapping); } catch (Exception e) { e.printStackTrace(); System.out.println(""Error : "" + e.getMessage()); System.out.println(""------"" + testName + "" FAILED------\n\n""); assertTrue(e.getMessage(), !conformingMapping); } }" 334, ,"public FastestSlowestWinnerProducerDto fastestSlowestWinnerProducer(){ List prod = producerRepository.findAll(); System.out.println(""JOEL: "" + prod.stream().filter(p -> p.getName().equalsIgnoreCase(""Joel Silver"")).collect(Collectors.toList())); prod.stream().forEach(p -> p.setIndicateds(p.getIndicateds().stream().filter(i -> i.getWinner().equalsIgnoreCase(""yes"")).collect(Collectors.toList()))); List prodWinners = new ArrayList(); prod.stream().filter(p -> p.getIndicateds().size() > 1).forEach(p -> prodWinners.add(p)); HashMap> intervalMap = new HashMap>(); prodWinners.forEach(p -> p.getIndicateds().stream().iterator().forEachRemaining(i1 -> this.difference(p, i1, intervalMap))); return new FastestSlowestWinnerProducerDto(intervalMap.get(intervalMap.keySet().stream().mapToInt(t -> t).min().getAsInt()), intervalMap.get(intervalMap.keySet().stream().mapToInt(t -> t).max().getAsInt())); }","public FastestSlowestWinnerProducerDto fastestSlowestWinnerProducer(){ List prod = producerRepository.findAll(); prod.stream().forEach(p -> p.setIndicateds(p.getIndicateds().stream().filter(i -> i.getWinner().equalsIgnoreCase(WinnerEnum.YES.getWinner())).collect(Collectors.toList()))); List prodWinners = new ArrayList(); prod.stream().filter(p -> p.getIndicateds().size() > 1).forEach(p -> prodWinners.add(p)); HashMap> intervalMap = new HashMap>(); prodWinners.forEach(p -> p.getIndicateds().stream().iterator().forEachRemaining(i1 -> this.calculateInterval(p, i1, intervalMap))); return new FastestSlowestWinnerProducerDto(intervalMap.get(intervalMap.keySet().stream().mapToInt(t -> t).min().getAsInt()), intervalMap.get(intervalMap.keySet().stream().mapToInt(t -> t).max().getAsInt())); }" 335, ,"private void processData(ByteBuffer data) throws IOException, InterruptedException{ int firstPacketElement = data.getInt(); int seqNum = firstPacketElement & ~LAST_MESSAGE_FLAG_BIT_MASK; boolean isEndOfStream = ((firstPacketElement & LAST_MESSAGE_FLAG_BIT_MASK) != 0); if (seqNum > maxSeqNum || seqNum < 0) { throw new IllegalStateException(""got insane sequence number""); } int offset = seqNum * DATA_PER_FULL_PACKET_WITH_SEQUENCE_NUM * WORD_SIZE; int trueDataLength = offset + data.limit() - SEQUENCE_NUMBER_SIZE; if (trueDataLength > dataReceiver.capacity()) { throw new IllegalStateException(""received more data than expected""); } if (!isEndOfStream || data.limit() != END_FLAG_SIZE) { data.position(SEQUENCE_NUMBER_SIZE); data.get(dataReceiver.array(), offset, trueDataLength - offset); } receivedSeqNums.set(seqNum); if (isEndOfStream) { if (!checkAllReceived()) { finished |= retransmitMissingSequences(); } else { finished = true; } } }","private void processData(ByteBuffer data) throws IOException, InterruptedException{ int firstPacketElement = data.getInt(); int seqNum = firstPacketElement & ~LAST_MESSAGE_FLAG_BIT_MASK; boolean isEndOfStream = ((firstPacketElement & LAST_MESSAGE_FLAG_BIT_MASK) != 0); if (seqNum > maxSeqNum || seqNum < 0) { throw new IllegalStateException(""got insane sequence number""); } int offset = seqNum * DATA_WORDS_PER_PACKET * WORD_SIZE; int trueDataLength = offset + data.limit() - SEQUENCE_NUMBER_SIZE; if (trueDataLength > dataReceiver.capacity()) { throw new IllegalStateException(""received more data than expected""); } if (!isEndOfStream || data.limit() != END_FLAG_SIZE) { data.position(SEQUENCE_NUMBER_SIZE); data.get(dataReceiver.array(), offset, trueDataLength - offset); } receivedSeqNums.set(seqNum); if (isEndOfStream) { finished = retransmitMissingSequences(); } }" 336, ,"private String doConvert(ILoggingEvent event){ boolean maskMeRequired = false; Object[] argumentArray = event.getArgumentArray(); if (argumentArray != null && argumentArray.length > 0) { for (Object obj : argumentArray) { MaskMe annotation = obj.getClass().getAnnotation(MaskMe.class); if (annotation != null) { maskMeRequired = true; break; } } if (maskMeRequired) { List maskedObjs = mask(argumentArray); return MessageFormatter.arrayFormat(event.getMessage(), maskedObjs.toArray()).getMessage(); } } return event.getFormattedMessage(); }","private String doConvert(ILoggingEvent event){ boolean maskMeRequired = false; Object[] argumentArray = event.getArgumentArray(); if (argumentArray != null && argumentArray.length > 0) { for (Object obj : argumentArray) { if (obj.getClass().isAnnotationPresent(Mask.class)) { maskMeRequired = true; break; } } if (maskMeRequired) { val maskedObjs = mask(argumentArray); return MessageFormatter.arrayFormat(event.getMessage(), maskedObjs.toArray()).getMessage(); } } return event.getFormattedMessage(); }" 337, ,"public static int[] findOrder(int numCourses, int[][] prerequisites){ final Deque courses = new ArrayDeque<>(numCourses); final COLOR[] discoveryStatus = new COLOR[numCourses]; for (int i = 0; i < numCourses; i++) discoveryStatus[i] = COLOR.WHITE; final Map> adjList = new HashMap<>(); for (int[] edge : prerequisites) adjList.merge(edge[1], new ArrayList<>(Arrays.asList(edge[0])), (l1, l2) -> { l1.addAll(l2); return l1; }); for (int u = 0; u < numCourses; u++) { if (discoveryStatus[u] == COLOR.WHITE) { final boolean dependencyFound = findDependencies(u, courses, discoveryStatus, adjList); if (!dependencyFound) return new int[0]; } } final int[] coursesArr = new int[numCourses]; for (int i = 0; i < numCourses; i++) coursesArr[i] = courses.poll(); return coursesArr; }","public static int[] findOrder(int numCourses, int[][] prerequisites){ final Deque courses = new ArrayDeque<>(numCourses); final COLOR[] discoveryStatus = new COLOR[numCourses]; for (int i = 0; i < numCourses; i++) discoveryStatus[i] = COLOR.WHITE; final Map> adjList = new HashMap<>(); for (int[] edge : prerequisites) adjList.computeIfAbsent(edge[1], unused -> new ArrayList<>()).add(edge[0]); for (int u = 0; u < numCourses; u++) { if (discoveryStatus[u] == COLOR.WHITE) { final boolean dependencyFound = findDependencies(u, courses, discoveryStatus, adjList); if (!dependencyFound) return new int[0]; } } final int[] coursesArr = new int[numCourses]; for (int i = 0; i < numCourses; i++) coursesArr[i] = courses.poll(); return coursesArr; }" 338, ,"public Integer divide(Integer a, Integer b){ try { return a / b; } catch (Exception e) { System.out.println(""*****Invalid Operation *****""); e.printStackTrace(); System.out.println(""****************************""); return 0; } }","public Integer divide(Integer a, Integer b){ try { return a / b; } catch (Exception e) { e.printStackTrace(); return 0; } }" 339, ,"public Gender checkGenderByFullName(String name){ String[] split = name.split("" ""); int femaleCounter = 0; int maleCounter = 0; for (String element : split) { if (checkIfNameExist(FEMALE_PATH, element)) { femaleCounter++; } else if (checkIfNameExist(MALE_PATH, element)) { maleCounter++; } } return estimateGender(femaleCounter, maleCounter); }","public Gender checkGenderByFullName(String name){ String[] split = name.split("" ""); int femaleCounter = 0; int maleCounter = 0; for (String element : split) { if (checkIfNameExist(FEMALE_PATH, element)) femaleCounter++; else if (checkIfNameExist(MALE_PATH, element)) maleCounter++; } return estimateGender(femaleCounter, maleCounter); }" 340, ,"public void replaceBody(MilterContext context, byte[] body) throws MilterException{ int length; if (body.length > MILTER_CHUNK_SIZE) { length = MILTER_CHUNK_SIZE; } else { length = body.length; } int offset = 0; while (offset < body.length) { MilterPacket packet = MilterPacket.builder().command(SMFIR_REPLBODY).payload(body, offset, length).build(); context.sendPacket(packet); offset += length; if (offset + length >= body.length) { length = body.length - offset; } } }","public void replaceBody(MilterContext context, byte[] body) throws MilterException{ int length = Math.min(body.length, MILTER_CHUNK_SIZE); int offset = 0; while (offset < body.length) { MilterPacket packet = MilterPacket.builder().command(SMFIR_REPLBODY).payload(body, offset, length).build(); context.sendPacket(packet); offset += length; if (offset + length >= body.length) { length = body.length - offset; } } }" 341, ,"public void givenUserWhenPostUserThenUserIsCreatedTest(){ user = UserTestDataGenerator.generateUser(); ApiResponse actualApiResponse = given().contentType(""application/json"").body(user).when().post(""user"").then().statusCode(200).extract().as(ApiResponse.class); ApiResponse expectedApiResponse = new ApiResponse(); expectedApiResponse.setCode(200); expectedApiResponse.setType(""unknown""); expectedApiResponse.setMessage(user.getId().toString()); Assertions.assertThat(actualApiResponse).describedAs(""Send User was different than received by API"").usingRecursiveComparison().isEqualTo(expectedApiResponse); }","public void givenUserWhenPostUserThenUserIsCreatedTest(){ user = UserTestDataGenerator.generateUser(); ApiResponse actualApiResponse = given().contentType(""application/json"").body(user).when().post(""user"").then().statusCode(200).extract().as(ApiResponse.class); ApiResponse expectedApiResponse = ApiResponse.builder().code(HttpStatus.SC_OK).type(""unknown"").message(user.getId().toString()).build(); Assertions.assertThat(actualApiResponse).describedAs(""Send User was different than received by API"").usingRecursiveComparison().isEqualTo(expectedApiResponse); }" 342, ,"public Optional create(Map fields){ Optional result = Optional.empty(); if (isInterviewResultFormValid(fields)) { byte rating = Byte.parseByte(fields.get(RequestParameter.INTERVIEW_RESULT_RATING)); String comment = fields.get(RequestParameter.INTERVIEW_RESULT_COMMENT); InterviewResult interviewResult = new InterviewResult(rating, comment); result = Optional.of(interviewResult); } return result; }","public Optional create(Map fields){ Optional result = Optional.empty(); if (isInterviewResultFormValid(fields)) { byte rating = Byte.parseByte(fields.get(RequestParameter.INTERVIEW_RESULT_RATING)); String comment = fields.get(RequestParameter.INTERVIEW_RESULT_COMMENT); result = Optional.of(new InterviewResult(rating, comment)); } return result; }" 343, ," double evaluate(JavaRDD evalData){ double totalSquaredDist = 0.0; for (ClusterMetric metric : fetchClusterMetrics(evalData).values().collect()) { totalSquaredDist += metric.getSumSquaredDist(); } return totalSquaredDist; }"," double evaluate(JavaRDD evalData){ return fetchClusterMetrics(evalData).values().mapToDouble(ClusterMetric::getSumSquaredDist).sum(); }" 344, ,"public void delete(int i){ validateIndex(i); if (!contains(i)) throw new NoSuchElementException(""index is not in the priority queue""); int index = qp[i]; exch(index, n--); swim(index); sink(index); keys[i] = null; qp[i] = -1; }","public void delete(int i){ validateIndex(i); noSuchElement(!contains(i), ""index is not in the priority queue""); int index = qp[i]; exch(index, n--); swim(index); sink(index); keys[i] = null; qp[i] = -1; }" 345, ,"protected Object invokeMethod(Object object, Method method, Object... params){ String failMessage = ""Could not invoke the method '"" + method.getName() + ""' in the class "" + method.getDeclaringClass().getSimpleName() + BECAUSE; try { return method.invoke(object, params); } catch (@SuppressWarnings(""unused"") IllegalAccessException iae) { fail(failMessage + "" access to the method was denied. Make sure to check the modifiers of the method.""); } catch (@SuppressWarnings(""unused"") IllegalArgumentException iae) { fail(failMessage + "" the parameters are not implemented right. Make sure to check the parameters of the method""); } catch (InvocationTargetException e) { fail(failMessage + "" of an exception within the method: "" + e.getCause()); } return null; }","protected Object invokeMethod(Object object, Method method, Object... params){ String failMessage = ""Could not invoke the method '"" + method.getName() + ""' in the class "" + method.getDeclaringClass().getSimpleName() + BECAUSE; try { invokeMethodRethrowing(object, method, params); } catch (Throwable e) { fail(failMessage + "" of an exception within the method: "" + e); } return null; }" 346, ,"public void set(T value, int index){ if (index < size && index >= 0) { elements[index] = value; } else { throw new ArrayIndexOutOfBoundsException(); } }","public void set(T value, int index){ if (index >= size || index < 0) { throw new ArrayIndexOutOfBoundsException(); } elements[index] = value; }" 347, ,"public void testUpdateViewTime(){ try { List userList = userService.getUers(); User user = new User(""nobody@email.com"", ""nobody""); user.setId(userList.size() + 10); User userRe = userService.updateLastviewTime(user); log.info(""----- userRe : "" + userRe); Assert.fail(""Can not update the unregistered user""); } catch (NewsfeedException e) { Assert.assertTrue(e.getMessage().contains(""Not Found"")); } try { User user = userService.createUser(""abcde@email.com"", ""abcde""); User userRe = userService.updateLastviewTime(user); Assert.assertEquals(user.getId(), userRe.getId()); Assert.assertEquals(user.getLastViewTime(), userRe.getLastViewTime()); Assert.assertEquals(null, userService.getUser(user.getId()).getLastViewTime()); } catch (NewsfeedException e) { Assert.fail(""Fail to update""); } }","public void testUpdateViewTime(){ try { List userList = userService.getUsers(); User user = new User(""nobody@email.com"", ""nobody""); user.setId(userList.size() + 10); User userRe = userService.updateLastviewTime(user.getId(), System.currentTimeMillis()); log.info(""----- userRe : "" + userRe); Assert.fail(""Can not update the unregistered user""); } catch (NewsfeedException e) { Assert.assertTrue(e.getMessage().contains(""Not Found"")); } try { User user = userService.createUser(""abcde@email.com"", ""abcde""); User userRe = userService.updateLastviewTime(user.getId(), 0); Assert.assertEquals(user.getId(), userRe.getId()); Assert.assertEquals(0, userService.getUser(user.getId()).getLastviewTime().getTime()); } catch (NewsfeedException e) { Assert.fail(""Fail to update""); } }" 348, ,"public void setValue(Object object, String fieldName, Object value){ if (object == null) { throw new NullPointerException(""provided object is null""); } if (fieldName == null) { throw new NullPointerException(""provided field name is null""); } var objectType = object.getClass(); Field field = util.getFieldSafe(objectType, fieldName); if (field == null) { throw new FieldNotFoundException(String.format(""field '%s'.'%s' is not found"", objectType.getName(), fieldName)); } var fieldType = field.getType(); try { if (value == null) { field.setAccessible(true); field.set(object, null); } else { var valueType = value.getClass(); if (fieldType.isAssignableFrom(valueType)) { field.setAccessible(true); field.set(object, value); } else { throw new ValueNotAssignException(String.format(""field '%s' with class '%s' can not be assign with instance which class '%s'"", fieldName, fieldType.getName(), valueType.getName())); } } } catch (IllegalAccessException e) { throw new RuntimeException(e); } }","public void setValue(Object object, String fieldName, Object value){ if (object == null) { throw new NullPointerException(""provided object is null""); } if (fieldName == null) { throw new NullPointerException(""provided field name is null""); } var objectType = object.getClass(); Field field = util.getFieldSafe(objectType, fieldName); if (field == null) { throw new FieldNotFoundException(String.format(""field '%s'.'%s' is not found"", objectType.getName(), fieldName)); } var fieldType = field.getType(); try { field.setAccessible(true); if (value == null) { field.set(object, null); } else { var valueType = value.getClass(); if (fieldType.isAssignableFrom(valueType)) { field.set(object, value); } else { throw new ValueNotAssignException(String.format(""field '%s' with class '%s' can not be assign with instance which class '%s'"", fieldName, fieldType.getName(), valueType.getName())); } } } catch (IllegalAccessException e) { throw new RuntimeException(e); } }" 349, ,"public org.jailbreak.api.representations.Representations.Donation.DonationsFilters buildPartial(){ org.jailbreak.api.representations.Representations.Donation.DonationsFilters result = new org.jailbreak.api.representations.Representations.Donation.DonationsFilters(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.teamId_ = teamId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.sinceTime_ = sinceTime_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.limit_ = limit_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.type_ = type_; result.bitField0_ = to_bitField0_; onBuilt(); return result; }","public org.jailbreak.api.representations.Representations.Donation.DonationsFilters buildPartial(){ org.jailbreak.api.representations.Representations.Donation.DonationsFilters result = new org.jailbreak.api.representations.Representations.Donation.DonationsFilters(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.teamId_ = teamId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.sinceTime_ = sinceTime_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.type_ = type_; result.bitField0_ = to_bitField0_; onBuilt(); return result; }" 350, ,"public void testSelectRequest_Default(){ UriInfo uriInfo = mock(UriInfo.class); @SuppressWarnings(""unchecked"") MultivaluedMap params = mock(MultivaluedMap.class); when(uriInfo.getQueryParameters()).thenReturn(params); ResourceEntity resourceEntity = parser.parseSelect(getLrEntity(E1.class), uriInfo, null); assertNotNull(resourceEntity); assertTrue(resourceEntity.isIdIncluded()); assertEquals(3, resourceEntity.getAttributes().size()); assertTrue(resourceEntity.getChildren().isEmpty()); }","public void testSelectRequest_Default(){ @SuppressWarnings(""unchecked"") MultivaluedMap params = mock(MultivaluedMap.class); ResourceEntity resourceEntity = parser.parseSelect(getLrEntity(E1.class), params, null); assertNotNull(resourceEntity); assertTrue(resourceEntity.isIdIncluded()); assertEquals(3, resourceEntity.getAttributes().size()); assertTrue(resourceEntity.getChildren().isEmpty()); }" 351, ,"public SCCSignature sign(AbstractSCCKey key, PlaintextContainerInterface plaintext) throws SCCException{ if (key.getKeyType() == KeyType.Asymmetric) { if (usedAlgorithm == null) { ArrayList algorithms = currentSCCInstance.getUsage().getSigning(); for (int i = 0; i < algorithms.size(); i++) { SCCAlgorithm sccalgorithmID = algorithms.get(i); if (getEnums().contains(sccalgorithmID)) { switch(sccalgorithmID) { case ECDSA_512: return SecureCryptoConfig.createSignMessage(plaintext, key, AlgorithmID.ECDSA_512); case ECDSA_256: return SecureCryptoConfig.createSignMessage(plaintext, key, AlgorithmID.ECDSA_256); case ECDSA_384: return SecureCryptoConfig.createSignMessage(plaintext, key, AlgorithmID.ECDSA_384); default: break; } } } } else { switch(usedAlgorithm) { case ECDSA_512: return SecureCryptoConfig.createSignMessage(plaintext, key, AlgorithmID.ECDSA_512); case ECDSA_256: return SecureCryptoConfig.createSignMessage(plaintext, key, AlgorithmID.ECDSA_256); case ECDSA_384: return SecureCryptoConfig.createSignMessage(plaintext, key, AlgorithmID.ECDSA_384); default: break; } } } else { throw new SCCException(""The used SCCKey has the wrong KeyType for this use case. "", new InvalidKeyException()); } throw new SCCException(standardError, new CoseException(null)); }","public SCCSignature sign(AbstractSCCKey key, PlaintextContainerInterface plaintext) throws SCCException{ if (key.getKeyType() == KeyType.Asymmetric) { if (usedAlgorithm == null) { ArrayList algorithms = currentSCCInstance.getUsage().getSigning(); for (int i = 0; i < algorithms.size(); i++) { SCCAlgorithm sccalgorithmID = algorithms.get(i); if (getEnums().contains(sccalgorithmID)) { return decideForAlgoSigning(sccalgorithmID, key, plaintext); } } } else { return decideForAlgoSigning(usedAlgorithm, key, plaintext); } } else { throw new SCCException(""The used SCCKey has the wrong KeyType for this use case. "", new InvalidKeyException()); } throw new SCCException(standardError, new CoseException(null)); }" 352, ,"protected String getSetterName(MetaField f){ StringBuffer methname = new StringBuffer(); methname.append(""set""); int c = f.getName().charAt(0); if (c >= 'a' && c <= 'z') { c = c - ('a' - 'A'); } methname.append((char) c); methname.append(f.getName().substring(1)); return methname.toString(); }","protected String getSetterName(MetaField f){ StringBuilder b = new StringBuilder(); b.append(""set""); uppercase(b, f.getName()); return b.toString(); }" 353, ,"public void cancelQuery(){ SwingUtilities.invokeLater(new Runnable() { public void run() { if (query_finished != 'f') { query_finished = 'c'; block_util.unblock(); } } }); }","public void cancelQuery(){ SwingUtilities.invokeLater(() -> { if (query_finished != 'f') { query_finished = 'c'; block_util.unblock(); } }); }" 354, ,"private int benchJavaMath(){ long timeout = BENCH_TIME; long time = System.currentTimeMillis() + (1000 * timeout); double x, y, val, rate; int count = 0; Random rnd = new Random(); while (time > System.currentTimeMillis()) { x = rnd.nextDouble(); y = rnd.nextDouble(); val = Math.log(x) - y * (Math.sqrt(Math.pow(x, Math.cos(y)))); count++; } rate = count / timeout; return count; }","private int benchJavaMath(){ long time = System.currentTimeMillis() + (1000 * BENCH_TIME); double x, y, val, rate; int count = 0; Random rnd = new Random(); while (time > System.currentTimeMillis()) { x = rnd.nextDouble(); y = rnd.nextDouble(); val = Math.log(x) - y * (Math.sqrt(Math.pow(x, Math.cos(y)))); count++; } return count; }" 355, ,"public String validateAndRegisterNewUser(UserDTO userDTO, BindingResult result) throws MessagingException{ if (result.hasErrors()) { List errors = result.getAllErrors(); for (ObjectError error : errors) { log.info(""Can't register new user, errors occurred during filling form {}"", error); } return ""register-user-form""; } else { Authorities authority = new Authorities(); User user = createUserForm(userDTO, authority); userService.saveUser(user); sendCredentialsMail(userDTO); log.info(""created new user {} sent email on address {}"", userDTO.getUsername(), userDTO.getEmail()); return ""register-success-page""; } }","public String validateAndRegisterNewUser(UserDTO userDTO, BindingResult result) throws MessagingException{ if (result.hasErrors()) { List errors = result.getAllErrors(); for (ObjectError error : errors) { log.info(""Can't register new user, errors occurred during filling form {}"", error); } return ""register-user-form""; } else { userService.saveUser(createUserForm(userDTO, new Authorities())); sendCredentialsMail(userDTO); log.info(""created new user {} sent email on address {}"", userDTO.getUsername(), userDTO.getEmail()); return ""register-success-page""; } }" 356, ,"public void save(TripRequest tripRequest) throws SQLException, NamingException{ Context ctx = new InitialContext(); Context envContext = (Context) ctx.lookup(""java:comp/env""); DataSource dataSource = (DataSource) envContext.lookup(""jdbc/TestDB""); Connection con = null; try { con = dataSource.getConnection(); PreparedStatement insertTripRequest = con.prepareStatement(""INSERT INTO trip_requests"" + ""(trip_id, car_id, message, date_of_creation) VALUES (?, ?, ?, NOW())""); insertTripRequest.setLong(1, tripRequest.getTripInfo().getId()); insertTripRequest.setLong(2, tripRequest.getCarInfo().getId()); if (tripRequest.getMessage() != null) { insertTripRequest.setString(3, tripRequest.getMessage()); } else { insertTripRequest.setNull(3, Types.VARCHAR); } insertTripRequest.execute(); insertTripRequest.close(); } finally { if (con != null) try { con.close(); } catch (Exception ignore) { } } }","public void save(TripRequest tripRequest) throws SQLException, NamingException{ Connection con = null; try { con = dataSource.getConnection(); PreparedStatement insertTripRequest = con.prepareStatement(""INSERT INTO trip_requests"" + ""(trip_id, car_id, message, date_of_creation) VALUES (?, ?, ?, NOW())""); insertTripRequest.setLong(1, tripRequest.getTripInfo().getId()); insertTripRequest.setLong(2, tripRequest.getCarInfo().getId()); if (tripRequest.getMessage() != null) { insertTripRequest.setString(3, tripRequest.getMessage()); } else { insertTripRequest.setNull(3, Types.VARCHAR); } insertTripRequest.execute(); insertTripRequest.close(); } finally { if (con != null) try { con.close(); } catch (Exception ignore) { } } }" 357, ,"public void addColumnFamily(TableName tableName, ColumnFamilyDescriptor columnFamilyDesc) throws IOException{ Modification modification = Modification.newBuilder().setId(columnFamilyDesc.getNameAsString()).setCreate(tableAdapter2x.toColumnFamily(columnFamilyDesc)).build(); modifyColumns(tableName, columnFamilyDesc.getNameAsString(), ""add"", modification); }","public void addColumnFamily(TableName tableName, ColumnFamilyDescriptor columnFamilyDesc) throws IOException{ modifyColumns(tableName, columnFamilyDesc.getNameAsString(), ""add"", ModifyTableBuilder.create().add(TableAdapter2x.toHColumnDescriptor(columnFamilyDesc))); }" 358, ,"public Place build(){ log.info(""Creating place {}"", CODE); Place p = new Place(); p.setName(CODE); p.setCode(CODE); PlaceBranch main = new PlaceBranch(); main.setPlace(p); main.setName(""Shopping Multiplaza Casa Central""); main.setLatitude(-25.3167006); main.setLongitude(-57.572267); main.setImage(""http://www.maxicambios.com.py/media/1044/asuncion_multiplaza.jpg""); main.setPhoneNumber(""(021) 525105/8""); main.setSchedule(""Lunes a Sábados: 8:00 a 21:00 Hs.\n"" + ""Domingos: 10:00 a 21:00 Hs.""); main.setRemoteCode(""0""); PlaceBranch cde = new PlaceBranch(); cde.setPlace(p); cde.setName(""Casa Central CDE""); cde.setLatitude(-25.5083135); cde.setLongitude(-54.6384264); cde.setImage(""http://www.maxicambios.com.py/media/1072/matriz_cde_original.jpg""); cde.setPhoneNumber(""(061) 573106-574270-574295-509511/13""); cde.setSchedule(""Lunes a viernes: 7:00 a 19:30 Hs. \n Sabados: 7:00 a 12:00 Hs.""); cde.setRemoteCode(""13""); p.setBranches(Arrays.asList(main, cde)); return p; }","public Place build(){ log.info(""Creating place {}"", CODE); Place place = new Place(); place.setName(CODE); place.setCode(CODE); PlaceBranch main = new PlaceBranch(); main.setName(""Shopping Multiplaza Casa Central""); main.setLatitude(-25.3167006); main.setLongitude(-57.572267); main.setImage(""http://www.maxicambios.com.py/media/1044/asuncion_multiplaza.jpg""); main.setPhoneNumber(""(021) 525105/8""); main.setSchedule(""Lunes a Sábados: 8:00 a 21:00 Hs.\n"" + ""Domingos: 10:00 a 21:00 Hs.""); main.setRemoteCode(""0""); PlaceBranch cde = new PlaceBranch(); cde.setName(""Casa Central CDE""); cde.setLatitude(-25.5083135); cde.setLongitude(-54.6384264); cde.setImage(""http://www.maxicambios.com.py/media/1072/matriz_cde_original.jpg""); cde.setPhoneNumber(""(061) 573106-574270-574295-509511/13""); cde.setSchedule(""Lunes a viernes: 7:00 a 19:30 Hs. \n Sabados: 7:00 a 12:00 Hs.""); cde.setRemoteCode(""13""); place.setBranches(Arrays.asList(main, cde)); return place; }" 359, ,"protected void createSchema(){ final Session session = configContext.getSession(); final List> manageEntities = configContext.getManageEntities().isEmpty() ? entityClasses : configContext.getManageEntities(); if (configContext.isForceSchemaGeneration()) { for (AbstractUDTClassProperty x : getUdtClassProperties()) { final long udtCountForClass = entityProperties.stream().filter(entityProperty -> manageEntities.contains(entityProperty.entityClass)).flatMap(entityProperty -> entityProperty.allColumns.stream()).filter(property -> property.containsUDTProperty()).filter(property -> property.getUDTClassProperties().contains(x)).count(); if (udtCountForClass > 0) generateUDTAtRuntime(session, x); } final long viewCount = entityProperties.stream().filter(AbstractEntityProperty::isView).count(); if (viewCount > 0) { final Map, AbstractEntityProperty> entityPropertiesMap = entityProperties.stream().filter(AbstractEntityProperty::isTable).collect(Collectors.toMap(x -> x.entityClass, x -> x)); entityProperties.stream().filter(AbstractEntityProperty::isView).map(x -> (AbstractViewProperty) x).forEach(x -> x.setBaseClassProperty(entityPropertiesMap.get(x.getBaseEntityClass()))); } entityProperties.stream().filter(x -> manageEntities.contains(x.entityClass)).forEach(x -> generateSchemaAtRuntime(session, x)); } }","protected void createSchema(){ final Session session = configContext.getSession(); final List> manageEntities = configContext.getManageEntities().isEmpty() ? entityClasses : configContext.getManageEntities(); for (AbstractUDTClassProperty x : getUdtClassProperties()) { final long udtCountForClass = entityProperties.stream().filter(entityProperty -> manageEntities.contains(entityProperty.entityClass)).flatMap(entityProperty -> entityProperty.allColumns.stream()).filter(property -> property.containsUDTProperty()).filter(property -> property.getUDTClassProperties().contains(x)).count(); if (udtCountForClass > 0) generateUDTAtRuntime(session, x); } final long viewCount = entityProperties.stream().filter(AbstractEntityProperty::isView).count(); if (viewCount > 0) { final Map, AbstractEntityProperty> entityPropertiesMap = entityProperties.stream().filter(AbstractEntityProperty::isTable).collect(Collectors.toMap(x -> x.entityClass, x -> x)); entityProperties.stream().filter(AbstractEntityProperty::isView).map(x -> (AbstractViewProperty) x).forEach(x -> x.setBaseClassProperty(entityPropertiesMap.get(x.getBaseEntityClass()))); } entityProperties.stream().filter(x -> manageEntities.contains(x.entityClass)).forEach(x -> generateSchemaAtRuntime(session, x)); }" 360, ,"public Map deleteSpecificUsersInsideTheMap(String userName){ try { pCheckUser.setString(1, userName); pDeleteUser.setString(1, userName); Iterator user = storeData.keySet().iterator(); ResultSet rs = pCheckUser.executeQuery(); if (rs.next()) while (user.hasNext()) if (user.next().contains(userName)) user.remove(); pDeleteUser.executeUpdate(); } catch (SQLException e) { System.out.println(""Error: "" + e); } return storeData; }","public Map deleteSpecificUsersInsideTheMap(String userName){ try { pCheckUser.setString(1, userName); pDeleteUser.setString(1, userName); Iterator user = storeData.keySet().iterator(); while (user.hasNext()) if (user.next().contains(userName)) user.remove(); pDeleteUser.executeUpdate(); } catch (SQLException e) { System.out.println(""Error: "" + e); } return storeData; }" 361, ,"public void setDelimiter(String delimiter){ Preconditions.checkTrue(Strings.isNotEmpty(delimiter), ""delimiter is null or empty""); this.delimiter = ByteBuffer.wrap(delimiter.getBytes()); if (buf != null) { this.nextScanDelimiterStartPosition = buf.position(); } }","public void setDelimiter(String delimiter){ Preconditions.checkTrue(Strings.isNotEmpty(delimiter), ""delimiter is null or empty""); this.delimiter = ByteBuffer.wrap(delimiter.getBytes()); }" 362, ,"public synchronized void init(){ String topic = messageAdapter.getDestination().getDestinationName(); int defaultSize = getPartitionNum(topic); if (poolSize == 0 || poolSize > defaultSize) setPoolSize(defaultSize); logger.info(""Message receiver pool initializing. poolSize : "" + poolSize + "" config : "" + props.toString()); consumer = kafka.consumer.Consumer.createJavaConsumerConnector(new ConsumerConfig(props)); Map topicCountMap = new HashMap(); topicCountMap.put(topic, new Integer(poolSize)); VerifiableProperties verProps = new VerifiableProperties(props); @SuppressWarnings(""unchecked"") Decoder keyDecoder = (Decoder) RefleTool.newInstance(keyDecoderClass, verProps); @SuppressWarnings(""unchecked"") Decoder valDecoder = (Decoder) RefleTool.newInstance(valDecoderClass, verProps); Map>> consumerMap = consumer.createMessageStreams(topicCountMap, keyDecoder, valDecoder); List> streams = consumerMap.get(topic); int threadNumber = 0; for (final KafkaStream stream : streams) { pool.submit(new ReceiverThread(stream, messageAdapter, threadNumber)); threadNumber++; } }","public synchronized void init(){ String topic = messageAdapter.getDestination().getDestinationName(); int defaultSize = getReceiver().getPartitionCount(topic); if (poolSize == 0 || poolSize > defaultSize) setPoolSize(defaultSize); logger.info(""Message receiver pool initializing. poolSize : "" + poolSize + "" config : "" + props.toString()); consumer = kafka.consumer.Consumer.createJavaConsumerConnector(new ConsumerConfig(props)); Map topicCountMap = new HashMap(); topicCountMap.put(topic, new Integer(poolSize)); VerifiableProperties verProps = new VerifiableProperties(props); @SuppressWarnings(""unchecked"") Decoder keyDecoder = (Decoder) RefleTool.newInstance(keyDecoderClass, verProps); @SuppressWarnings(""unchecked"") Decoder valDecoder = (Decoder) RefleTool.newInstance(valDecoderClass, verProps); Map>> consumerMap = consumer.createMessageStreams(topicCountMap, keyDecoder, valDecoder); List> streams = consumerMap.get(topic); for (final KafkaStream stream : streams) { pool.submit(new ReceiverThread(stream, messageAdapter)); } }" 363, ,"public void negativeEvaluteEqualsToString() throws Exception{ Map attributes = new HashMap<>(); attributes.put(""name"", ""arshu""); String feature = ""Name Feature""; String expression = ""name == ganesh""; final GatingValidator validator = new GatingValidator(); Assert.assertFalse(validator.isAllowed(expression, feature, attributes)); }","public void negativeEvaluteEqualsToString() throws Exception{ Map attributes = new HashMap<>(); attributes.put(""name"", ""arshu""); String feature = ""Name Feature""; String expression = ""name == ganesh""; Assert.assertFalse(validator.isAllowed(expression, feature, attributes)); }" 364, ,"public ResponseEntity> create(@RequestBody UserRequestDTO userRequestDto){ ResponseDTO response = new ResponseDTO(); User user = new User(); try { user = userRequestDto.toUser(); ResponseDTO userResult = this.userService.save(user); if (userResult.getData() != null) { UserDTO userDTO = new UserDTO(); userDTO.copyFrom(userResult.getData()); response.setData(userDTO); } response.setErrorMessage(userResult.getErrorMessage()); } catch (IllegalArgumentException e) { response.setErrorMessage(MessageConst.ERROR_ROLE_INVALID); } return new ResponseEntity>(response, HttpStatus.OK); }","public ResponseEntity> create(@RequestBody UserRequestDTO userRequestDto){ ResponseDTO response = new ResponseDTO(); try { User user = userRequestDto.toUser(); ResponseDTO userResult = this.userService.save(user); if (userResult.getData() != null) { response.setData(userResult.getData()); } response.setErrorMessage(userResult.getErrorMessage()); } catch (IllegalArgumentException e) { response.setErrorMessage(MessageConst.ERROR_ROLE_INVALID); } return new ResponseEntity>(response, HttpStatus.OK); }" 365, ," final JsonParser createJsonParser(final Object input) throws IOException, NoSuchAlgorithmException{ final JsonFactory f = new JsonFactory(); JsonParser jp = null; InputStream my_is = null; if (input instanceof String) { my_is = new ByteArrayInputStream(((String) input).getBytes(StandardCharsets.UTF_8)); } else if (input instanceof File) { my_is = new FileInputStream((File) input); } else if (input instanceof URL) { my_is = ((URL) input).openStream(); } else if (input instanceof InputStream) { my_is = (InputStream) input; } else { throw new IllegalStateException(""cx parser does not know how to handle input of type "" + input.getClass()); } if (_calculate_md5_checksum) { _md = MessageDigest.getInstance(CxioUtil.MD5); my_is = new DigestInputStream(my_is, _md); } else { _md = null; } jp = f.createParser(my_is); return jp; }"," final JsonParser createJsonParser(final Object input) throws IOException{ final JsonFactory f = new JsonFactory(); JsonParser jp = null; InputStream my_is = null; if (input instanceof String) { my_is = new ByteArrayInputStream(((String) input).getBytes(StandardCharsets.UTF_8)); } else if (input instanceof File) { my_is = new FileInputStream((File) input); } else if (input instanceof URL) { my_is = ((URL) input).openStream(); } else if (input instanceof InputStream) { my_is = (InputStream) input; } else { throw new IllegalStateException(""cx parser does not know how to handle input of type "" + input.getClass()); } jp = f.createParser(my_is); return jp; }" 366, ,"public List allElements(){ ArrayList elems = new ArrayList(); for (int i = 0; i < elements.size(); ++i) { Object ob = elements.get(i); if (ob instanceof Operator) { } else if (ob instanceof FunctionDef) { Expression[] params = ((FunctionDef) ob).getParameters(); for (int n = 0; n < params.length; ++n) { elems.addAll(params[n].allElements()); } } else if (ob instanceof TObject) { TObject tob = (TObject) ob; if (tob.getTType() instanceof TArrayType) { Expression[] exp_list = (Expression[]) tob.getObject(); for (int n = 0; n < exp_list.length; ++n) { elems.addAll(exp_list[n].allElements()); } } else { elems.add(ob); } } else { elems.add(ob); } } return elems; }","public List allElements(){ ArrayList elems = new ArrayList(); for (Object ob : elements) { if (ob instanceof Operator) { } else if (ob instanceof FunctionDef) { Expression[] params = ((FunctionDef) ob).getParameters(); for (Expression param : params) { elems.addAll(param.allElements()); } } else if (ob instanceof TObject) { TObject tob = (TObject) ob; if (tob.getTType() instanceof TArrayType) { Expression[] exp_list = (Expression[]) tob.getObject(); for (Expression expression : exp_list) { elems.addAll(expression.allElements()); } } else { elems.add(ob); } } else { elems.add(ob); } } return elems; }" 367, ,"public HamtNode assign(@Nonnull CollisionMap collisionMap, int hashCode, @Nonnull K hashKey, @Nullable V newValue){ final int thisHashCode = this.hashCode; final K thisKey = key; final V thisValue = this.value; if (thisHashCode == hashCode) { if (thisKey.equals(hashKey)) { if (newValue == thisValue) { return this; } else { return new HamtSingleKeyLeafNode<>(hashCode, thisKey, newValue); } } else { final CollisionMap.Node thisNode = collisionMap.update(collisionMap.emptyNode(), thisKey, thisValue); return new HamtMultiKeyLeafNode<>(hashCode, collisionMap.update(thisNode, hashKey, newValue)); } } else { final CollisionMap.Node thisNode = collisionMap.update(collisionMap.emptyNode(), thisKey, thisValue); final HamtNode expanded = HamtBranchNode.forLeafExpansion(collisionMap, thisHashCode, thisNode); return expanded.assign(collisionMap, hashCode, hashKey, newValue); } }","public HamtNode assign(@Nonnull CollisionMap collisionMap, int hashCode, @Nonnull K hashKey, @Nullable V newValue){ final int thisHashCode = this.hashCode; final K thisKey = this.key; final V thisValue = this.value; if (thisHashCode == hashCode) { if (thisKey.equals(hashKey)) { if (newValue == thisValue) { return this; } else { return new HamtSingleKeyLeafNode<>(hashCode, thisKey, newValue); } } else { final CollisionMap.Node thisNode = collisionMap.single(thisKey, thisValue); return new HamtMultiKeyLeafNode<>(hashCode, collisionMap.update(thisNode, hashKey, newValue)); } } else { final HamtNode expanded = HamtBranchNode.forLeafExpansion(collisionMap, thisHashCode, thisKey, thisValue); return expanded.assign(collisionMap, hashCode, hashKey, newValue); } }" 368, ,"public TranslationResult visit(final SentenceMeatConjunction node, final FrVisitorArgument argument){ final TranslationResult result = new TranslationResult(node); final ConceptBookEntry conceptBookEntry = this.frTranslator.getConceptBook().get(node.getConjunction().getConcept()); final List defaultTargets = conceptBookEntry.getDefaultTargets(Language.FR); if (defaultTargets.isEmpty()) { result.setTranslation(conceptBookEntry.getConceptPhrase()); } else if (node.getConjunction().getToken().getType() == TokenType.SEPARATOR_SE) { result.setTranslation(String.format(""%s%s"", argument.getSentenceMeatIndex() > 0 ? "", "" : """", defaultTargets.get(0).getMainPhrase())); } else { result.setTranslation(String.format(""%s%s"", argument.getSentenceMeatIndex() > 0 ? "" "" : """", defaultTargets.get(0).getMainPhrase())); } return result; }","public TranslationResult visit(final SentenceMeatConjunction node, final FrVisitorArgument argument){ final TranslationResult result = new TranslationResult(node); final TranslationTarget conjunctionTarget = this.frTranslator.getFirstDefaultTarget(node.getConjunction().getConcept()); if ("","".equals(conjunctionTarget.getMainPhrase())) { result.setTranslation(conjunctionTarget.getMainPhrase()); } else if (node.getConjunction().getToken().getType() == TokenType.SEPARATOR_SE) { result.setTranslation(String.format(""%s%s"", argument.getSentenceMeatIndex() > 0 ? "", "" : """", conjunctionTarget.getMainPhrase())); } else { result.setTranslation(String.format(""%s%s"", argument.getSentenceMeatIndex() > 0 ? "" "" : """", conjunctionTarget.getMainPhrase())); } return result; }" 369, ,"public void testBusinessKeyDboEquals(){ businessKeyDbo11.setBusinessKey(1L); businessKeyDbo12.setBusinessKey(2L); businessKeyDbo21.setBusinessKey(1L); surrogateKeyDbo11.setSurrogateKey(1L); surrogateKeyDbo12.setSurrogateKey(2L); assertTrue(businessKeyDbo11.equals(businessKeyDbo11)); assertTrue(businessKeyDbo12.equals(businessKeyDbo12)); assertFalse(businessKeyDbo11.equals(businessKeyDbo12)); assertFalse(businessKeyDbo12.equals(businessKeyDbo11)); assertFalse(businessKeyDbo11.equals(null)); businessKeyDbo12.setBusinessKey(1L); assertTrue(businessKeyDbo11.equals(businessKeyDbo12)); assertTrue(businessKeyDbo12.equals(businessKeyDbo11)); assertFalse(businessKeyDbo11.equals(businessKeyDbo21)); assertFalse(businessKeyDbo11.equals(databaseObject1)); assertFalse(businessKeyDbo11.equals(surrogateKeyDbo11)); }","public void testBusinessKeyDboEquals(){ businessKeyDbo11.setBusinessKey(1L); businessKeyDbo12.setBusinessKey(2L); businessKeyDbo21.setBusinessKey(1L); surrogateKeyDbo11.setSurrogateKey(1L); assertTrue(businessKeyDbo11.equals(businessKeyDbo11)); assertTrue(businessKeyDbo12.equals(businessKeyDbo12)); assertFalse(businessKeyDbo11.equals(businessKeyDbo12)); assertFalse(businessKeyDbo12.equals(businessKeyDbo11)); assertFalse(businessKeyDbo11.equals(null)); businessKeyDbo12.setBusinessKey(1L); assertTrue(businessKeyDbo11.equals(businessKeyDbo12)); assertTrue(businessKeyDbo12.equals(businessKeyDbo11)); assertFalse(businessKeyDbo11.equals(businessKeyDbo21)); assertFalse(businessKeyDbo11.equals(databaseObject1)); assertFalse(businessKeyDbo11.equals(surrogateKeyDbo11)); }" 370, ,"public void updateMemberTest(){ Mockito.when(manager.createQuery(Mockito.anyString())).thenReturn(query); List members = new ArrayList(); Members member = new Members(1, ""Krystal"", ""Ryan""); Mockito.when(query.getResultList()).thenReturn(members); Mockito.when(manager.find(Members.class, 1)).thenReturn(member); String reply = repo.updateMember(1, j1.getJSONForObject(member)); Assert.assertEquals(""{\""message\"": \""Member successfully updated\""}"", reply); }","public void updateMemberTest(){ Mockito.when(manager.createQuery(Mockito.anyString())).thenReturn(query); List members = new ArrayList(); Mockito.when(query.getResultList()).thenReturn(members); Mockito.when(manager.find(Members.class, 1)).thenReturn(member); String reply = repo.updateMember(1, j1.getJSONForObject(member)); Assert.assertEquals(""{\""message\"": \""Member successfully updated\""}"", reply); }" 371, ,"public void updateParameters(NodeList parameters, MenuItem menuItem, Algorithm algorithmInstance){ for (int i = 0; i < parameters.getLength(); i++) { if (parameters.item(i).getNodeType() == Node.ELEMENT_NODE) { if (parameters.item(i).getNodeName().equals(""parameters"")) { final NodeList parametersList = parameters.item(i).getChildNodes(); int row = 1; for (int j = 0; j < parametersList.getLength(); j++) { if (parametersList.item(j).getNodeType() == Node.ELEMENT_NODE) { Element param = (Element) parametersList.item(j); if (param.getAttribute(""type"").equals(""slider"")) { String range = param.getAttribute(""range""); String[] ranges = range.split(""-""); int min = Integer.parseInt(ranges[0]); int max = Integer.parseInt(ranges[1]); menuItem.setOnAction(event -> { sliderZoom.setMin(min); sliderZoom.setMax(max); sliderZoom.setMajorTickUnit(Math.round(max / 4)); choosedAlgorithm = algorithmInstance; }); } } } } } } }","public void updateParameters(NodeList parameters, MenuItem menuItem, Algorithm algorithmInstance){ for (int i = 0; i < parameters.getLength(); i++) { if (parameters.item(i).getNodeType() == Node.ELEMENT_NODE && parameters.item(i).getNodeName().equals(""parameters"")) { final NodeList parametersList = parameters.item(i).getChildNodes(); int row = 1; for (int j = 0; j < parametersList.getLength(); j++) { if (parametersList.item(j).getNodeType() == Node.ELEMENT_NODE) { Element param = (Element) parametersList.item(j); if (param.getAttribute(""type"").equals(""slider"")) { String range = param.getAttribute(""range""); String[] ranges = range.split(""-""); int min = Integer.parseInt(ranges[0]); int max = Integer.parseInt(ranges[1]); menuItem.setOnAction(event -> { sliderZoom.setMin(min); sliderZoom.setMax(max); sliderZoom.setMajorTickUnit(Math.round(max / 4f)); choosedAlgorithm = algorithmInstance; }); } } } } } }" 372, ,"public int updatePersonById(UUID id, Person person){ Optional personOptional = selectPersonById(id); if (!personOptional.isPresent()) return 0; int index = DB.indexOf(personOptional.get()); PersonUtils.personQualifierUpdate(id, person); DB.set(index, person); return 1; }","public int updatePersonById(UUID id, Person person){ Optional personOptional = selectPersonById(id); if (!personOptional.isPresent()) return 0; int index = DB.indexOf(personOptional.get()); DB.set(index, person); return 1; }" 373, ,"public JsonNode readJsonLocal(String jsonFileLink){ JsonNode jsonNode = null; ObjectMapper mapper = new ObjectMapper(); try { BufferedReader br = new BufferedReader(new FileReader(jsonFileLink)); jsonNode = mapper.readTree(br); } catch (Exception e) { log.error(""Hey, could not read local directory: {}"", jsonFileLink); } return jsonNode; }","public JsonNode readJsonLocal(String jsonFileLink){ JsonNode jsonNode = null; try { BufferedReader br = new BufferedReader(new FileReader(jsonFileLink)); jsonNode = mapper.readTree(br); } catch (Exception e) { log.error(""Hey, could not read local directory: {}"", jsonFileLink); } return jsonNode; }" 374, ,"public void assertLoad() throws IOException{ AgentPathBuilder builder = new AgentPathBuilder(); ReflectiveUtil.setProperty(builder, ""agentPath"", new File(getResourceUrl())); AgentConfiguration configuration = AgentConfigurationLoader.load(); assertNotNull(configuration); }","public void assertLoad() throws IOException{ ReflectiveUtil.setStaticField(AgentPathBuilder.class, ""agentPath"", new File(getResourceUrl())); AgentConfiguration configuration = AgentConfigurationLoader.load(); assertNotNull(configuration); }" 375, ,"public List createRandomAngebotList() throws ParseException{ for (int i = 0; i < 10; i++) { Faker faker = new Faker(); long fakeAngebotsID = faker.number().randomNumber(); String fakeAngebotsName = faker.funnyName().name(); long fakeangebotsEinzelpreis = faker.number().randomNumber(); long fakeangebotsGesamtpreis = faker.number().numberBetween(faker.number().randomNumber(), 1500); int fakeMenge = faker.number().randomDigit(); Angebot randomAngebot = new Angebot(); randomAngebot = Angebot.builder().angebotsID(fakeAngebotsID).angebotsName(fakeAngebotsName).angebotsEinzelpreis(fakeangebotsEinzelpreis).angebotsGesamtpreis(fakeangebotsGesamtpreis).menge(fakeMenge).build(); randomAngebotList.add(randomAngebot); angebot_repository.save(randomAngebot); } return randomAngebotList; }","public void createRandomAngebotList(){ for (int i = 0; i < 10; i++) { Faker faker = new Faker(); long fakeAngebotsID = faker.number().randomNumber(); String fakeAngebotsName = faker.funnyName().name(); long fakeangebotsEinzelpreis = faker.number().randomNumber(); long fakeangebotsGesamtpreis = faker.number().numberBetween(faker.number().randomNumber(), 1500); int fakeMenge = faker.number().randomDigit(); Angebot randomAngebot = Angebot.builder().angebotsID(fakeAngebotsID).angebotsName(fakeAngebotsName).angebotsEinzelpreis(fakeangebotsEinzelpreis).angebotsGesamtpreis(fakeangebotsGesamtpreis).menge(fakeMenge).build(); angebot_repository.save(randomAngebot); } }" 376, ," static ListNode removeNthFromEnd(ListNode head, int n){ ListNode nDelay = head; int counter = 0; for (ListNode curr = head; curr != null; curr = curr.next) { counter++; if (counter > n + 1) nDelay = nDelay.next; } if (n == counter) return head.next; nDelay.next = nDelay.next.next; return head; }"," static ListNode removeNthFromEnd(ListNode head, int n){ ListNode dummyHead = new ListNode<>(null, head); ListNode nDelay = dummyHead; int counter = 0; for (ListNode curr = head; curr != null; curr = curr.next) { counter++; if (counter > n) nDelay = nDelay.next; } nDelay.next = nDelay.next.next; return dummyHead.next; }" 377, ,"private static int placeCardOnStone(VerticalLayout stoneLayout){ if (selectedCard == null || selectedStone == null || selectedStone.isFullFor(activePlayer)) { return 0; } selectedStone.addCardFor(activePlayer, selectedCard); activePlayerHand.removeCard(selectedCard); ClanCardImage clanCardImage = new ClanCardImage(selectedCard, true, activePlayer); if (activePlayer.getId() == 0) { stoneLayout.addComponentAsFirst(clanCardImage); } else { stoneLayout.add(clanCardImage); } activePlayer = game.getBoard().getOpponentPlayer(activePlayer); final Player stoneOwner = selectedStone.getOwnBy(); if (stoneOwner == null) { selectedCard = null; selectedStone = null; return 1; } stoneLayout.getChildren().map(Component::getElement).filter(stoneChildElement -> stoneOwner.getName().equals(stoneChildElement.getAttribute(""added-by""))).forEach(ownerCardElement -> ownerCardElement.setAttribute(""class"", ""smallcarte winningArea"")); stoneOwner.setScore(stoneOwner.getScore() + 1); int i = 0; int nbAdjacentOwned = border.getNbrAdjacentStones(stoneOwner); if (nbAdjacentOwned >= 3 || stoneOwner.getScore() >= 5) { winningPlayer = stoneOwner; return 2; } else { selectedCard = null; selectedStone = null; return 1; } }","private static GameHandler.ResponseCode placeCardOnStone(VerticalLayout stoneLayout){ GameHandler.ResponseCode responseCode = gameHandler.placeCardOnStone(activePlayer, selectedCard, selectedStone); switch(responseCode) { case NO_ACTION: break; case OK: ClanCardImage clanCardImage = new ClanCardImage(selectedCard, true, activePlayer); if (activePlayer.getId() == 0) { stoneLayout.addComponentAsFirst(clanCardImage); } else { stoneLayout.add(clanCardImage); } activePlayer = game.getBoard().getOpponentPlayer(activePlayer); final Player stoneOwner = selectedStone.getOwnBy(); if (stoneOwner != null) { stoneLayout.getChildren().map(Component::getElement).filter(stoneChildElement -> stoneOwner.getName().equals(stoneChildElement.getAttribute(""added-by""))).forEach(ownerCardElement -> ownerCardElement.setAttribute(""class"", ""smallcarte winningArea"")); } selectedCard = null; selectedStone = null; break; case GAME_FINISHED: winningPlayer = selectedStone.getOwnBy(); } return responseCode; }" 378, ,"public void search(final String startDate, final DurationEnum duration, final int threshold){ final LogDataProcessor logDataProcessor = LogDataProcessorFactory.getInstance().makeLogDataProcessor(); final List logEntries = new ArrayList<>(); final String searchToken = this.searchTokenExtractionStrategy.extractSearchToken(startDate, duration); final Path logFile = Paths.get(this.sourceFilePath); try (Stream stream = Files.lines(logFile)) { final Map entriesByIp = stream.filter(line -> { String[] split = line.split(SPLIT_PATTERN); logEntries.add(new LogEntry(split[0], split[1], split[2].replaceAll(""\"""", """"))); return line.contains(searchToken); }).collect(Collectors.groupingBy(l -> l.split(SPLIT_PATTERN)[1], Collectors.counting())); entriesByIp.entrySet().stream().filter(entry -> entry.getValue() > threshold).forEach(System.out::println); logDataProcessor.processData(logEntries); } catch (IOException e) { LOGGER.error(""An ERROR occurred while reading the file."", e); throw new RuntimeException(e); } }","public void search(final String startDate, final DurationEnum duration, final int threshold){ final LogDataProcessor logDataProcessor = LogDataProcessorFactory.getInstance().makeLogDataProcessor(); logDataProcessor.processData(this.sourceFilePath); final String searchToken = this.searchTokenExtractionStrategy.extractSearchToken(startDate, duration); final Path logFile = Paths.get(this.sourceFilePath); try (Stream stream = Files.lines(logFile)) { final Map entriesByIp = stream.filter(line -> line.contains(searchToken)).collect(Collectors.groupingBy(l -> l.split(AppConstants.SPLIT_PATTERN)[1], Collectors.counting())); entriesByIp.entrySet().stream().filter(entry -> entry.getValue() > threshold).forEach(System.out::println); } catch (IOException e) { LOGGER.error(""An ERROR occurred while reading the file."", e); throw new RuntimeException(e); } }" 379, ,"public void deleteComment(BlogPost blogPost, BlogPostComment comment){ this.commentRepository.delete(comment); blogPost.getComments().remove(comment); update(blogPost); }","public void deleteComment(BlogPost blogPost, BlogPostComment comment){ blogPost.getComments().remove(comment); update(blogPost); }" 380, ,"public void testJoinVirtualQueueNotHead(){ int position = 2; virtualQueueStatus.setPosition(position); employee.setTotalTimeSpent(5); employee.setNumRegisteredStudents(1); Set employees = Sets.newHashSet(Collections.singleton(""e1"")); VirtualQueueData virtualQueueData = new VirtualQueueData(""vq1"", employees); doNothing().when(validationService).checkValidCompanyId(anyString()); doNothing().when(validationService).checkValidStudentId(anyString()); doReturn(virtualQueueStatus).when(virtualQueueWorkflow).joinQueue(anyString(), any(), any()); doReturn(virtualQueueData).when(virtualQueueWorkflow).getVirtualQueueData(anyString(), any()); doReturn(employee).when(employeeHashOperations).get(anyString(), any()); JoinQueueResponse response = queueService.joinVirtualQueue(""c1"", Role.SWE, student); verify(validationService).checkValidStudentId(anyString()); verify(validationService).checkValidCompanyId(anyString()); verify(virtualQueueWorkflow).joinQueue(anyString(), any(), any()); assertNotNull(response); assertNotNull(response.getQueueStatus()); assertEquals(response.getQueueStatus().getCompanyId(), ""c1""); assertEquals(response.getQueueStatus().getQueueId(), ""vq1""); assertEquals(response.getQueueStatus().getRole(), Role.SWE); assertEquals(response.getQueueStatus().getPosition(), MAX_EMPLOYEE_QUEUE_SIZE + position); assertEquals(response.getQueueStatus().getQueueType(), QueueType.VIRTUAL); assertNotEquals(response.getQueueStatus().getWaitTime(), 0); assertNull(response.getQueueStatus().getEmployee()); }","public void testJoinVirtualQueueNotHead(){ int position = 2; virtualQueueStatus.setPosition(position); int timeSpent = 5; int numStudents = 2; employee.setTotalTimeSpent(timeSpent); employee.setNumRegisteredStudents(numStudents); Set employees = Sets.newHashSet(Collections.singleton(""e1"")); VirtualQueueData virtualQueueData = new VirtualQueueData(""vq1"", employees); int expectedWaitTime = (int) (((position + MAX_EMPLOYEE_QUEUE_SIZE - 1.) * timeSpent / numStudents) / employees.size()); doNothing().when(validationService).checkValidCompanyId(anyString()); doNothing().when(validationService).checkValidStudentId(anyString()); doReturn(virtualQueueStatus).when(virtualQueueWorkflow).joinQueue(anyString(), any(), any()); doReturn(virtualQueueData).when(virtualQueueWorkflow).getVirtualQueueData(anyString(), any()); doReturn(employee).when(employeeHashOperations).get(anyString(), any()); JoinQueueResponse response = queueService.joinVirtualQueue(""c1"", Role.SWE, student); verify(validationService).checkValidStudentId(anyString()); verify(validationService).checkValidCompanyId(anyString()); verify(virtualQueueWorkflow).joinQueue(anyString(), any(), any()); assertNotNull(response); assertNotNull(response.getQueueStatus()); validateVirtualQueueStatus(response.getQueueStatus(), position, expectedWaitTime); }" 381, ,"public IamToken requestToken(){ RequestBuilder builder = RequestBuilder.post(RequestBuilder.resolveRequestUrl(this.url, OPERATION_PATH)); builder.header(HttpHeaders.CONTENT_TYPE, HttpMediaType.APPLICATION_FORM_URLENCODED); if (StringUtils.isNotEmpty(this.cachedAuthorizationHeader)) { builder.header(HttpHeaders.AUTHORIZATION, this.cachedAuthorizationHeader); } FormBody formBody; final FormBody.Builder formBodyBuilder = new FormBody.Builder().add(GRANT_TYPE, REQUEST_GRANT_TYPE).add(API_KEY, apikey).add(RESPONSE_TYPE, CLOUD_IAM); if (!StringUtils.isEmpty(getScope())) { formBodyBuilder.add(SCOPE, getScope()); } formBody = formBodyBuilder.build(); builder.body(formBody); IamToken token; try { token = invokeRequest(builder, IamToken.class); } catch (Throwable t) { token = new IamToken(t); } return token; }","public IamToken requestToken(){ RequestBuilder builder = RequestBuilder.post(RequestBuilder.resolveRequestUrl(this.getURL(), OPERATION_PATH)); builder.header(HttpHeaders.CONTENT_TYPE, HttpMediaType.APPLICATION_FORM_URLENCODED); addAuthorizationHeader(builder); FormBody formBody; final FormBody.Builder formBodyBuilder = new FormBody.Builder().add(""grant_type"", ""urn:ibm:params:oauth:grant-type:apikey"").add(""apikey"", getApiKey()).add(""response_type"", ""cloud_iam""); if (!StringUtils.isEmpty(getScope())) { formBodyBuilder.add(""scope"", getScope()); } formBody = formBodyBuilder.build(); builder.body(formBody); IamToken token; try { token = invokeRequest(builder, IamToken.class); } catch (Throwable t) { token = new IamToken(t); } return token; }" 382, ,"public static synchronized void loop(String filename){ if (filename == null) throw new IllegalArgumentException(); final AudioInputStream ais = getAudioInputStreamFromFile(filename); try { Clip clip = AudioSystem.getClip(); clip.open(ais); clip.loop(Clip.LOOP_CONTINUOUSLY); } catch (IOException | LineUnavailableException e) { e.printStackTrace(); } new Thread(new Runnable() { public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); }","public static synchronized void loop(String filename){ requiresNotNull(filename); final AudioInputStream ais = getAudioInputStreamFromFile(filename); try { Clip clip = AudioSystem.getClip(); clip.open(ais); clip.loop(Clip.LOOP_CONTINUOUSLY); } catch (IOException | LineUnavailableException e) { e.printStackTrace(); } new Thread(new Runnable() { public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); }" 383, ,"public int parseInt(String s) throws NumberFormatException{ if (s == null || s.isEmpty()) { return 0; } if (s.matches(""(\\+|-)?[0-9]+"")) { return Integer.parseInt(s); } else if (s.matches(""(\\+|-)?[0-9a-fA-F]+"")) { return Integer.parseInt(s.toUpperCase(), 16); } else if (s.matches(""(\\+|-)?(x|$)[0-9a-fA-F]+"")) { String upper = s.toUpperCase(); boolean positive = true; if (upper.startsWith(""-"")) { positive = false; } for (int i = 0; i < upper.length(); i++) { char c = upper.charAt(i); if ((c >= '0' && c <= '9') || (c >= 'A' & c <= 'F')) { int value = Integer.parseInt(s.substring(i), 16); if (!positive) { value *= -1; } return value; } } } throw new NumberFormatException(""Could not interpret int value "" + s); }","public int parseInt(String s) throws NumberFormatException{ if (s == null || s.isEmpty()) { return 0; } if (s.matches(""(\\+|-)?[0-9]+"")) { return Integer.parseInt(s); } else { String upper = s.toUpperCase(); boolean positive = true; if (upper.startsWith(""-"")) { positive = false; upper = upper.substring(1); } for (int i = 0; i < upper.length(); i++) { char c = upper.charAt(i); if ((c >= '0' && c <= '9') || (c >= 'A' & c <= 'F')) { int value = Integer.parseInt(s.substring(i), 16); if (!positive) { value *= -1; } return value; } } } throw new NumberFormatException(""Could not interpret int value "" + s); }" 384, ,"public TranslationResult visit(final SentenceMeatConjunction node, final EsVisitorArgument argument){ final TranslationResult result = new TranslationResult(node); final ConceptBookEntry conceptBookEntry = this.esTranslator.getConceptBook().get(node.getConjunction().getConcept()); final List defaultTargets = conceptBookEntry.getDefaultTargets(Language.ES); if (defaultTargets.isEmpty()) { result.setTranslation(conceptBookEntry.getConceptPhrase()); } else if (node.getConjunction().getToken().getType() == TokenType.SEPARATOR_SE) { result.setTranslation(String.format(""%s%s"", argument.getSentenceMeatIndex() > 0 ? "" "" : """", defaultTargets.get(0).getMainPhrase())); } else { result.setTranslation(String.format(""%s%s"", argument.getSentenceMeatIndex() > 0 ? "", "" : """", defaultTargets.get(0).getMainPhrase())); } return result; }","public TranslationResult visit(final SentenceMeatConjunction node, final EsVisitorArgument argument){ final TranslationResult result = new TranslationResult(node); final TranslationTarget conjunctionTarget = this.esTranslator.getFirstDefaultTarget(node.getConjunction().getConcept()); if ("","".equals(conjunctionTarget.getMainPhrase())) { result.setTranslation(conjunctionTarget.getMainPhrase()); } else if (node.getConjunction().getToken().getType() == TokenType.SEPARATOR_SE) { result.setTranslation(String.format(""%s%s"", argument.getSentenceMeatIndex() > 0 ? "" "" : """", conjunctionTarget.getMainPhrase())); } else { result.setTranslation(String.format(""%s%s"", argument.getSentenceMeatIndex() > 0 ? "", "" : """", conjunctionTarget.getMainPhrase())); } return result; }" 385, ,"private T getSingleResult(String field, Class type){ try (PgClosableConnection closableConnection = this.pool.getConnection()) { DSLContext create = DSL.using(closableConnection.getConnection(), SQLDialect.POSTGRES); return create.selectFrom(""example.user"").where(""id = {0}"", this.id).fetchOne(field, type); } catch (Exception e) { throw new DbRuntimeException(e); } }","private T getSingleResult(String field, Class type){ try (PgClosableConnection closableConnection = this.pool.getConnection()) { return closableConnection.context().selectFrom(""example.user"").where(""id = {0}"", this.id).fetchOne(field, type); } catch (Exception e) { throw new DbRuntimeException(e); } }" 386, ,"public void setDirectorySymbolicLink(CommonFile directory) throws FileSystemException, IllegalArgumentException{ checkFileType(directory); checkSymbolicLink(directory); try { String path = getSymLinkTargetPath(directory); String currWorkingDir = this.directory.getFilePath(); if (directory instanceof LocalFile) { path = UI.resolveLocalPath(path, currWorkingDir).getResolvedPath(); } else { path = UI.resolveRemotePath(path, currWorkingDir, true, this.fileSystem.getFTPConnection()).getResolvedPath(); } CommonFile targetFile = fileSystem.getFile(path); setDirectory(targetFile); refresh(); } catch (IOException ex) { UI.doException(ex, UI.ExceptionType.EXCEPTION, FTPSystem.isDebugEnabled()); } catch (FTPException ex) { UI.doException(ex, UI.ExceptionType.ERROR, FTPSystem.isDebugEnabled()); } }","public void setDirectorySymbolicLink(CommonFile directory) throws FileSystemException, IllegalArgumentException{ checkFileType(directory); checkSymbolicLink(directory); try { String path = getSymLinkTargetPath(directory); CommonFile targetFile = fileSystem.getFile(path); setDirectory(targetFile); refresh(); } catch (IOException ex) { UI.doException(ex, UI.ExceptionType.EXCEPTION, FTPSystem.isDebugEnabled()); } catch (FTPException ex) { UI.doException(ex, UI.ExceptionType.ERROR, FTPSystem.isDebugEnabled()); } }" 387, ,"public RevenueExpenseReportRes getRevenueExpenseReportData(ReportReq reportReq){ RevenueExpenseReportRes revenueExpenseReportRes = new RevenueExpenseReportRes(); if (reportReq.getVehicleId() != null) { revenueExpenseReportRes.setRevenueExpenses(reportComponent.getVehicleRevenueExpenseReportData(reportReq)); } else { revenueExpenseReportRes.setRevenueExpenses(reportComponent.getCompanyRevenueExpenseReportData(reportReq)); } return revenueExpenseReportRes; }","public RevenueExpenseReportRes getRevenueExpenseReportData(ReportReq reportReq){ return reportComponent.getRevenueExpenseDetailReportData(reportReq); }" 388, ,"public boolean move(Move move, ChessboardState moveFor){ if (!getValidator().isMovementValid(move, this, moveFor)) { return false; } Point start = move.getStart(); Point end = move.getEnd(); ChessboardState originalStartState = getSlotState(start); ChessboardState originalEndState = getSlotState(end); set(start, originalEndState); set(end, moveFor); return true; }","public boolean move(Move move, ChessboardState moveFor){ if (!getValidator().isMovementValid(move, this, moveFor)) { return false; } Point start = move.getStart(); Point end = move.getEnd(); ChessboardState originalEndState = getSlotState(end); set(start, originalEndState); set(end, moveFor); return true; }" 389, ,"public void getQuestions() throws Exception{ List questions = config.getQuestions(); assertEquals(""QA"", questions.get(0)[0]); assertEquals(5, questions.get(0).length); assertEquals(""Question #1"", questions.get(0)[1]); assertEquals(""key1"", questions.get(0)[2]); assertEquals(""P1"", questions.get(0)[3]); assertEquals(""P2"", questions.get(0)[4]); assertEquals(""QB"", questions.get(1)[0]); assertEquals(4, questions.get(1).length); assertEquals(""Question #2"", questions.get(1)[1]); assertEquals(""key2"", questions.get(1)[2]); assertEquals(""P3"", questions.get(1)[3]); assertEquals(""QC"", questions.get(2)[0]); assertEquals(3, questions.get(2).length); assertEquals(""Question #3"", questions.get(2)[1]); assertEquals(""key3"", questions.get(2)[2]); }","public void getQuestions() throws Exception{ List questions = config.getQuestions(); assertEquals(""QA"", questions.get(0).getKey()); assertEquals(""Question #1"", questions.get(0).getQuestion()); assertEquals(""key1"", questions.get(0).getResolverKey()); assertEquals(""P1"", questions.get(0).getParms()[0]); assertEquals(""P2"", questions.get(0).getParms()[1]); assertEquals(""QB"", questions.get(1).getKey()); assertEquals(""Question #2"", questions.get(1).getQuestion()); assertEquals(""key2"", questions.get(1).getResolverKey()); assertEquals(""P3"", questions.get(1).getParms()[0]); assertEquals(""QC"", questions.get(2).getKey()); assertEquals(""Question #3"", questions.get(2).getQuestion()); assertEquals(""key3"", questions.get(2).getResolverKey()); }" 390, ,"public static long getSiteGroupIdByName(final String siteName, final long company, final String locationName){ long siteGroupId = 0; if (siteName.toLowerCase().equals(""global"")) { try { siteGroupId = GroupLocalServiceUtil.getCompanyGroup(company).getGroupId(); } catch (PortalException e) { LOG.error(""Id of global site could not be retrieved!""); LOG.error((Throwable) e); } catch (SystemException e) { LOG.error(""Id of global site could not be retrieved!""); LOG.error((Throwable) e); } } else { try { siteGroupId = GroupLocalServiceUtil.getGroup(company, getSiteName(siteName)).getGroupId(); } catch (PortalException e) { LOG.error(String.format(""Id of site %1$s could not be retrieved for %2$s"", siteName, locationName)); LOG.error((Throwable) e); } catch (SystemException e) { LOG.error(String.format(""Id of site %1$s could not be retrieved for%2$s"", siteName, locationName)); LOG.error((Throwable) e); } } return siteGroupId; }","public static long getSiteGroupIdByName(final String siteName, final long company, final String locationName){ long siteGroupId = 0; if (siteName.equalsIgnoreCase(""global"")) { try { siteGroupId = GroupLocalServiceUtil.getCompanyGroup(company).getGroupId(); } catch (PortalException e) { LOG.error(""Id of global site could not be retrieved!""); LOG.error((Throwable) e); } } else { try { siteGroupId = GroupLocalServiceUtil.getGroup(company, getSiteName(siteName)).getGroupId(); } catch (PortalException e) { LOG.error(String.format(""Id of site %1$s could not be retrieved for %2$s"", siteName, locationName)); LOG.error((Throwable) e); } catch (SystemException e) { LOG.error(String.format(""Id of site %1$s could not be retrieved for%2$s"", siteName, locationName)); LOG.error((Throwable) e); } } return siteGroupId; }" 391, ,"private static Collection> getClassesInPackageAnnotatedBy(String thePackage, Reflections reflections, Class annotation){ Set> classes = reflections.getTypesAnnotatedWith(annotation); for (Iterator> it = classes.iterator(); it.hasNext(); ) { String classPackage = it.next().getPackage().getName(); if (!classPackage.equals(thePackage)) { it.remove(); } } return classes; }","private static Collection> getClassesInPackageAnnotatedBy(String thePackage, Reflections reflections, Class annotation){ return reflections.getTypesAnnotatedWith(annotation).stream().filter(c -> c.getPackage().getName().equals(thePackage)).collect(Collectors.toList()); }" 392, ,"public Builder snapshot_id(final String snapshot_id){ assert (snapshot_id != null); assert (!snapshot_id.equals("""")); return setBodyParameter(""snapshot_id"", snapshot_id); }","public Builder snapshot_id(final String snapshot_id){ assertHasAndNotNull(snapshot_id); return setBodyParameter(""snapshot_id"", snapshot_id); }" 393, ,"public UserBO getUser() throws Exception{ LoginBO userLogin = userLoginService.getUserLogin(); Optional rs = userRepository.findById(userLogin.getUserId()); if (rs.isPresent()) { Users user = rs.get(); UserBO userBO = UserBO.builder().name(user.getName()).surname(user.getSurname()).dateOfBirth(user.getDateOfBirth()).build(); try { List list = orderService.listOrder(user.getId()); for (OrderBO order : list) { userBO.addBooks(order.getBookId()); } } catch (ExceptionDataNotFound orderNotFound) { log.info(orderNotFound.getMessage()); } return userBO; } throw new ExceptionDataNotFound(""user"", """"); }","public UserBO getUser() throws Exception{ LoginBO userLogin = userLoginService.getUserLogin(); if (null != userLogin) { UserBO userBO = userLogin.getUserInfo(); try { List list = orderService.findByUsername(userLogin.getUsername()); for (OrderBO order : list) { userBO.addBooks(order.getBookId()); } } catch (ExceptionDataNotFound orderNotFound) { log.info(orderNotFound.getMessage()); } return userBO; } throw new ExceptionDataNotFound(""user"", """"); }" 394, ,"public void addProject(final File projectRoot){ final File wcRoot = this.determineWorkingCopyRoot(projectRoot); if (wcRoot != null) { boolean wcCreated = false; synchronized (this.projectsPerWcMap) { Set projects = this.projectsPerWcMap.get(wcRoot); if (projects == null) { projects = new LinkedHashSet<>(); this.projectsPerWcMap.put(wcRoot, projects); wcCreated = true; } projects.add(projectRoot); } if (wcCreated) { final Job job = Job.create(""Analyzing SVN working copy at "" + wcRoot, new IJobFunction() { @Override public IStatus run(final IProgressMonitor monitor) { SvnWorkingCopyManager.getInstance().getWorkingCopy(wcRoot); return Status.OK_STATUS; } }); job.schedule(); } } }","public void addProject(final File projectRoot){ final File wcRoot = this.determineWorkingCopyRoot(projectRoot); if (wcRoot != null) { boolean wcCreated = false; synchronized (this.projectsPerWcMap) { Set projects = this.projectsPerWcMap.get(wcRoot); if (projects == null) { projects = new LinkedHashSet<>(); this.projectsPerWcMap.put(wcRoot, projects); wcCreated = true; } projects.add(projectRoot); } if (wcCreated) { SvnWorkingCopyManager.getInstance().getWorkingCopy(wcRoot); } } }" 395, ,"public ApiToken authenticateForToken(String accessKey, String secret){ logger.debug(""Obtaining access token for application {} given key {}"", stormpathClientHelper.getApplicationName(), accessKey); HttpRequest tokenRequest = buildHttpRequest(accessKey, secret); AccessTokenResult result = (AccessTokenResult) stormpathClientHelper.getApplication().authenticateOauthRequest(tokenRequest).withTtl(3600).execute(); TokenResponse token = result.getTokenResponse(); return buildApiToken(token); }","public OauthTokenResponse authenticateForToken(String accessKey, String secret){ logger.debug(""Obtaining access token for application {} given key {}"", stormpathClientHelper.getApplicationName(), accessKey); HttpRequest tokenRequest = buildHttpRequest(accessKey, secret); AccessTokenResult result = (AccessTokenResult) stormpathClientHelper.getApplication().authenticateOauthRequest(tokenRequest).withTtl(3600).execute(); return buildOauthTokenResponse(result.getTokenResponse(), result.getAccount()); }" 396, ,"public void actionPerformed(ActionEvent e){ ResourceClassSingleton.getInstance().changeStatusIsWindowOpenedUp(); FiguresJoe.figureScript2(driverManager.getCurrentDriver()); TestJobs2dApp testJobs2dApp = new TestJobs2dApp(); testJobs2dApp.getLogger().info(""Remaining ink: "" + ResourceClassSingleton.getInstance().getInk()); testJobs2dApp.getLogger().info(""Remaining usage: "" + ResourceClassSingleton.getInstance().getUsage()); }","public void actionPerformed(ActionEvent e){ ResourceClassSingleton.getInstance().changeStatusIsWindowOpenedUp(); FiguresJoe.figureScript2(driverManager.getCurrentDriver()); }" 397, ,"public AsyncFuture error(LazyTransform transform){ final int state = sync.state(); if (!isStateReady(state)) return async.error(this, transform); if (state == CANCELLED) return async.cancelled(); if (state == RESOLVED) return async.resolved((T) sync.result(state)); final Throwable cause = (Throwable) sync.result(state); try { return (AsyncFuture) transform.transform(cause); } catch (Exception e) { return async.failed(new TransformException(e)); } }","public AsyncFuture error(LazyTransform transform){ final int state = sync.state(); if (!isStateReady(state)) return async.error(this, transform); if (state == FAILED) { final Throwable cause = (Throwable) sync.result(state); try { return (AsyncFuture) transform.transform(cause); } catch (Exception e) { return async.failed(new TransformException(e)); } } return this; }" 398, ,"public static void setOffsets(String zkServers, String groupID, Map offsets){ try (AutoZkClient zkClient = new AutoZkClient(zkServers)) { for (Map.Entry entry : offsets.entrySet()) { TopicAndPartition topicAndPartition = entry.getKey(); ZKGroupTopicDirs topicDirs = new ZKGroupTopicDirs(groupID, topicAndPartition.topic()); int partition = topicAndPartition.partition(); long offset = entry.getValue(); String partitionOffsetPath = topicDirs.consumerOffsetDir() + ""/"" + partition; ZkUtils.updatePersistentPath(zkClient, partitionOffsetPath, Long.toString(offset)); } } }","public static void setOffsets(String zkServers, String groupID, Map offsets){ try (AutoZkClient zkClient = new AutoZkClient(zkServers)) { offsets.forEach((topicAndPartition, offset) -> { ZKGroupTopicDirs topicDirs = new ZKGroupTopicDirs(groupID, topicAndPartition.topic()); int partition = topicAndPartition.partition(); String partitionOffsetPath = topicDirs.consumerOffsetDir() + ""/"" + partition; ZkUtils.updatePersistentPath(zkClient, partitionOffsetPath, Long.toString(offset)); }); } }" 399, ,"public ResponseEntity importDependencies(@RequestBody Collection dependencies){ System.out.println(""Received dependencies from Milla""); List savedDependencies = new ArrayList<>(); for (Dependency dependency : dependencies) { if (dependencyRepository.findById(dependency.getId()) == null) { savedDependencies.add(dependency); } else { System.out.println(""Found a duplicate "" + dependency.getId()); } } dependencyRepository.save(savedDependencies); System.out.println(""Dependencies saved "" + dependencyRepository.count()); savedDependencies.clear(); return new ResponseEntity<>(""Dependencies saved"", HttpStatus.OK); }","public ResponseEntity importDependencies(@RequestBody Collection dependencies){ return updateService.importDependencies(dependencies); }" 400, ,"public App testInterface(@PathVariable(name = ""version"") VERSION version){ App app = new App(""Listing"", getVersionedPojos(version)); return app; }","public App testInterface(@PathVariable(name = ""version"") VERSION version){ return new App(""Listing"", getVersionedPojos(version)); }" 401, ,"public ResponseEntity createGame(@RequestBody TicTacToeDTO ticTacToeDTO){ UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String username = principal.getUsername(); TicTacToeGameDTO createdGameDto; try { createdGameDto = ticTacToeService.createGame(ticTacToeDTO, username); } catch (RuntimeException e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } template.convertAndSend(""/tictactoe/add"", createdGameDto); return new ResponseEntity<>(createdGameDto, HttpStatus.OK); }","public ResponseEntity createGame(@RequestBody TicTacToeDTO ticTacToeDTO){ UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String username = principal.getUsername(); TicTacToeGameDTO createdGameDto = ticTacToeService.createGame(ticTacToeDTO, username); template.convertAndSend(""/tictactoe/add"", createdGameDto); return new ResponseEntity<>(createdGameDto, HttpStatus.OK); }" 402, ,"private void saveData(){ configurationManager.loadProfile(String.valueOf((profileBox.getSelectedItem()))); ConnectionBuilder connParameters = new ConnectionBuilder.Builder(connNameTF.getText()).userName(usernameTF.getText()).password(passwordTF.getText()).url(urlTF.getText()).jar(jarTF.getText()).profile(String.valueOf((profileBox.getSelectedItem()))).driverName(configurationManager.getIProfile().getDriverName()).rawRetainDays(rawDataDaysRetainTF.getText()).olapRetainDays(olapDataDaysRetainTF.getText()).build(); configurationManager.saveConnection(connParameters); }","private void saveData(){ ConnectionBuilder connParameters = new ConnectionBuilder.Builder(connNameTF.getText()).userName(usernameTF.getText()).password(passwordTF.getText()).url(urlTF.getText()).jar(jarTF.getText()).profile(String.valueOf((profileBox.getSelectedItem()))).driverName(configurationManager.getIProfile().getDriverName()).rawRetainDays(rawDataDaysRetainTF.getText()).olapRetainDays(olapDataDaysRetainTF.getText()).build(); configurationManager.saveConnection(connParameters); }" 403, ,"public ResponseEntity makeTransfer(@PathVariable String number1, @PathVariable String number2, @PathVariable Double money) throws AccountDoesNotExistException{ Account firstAccount = accountService.getOneAccount(number1); Account secondAccount = accountService.getOneAccount(number2); List updatedAccounts = transferService.makeTransfer(firstAccount, secondAccount, money); return new ResponseEntity<>(updatedAccounts, HttpStatus.OK); }","public ResponseEntity makeTransfer(@PathVariable String firstAccountNumber, @PathVariable String secondAccountNumber, @PathVariable Double money) throws AccountDoesNotExistException{ List updatedAccounts = transferService.makeTransfer(firstAccountNumber, secondAccountNumber, money); return new ResponseEntity<>(updatedAccounts, HttpStatus.OK); }"