auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static org.kframework.definition.Definition from(String definitionText, String mainModuleName, Source source, List<File> lookupDirectories) throws IOException { File tmpDir = Files.createTempDir(); File tempDir = new File(tmpDir.getAbsolutePath() + File.pathSeparator + "tempDir"); File definitionDir = new File(tmpDir.getAbsolutePath() + File.pathSeparator + "definitionDir"); File workingDir = new File(tmpDir.getAbsolutePath() + File.pathSeparator + "workingDir"); File kompiledDir = new File(tmpDir.getAbsolutePath() + File.pathSeparator + "kompiledDir"); if(!tempDir.mkdir() || !definitionDir.mkdir() || !workingDir.mkdir() || !kompiledDir.mkdir()) { throw new AssertionError("Could not create one of the temporary directories"); } GlobalOptions globalOptions = new GlobalOptions(); KExceptionManager kem = new KExceptionManager(globalOptions); FileUtil fileUtil = new FileUtil(tempDir, Providers.of(definitionDir), workingDir, Providers.of(kompiledDir), globalOptions, System.getenv()); ParserUtils parserUtils = new ParserUtils(fileUtil::resolveWorkingDirectory, kem, globalOptions); org.kframework.definition.Definition definition = parserUtils.loadDefinition( mainModuleName, mainModuleName, definitionText, source, workingDir, lookupDirectories, true, false ); return definition; }

Target:
public static org.kframework.definition.Definition from(String definitionText, String mainModuleName, Source source, List<File> lookupDirectories) { File tempDir = Files.createTempDir(); File theFileUtilTempDir = new File(tempDir.getAbsolutePath() + File.pathSeparator + "tempDir"); File definitionDir = new File(tempDir.getAbsolutePath() + File.pathSeparator + "definitionDir"); File workingDir = new File(tempDir.getAbsolutePath() + File.pathSeparator + "workingDir"); File kompiledDir = new File(tempDir.getAbsolutePath() + File.pathSeparator + "kompiledDir"); if(!theFileUtilTempDir.mkdir() || !definitionDir.mkdir() || !workingDir.mkdir() || !kompiledDir.mkdir()) { throw new AssertionError("Could not create one of the temporary directories"); } GlobalOptions globalOptions = new GlobalOptions(); KExceptionManager kem = new KExceptionManager(globalOptions); FileUtil fileUtil = new FileUtil(theFileUtilTempDir, Providers.of(definitionDir), workingDir, Providers.of(kompiledDir), globalOptions, System.getenv()); ParserUtils parserUtils = new ParserUtils(fileUtil::resolveWorkingDirectory, kem, globalOptions); org.kframework.definition.Definition definition = parserUtils.loadDefinition( mainModuleName, mainModuleName, definitionText, source, workingDir, lookupDirectories, true, false ); return definition; }
Source:
public void scheduleInitial(SourceScheduler scheduler) { checkState(!initialScheduled); initialScheduled = true; int driverGroupsScheduledPerTask = 0; while (!driverGroupQueue.isEmpty()) { for (int i = 0; i < nodeByTaskId.size() && !driverGroupQueue.isEmpty(); i++) { int driverGroupId = driverGroupQueue.dequeueInt(); checkState(!bucketNodeMap.getAssignedNode(driverGroupId).isPresent()); bucketNodeMap.assignOrUpdateBucketToNode(driverGroupId, nodeByTaskId.get(i)); scheduler.startLifespan(Lifespan.driverGroup(driverGroupId), partitionHandles.get(driverGroupId)); taskByDriverGroup[driverGroupId] = i; runningDriverGroupIdsByTask[i].add(driverGroupId); } driverGroupsScheduledPerTask++; if (concurrentLifespansPerTask.isPresent() && driverGroupsScheduledPerTask == concurrentLifespansPerTask.getAsInt()) { break; } } }

Target:
public void scheduleInitial(SourceScheduler scheduler) { checkState(!initialScheduled, "Initial scheduling happened before scheduleInitial is called"); int driverGroupsScheduledPerTask = 0; synchronized (this) { while (!driverGroupQueue.isEmpty()) { for (int i = 0; i < nodeByTaskId.size() && !driverGroupQueue.isEmpty(); i++) { int driverGroupId = driverGroupQueue.dequeueInt(); checkState(!bucketNodeMap.getAssignedNode(driverGroupId).isPresent()); bucketNodeMap.assignOrUpdateBucketToNode(driverGroupId, nodeByTaskId.get(i)); scheduler.startLifespan(Lifespan.driverGroup(driverGroupId), partitionHandles.get(driverGroupId)); taskByDriverGroup[driverGroupId] = i; runningDriverGroupIdsByTask[i].add(driverGroupId); } driverGroupsScheduledPerTask++; if (concurrentLifespansPerTask.isPresent() && driverGroupsScheduledPerTask == concurrentLifespansPerTask.getAsInt()) { break; } } initialScheduled = true; } }
Source:
private void setTextViewTypefaceToCurrentFont(TextView textView, int textStyle) { if (textStyle < 0 || textStyle > 3) { textStyle = textView.getTypeface() == null ? Typeface.NORMAL : textView.getTypeface().getStyle(); } if (currentFont != null) textView.setTypeface(currentFont, textStyle); else Timber.e("currentFont is null"); }

Target:
private void setTextViewTypefaceToCurrentFont(TextView textView, int textStyle) { if (!isValidTextStyle(textStyle)) { textStyle = textView.getTypeface() != null ? textView.getTypeface().getStyle() : Typeface.NORMAL; } if (currentFont != null) textView.setTypeface(currentFont, textStyle); else Timber.w("Couldn't set typeface as currentFont is null"); }
Source:
public boolean matches(Method method) throws SignatureMismatchException { if (skipMethod(method)) { return false; } Collection<SignatureMismatch> mismatches = match(method); boolean hasErrors = mismatches.stream() .anyMatch(mismatch -> ERROR == mismatch.getSeverity()); List<SignatureMismatch> warnings = mismatches.stream() .filter(mismatch -> WARN == mismatch.getSeverity()) .collect(toList()); if (hasErrors) { throw new SignatureMismatchException(mismatches); } if (!warnings.isEmpty()) { Logger logger = Logging.get(MethodSignature.class); warnings.forEach(warning -> logger.warn(warning.toString())); } return true; }

Target:
public boolean matches(Method method) throws SignatureMismatchException { if (skipMethod(method)) { return false; } Collection<SignatureMismatch> mismatches = match(method); boolean hasErrors = mismatches.stream() .anyMatch(SignatureMismatch::isError); List<SignatureMismatch> warnings = mismatches.stream() .filter(SignatureMismatch::isWarning) .collect(toList()); if (hasErrors) { throw new SignatureMismatchException(mismatches); } if (!warnings.isEmpty()) { warnings.stream() .map(SignatureMismatch::toString) .forEach(this::_warn); } return true; }
Source:
public void testOverride() throws Exception { deployContrib(Thread.currentThread().getContextClassLoader().getResource("test-nxtreemanager-contrib.xml")); applyInlineDeployments(); postSetUp(); String filterName = "navigation"; assertEquals("tree_children", treeManager.getPageProviderName(filterName)); assertNotNull(treeManager.getFilter(filterName)); assertNull(treeManager.getLeafFilter(filterName)); assertNotNull(treeManager.getSorter(filterName)); }

Target:
public void testOverride() throws Exception { pushInlineDeployments("org.nuxeo.ecm.webapp.base.tests:test-nxtreemanager-contrib.xml"); String filterName = "navigation"; assertEquals("tree_children", treeManager.getPageProviderName(filterName)); assertNotNull(treeManager.getFilter(filterName)); assertNull(treeManager.getLeafFilter(filterName)); assertNotNull(treeManager.getSorter(filterName)); }
Source:
public boolean hasRadiologyOrderCompletedRadiologyReport(RadiologyOrder radiologyOrder) { List<RadiologyReport> radiologyReports = sessionFactory.getCurrentSession().createCriteria(RadiologyReport.class) .add(Restrictions.like("radiologyOrder", radiologyOrder)).add( Restrictions.like("radiologyReportStatus", RadiologyReportStatus.COMPLETED)).list(); if (radiologyReports.size() == 1) { return true; } else { return false; } }

Target:
public boolean hasRadiologyOrderCompletedRadiologyReport(RadiologyOrder radiologyOrder) { List<RadiologyReport> radiologyReports = sessionFactory.getCurrentSession().createCriteria(RadiologyReport.class) .add(Restrictions.eq("radiologyOrder", radiologyOrder)).add( Restrictions.eq("reportStatus", RadiologyReportStatus.COMPLETED)).list(); return radiologyReports.size() == 1 ? true : false; }
Source:
public void testBetaMemoryLeakOnFactDelete() { String drl = "rule R1 when\n" + " $a : Integer(this == 1)\n" + " $b : String()\n" + " $c : Integer(this == 2)\n" + "then \n" + "end\n" + "rule R2 when\n" + " $a : Integer(this == 1)\n" + " $b : String()\n" + "then \n" + "end\n"; KieSession ksession = new KieHelper().addContent(drl, ResourceType.DRL) .build() .newKieSession(); FactHandle fh1 = ksession.insert(1); FactHandle fh2 = ksession.insert("test"); ksession.fireAllRules(); ksession.delete(fh1); ksession.delete(fh2); ksession.fireAllRules(); NodeMemories nodeMemories = ((InternalWorkingMemory) ksession).getNodeMemories(); for (int i = 0; i < nodeMemories.length(); i++) { Memory memory = nodeMemories.peekNodeMemory(i); if (memory != null && memory.getSegmentMemory() != null) { LeftTuple deleteFirst = memory.getSegmentMemory().getStagedLeftTuples().getDeleteFirst(); assertThat(deleteFirst).isNull(); } } }

Target:
public void testBetaMemoryLeakOnFactDelete() { final String drl = "rule R1 when\n" + " $a : Integer(this == 1)\n" + " $b : String()\n" + " $c : Integer(this == 2)\n" + "then \n" + "end\n" + "rule R2 when\n" + " $a : Integer(this == 1)\n" + " $b : String()\n" + "then \n" + "end\n"; final KieSession ksession = new KieHelper().addContent(drl, ResourceType.DRL) .build() .newKieSession(); final FactHandle fh1 = ksession.insert(1); final FactHandle fh2 = ksession.insert("test"); ksession.fireAllRules(); ksession.delete(fh1); ksession.delete(fh2); ksession.fireAllRules(); final NodeMemories nodeMemories = ((InternalWorkingMemory) ksession).getNodeMemories(); for (int i = 0; i < nodeMemories.length(); i++) { final Memory memory = nodeMemories.peekNodeMemory(i); if (memory != null && memory.getSegmentMemory() != null) { final LeftTuple deleteFirst = memory.getSegmentMemory().getStagedLeftTuples().getDeleteFirst(); assertThat(deleteFirst).isNull(); } } }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { final RepositoryTreeNode node = getSelectedNodes(event).get(0); if (node.getType() == RepositoryTreeNodeType.ADDITIONALREF) { Ref ref = (Ref) node.getObject(); try { RevCommit baseCommit = new RevWalk(node.getRepository()) .parseCommit(ref.getLeaf().getObjectId()); WizardDialog dlg = new WizardDialog( getShell(event), new CreateBranchWizard(node.getRepository(), baseCommit.name())); dlg.setHelpAvailable(false); dlg.open(); } catch (IOException e) { Activator.handleError(e.getMessage(), e, true); } return null; } String base = null; if (node.getObject() instanceof Ref) base = ((Ref) node.getObject()).getName(); else { Ref branch; try { String sourceRef = node.getRepository().getConfig().getString( ConfigConstants.CONFIG_WORKFLOW_SECTION, null, ConfigConstants.CONFIG_KEY_DEFBRANCHSTARTPOINT); if (node.getRepository().getRef(sourceRef) != null) branch = node.getRepository().getRef(sourceRef); else { if (node.getRepository().getFullBranch() .startsWith(Constants.R_HEADS)) { branch = node.getRepository().getRef( node.getRepository().getFullBranch()); } else { String ref = Activator .getDefault() .getRepositoryUtil() .mapCommitToRef(node.getRepository(), node.getRepository().getFullBranch(), false); if (ref == null) branch = null; else { if (ref.startsWith(Constants.R_TAGS)) branch = null; else branch = node.getRepository().getRef(ref); } } } } catch (IOException e) { branch = null; } if (branch != null) base = branch.getName(); } new WizardDialog(getShell(event), new CreateBranchWizard(node .getRepository(), base)).open(); return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { final RepositoryTreeNode node = getSelectedNodes(event).get(0); if (node.getType() == RepositoryTreeNodeType.ADDITIONALREF) { Ref ref = (Ref) node.getObject(); try { RevCommit baseCommit = new RevWalk(node.getRepository()) .parseCommit(ref.getLeaf().getObjectId()); WizardDialog dlg = new WizardDialog( getShell(event), new CreateBranchWizard(node.getRepository(), baseCommit.name())); dlg.setHelpAvailable(false); dlg.open(); } catch (IOException e) { Activator.handleError(e.getMessage(), e, true); } return null; } String base = null; if (node.getObject() instanceof Ref) base = ((Ref) node.getObject()).getName(); new WizardDialog(getShell(event), new CreateBranchWizard(node .getRepository(), base)).open(); return null; }
Source:
public Builder runSafeService(Executor runSafeService) { this.runSafeService = runSafeService; return null; }

Target:
public Builder runSafeService(Executor runSafeService) { this.runSafeService = runSafeService; return this; }
Source:
public App(AppConfig appConfig) { this.appConfig = appConfig; ExecutorService collectionThreadPool = null; ExecutorService recoveryThreadPool = null; if (!appConfig.isEmbedded()) { collectionThreadPool = buildExecutorService(appConfig.getThreadPoolSize()); recoveryThreadPool = buildExecutorService(appConfig.getReconnectionThreadPoolSize()); } recoveryProcessor = new TaskProcessor(recoveryThreadPool, appConfig.getReporter()); collectionProcessor = new TaskProcessor(collectionThreadPool, appConfig.getReporter()); if (appConfig.remoteEnabled()) { client = new HttpClient(appConfig.getIpcHost(), appConfig.getIpcPort(), false); } this.configs = getConfigs(appConfig); }

Target:
public App(AppConfig appConfig) { this.appConfig = appConfig; ExecutorService collectionThreadPool = null; ExecutorService recoveryThreadPool = null; if (!appConfig.isEmbedded()) { collectionThreadPool = buildExecutorService(appConfig.getThreadPoolSize(), COLLECTION_POOL_NAME); recoveryThreadPool = buildExecutorService(appConfig.getReconnectionThreadPoolSize(), RECOVERY_POOL_NAME); } recoveryProcessor = new TaskProcessor(recoveryThreadPool, appConfig.getReporter()); collectionProcessor = new TaskProcessor(collectionThreadPool, appConfig.getReporter()); if (appConfig.remoteEnabled()) { client = new HttpClient(appConfig.getIpcHost(), appConfig.getIpcPort(), false); } this.configs = getConfigs(appConfig); }
Source:
public void testTwoNodesDieOnRequest() throws Exception { CountDownLatch nodeStopLatch = new CountDownLatch(2); Ignite srv1 = startGrid(0); replaceWithStoppingMappingRequestListener( ((GridKernalContext)U.field(srv1, "ctx")).io(), 0, nodeStopLatch); Ignite srv2 = startGrid(1); replaceWithStoppingMappingRequestListener( ((GridKernalContext)U.field(srv2, "ctx")).io(), 1, nodeStopLatch); Ignite srv3 = startGrid(2); replaceWithCountingMappingRequestListener(((GridKernalContext)U.field(srv3, "ctx")).io()); srv3.cache(DEFAULT_CACHE_NAME).put( 1, new Organization(1, "Microsoft", "One Microsoft Way Redmond, WA 98052-6399, USA")); clientMode = true; Ignite cl1 = startClientGrid(4); cl1.cache(DEFAULT_CACHE_NAME).get(1); nodeStopLatch.await(5_000, TimeUnit.MILLISECONDS); int result = mappingReqsCounter.get(); assertEquals("Expected requests count is 3, actual is " + result, 3, result); }

Target:
public void testTwoNodesDieOnRequest() throws Exception { CountDownLatch nodeStopLatch = new CountDownLatch(2); Ignite srv1 = startGrid(0); replaceWithStoppingMappingRequestListener( ((GridKernalContext)U.field(srv1, "ctx")).io(), 0, nodeStopLatch); Ignite srv2 = startGrid(1); replaceWithStoppingMappingRequestListener( ((GridKernalContext)U.field(srv2, "ctx")).io(), 1, nodeStopLatch); Ignite srv3 = startGrid(2); replaceWithCountingMappingRequestListener(((GridKernalContext)U.field(srv3, "ctx")).io()); srv3.cache(DEFAULT_CACHE_NAME).put( 1, new Organization(1, "Microsoft", "One Microsoft Way Redmond, WA 98052-6399, USA")); Ignite cl1 = startClientGrid(4); cl1.cache(DEFAULT_CACHE_NAME).get(1); nodeStopLatch.await(5_000, TimeUnit.MILLISECONDS); int result = mappingReqsCounter.get(); assertEquals("Expected requests count is 3, actual is " + result, 3, result); }
Source:
public OvfEntityData mapRow(ResultSet rs, int rowNum) throws SQLException { OvfEntityData entity = new OvfEntityData(); entity.setEntityId(getGuid(rs, "entity_guid")); entity.setEntityName(rs.getString("entity_name")); entity.setEntityType(rs.getString("entity_type")); entity.setArchitecture(rs.getInt("architecture")); entity.setLowestCompVersion(new Version(rs.getString("lowest_comp_version"))); entity.setStorageDomainId(getGuid(rs, "storage_domain_id")); entity.setOvfData(rs.getString("ovf_data")); entity.setOvfExtraData(rs.getString("ovf_extra_data")); return entity; }

Target:
public OvfEntityData mapRow(ResultSet rs, int rowNum) throws SQLException { OvfEntityData entity = new OvfEntityData(); entity.setEntityId(getGuid(rs, "entity_guid")); entity.setEntityName(rs.getString("entity_name")); entity.setEntityType(VmEntityType.valueOf(rs.getString("entity_type"))); entity.setArchitecture(ArchitectureType.forValue(rs.getInt("architecture"))); entity.setLowestCompVersion(new Version(rs.getString("lowest_comp_version"))); entity.setStorageDomainId(getGuid(rs, "storage_domain_id")); entity.setOvfData(rs.getString("ovf_data")); entity.setOvfExtraData(rs.getString("ovf_extra_data")); return entity; }
Source:
public static void registerFormat(String name, Format<?> fmt) { if (fmt == null) throw new NullPointerException(); FormatEntry old = null; FormatEntry entry = new FormatEntry(fmt, 1); while (!replace(formats, name, old, entry)) { old = formats.get(name); if (old == null) { entry = new FormatEntry(fmt, 1); continue; } if (!old.format.equals(fmt)) throw new JGitInternalException(MessageFormat.format( JGitText.get().archiveFormatAlreadyRegistered, name)); entry = new FormatEntry(old.format, old.refcnt + 1); } }

Target:
public static void registerFormat(String name, Format<?> fmt) { if (fmt == null) throw new NullPointerException(); FormatEntry old, entry; do { old = formats.get(name); if (old == null) { entry = new FormatEntry(fmt, 1); continue; } if (!old.format.equals(fmt)) throw new JGitInternalException(MessageFormat.format( JGitText.get().archiveFormatAlreadyRegistered, name)); entry = new FormatEntry(old.format, old.refcnt + 1); } while (!replace(formats, name, old, entry)); }
Source:
public InstrumentTextSegmentExporter(IObservingLogSegment segment) { this(segment, null); }

Target:
public InstrumentTextSegmentExporter(IObservingLogSegment segment) { super(segment); _thisProgramOnly = None.instance(); }
Source:
public void onSuccess(List<DepictedItem> mediaList) { isLoading = false; hasMoreImages = false; progressBar.setVisibility(View.GONE); depictionNotFound.setVisibility(GONE); bottomProgressBar.setVisibility(GONE); int itemCount=layoutManager.getItemCount(); depictionsAdapter.addAll(mediaList); if(itemCount!=0) { depictionsAdapter.notifyItemRangeInserted(itemCount, mediaList.size()-1); }else{ depictionsAdapter.notifyDataSetChanged(); } }

Target:
public void onSuccess(List<DepictedItem> mediaList) { isLoading = false; progressBar.setVisibility(View.GONE); depictionNotFound.setVisibility(GONE); bottomProgressBar.setVisibility(GONE); int itemCount = layoutManager.getItemCount(); depictionsAdapter.addAll(mediaList); if(itemCount!=0) { depictionsAdapter.notifyItemRangeInserted(itemCount, mediaList.size()-1); }else{ depictionsAdapter.notifyDataSetChanged(); } }
Source:
public boolean apply(URI uri) { return DiModel.DI_FILE_EXTENSION.equals(uri.fileExtension()); }

Target:
public boolean apply(URI uri) { return fileExtensions.contains(uri.fileExtension()); }
Source:
public void clearLevel(String loggerName) { loggers.computeIfAbsent(loggerName, java.util.logging.Logger::getLogger) .setLevel(null); }

Target:
public synchronized void clearLevel(String loggerName) { java.util.logging.Logger logger = loggers.remove(loggerName); if (logger != null) { logger.setLevel(null); } }
Source:
public void discover() { DomainControllerData data = readFromFile(MASTER); if (data != null) { String host = data.getHost(); int port = data.getPort(); String protocol = Protocol.REMOTE.name(); try { StaticDiscoveryResourceDefinition.HOST.getValidator() .validateParameter(StaticDiscoveryResourceDefinition.HOST.getName(), host == null? new ModelNode() : new ModelNode(host)); StaticDiscoveryResourceDefinition.PORT.getValidator() .validateParameter(StaticDiscoveryResourceDefinition.PORT.getName(), new ModelNode(port)); StaticDiscoveryResourceDefinition.PROTOCOL.getValidator() .validateParameter(StaticDiscoveryResourceDefinition.PROTOCOL.getName(), new ModelNode(protocol)); } catch (OperationFailedException e) { throw new IllegalStateException(e.getFailureDescription().asString()); } setRemoteDomainControllerHost(host); setRemoteDomainControllerPort(port); setRemoteDomainControllerProtocol(protocol); } else { throw HostControllerLogger.ROOT_LOGGER.failedMarshallingDomainControllerData(); } }

Target:
public void discover() { List<DomainControllerData> dataDc = readFromFile(MASTER); List<StaticDiscovery> options = new ArrayList<StaticDiscovery>(dataDc.size()); for (DomainControllerData data : dataDc) { if (data != null) { StaticDiscovery discovery = new StaticDiscovery(data.getProtocol(), data.getHost(), data.getPort()); String host = data.getHost(); try { StaticDiscoveryResourceDefinition.HOST.getValidator() .validateParameter(StaticDiscoveryResourceDefinition.HOST.getName(), host == null ? new ModelNode() : new ModelNode(host)); StaticDiscoveryResourceDefinition.PORT.getValidator() .validateParameter(StaticDiscoveryResourceDefinition.PORT.getName(), new ModelNode(discovery.getRemoteDomainControllerPort())); StaticDiscoveryResourceDefinition.PROTOCOL.getValidator() .validateParameter(StaticDiscoveryResourceDefinition.PROTOCOL.getName(), new ModelNode(discovery.getRemoteDomainControllerProtocol())); options.add(discovery); } catch (OperationFailedException e) { } } else { throw HostControllerLogger.ROOT_LOGGER.failedMarshallingDomainControllerData(); } } if (options.isEmpty()) { throw HostControllerLogger.ROOT_LOGGER.failedMarshallingDomainControllerData(); } DiscoveryHostStategy.DEFAULT_STRATEGY.organize(options); setRemoteDomainControllerHost(options.get(0).getRemoteDomainControllerHost()); setRemoteDomainControllerPort(options.get(0).getRemoteDomainControllerPort()); setRemoteDomainControllerProtocol(options.get(0).getRemoteDomainControllerProtocol()); }
Source:
private void prepareStubFile(File file) { try { List<String> lines = FileUtils.readLines(file); List<String> parsedLines = new ArrayList<>(); boolean skipLine = false; for (String line : lines) { if (line.contains(beginSolution)) { skipLine = true; } else if (skipLine && line.contains(endSolution)) { skipLine = false; } else if (!skipLine && !line.contains(stubMarker)) { parsedLines.add(line); } else if (line.contains(stubMarker)) { String start = line.substring(0, line.indexOf(stubMarker) - 1); String end = line.substring(line.indexOf(stubMarker) + stubMarker.length()); parsedLines.add(start + end); } } FileUtils.writeLines(file, parsedLines); } catch (IOException ex) { System.out.println("Unexpected IOException, preparation of file {" + file.getAbsolutePath() + "} interrupted"); } }

Target:
private void prepareStubFile(File file) { try { List<String> lines = Files.readAllLines(file.toPath(), charset); List<String> filteredLines = new ArrayList<>(); boolean skipLine = false; for (String line : lines) { if (line.contains(beginSolution)) { skipLine = true; } else if (skipLine && line.contains(endSolution)) { skipLine = false; } else if (line.contains(stubMarker)) { String start = line.substring(0, line.indexOf(stubMarker) - 1); String end = line.substring(line.indexOf(stubMarker) + stubMarker.length()); filteredLines.add(start + end); } else if (!skipLine && !line.contains(stubMarker)) { filteredLines.add(line); } } Files.write(file.toPath(), filteredLines, charset); } catch (IOException ex) { throw new RuntimeException("Unexpected IOException, preparation of file {" + file.getAbsolutePath() + "} interrupted", ex); } }
Source:
private void fillCache(){ for ( int numAlleles = 1; numAlleles < staticCache.length; numAlleles++ ) { for ( int ploidy = 1; ploidy < staticCache[numAlleles].length; ploidy++ ) { staticCache[numAlleles][ploidy] = GenotypeLikelihoods.calcNumLikelihoods(numAlleles, ploidy); } } }

Target:
private void fillCache(){ for ( int numAlleles = 0; numAlleles < staticCache.length; numAlleles++ ) { for ( int ploidy = 0; ploidy < staticCache[numAlleles].length; ploidy++ ) { staticCache[numAlleles][ploidy] = GenotypeLikelihoods.calcNumLikelihoods(numAlleles+1, ploidy+1); } } }
Source:
void configExtractor() throws IngestModule.IngestModuleException { List<DomainCategorizer> foundProviders = Lookup.getDefault().lookupAll(DomainCategorizer.class).stream() .filter(provider -> provider != null) .sorted((a, b) -> a.getClass().getName().compareToIgnoreCase(b.getClass().getName())) .collect(Collectors.toList()); foundProviders.add(new DefaultDomainCategorizer()); for (DomainCategorizer provider : foundProviders) { try { provider.initialize(); } catch (DomainCategorizerException ex) { throw new IngestModule.IngestModuleException("There was an error instantiating the provider: " + provider.getClass().getSimpleName(), ex); } } this.domainProviders = foundProviders == null ? Collections.emptyList() : foundProviders; }

Target:
void configExtractor() throws IngestModule.IngestModuleException { Collection<? extends DomainCategorizer> lookupList = Lookup.getDefault().lookupAll(DomainCategorizer.class); if (lookupList == null) { lookupList = Collections.emptyList(); } List<DomainCategorizer> foundProviders = lookupList.stream() .filter(provider -> provider != null) .sorted((a, b) -> a.getClass().getName().compareToIgnoreCase(b.getClass().getName())) .collect(Collectors.toList()); foundProviders.add(new DefaultDomainCategorizer()); for (DomainCategorizer provider : foundProviders) { try { provider.initialize(); } catch (DomainCategorizerException ex) { throw new IngestModule.IngestModuleException("There was an error instantiating the provider: " + provider.getClass().getSimpleName(), ex); } } this.domainProviders = foundProviders; }
Source:
public boolean terminateSolver(Object problemId) { Objects.requireNonNull(problemId); logger.debug("Terminating solver of problemId ({}).", problemId); synchronized (this) { if (!isProblemSubmitted(problemId)) { throw new IllegalArgumentException("Problem (" + problemId + ") was not submitted or finished solving."); } SolverTask<Solution_> solverTask = problemIdToSolverTaskMap.get(problemId); boolean willTerminate = solverTask.stopSolver(); if (!willTerminate) { logger.error("Cannot terminate solver of problemId ({}).", problemId); return false; } List<Future> problemEventHandlersFutures = problemIdToEventHandlerFuturesMap.get(problemId); problemEventHandlersFutures.forEach(future -> future.cancel(false)); return cleanupResources(problemId); } }

Target:
public void terminateSolver(Object problemId) { Objects.requireNonNull(problemId); logger.info("Terminating solver of problemId ({}).", problemId); synchronized (this) { if (!isProblemSubmitted(problemId)) { throw new IllegalArgumentException("Problem (" + problemId + ") either was not submitted or finished solving."); } problemIdToSolverTaskMap.get(problemId).terminateEarly(); List<Future> problemEventHandlersFutures = problemIdToFuturesMap.get(problemId); problemEventHandlersFutures.forEach(future -> future.cancel(false)); cleanupResources(problemId); } }
Source:
private void addPrePostProcessingNodes(RenderGraph renderGraph) { Node prePostCompositeNode = new PrePostCompositeNode(context); renderGraph.addNode(prePostCompositeNode, "prePostCompositeNode"); Node simpleBlendMaterialsNode = new SimpleBlendMaterialsNode(context); renderGraph.addNode(simpleBlendMaterialsNode, "simpleBlendMaterialsNode"); Node opaqueObjectsNode = renderGraph.findNode(new SimpleUri("engine:opaqueObjectsNode")); Node opaqueBlocksNode = renderGraph.findNode(new SimpleUri("engine:opaqueBlocksNode")); Node alphaRejectBlocksNode = renderGraph.findNode(new SimpleUri("engine:alphaRejectBlocksNode")); Node overlaysNode = renderGraph.findNode(new SimpleUri("engine:overlaysNode")); Node hazeFinalNode = renderGraph.findNode(new SimpleUri("engine:hazeFinalNode")); Node chunksRefractiveReflectiveNode = renderGraph.findNode(new SimpleUri("engine:chunksRefractiveReflectiveNode")); Node applyDeferredLightingNode = renderGraph.findNode(new SimpleUri("engine:applyDeferredLightingNode")); Node outlineNode = renderGraph.findNode(new SimpleUri("engine:outlineNode")); Node blurredAmbientOcclusionNode = renderGraph.findNode(new SimpleUri("engine:blurredAmbientOcclusionNode")); renderGraph.connect(opaqueObjectsNode, prePostCompositeNode); renderGraph.connect(opaqueBlocksNode, prePostCompositeNode); renderGraph.connect(alphaRejectBlocksNode, prePostCompositeNode); renderGraph.connect(overlaysNode, prePostCompositeNode); renderGraph.connect(hazeFinalNode, prePostCompositeNode); renderGraph.connect(chunksRefractiveReflectiveNode, prePostCompositeNode); renderGraph.connect(applyDeferredLightingNode, prePostCompositeNode); renderGraph.connect(outlineNode, prePostCompositeNode); renderGraph.connect(blurredAmbientOcclusionNode, prePostCompositeNode); renderGraph.connect(prePostCompositeNode, simpleBlendMaterialsNode); }

Target:
private void addPrePostProcessingNodes(RenderGraph renderGraph) { Node overlaysNode = renderGraph.findNode("engine:overlaysNode"); Node hazeFinalNode = renderGraph.findNode("engine:hazeFinalNode"); Node chunksRefractiveReflectiveNode = renderGraph.findNode("engine:chunksRefractiveReflectiveNode"); Node applyDeferredLightingNode = renderGraph.findNode("engine:applyDeferredLightingNode"); Node outlineNode = renderGraph.findNode("engine:outlineNode"); Node blurredAmbientOcclusionNode = renderGraph.findNode("engine:blurredAmbientOcclusionNode"); Node prePostCompositeNode = new PrePostCompositeNode(context); renderGraph.addNode(prePostCompositeNode, "prePostCompositeNode"); renderGraph.connect(overlaysNode, prePostCompositeNode); renderGraph.connect(hazeFinalNode, prePostCompositeNode); renderGraph.connect(chunksRefractiveReflectiveNode, prePostCompositeNode); renderGraph.connect(applyDeferredLightingNode, prePostCompositeNode); renderGraph.connect(outlineNode, prePostCompositeNode); renderGraph.connect(blurredAmbientOcclusionNode, prePostCompositeNode); Node simpleBlendMaterialsNode = new SimpleBlendMaterialsNode(context); renderGraph.addNode(simpleBlendMaterialsNode, "simpleBlendMaterialsNode"); renderGraph.connect(prePostCompositeNode, simpleBlendMaterialsNode); }
Source:
public List<DispoItem> copyData(Map<String, ArtifactReadable> nameToCoverageUnit, List<DispoItem> dispoItems, OperationReport report) { Map<String, DispoItem> nameToDispoItem = getNameToDispoItemMap(dispoItems); List<DispoItem> modifiedItems = new ArrayList<DispoItem>(); for (String name : nameToCoverageUnit.keySet()) { ArtifactReadable coverageUnit = nameToCoverageUnit.get(name); DispoItem dispoItem = nameToDispoItem.get(name); if (dispoItem != null) { List<DispoAnnotationData> newAnnotations = copyCoverageData(coverageUnit, dispoItem, report); if (!newAnnotations.isEmpty()) { DispoItemData newItem = new DispoItemData(); newItem.setName(dispoItem.getName()); newItem.setGuid(dispoItem.getGuid()); newItem.setAnnotationsList(DispoUtil.listAsJsonArray(newAnnotations)); String newStatus; try { newItem.setDiscrepanciesList(dispoItem.getDiscrepanciesList()); newStatus = dispoConnector.getItemStatus(newItem); newItem.setStatus(newStatus); } catch (JSONException ex) { } modifiedItems.add(newItem); } } } return modifiedItems; }

Target:
public List<DispoItem> copyData(Map<String, ArtifactReadable> nameToCoverageUnit, List<DispoItem> dispoItems, OperationReport report) { Map<String, DispoItem> nameToDispoItem = getNameToDispoItemMap(dispoItems); List<DispoItem> modifiedItems = new ArrayList<DispoItem>(); for (Entry<String, ArtifactReadable> entry : nameToCoverageUnit.entrySet()) { DispoItem dispoItem = nameToDispoItem.get(entry.getKey()); if (dispoItem != null) { List<DispoAnnotationData> newAnnotations = copyCoverageData(entry.getValue(), dispoItem, report); if (!newAnnotations.isEmpty()) { DispoItemData newItem = new DispoItemData(); newItem.setName(dispoItem.getName()); newItem.setGuid(dispoItem.getGuid()); newItem.setAnnotationsList(DispoUtil.listAsJsonArray(newAnnotations)); String newStatus; try { newItem.setDiscrepanciesList(dispoItem.getDiscrepanciesList()); newStatus = dispoConnector.getItemStatus(newItem); newItem.setStatus(newStatus); } catch (JSONException ex) { report.addMessageForItem(newItem.getName(), "Could not determine Status"); } modifiedItems.add(newItem); } } } return modifiedItems; }
Source:
private PaymentWorksVendor pmwPendingNewVendorRequestInitialSaveToKfsStagingTable(PaymentWorksVendor pmwVendor) { LOG.info("pmwPendingNewVendorRequestSavesToKfsStagingTableSuccessful: entered"); pmwVendor.setPmwRequestStatus(PaymentWorksConstants.PaymentWorksNewVendorRequestStatusType.PENDING.getText()); pmwVendor.setPmwTransactionType(PaymentWorksConstants.PaymentWorksTransactionType.NEW_VENDOR); pmwVendor.setKfsVendorProcessingStatus(PaymentWorksConstants.KFSVendorProcessingStatus.VENDOR_REQUESTED); PaymentWorksVendor savedNewVendorRequestedDetail = null; savedNewVendorRequestedDetail = getPaymentWorksVendorDao().savePaymentWorksVendorToStagingTable(pmwVendor); return savedNewVendorRequestedDetail; }

Target:
private PaymentWorksVendor pmwPendingNewVendorRequestInitialSaveToKfsStagingTable(PaymentWorksVendor pmwVendor) { LOG.info("pmwPendingNewVendorRequestSavesToKfsStagingTableSuccessful: entered"); pmwVendor = setStatusValuesForPaymentWorksPendingNewVendorRequestedInKfs(pmwVendor); PaymentWorksVendor savedNewVendorRequestedDetail = null; savedNewVendorRequestedDetail = savePaymentWorksVendorToStagingTable(pmwVendor); return savedNewVendorRequestedDetail; }
Source:
public void multiple_assignment() { PyFunctionDefTree functionTree = functionTreesByName.get("multiple_assignment"); Set<TreeSymbol> symbols = functionTree.localVariables(); Map<String, TreeSymbol> symbolByName = symbols.stream().collect(Collectors.toMap(TreeSymbol::name, Functions.identity())); assertThat(symbolByName.keySet()).containsOnly("x", "y"); int functionStartLine = functionTree.firstToken().getLine(); TreeSymbol x = symbolByName.get("x"); assertThat(x.usages()).extracting(tree -> tree.firstToken().getLine()).containsOnly(functionStartLine + 1); TreeSymbol y = symbolByName.get("y"); assertThat(y.usages()).extracting(tree -> tree.firstToken().getLine()).containsOnly(functionStartLine + 1); }

Target:
public void multiple_assignment() { PyFunctionDefTree functionTree = functionTreesByName.get("multiple_assignment"); Map<String, TreeSymbol> symbolByName = getSymbolByName(functionTree); assertThat(symbolByName.keySet()).containsOnly("x", "y"); int functionStartLine = functionTree.firstToken().token().getLine(); TreeSymbol x = symbolByName.get("x"); assertThat(x.usages()).extracting(usage -> usage.tree().firstToken().token().getLine()).containsOnly(functionStartLine + 1); assertThat(x.usages()).extracting(Usage::kind).containsOnly(Usage.Kind.ASSIGNMENT_LHS); TreeSymbol y = symbolByName.get("y"); assertThat(y.usages()).extracting(usage -> usage.tree().firstToken().token().getLine()).containsOnly(functionStartLine + 1); assertThat(y.usages()).extracting(Usage::kind).containsOnly(Usage.Kind.ASSIGNMENT_LHS); }
Source:
protected void safeRun(IProgressMonitor progressMonitor) throws Exception { try { target.createRepository(repositoryName, CDOAdmin.TYPE_DEFAULT, repositoryProperties); } finally { repositoryName = null; repositoryProperties = null; } }

Target:
protected void safeRun(IProgressMonitor progressMonitor) throws Exception { try { target.createRepository(repositoryName, CDOAdmin.DEFAULT_TYPE, repositoryProperties); } finally { repositoryName = null; repositoryProperties = null; } }
Source:
public void shouldSendEventIfTheUserShouldResetPassword() throws Exception { List<MotechUser> users = prepareMotechUsersOne(); when(settingService.isPasswordResetReminderEnabled()).thenReturn(true); when(allUsers.retrieveAll()).thenReturn(users); eventHandler.handleEvent(event); List<MotechEvent> expectedEvent = prepareExpectedEvent(users); verify(allUsers, times(1)).retrieveAll(); verify(eventRelay, times(2)).sendEventMessage(eventCaptor.capture()); verify(settingService, times(1)).isPasswordResetReminderEnabled(); verify(settingService, times(1)).getNumberOfDaysForReminder(); verify(settingService, times(1)).getNumberOfDaysToChangePassword(); assertEquals(expectedEvent, eventCaptor.getAllValues()); }

Target:
public void shouldSendEventIfTheUserShouldResetPassword() throws Exception { List<MotechUser> users = prepareMotechUsersOne(); when(settingService.isPasswordResetReminderEnabled()).thenReturn(true); when(allUsers.retrieveAll()).thenReturn(users); eventHandler.handleEvent(event); List<MotechEvent> expectedEvent = prepareExpectedEvent(users); verify(allUsers).retrieveAll(); verify(eventRelay, times(2)).sendEventMessage(eventCaptor.capture()); verify(settingService).isPasswordResetReminderEnabled(); verify(settingService).getNumberOfDaysForReminder(); verify(settingService).getNumberOfDaysToChangePassword(); assertEquals(expectedEvent, eventCaptor.getAllValues()); }
Source:
int commitAll() { if (rebalanceInProgress) { return -1; } else { final Map<TaskId, Map<TopicPartition, OffsetAndMetadata>> consumedOffsetsAndMetadataPerTask = new HashMap<>(); for (final Task task : tasks.values()) { if (task.commitNeeded()) { consumedOffsetsAndMetadataPerTask.put(task.id(), task.prepareCommit()); task.markCommitted(); } } commit(consumedOffsetsAndMetadataPerTask); return consumedOffsetsAndMetadataPerTask.size(); } }

Target:
int commitAll() { if (rebalanceInProgress) { return -1; } else { int committed = 0; final Map<TaskId, Map<TopicPartition, OffsetAndMetadata>> consumedOffsetsAndMetadataPerTask = new HashMap<>(); for (final Task task : tasks.values()) { if (task.commitNeeded()) { task.prepareCommit(); final Map<TopicPartition, OffsetAndMetadata> offsetAndMetadata = task.committableOffsetsAndMetadata(); if (!offsetAndMetadata.isEmpty()) { consumedOffsetsAndMetadataPerTask.put(task.id(), offsetAndMetadata); } } } commitOffsetsOrTransaction(consumedOffsetsAndMetadataPerTask); for (final Task task : tasks.values()) { if (task.commitNeeded()) { ++committed; task.postCommit(); } } return committed; } }
Source:
private byte[] generateBytes(Strategy strategy) { switch (strategy) { case SECURE_RANDOM: return generateRandomBytes(20, Holder.SECURE_RANDOM); case SHORT_SECURE_RANDOM: return generateRandomBytes(5, Holder.SECURE_RANDOM); case SHORT_RANDOM: return generateRandomBytes(5, ThreadLocalRandom.current()); case SEQUENTIAL_UUID: default: return Holder.UNIQUE_ID.getId(); } }

Target:
private byte[] generateBytes(Strategy strategy) { switch (strategy) { case SECURE_RANDOM: return generateRandomBytes(16, Holder.SECURE_RANDOM); case LONG_SECURE_RANDOM: return generateRandomBytes(20, Holder.SECURE_RANDOM); case SHORT_SECURE_RANDOM: return generateRandomBytes(5, Holder.SECURE_RANDOM); case SHORT_RANDOM: return generateRandomBytes(5, ThreadLocalRandom.current()); case SEQUENTIAL_UUID: default: return Holder.UNIQUE_ID.getId(); } }
Source:
public TokenCredential build() { if (environment == null) { throw new IllegalArgumentException("To build a spring credential the environment must be set"); } List<TokenCredential> tokenCredentials = new ArrayList<>(); if (alternativePrefix != null) { tokenCredentials.add(populateTokenCredential(alternativePrefix)); } tokenCredentials.add(populateDefaultTokenCredential()); return new ChainedTokenCredentialBuilder().addAll(tokenCredentials).build(); }

Target:
public TokenCredential build() { if (environment == null) { throw new IllegalArgumentException("To build a spring credential the environment must be set."); } List<TokenCredential> tokenCredentials = new ArrayList<>(); if (alternativePrefix != null) { addToChain(tokenCredentials, populateTokenCredentialBasedOnClientId(alternativePrefix)); } addToChain(tokenCredentials, populateTokenCredentialBasedOnClientId(AZURE_CREDENTIAL_PREFIX)); addToChain(tokenCredentials, defaultManagedIdentityCredential()); return new ChainedTokenCredentialBuilder().addAll(tokenCredentials).build(); }
Source:
private synchronized void updatePostWithMediaUrl(MediaModel media){ if (media != null) { PostModel post = mPostStore.getPostByLocalPostId(media.getPostId()); if (post != null) { String content = post.getContent(); if (content != null) { MediaUploadReadyProcessor processor = new MediaUploadReadyProcessor(); PostModel modifiedPost = processor.replaceMediaFileWithUrlInPost(post, String.valueOf(media.getId()), FluxCUtils.mediaFileFromMediaModel(media)); if (modifiedPost != null) { post = modifiedPost; } if (!post.isLocalDraft()) { post.setIsLocallyChanged(true); } post.setDateLocallyChanged(DateTimeUtils.iso8601FromTimestamp(System.currentTimeMillis() / 1000)); savePostToDb(post); } } } }

Target:
private synchronized void updatePostWithMediaUrl(MediaModel media){ if (media != null) { PostModel post = mPostStore.getPostByLocalPostId(media.getPostId()); if (post != null) { MediaUploadReadyListener processor = new MediaUploadReadyProcessor(); PostModel modifiedPost = processor.replaceMediaFileWithUrlInPost(post, String.valueOf(media.getId()), FluxCUtils.mediaFileFromMediaModel(media)); if (modifiedPost != null) { post = modifiedPost; } if (!post.isLocalDraft()) { post.setIsLocallyChanged(true); } post.setDateLocallyChanged(DateTimeUtils.iso8601FromTimestamp(System.currentTimeMillis() / 1000)); savePostToDb(post); } } }
Source:
public void test() throws Exception { final Random rnd = new Random(0); final int iterations = 20; for(int i = 0; i < iterations; i++) { Collections.shuffle(inputRanges, rnd); doTest(inputRanges); } }

Target:
public void test() throws Exception { Collections.shuffle(inputRanges, RandomUtils.instance()); doTest(inputRanges); }
Source:
protected void executeCommand() { getParameters().setEntityInfo(getEntityInfo()); setSucceeded(true); if (images != null && !images.isEmpty()) { List<DiskImage> imageToRemove = new ArrayList<>(); for (DiskImage image : images) { if (image.getStorageIds().get(0).equals(getParameters().getStorageDomainId())) { image.setStorageIds(Collections.singletonList(getParameters().getStorageDomainId())); image.setStoragePoolId(getParameters().getStoragePoolId()); imageToRemove.add(image); } } RemoveAllVmImagesParameters removeAllVmImagesParameters = new RemoveAllVmImagesParameters(getVmId(), imageToRemove); removeAllVmImagesParameters.setParentCommand(getActionType()); removeAllVmImagesParameters.setEntityInfo(getParameters().getEntityInfo()); removeAllVmImagesParameters.setForceDelete(true); removeAllVmImagesParameters.setParentParameters(getParameters()); ActionReturnValue vdcRetValue = runInternalActionWithTasksContext(ActionType.RemoveAllVmImages, removeAllVmImagesParameters); if (vdcRetValue.getSucceeded()) { getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } else { getReturnValue().setFault(vdcRetValue.getFault()); setSucceeded(false); } } vmAndTemplatesGenerationsDao.deleteOvfGenerations(Collections.singletonList(ovfEntityData.getEntityId())); unregisteredOVFDataDao.removeEntity(ovfEntityData.getEntityId(), null); unregisteredDisksDao.removeUnregisteredDiskRelatedToVM(ovfEntityData.getEntityId(), null); }

Target:
protected void executeCommand() { getParameters().setEntityInfo(getEntityInfo()); setSucceeded(true); if (images != null && !images.isEmpty()) { List<DiskImage> imageToRemove = new ArrayList<>(); for (DiskImage image : images) { if (image.getStorageIds().get(0).equals(getParameters().getStorageDomainId())) { image.setStorageIds(Collections.singletonList(getParameters().getStorageDomainId())); image.setStoragePoolId(getParameters().getStoragePoolId()); imageToRemove.add(image); } } RemoveAllVmImagesParameters removeAllVmImagesParameters = new RemoveAllVmImagesParameters(ovfEntityData.getEntityId(), imageToRemove); removeAllVmImagesParameters.setParentCommand(getActionType()); removeAllVmImagesParameters.setEntityInfo(getParameters().getEntityInfo()); removeAllVmImagesParameters.setForceDelete(true); removeAllVmImagesParameters.setParentParameters(getParameters()); ActionReturnValue vdcRetValue = runInternalActionWithTasksContext(ActionType.RemoveAllVmImages, removeAllVmImagesParameters); if (vdcRetValue.getSucceeded()) { getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } else { getReturnValue().setFault(vdcRetValue.getFault()); setSucceeded(false); } } vmAndTemplatesGenerationsDao.deleteOvfGenerations(Collections.singletonList(ovfEntityData.getEntityId())); unregisteredOVFDataDao.removeEntity(ovfEntityData.getEntityId(), null); unregisteredDisksDao.removeUnregisteredDiskRelatedToVM(ovfEntityData.getEntityId(), null); }
Source:
public void applyConstraint(Layer layer, int iteration, int epoch) { Map<String,INDArray> paramTable = layer.paramTable(); if(paramTable == null || paramTable.isEmpty() ){ return; } ParamInitializer i = layer.conf().getLayer().initializer(); for(Map.Entry<String,INDArray> e : paramTable.entrySet()){ if(applyToWeights && i.isWeightParam(e.getKey()) || applyToBiases && i.isBiasParam(e.getKey())){ apply(e.getValue(), i.isBiasParam(e.getKey())); } } }

Target:
public void applyConstraint(Layer layer, int iteration, int epoch) { Map<String,INDArray> paramTable = layer.paramTable(); if(paramTable == null || paramTable.isEmpty() ){ return; } ParamInitializer i = layer.conf().getLayer().initializer(); for(Map.Entry<String,INDArray> e : paramTable.entrySet()){ if(applyToWeights && i.isWeightParam(e.getKey()) || applyToBiases && i.isBiasParam(e.getKey())){ apply(e.getValue()); } } }
Source:
private void sendMessage(ConsumerRecord<?, ?> record, long readTime, String strReadTime) throws InterruptedException { int count = 0; while (true) { count++; try { _lastEventReceivedTime = Instant.now(); _eventsProcessedRate.mark(); AGGREGATED_EVENTS_PROCESSED_RATE.mark(); int numBytes = record.serializedKeySize() + record.serializedValueSize(); _bytesProcessedRate.mark(numBytes); AGGREGATED_BYTES_PROCESSED_RATE.mark(numBytes); _producer.send(translate(record, readTime, strReadTime), null); return; } catch (RuntimeException e) { LOG.error("Error sending Message. task: ; error: {};", _taskName, e.toString()); LOG.error("Stack Trace: {}", Arrays.toString(e.getStackTrace())); if (_shouldDie || count >= RETRY_COUNT) { throw e; } LOG.warn("Sleeping for seconds before retrying.", _retrySleepDuration.getSeconds(), e); Thread.sleep(_retrySleepDuration.toMillis()); } } }

Target:
private void sendMessage(ConsumerRecord<?, ?> record, long readTime, String strReadTime) throws InterruptedException { int count = 0; while (true) { count++; try { _lastEventReceivedTime = Instant.now(); _eventsProcessedRate.mark(); AGGREGATED_EVENTS_PROCESSED_RATE.mark(); int numBytes = record.serializedKeySize() + record.serializedValueSize(); _bytesProcessedRate.mark(numBytes); AGGREGATED_BYTES_PROCESSED_RATE.mark(numBytes); _producer.send(translate(record, readTime, strReadTime), null); return; } catch (RuntimeException e) { LOG.error("Error sending Message. task: ; error: {};", _taskName, e.toString()); LOG.error("Stack Trace: {}", Arrays.toString(e.getStackTrace())); if (_shouldDie || count >= _retryCount) { LOG.info("Send messages failed with exception: {}", e); throw e; } LOG.warn("Sleeping for seconds before retrying. Retry of {}", _retrySleepDuration.getSeconds(), count, _retryCount); Thread.sleep(_retrySleepDuration.toMillis()); } } }
Source:
int getMaxCountPerBucket(long now) { if (now - _lastAccessTimestamp > _maxTimeRangeMs) { _lastAccessTimestamp = now - _defaultTimeRangeMs; } long startTimeUnits = _lastAccessTimestamp / _timeBucketWidthMs; int startIndex = (int) (startTimeUnits % _bucketCount); long numTimeUnits = now / _timeBucketWidthMs; int endIndex = (int) (numTimeUnits % _bucketCount); int maxCount = 0; for (int i = startIndex; i != endIndex; i = (++i % _bucketCount)) { if (numTimeUnits - _bucketStartTime.get(i) < _bucketCount) { maxCount = Math.max(_bucketHitCount.get(i), maxCount); } } _lastAccessTimestamp = now; return maxCount; }

Target:
int getMaxCountPerBucket(long now) { long then = _lastAccessTimestamp; if (now - then > _maxTimeRangeMs) { then = now - _defaultTimeRangeMs; } long startTimeUnits = then / _timeBucketWidthMs; int startIndex = (int) (startTimeUnits % _bucketCount); long numTimeUnits = now / _timeBucketWidthMs; int endIndex = (int) (numTimeUnits % _bucketCount); int maxCount = 0; for (int i = startIndex; i != endIndex; i = (++i % _bucketCount)) { if (numTimeUnits - _bucketStartTime.get(i) < _bucketCount) { maxCount = Math.max(_bucketHitCount.get(i), maxCount); } } _lastAccessTimestamp = now; return maxCount; }