Dataset Viewer
Auto-converted to Parquet Duplicate
Unnamed: 0
int64
0
403
cwe_id
stringclasses
1 value
source
stringlengths
56
2.02k
target
stringlengths
50
1.97k
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)) { ...
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)) { ...
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(bufferIniti...
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); ...
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) ...
public PartyDTO getPartyByPartyCode(String partyCode){ final TMsParty tMsParty = validateByPartyCode(partyCode); PartyDTO partyDTO = PartyMapper.INSTANCE.entityToDTO(tMsParty); setReferenceData(tMsParty, partyDTO); final List<PartyContactDTO> contactDTOList = partyContactService.getContactsByPartyCode(p...
3
public static long findMyBoardingPass(String fileName){ List<String> passes = readInBoardingPasses(fileName); List<Long> seatIds = passes.stream().map(boardingPass -> getBoardingPassSeatId(boardingPass)).sorted().collect(Collectors.toList()); long mySeatId = -1; for (Long seatId : seatIds) { if ...
public static long findMyBoardingPass(String fileName){ List<String> passes = readInBoardingPasses(fileName); return passes.stream().map(boardingPass -> getBoardingPassSeatId(boardingPass)).sorted().collect(Collectors.reducing(-1, (mySeatId, seatId) -> (mySeatId.longValue() == -1L || seatId.longValue() <= mySea...
4
public Set<Car> 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...
public Set<Car> findAllByOwnerId(long id) throws SQLException, NamingException{ Connection con = null; try { con = dataSource.getConnection(); PreparedStatement findAllCarsByOwnerIdStatement = con.prepareStatement("SELECT * FROM cars WHERE owner_id = ?"); findAllCarsByOwnerIdStatement.se...
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"); } ret...
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"); } ret...
6
public List<Diff> apply(Object beforeObject, Object afterObject, String description){ List<Diff> diffs = new LinkedList<>(); Collection before = (Collection) beforeObject; Collection after = (Collection) afterObject; if (!isNullOrEmpty(before) && isNullOrEmpty(after)) { for (Object object : befo...
public List<Diff> apply(Object beforeObject, Object afterObject, String description){ List<Diff> diffs = new LinkedList<>(); Collection before = (Collection) beforeObject; Collection after = (Collection) afterObject; if (!isNullOrEmpty(before) && isNullOrEmpty(after)) { before.forEach(object -> ...
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 BinaryOperationEx...
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 BinaryOperationEx...
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, ...
public void createPatients(Table table) throws Exception{ registrationFirstPage.createPatients(table); }
9
public Set<Driver> 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.ge...
public Set<Driver> findAll() throws SQLException, NamingException{ Connection con = null; try { con = dataSource.getConnection(); PreparedStatement findAllDriversStatement = con.prepareStatement("SELECT * FROM drivers ORDER BY id"); ResultSet drivers = findAllDriversStatement.executeQuer...
10
String transform(){ final String specialCharactersRegex = "[^a-zA-Z0-9\\s+]"; final String inputCharacters = "abcdefghijklmnopqrstuvwxyz"; Map<Character, ArrayList<String>> letterOccurenceMap = new LinkedHashMap<Character, ArrayList<String>>(); if (input.equals("")) { return input; } in...
String transform(){ Map<Character, ArrayList<String>> letterOccurrenceMap = new LinkedHashMap<Character, ArrayList<String>>(); if (input.equals("")) { return input; } input = input.toLowerCase(); input = input.replaceAll(specialCharactersRegex, ""); String[] words = input.split(" "); ...
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, schemaNam...
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, schemaNam...
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<Map<String, Object>> items(@PathVariable String table){ LOGGER.info("Getting items for " + table); List<Map<String, Object>> items = new ArrayList<>(); ScanRequest scanRequest = new ScanRequest().withTableName(table); try { List<Map<String, AttributeValue>> list = amazonDynamoDBClien...
public List<Map<String, Object>> items(@PathVariable String table){ LOGGER.info("Getting items for " + table); List<Map<String, Object>> items = new ArrayList<>(); scanRequest.withTableName(table); List<Map<String, AttributeValue>> list = amazonDynamoDBClient.scan(scanRequest).getItems(); LOGGER.inf...
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 pro...
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 pro...
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 < ...
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 < ...
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, servic...
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...
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); en...
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, e...
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(); ...
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 RuntimeExcept...
19
public SCCCiphertext encryptAsymmetric(AbstractSCCKey key, PlaintextContainerInterface plaintext) throws SCCException{ if (key.getKeyType() == KeyType.Asymmetric) { if (usedAlgorithm == null) { ArrayList<SCCAlgorithm> algorithms = currentSCCInstance.getUsage().getAsymmetricEncryption(); ...
public SCCCiphertext encryptAsymmetric(AbstractSCCKey key, PlaintextContainerInterface plaintext) throws SCCException{ if (key.getKeyType() == KeyType.Asymmetric) { if (usedAlgorithm == null) { ArrayList<SCCAlgorithm> algorithms = currentSCCInstance.getUsage().getAsymmetricEncryption(); ...
20
public List<RelationshipVector> getRelationships(final String relationshipName){ List<RelationshipVector> myrelationships = relationships.get(relationshipName.toLowerCase()); ArrayList<RelationshipVector> retRels = new ArrayList<RelationshipVector>(myrelationships); return retRels; }
public List<RelationshipVector> getRelationships(final String relationshipName){ List<RelationshipVector> myrelationships = relationships.get(relationshipName.toLowerCase()); return new ArrayList<>(myrelationships); }
21
public void openSecureChannel(EnumSet<SecurityLevel> 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 (s...
public void openSecureChannel(EnumSet<SecurityLevel> 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 ...
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 ..."); sock...
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 ..."); sock...
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 AnnotationProcessingExce...
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 AnnotationProcessingExce...
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 (i...
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 (i...
25
public void testInsert(){ GeneratedAlwaysRecord record = new GeneratedAlwaysRecord(); record.setId(100); record.setFirstName("Bob"); record.setLastName("Jones"); InsertStatementProvider<GeneratedAlwaysRecord> insertStatement = insert(record).into(generatedAlways).map(id).toProperty("id").map(firstNa...
public void testInsert(){ GeneratedAlwaysRecord record = new GeneratedAlwaysRecord(); record.setId(100); record.setFirstName("Bob"); record.setLastName("Jones"); InsertStatementProvider<GeneratedAlwaysRecord> insertStatement = insert(record).into(generatedAlways).map(id).toProperty("id").map(firstNa...
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; ...
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.getSe...
27
public List<MealView> 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<MealView> 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 = respons...
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 inpu...
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)) { r...
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.getB...
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("A...
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<Me...
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<MemoryPoolMXBean> he...
34
private BoundStatement buildStatementLatestVideoPage(String yyyymmdd, Optional<String> pagingState, AtomicBoolean cassandraPagingStateUsed, Optional<Instant> startingAddedDate, Optional<UUID> startingVideoId, int recordNeeded){ BoundStatementBuilder statementBuilder; if (startingAddedDate.isPresent() && startin...
private BoundStatement buildStatementLatestVideoPage(String yyyymmdd, Optional<String> pagingState, AtomicBoolean cassandraPagingStateUsed, Optional<Instant> startingAddedDate, Optional<UUID> startingVideoId, int recordNeeded){ BoundStatementBuilder statementBuilder = getBoundStatementBuilder(yyyymmdd, startingAdde...
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 Eleme...
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(); ...
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(EbicsN...
static EbicsBank sendHPB(final EbicsSession session) throws IOException, GeneralSecurityException, EbicsException{ final EbicsNoPubKeyDigestsRequest ebicsNoPubKeyDigestsRequest = HPBRequestElement.create(session); final byte[] xml = XmlUtil.prettyPrint(EbicsNoPubKeyDigestsRequest.class, ebicsNoPubKeyDigestsReq...
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")...
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"); ...
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, T...
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...
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 (!...
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)) { ...
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)...
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 (...
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 = obj...
44
private void getInstalledOs(SQLConnection connection, Handler<AsyncResult<List<JsonObject>>> next){ String query = "SELECT * FROM app_installer"; connection.query(query, selectHandler -> { if (selectHandler.failed()) { handleFailure(logger, selectHandler); } else { logger...
private void getInstalledOs(SQLConnection connection, Handler<AsyncResult<List<JsonObject>>> next){ connection.query(SELECT_APP_INSTALLER_QUERY, selectHandler -> { if (selectHandler.failed()) { handleFailure(logger, selectHandler); } else { logger.info("Installed OS: ", Json....
45
public Integer[] flattenArray(Object[] inputArray){ List<Integer> flattenedIntegerList = new ArrayList<Integer>(); for (Object element : inputArray) { if (element instanceof Integer[]) { Integer[] elementArray = (Integer[]) element; for (Integer currentElement : elementArray) { ...
public Integer[] flattenArray(Object[] inputArray){ List<Integer> flattenedIntegerList = new ArrayList<Integer>(); for (Object element : inputArray) { if (element instanceof Integer[]) { Integer[] elementArray = (Integer[]) element; Collections.addAll(flattenedIntegerList, elemen...
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(dt...
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(dt...
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.)...
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.)...
48
public void returnOnePositionForOneItemInInvoice(){ bookKeeper = new BookKeeper(new InvoiceFactory()); when(productData.getType()).thenReturn(productType); InvoiceBuilderImpl invoiceBuilderImpl = new InvoiceBuilderImpl(); invoiceBuilderImpl.setItemsQuantity(1); invoiceBuilderImpl.setProductData(prod...
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); ...
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 eve...
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.decreaseS...
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); MethodD...
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); MethodD...
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(s...
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,...
52
private static void setupPluginBootService(final Collection<PluginConfiguration> pluginConfigurations){ PluginServiceManager.setUpAllService(pluginConfigurations); PluginServiceManager.startAllService(pluginConfigurations); Runtime.getRuntime().addShutdownHook(new Thread(PluginServiceManager::cleanUpAllServ...
private static void setupPluginBootService(final Map<String, PluginConfiguration> pluginConfigurationMap){ PluginServiceManager.startAllService(pluginConfigurationMap); Runtime.getRuntime().addShutdownHook(new Thread(PluginServiceManager::closeAllService)); }
53
public void testCreateListing6() throws CommandParseFailException, UnsupportCommandException{ List<String> arg = new ArrayList<String>(); arg = CommandPaser.parse(clistCommand6); createListingCommand.setCommands(arg); createListingCommand.execute(); ResponseObject ret = registerUserCommand.getRetObj...
public void testCreateListing6() throws CommandParseFailException, UnsupportCommandException{ List<String> arg = new ArrayList<String>(); arg = CommandPaser.parse(clistCommand6); createListingCommand.setCommands(arg); ResponseObject ret = createListingCommand.execute(); System.out.println(ret.getMes...
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<JwtRequest> entity = new HttpEntity<JwtRequest>(jwtReque...
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")); ...
56
public List<Donation> getDonation(@QueryParam("filters") Optional<String> filters){ if (filters.isPresent()) { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new ProtobufModule()); DonationsFilters donationFilters; try { donationFilters = mapper.readValue...
public List<Donation> getDonation(@QueryParam("limit") Optional<Integer> maybeLimit, @QueryParam("filters") Optional<String> maybeFilters){ Integer limit = ResourcesHelper.limit(maybeLimit, defaultLimit, maxLimit); if (maybeFilters.isPresent()) { DonationsFilters filters = ResourcesHelper.decodeUrlEncod...
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.setBetweenE...
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.setBetweenE...
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); M...
public BuildManifest generateBuildTree(){ System.out.println("Starting optimization of blueprint '" + blueprint.getName() + "'"); BuildTreeBlueprintNode tree = generateBuildTree(1, blueprint); tree.updateTreePrices(); Map<EveType, Long> shoppingList = new HashMap<>(); Map<EveType, Long> buildList = ...
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<UserReport> findDeletedUserReports() throws ServiceException{ try { List<UserReport> reports = dao.findUserReportsByAvailability(false); return reports; } catch (DaoException e) { throw new ServiceException(e); } }
public List<UserReport> findDeletedUserReports() throws ServiceException{ try { return dao.findUserReportsByAvailability(false); } catch (DaoException e) { throw new ServiceException(e); } }
61
public Set<User> getParticipantOfTournament(@PathVariable Integer tournamentId){ Tournament tournament = tournamentService.getTournamenById(tournamentId); System.out.println(tournament.getUsers().size()); return tournament.getUsers(); }
public Set<User> 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); }...
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<Violation> minRule(String field, Integer value, int min){ Optional<Violation> isNotNull = notNullRule(field, value); if (isNotNull.isPresent()) { return isNotNull; } if (value < min) { return Optional.of(Violation.of(field, "validation.error.integer.value.smaller.t...
public static Optional<Violation> minRule(String field, Integer value, int min){ Optional<Violation> isNotNull = notNullRule(field, value); if (isNotNull.isPresent()) { return isNotNull; } return isTrueRule(() -> value >= min, Violation.of(field, "validation.error.integer.value.smaller.than.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<String, Object> attributes = new HashMap<>(); attributes.put("age", 25); String feature = "Age Feature"; String expression = "age == 25"; final GatingValidator validator = new GatingValidator(); Assert.assertTrue(validator.isAllo...
public void positiveEvaluteEqualsToInteger() throws Exception{ Map<String, Object> 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<MovieRating> movieRatings){ Map<Integer, MovieRating> newActualMovieRating = new HashMap<>(); for (MovieRating movieRating : movieRatings) { newActualMovieRating.put(movieRating.getMovie().getId(), movieRating); } Lock writeLock = LOCK.writeLock(); try { writeLo...
void invalidate(List<MovieRating> movieRatings){ Map<Integer, MovieRating> 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); invoiceBuilderI...
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.issuanc...
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 El...
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.isSelectionPatternAvai...
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.getD...
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.getD...
71
public List<String> tables(){ List<String> tables = new ArrayList<>(); for (DaoDescriptor descriptor : descriptorsSet) { tables.add(createRegularTableSql(descriptor)); } return tables; }
public List<String> 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();...
private void init(){ Properties uiStylesProperties = mainPanel.getUiStylesProperties(); Properties uiPositionProperties = mainPanel.getUiPositionProperties(); Properties generalProperties = mainPanel.getGeneralProperties(); setBackground(PropertyUtil.getColor(uiStylesProperties, UIConstants.Styles.VIDEO...
73
public List<Double> get(@PathParam("userID") String userID, @PathParam("itemID") List<PathSegment> pathSegmentsList) throws OryxServingException{ ALSServingModel model = getALSServingModel(); float[] userFeatures = model.getUserVector(userID); checkExists(userFeatures != null, userID); List<Double> resu...
public List<Double> get(@PathParam("userID") String userID, @PathParam("itemID") List<PathSegment> pathSegmentsList) throws OryxServingException{ ALSServingModel model = getALSServingModel(); float[] userFeatures = model.getUserVector(userID); checkExists(userFeatures != null, userID); return pathSegmen...
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); MethodDeclara...
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); MethodDeclara...
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 : cus...
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 : cus...
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 || "".eq...
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.generateJava...
78
private static void add(ConfigObject config, String prefix, Map<String, String> values){ for (Map.Entry<String, ConfigValue> e : config.entrySet()) { String nextPrefix = prefix + "." + e.getKey(); ConfigValue value = e.getValue(); switch(value.valueType()) { case OBJECT: ...
private static void add(ConfigObject config, String prefix, Map<String, String> values){ config.forEach((key, value) -> { String nextPrefix = prefix + "." + key; switch(value.valueType()) { case OBJECT: add((ConfigObject) value, nextPrefix, values); break;...
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())).for...
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<Integer> page, @RequestParam("size") Optional<Integer> size){ String myUserName; Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof UserDetails) { myUserName ...
public String showInactiveBugs(Model theModel, @RequestParam("page") Optional<Integer> page, @RequestParam("size") Optional<Integer> size){ UserUtility userUtility = new UserUtility(); int currentPage = page.orElse(1); int pageSize = size.orElse(15); Page<Bug> inactiveBugPage = bugService.findPaginatedU...
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) { ...
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) { ...
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); } c...
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)); ...
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 serv...
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 serv...
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...
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.findAllByEnterpris...
89
public void testSelectRequest_Query_Filter(){ @SuppressWarnings("unchecked") MultivaluedMap<String, String> params = mock(MultivaluedMap.class); when(params.getFirst("query")).thenReturn("Bla"); when(params.getFirst(SenchaRequestParser.FILTER)).thenReturn("[{\"property\":\"name\",\"value\":\"xyz\"}]"); ...
public void testSelectRequest_Query_Filter(){ @SuppressWarnings("unchecked") MultivaluedMap<String, String> params = mock(MultivaluedMap.class); when(params.get("query")).thenReturn(Collections.singletonList("Bla")); when(params.get(SenchaRequestParser.FILTER)).thenReturn(Collections.singletonList("[{\"...
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 fibSeri...
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<Integer, Integer> 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....
public int getProductOfTwo(){ Map<Integer, Integer> 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); ...
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()); ...
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(getPr...
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<Country, Integer> entry = new ArrayL...
private PlaceArmy generatePlaceArmyOrder(Adjutant adjutant, Game game){ if (_placementsToMake == null) { _placementsToMake = computePlacements(game); } Map.Entry<Country, Integer> entry = new ArrayList<>(_placementsToMake.entrySet()).get(0); PlaceArmy order = new PlaceArmy(adjutant, entry.getKey...
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); ...
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(transactionSecon...
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;...
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...
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"); }...
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"); }...
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); ...
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); ...
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
6