auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ReturnState addPartitions(RpcController controller, AddPartitionsProto request) throws ServiceException { TableIdentifierProto identifier = request.getTableIdentifier(); String databaseName = identifier.getDatabaseName(); String tableName = identifier.getTableName(); if (metaDictionary.isSystemDatabase(databaseName)) { throw new ServiceException(databaseName + " is a system database. It does not contain any partitioned tables."); } rlock.lock(); try { boolean contain; contain = store.existDatabase(databaseName); if (contain) { contain = store.existTable(databaseName, tableName); if (contain) { if (store.existPartitionMethod(databaseName, tableName)) { store.addPartitions(databaseName, tableName, request.getPartitionDescList(), request.getIfNotExists()); return OK; } else { return errUndefinedPartitionMethod(tableName); } } else { return errUndefinedTable(tableName); } } else { return errUndefinedDatabase(databaseName); } } catch (Throwable t) { printStackTraceIfError(LOG, t); return returnError(t); } finally { rlock.unlock(); } }

Target:
public ReturnState addPartitions(RpcController controller, AddPartitionsProto request) { TableIdentifierProto identifier = request.getTableIdentifier(); String databaseName = identifier.getDatabaseName(); String tableName = identifier.getTableName(); rlock.lock(); try { boolean contain; contain = store.existDatabase(databaseName); if (contain) { contain = store.existTable(databaseName, tableName); if (contain) { if (store.existPartitionMethod(databaseName, tableName)) { store.addPartitions(databaseName, tableName, request.getPartitionDescList(), request.getIfNotExists()); return OK; } else { return errUndefinedPartitionMethod(tableName); } } else { return errUndefinedTable(tableName); } } else { return errUndefinedDatabase(databaseName); } } catch (Throwable t) { printStackTraceIfError(LOG, t); return returnError(t); } finally { rlock.unlock(); } }
Source:
public String getText() { if (linesOfText.length > 0) { String arrayText = String.join("\n", linesOfText); if (text.get().equals("")) { return text.get() + "\n" + arrayText; } return text.get() + arrayText; } else { return text.get(); } }

Target:
public String getText() { return String.join("\n", ObjectArrays.concat(text.get(), linesOfText)); }
Source:
public final void setProducer(Producer producer) { producer = onSetProducer(producer); int toRequest = requested; boolean setProducer = false; synchronized (this) { p = producer; if (op != null) { if (toRequest < 0) { setProducer = true; } } } if (setProducer) { op.setProducer(p); } else { p.request(toRequest); } }

Target:
public final void setProducer(Producer producer) { producer = onSetProducer(producer); int toRequest = requested; boolean setProducer = false; synchronized (this) { p = producer; if (op != null) { if (toRequest == Integer.MIN_VALUE) { setProducer = true; } } } if (setProducer) { op.setProducer(p); } else { if (toRequest == Integer.MIN_VALUE) { p.request(-1); } else { p.request(toRequest); } } }
Source:
private void mockJerseyClient() { MetricRegistry metricRegistry = mock(MetricRegistry.class); when(environment.metrics()).thenReturn(metricRegistry); when(clientFactory.createWithDropwizardClient(any(PaymentGatewayName.class), any(MetricRegistry.class))) .thenReturn(client); WebTarget webTarget = mock(WebTarget.class); when(client.target(any(String.class))).thenReturn(webTarget); when(webTarget.request()).thenReturn(invocationBuilder); when(invocationBuilder.post(any(Entity.class))).thenReturn(response); }

Target:
private void mockJerseyClient() { MetricRegistry metricRegistry = mock(MetricRegistry.class); when(environment.metrics()).thenReturn(metricRegistry); when(clientFactory.createWithDropwizardClient(any(PaymentGatewayName.class), any(MetricRegistry.class))) .thenReturn(client); when(webTarget.request()).thenReturn(invocationBuilder); }
Source:
private void hideKeyboard() { View view = this.getCurrentFocus(); if (view != null) { InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } }

Target:
private void hideKeyboard() { View view = getCurrentFocus(); if (view != null) { InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } }
Source:
public void start() throws Exception { Preconditions.checkNotNull(config); Preconditions.checkArgument( config.getScheme().startsWith("http") ); LOGGER.info("Neo4jConfiguration.start {}", config); Preconditions.checkNotNull(client); }

Target:
public void start() throws Exception { Objects.nonNull(config); assertThat("config.getScheme().startsWith(\"http\")", config.getScheme().startsWith("http")); LOGGER.info("Neo4jConfiguration.start {}", config); Objects.nonNull(client); }
Source:
private void store(BinlogPosition newPosition) { if ( newPosition == null ) return; String sql = "INSERT INTO `" + this.schemaDatabaseName + "`.`positions` set " + "server_id = ?, " + "binlog_file = ?, " + "binlog_position = ? " + "ON DUPLICATE KEY UPDATE binlog_file=?, binlog_position=?"; try(Connection c = connectionPool.getConnection() ){ PreparedStatement s = c.prepareStatement(sql); LOGGER.debug("Writing binlog position to " + this.schemaDatabaseName + ".positions: " + newPosition); s.setLong(1, serverID); s.setString(2, newPosition.getFile()); s.setLong(3, newPosition.getOffset()); s.setString(4, newPosition.getFile()); s.setLong(5, newPosition.getOffset()); s.execute(); storedPosition.set(newPosition); } catch ( SQLException e ) { LOGGER.error("received SQLException while trying to save to " + this.schemaDatabaseName + ".positions: "); LOGGER.error(e.getLocalizedMessage()); this.requestStop(); this.exception = e; } }

Target:
private void store(BinlogPosition newPosition) { if ( newPosition == null ) return; String sql = "INSERT INTO `positions` set " + "server_id = ?, " + "binlog_file = ?, " + "binlog_position = ? " + "ON DUPLICATE KEY UPDATE binlog_file=?, binlog_position=?"; try(Connection c = getConnection() ){ PreparedStatement s = c.prepareStatement(sql); LOGGER.debug("Writing binlog position to " + this.schemaDatabaseName + ".positions: " + newPosition); s.setLong(1, serverID); s.setString(2, newPosition.getFile()); s.setLong(3, newPosition.getOffset()); s.setString(4, newPosition.getFile()); s.setLong(5, newPosition.getOffset()); s.execute(); storedPosition.set(newPosition); } catch ( SQLException e ) { LOGGER.error("received SQLException while trying to save to " + this.schemaDatabaseName + ".positions: "); LOGGER.error(e.getLocalizedMessage()); this.requestStop(); this.exception = e; } }
Source:
private static boolean updateDiskProfileForBackwardCompatibility(DiskImage diskImage, List<DiskProfile> diskProfilesList, Set<Guid> permittedDiskProfilesIds, DbUser user) { if (diskProfilesList.isEmpty()) { return false; } for (DiskProfile diskProfile : diskProfilesList) { if (diskProfilePermitted(diskProfile, permittedDiskProfilesIds, user)) { permittedDiskProfilesIds.add(diskProfile.getId()); diskImage.setDiskProfileId(diskProfile.getId()); return true; } } return false; }

Target:
private static boolean updateDiskProfileForBackwardCompatibility(DiskImage diskImage, List<DiskProfile> diskProfilesList, Set<Guid> permittedDiskProfilesIds, DbUser user) { for (DiskProfile diskProfile : diskProfilesList) { if (isDiskProfilePermitted(diskProfile, permittedDiskProfilesIds, user)) { permittedDiskProfilesIds.add(diskProfile.getId()); diskImage.setDiskProfileId(diskProfile.getId()); return true; } } return false; }
Source:
public ValueMatcher makeMatcher(ColumnSelectorFactory columnSelectorFactory) { final DimensionSelector dimensionSelector = columnSelectorFactory.makeDimensionSelector(dimension, null); if (dimensionSelector == null) { return new BooleanValueMatcher(Strings.isNullOrEmpty(fn.apply(value))); } else { return new ValueMatcher() { @Override public boolean matches() { final IndexedInts row = dimensionSelector.getRow(); final int size = row.size(); for (int i = 0; i < size; ++i) { if (value.equals(fn.apply(dimensionSelector.lookupName(row.get(i))))) { return true; } } return false; } }; } }

Target:
public ValueMatcher makeMatcher(ColumnSelectorFactory columnSelectorFactory) { final DimensionSelector dimensionSelector = columnSelectorFactory.makeDimensionSelector(dimension, null); if (dimensionSelector == null) { return new BooleanValueMatcher(value.equals(Strings.nullToEmpty(fn.apply(null)))); } else { final BitSet bitSetOfIds = new BitSet(dimensionSelector.getValueCardinality()); for (int i = 0; i < dimensionSelector.getValueCardinality(); i++) { if (value.equals(Strings.nullToEmpty(fn.apply(dimensionSelector.lookupName(i))))) { bitSetOfIds.set(i); } } return new ValueMatcher() { @Override public boolean matches() { final IndexedInts row = dimensionSelector.getRow(); final int size = row.size(); for (int i = 0; i < size; ++i) { if (bitSetOfIds.get(row.get(i))) { return true; } } return false; } }; } }
Source:
void setDefaults(final Context context, final String clientId) { sClientId = clientId; sApplicationName = context.getPackageName(); try { sApplicationVersion = context.getPackageManager().getPackageInfo(sApplicationName, 0).versionName; } catch (PackageManager.NameNotFoundException nnfe) { sApplicationVersion = "0.0.0.0"; } sClientIp = "0.0.0.0"; }

Target:
void setDefaults(final Context context, final String clientId) { sClientId = clientId; sApplicationName = context.getPackageName(); try { sApplicationVersion = context.getPackageManager().getPackageInfo(sApplicationName, 0).versionName; } catch (PackageManager.NameNotFoundException nnfe) { sApplicationVersion = "NA"; } sClientIp = "NA"; try { sDeviceId = StringExtensions.createHash(Secure.getString(context.getContentResolver(), Secure.ANDROID_ID)); } catch (UnsupportedEncodingException | NoSuchAlgorithmException e) { sDeviceId = ""; } if (mDefaultEventCount == 0) { setEvent(EventStrings.APPLICATION_NAME, sApplicationName); setEvent(EventStrings.APPLICATION_VERSION, sApplicationVersion); setEvent(EventStrings.CLIENT_ID, sClientId); setEvent(EventStrings.CLIENT_IP, sClientIp); setEvent(EventStrings.DEVICE_ID, sDeviceId); mDefaultEventCount = mEventList.size(); } }
Source:
public void testOptionalNull() { OptionalModel expected = new OptionalModel(); expected.field = null; OptionalModel result = unmarshal(OptionalModel.class, marshal(expected)); assertThat(result, is(expected)); }

Target:
public void testOptionalNull() { OptionalModel expected = new OptionalModel(); OptionalModel result = unmarshal(gson, OptionalModel.class, marshal(gson, expected)); assertThat(result, is(expected)); }
Source:
public void generate(Cube cube, GeneratorStage targetStage) { GeneratorStage stage = cube.getCurrentStage(); if (cube.getTargetStage().precedes(targetStage)) { cube.setTargetStage(targetStage); } if (cube.getCurrentStage().precedes(cube.getTargetStage())) { if (stage instanceof DependencyProvider) { Dependency dependency = ((DependencyProvider) stage).getDependency(cube); if (dependency != null) { Dependent dependent = new Dependent(cube, dependency); this.dependencyManager.register(dependent); if (dependent.isSatisfied()) { stage.getProcessor().processor.add(cube.getAddress()); } } } else { stage.getProcessor().processor.add(cube.getAddress()); } } }

Target:
public void generate(Cube cube, GeneratorStage targetStage) { GeneratorStage stage = cube.getCurrentStage(); if (cube.getTargetStage().precedes(targetStage)) { cube.setTargetStage(targetStage); } if (cube.getCurrentStage().precedes(cube.getTargetStage())) { Dependency dependency = stage.getDependency(cube); if (dependency != null) { Dependent dependent = new Dependent(cube, dependency); this.dependencyManager.register(dependent); if (dependent.isSatisfied()) { stage.getProcessor().processor.add(cube.getAddress()); } } else { stage.getProcessor().processor.add(cube.getAddress()); } } }
Source:
public void shouldFitTheSampleSequentialModel() throws Exception { File model = prepareResource("theano_mnist/model.h5"); File features = prepareResource("theano_mnist/x_train.h5"); File labels = prepareResource("theano_mnist/y_train.h5"); EntryPointFitParameters entryPointParameters = EntryPointFitParameters .builder() .modelFilePath(model.getAbsolutePath()) .trainFeaturesFile(features.getAbsolutePath()) .trainLabelsFile(labels.getAbsolutePath()) .batchSize(128) .nbEpoch(2) .type("sequential") .build(); deepLearning4jEntryPoint.fit(entryPointParameters); }

Target:
public void shouldFitTheSampleSequentialModel() throws Exception { final File model = prepareResource("theano_mnist/model.h5"); final Path features = prepareFeatures("theano_mnist"); final Path labels = prepareLabels("theano_mnist"); EntryPointFitParameters entryPointParameters = EntryPointFitParameters .builder() .modelFilePath(model.getAbsolutePath()) .trainFeaturesDirectory(features.toAbsolutePath().toString()) .trainLabelsDirectory(labels.toAbsolutePath().toString()) .batchSize(128) .nbEpoch(2) .type(KerasModelType.SEQUENTIAL) .build(); deepLearning4jEntryPoint.fit(entryPointParameters); }
Source:
protected String[] finalizeScript(ArrayList<String> cmdList) { String[] script; script = new String[cmdList.size() + 4]; script[0] = "stap"; if(getRunLocal() == false) script[script.length-1] = tmpfileName; else script[script.length-1] = fileName; for(int i=0; i< cmdList.size(); i++) { script[i+1] = cmdList.get(i).toString(); } script[script.length-3]="-m"; String modname; if(getRunLocal() == false) { modname = serverfileName.substring(0, serverfileName.indexOf('.')); } else { modname = fileName.substring(fileName.lastIndexOf('/')+1); Pattern validModName = Pattern.compile("^[a-z0-9_]+(.stp)$"); Matcher modNameMatch = validModName.matcher(modname); if(!modNameMatch.find()){ continueRun = false; Shell parent = PlatformUI.getWorkbench().getDisplay().getActiveShell(); MessageDialog.openError(parent, Messages.ScriptRunAction_InvalidScriptTitle, Messages.ScriptRunAction_InvalidScriptTMessage); return new String[0]; } modname = modname.substring(0, modname.indexOf('.')); } if (modname.indexOf('-') != -1) modname = modname.substring(0, modname.indexOf('-')); script[script.length-2]=modname; return script; }

Target:
protected String[] finalizeScript(ArrayList<String> cmdList) { String[] script; script = new String[cmdList.size() + 4]; script[0] = "stap"; if(getRunLocal() == false) script[script.length-1] = tmpfileName; else script[script.length-1] = fileName; for(int i=0; i< cmdList.size(); i++) { script[i+1] = cmdList.get(i).toString(); } script[script.length-3]="-m"; String modname; if(getRunLocal() == false) { modname = serverfileName.substring(0, serverfileName.lastIndexOf(".stp")); } else { modname = fileName.substring(fileName.lastIndexOf('/')+1); modname = modname.substring(0, modname.lastIndexOf(".stp")); } Pattern validModName = Pattern.compile("^[a-z0-9_]+$"); Matcher modNameMatch = validModName.matcher(modname); if (!modNameMatch.matches()) { continueRun = false; Shell parent = PlatformUI.getWorkbench().getDisplay() .getActiveShell(); MessageDialog.openError(parent, Messages.ScriptRunAction_InvalidScriptTitle, Messages.ScriptRunAction_InvalidScriptTMessage); return new String[0]; } script[script.length-2]=modname; return script; }
Source:
private String getUnEncryptedValue(String value) { String[] envRefs = StringUtils.substringsBetween(value, "[", "]"); if (envRefs != null && envRefs.length == 1) { return envRefs[0]; } else { return null; } }

Target:
private String getUnEncryptedValue(String value) { String[] unEncryptedRefs = StringUtils.substringsBetween(value, ConfigConstants.SECTION_PREFIX, ConfigConstants.SECTION_SUFFIX); if (unEncryptedRefs != null && unEncryptedRefs.length == 1) { return unEncryptedRefs[0]; } else { return null; } }
Source:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append(uuid.toString()); sb.append("|"); sb.append(sessionId); sb.append('|'); sb.append(who); sb.append('|'); sb.append(when); sb.append('|'); sb.append(what); sb.append('|'); sb.append(elapsed); sb.append('|'); if (params != null) { sb.append('['); for (int i = 0; i < params.size(); i++) { if (i > 0) sb.append(','); if(params != null) { Set<String> paramNames = params.keySet(); for (String paramName : paramNames) { sb.append("name="); sb.append(paramName); int numValues = 0; Collection<?> paramValues = params.get(paramName); for (Object paramValue : paramValues) { sb.append(Objects.firstNonNull(paramValue, "null")); if(numValues++ > 0) { sb.append(","); } } } } } sb.append(']'); } sb.append('|'); if (result != null) { sb.append(result); } return sb.toString(); }

Target:
public String toString() { return String.format("AuditEvent UUID:%s, SID:%s, TS:%d, who:%s, what:%s", uuid.get(), sessionId, when, who, what); }
Source:
public void createControl(Composite parent) { super.createControl(parent); TreeViewer viewer= getTreeViewer(); viewer.setContentProvider(new SpecfileContentProvider(editor)); IProject project = null; if (input instanceof IFileEditorInput) { IFileEditorInput fileEditorInput= (IFileEditorInput) input; project = fileEditorInput.getFile().getProject(); } if (project!=null) { SpecfileLabelProvider labelProvider = new SpecfileLabelProvider(); labelProvider.setProject(project); viewer.setLabelProvider(labelProvider); } else { viewer.setLabelProvider(new SpecfileLabelProvider()); } viewer.addSelectionChangedListener(this); if (input != null) { viewer.setInput(input); } }

Target:
public void createControl(Composite parent) { super.createControl(parent); TreeViewer viewer= getTreeViewer(); viewer.setContentProvider(new SpecfileContentProvider(editor)); IProject project = null; if (input instanceof IFileEditorInput) { IFileEditorInput fileEditorInput= (IFileEditorInput) input; project = fileEditorInput.getFile().getProject(); } SpecfileLabelProvider labelProvider = new SpecfileLabelProvider(); if (project!=null) { labelProvider.setProject(project); } viewer.setLabelProvider(labelProvider); viewer.addSelectionChangedListener(this); if (input != null) { viewer.setInput(input); } }
Source:
public void test() throws Exception { assertThat(g.rule(Tree.Kind.FLOW_FUNCTION_TYPE)) .matches("(str: string) => void") .matches("(str: string, number) => void") .matches("() => void") .matches("(string, string,) => void") .matches("(name: string, ...numbers:SomeArrayType) => void") .matches("(name: string, middle?: string) => void") .matches("(string, SomeArrayType) => SomeType") .matches("(await: number) => void") .matches("string => number") .matches("number | string => number") ; }

Target:
public void test() throws Exception { assertThat(g.rule(Tree.Kind.FLOW_FUNCTION_TYPE)) .matches("(str: string) => void") .matches("(str: string, number) => void") .matches("() => void") .matches("(string, string,) => void") .matches("(name: string, ...numbers:SomeArrayType) => void") .matches("(name: string, middle?: string) => void") .matches("(string, SomeArrayType) => SomeType") .matches("(await: number) => void") .matches("string => number") ; }
Source:
public void sendText(String text) { if (channel == null) { logger.error("Channel is null. Cannot send text."); throw new NullPointerException("Cannot find the channel to write"); } channel.writeAndFlush(new TextWebSocketFrame(text)); }

Target:
public void sendText(String text) { if (channel == null) { logger.error("Channel is null. Cannot send text."); throw new IllegalArgumentException("Cannot find the channel to write"); } channel.writeAndFlush(new TextWebSocketFrame(text)); }
Source:
private static ImmutableList<Worker> getWorkerFromZK(Collection<ZkWorker> workers) { return ImmutableList.copyOf( Collections2.transform( workers, new Function<ZkWorker, Worker>() { @Override public Worker apply(ZkWorker input) { return input.getWorker(); } } ) ); }

Target:
private static ImmutableList<Worker> getWorkerFromZK(Collection<ZkWorker> workers) { return ImmutableList.copyOf(Collections2.transform(workers, ZkWorker::getWorker)); }
Source:
private Object handleTxCommand(TxInvocationContext ctx, TransactionBoundaryCommand command) throws Throwable { Address origin = ctx.isOriginLocal() ? ctx.getOrigin() : ctx.getGlobalTransaction().getAddress(); if (trace) log.tracef("handleTxCommand for command %s, origin %s", command, origin); if (isLocalOnly(command)) { return invokeNextInterceptor(ctx, command); } updateTopologyId(command); int retryTopologyId = -1; Object localResult = null; try { localResult = invokeNextInterceptor(ctx, command); } catch (OutdatedTopologyException e) { retryTopologyId = Math.max(currentTopologyId(), command.getTopologyId() + 1); } boolean async = isTxCommandAsync(command); if (async) { stateTransferManager.forwardCommandIfNeeded(command, getAffectedKeys(ctx, command), origin); return null; } if (ctx.isOriginLocal()) { if (retryTopologyId > 0) { command.setTopologyId(retryTopologyId); waitForTransactionData(retryTopologyId); log.tracef("Retrying command %s for topology %d", command, retryTopologyId); localResult = handleTxCommand(ctx, command); } } else { if (currentTopologyId() > command.getTopologyId()) { if (rollbackOnOldTopologyId((RemoteTxInvocationContext) ctx, command)) { RollbackCommand rollbackCommand = commandsFactory.buildRollbackCommand(command.getGlobalTransaction()); try { invokeNextInterceptor(ctx, rollbackCommand); } catch (Exception e) { } } localResult = UnsureResponse.INSTANCE; } } return localResult; }

Target:
private Object handleTxCommand(TxInvocationContext ctx, TransactionBoundaryCommand command) throws Throwable { Address origin = ctx.isOriginLocal() ? ctx.getOrigin() : ctx.getGlobalTransaction().getAddress(); if (trace) log.tracef("handleTxCommand for command %s, origin %s", command, origin); if (isLocalOnly(command)) { return invokeNextInterceptor(ctx, command); } updateTopologyId(command); int retryTopologyId = -1; Object localResult = null; try { localResult = invokeNextInterceptor(ctx, command); } catch (OutdatedTopologyException e) { retryTopologyId = Math.max(currentTopologyId(), command.getTopologyId() + 1); } boolean async = isTxCommandAsync(command); if (async) { stateTransferManager.forwardCommandIfNeeded(command, getAffectedKeys(ctx, command), origin); return null; } if (ctx.isOriginLocal()) { if (retryTopologyId > 0) { command.setTopologyId(retryTopologyId); waitForTransactionData(retryTopologyId); log.tracef("Retrying command %s for topology %d", command, retryTopologyId); localResult = handleTxCommand(ctx, command); } } else { if (currentTopologyId() > command.getTopologyId()) { localResult = UnsureResponse.INSTANCE; } } return localResult; }
Source:
public static int[] getWeekendDays(Locale locale) { if (thuFryWeekendDaysCountries.contains(locale.getCountry())) { return new int[]{Calendar.THURSDAY, Calendar.FRIDAY}; } else if (frySunWeekendDaysCountries.contains(locale.getCountry())) { return new int[]{Calendar.FRIDAY, Calendar.SUNDAY}; } else if (fryWeekendDaysCountries.contains(locale.getCountry())) { return new int[]{Calendar.FRIDAY}; } else if (sunWeekendDaysCountries.contains(locale.getCountry())) { return new int[]{Calendar.SUNDAY}; } else if (frySatWeekendDaysCountries.contains(locale.getCountry())) { return new int[]{Calendar.FRIDAY, Calendar.SATURDAY}; } else { return new int[]{Calendar.SATURDAY, Calendar.SUNDAY}; } }

Target:
public static int[] getWeekendDays(Locale locale) { if (THU_FRY_WEEKEND_DAYS_COUNTRIES.contains(locale.getCountry())) { return new int[]{Calendar.THURSDAY, Calendar.FRIDAY}; } else if (FRY_SUN_WEEKEND_DAYS_COUNTRIES.contains(locale.getCountry())) { return new int[]{Calendar.FRIDAY, Calendar.SUNDAY}; } else if (FRY_WEEKEND_DAYS_COUNTRIES.contains(locale.getCountry())) { return new int[]{Calendar.FRIDAY}; } else if (SUN_WEEKEND_DAYS_COUNTRIES.contains(locale.getCountry())) { return new int[]{Calendar.SUNDAY}; } else if (FRY_SAT_WEEKEND_DAYS_COUNTRIES.contains(locale.getCountry())) { return new int[]{Calendar.FRIDAY, Calendar.SATURDAY}; } else { return new int[]{Calendar.SATURDAY, Calendar.SUNDAY}; } }
Source:
public List<Versioned<byte[]>> get(ByteArray key, byte[] transforms) throws PersistenceFailureException { StoreUtils.assertValidKey(key); long startTimeNs = -1; if(logger.isTraceEnabled()) startTimeNs = System.nanoTime(); List<Versioned<byte[]>> value = null; try { byte[] result = getRocksDB().get(key.get()); if(result != null) { value = StoreBinaryFormat.fromByteArray(result); } else { return Collections.emptyList(); } } catch(RocksDBException e) { logger.error(e); throw new PersistenceFailureException(e); } finally { if(logger.isTraceEnabled()) { logger.trace("Completed GET (" + getName() + ") from key " + key + " (keyRef: " + System.identityHashCode(key) + ") in " + (System.nanoTime() - startTimeNs) + " ns at " + System.currentTimeMillis()); } } return value; }

Target:
public List<Versioned<byte[]>> get(ByteArray key, byte[] transforms) throws PersistenceFailureException { StoreUtils.assertValidKey(key); if(enableReadLocks) { synchronized(this.locks.lockFor(key.get())) { return getValueForKey(key, transforms); } } else { return getValueForKey(key, transforms); } }
Source:
protected String getMemento(CTabFolder activeFolder) throws CoreException { Document document = DebugPlugin.newDocument(); Element memoryTabsList = document.createElement(MEMORY_TABS_LIST); int tabCount = 0; for (CTabItem tab : activeFolder.getItems()) { if (getMemoryBlocks(tab).isEmpty()) { continue; } Element memoryTab = document.createElement(MEMORY_TAB); String memorySpace = (String) tab.getData(KEY_MEMORY_SPACE); memoryTab.setAttribute(ATTR_MEMORY_SPACE, memorySpace); IMemoryRenderingType type = (IMemoryRenderingType) tab.getData(KEY_RENDERING_TYPE); memoryTab.setAttribute(ATTR_RENDERING, type.getId()); BigInteger evaluatedAddress = (BigInteger)tab.getData(KEY_EXPRESSION_ADDRESS); memoryTab.setAttribute(ATTR_ADDRESS, HEX_PREFIX + evaluatedAddress.toString(HEX_RADIX)); memoryTabsList.appendChild(memoryTab); tabCount++; } if (tabCount == 0) { return null; } else { document.appendChild(memoryTabsList); return DebugPlugin.serializeDocument(document); } }

Target:
protected String getMemento(CTabFolder activeFolder) throws CoreException { Document document = DebugPlugin.newDocument(); Element memoryTabsList = document.createElement(MEMORY_TABS_LIST); int tabCount = 0; for (CTabItem tab : activeFolder.getItems()) { if (getMemoryBlocks(tab).isEmpty()) { continue; } Element memoryTab = document.createElement(MEMORY_TAB); String memorySpace = (String) tab.getData(KEY_MEMORY_SPACE); memoryTab.setAttribute(ATTR_MEMORY_SPACE, memorySpace); IMemoryRenderingType type = (IMemoryRenderingType) tab.getData(KEY_RENDERING_TYPE); memoryTab.setAttribute(ATTR_RENDERING, type.getId()); String expression = (String) tab.getData(KEY_EXPRESSION); if (expression != null) { memoryTab.setAttribute(ATTR_ADDRESS, expression); } else { BigInteger evaluatedAddress = (BigInteger) tab.getData(KEY_EXPRESSION_ADDRESS); memoryTab.setAttribute(ATTR_ADDRESS, HEX_PREFIX + evaluatedAddress.toString(HEX_RADIX)); } memoryTabsList.appendChild(memoryTab); tabCount++; } if (tabCount == 0) { return null; } else { document.appendChild(memoryTabsList); return DebugPlugin.serializeDocument(document); } }
Source:
private void composedBlobIdAndDeserialize(short version) throws Exception { String srcUUID = UUID.randomUUID().toString(); String srcBlobIdStr; switch (version) { case BLOB_ID_V1: srcBlobIdStr = buildBlobIdLike(version, null, null, null, null, referencePartitionId, srcUUID.length(), srcUUID); break; case BLOB_ID_V2: srcBlobIdStr = buildBlobIdLike(version, referenceFlag, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId, srcUUID.length(), srcUUID); break; default: throw new IllegalArgumentException("Invalid version number blob" + version); } deserializeBlobIdAndAssert(version, srcBlobIdStr, referencePartitionId); }

Target:
private void composedBlobIdAndDeserialize(short version) throws Exception { String srcUUID = UUID.randomUUID().toString(); String srcBlobIdStr; srcBlobIdStr = buildBlobIdLike(version, referenceFlag, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId, srcUUID.length(), srcUUID); deserializeBlobIdAndAssert(version, srcBlobIdStr); }
Source:
public <U> Object traverse(Collection<? extends T> roots, TraverserVisitor<? super T> visitor) { assertNotNull(roots); assertNotNull(visitor); traverserState.addNewContexts(roots, traverserState.newContext(null, null, rootVars)); TraverserContext currentContext = null; traverseLoop: while (!traverserState.isEmpty()) { Object top = traverserState.pop(); if (top == TraverserState.Marker.END_LIST) { TraversalControl traversalControl = visitor.leave((TraverserContext) traverserState.pop()); assertNotNull(traversalControl, "result of leave must not be null"); switch (traversalControl) { case QUIT: break traverseLoop; case ABORT: case CONTINUE: continue; default: assertShouldNeverHappen(); } } currentContext = (TraverserContext) top; if (currentContext.isVisited()) { visitor.backRef(currentContext); } else { TraversalControl traversalControl = visitor.enter(currentContext); assertNotNull(traversalControl, "result of enter must not be null"); this.traverserState.addVisited((T) currentContext.thisNode()); switch (traversalControl) { case QUIT: break traverseLoop; case ABORT: continue; case CONTINUE: traverserState.pushAll(currentContext, getChildren); continue; default: assertShouldNeverHappen(); } } } return currentContext.getResult(); }

Target:
public TraverserResult traverse(Collection<? extends T> roots, TraverserVisitor<? super T> visitor) { assertNotNull(roots); assertNotNull(visitor); traverserState.addNewContexts(roots, traverserState.newContext(null, null, rootVars)); TraverserContext currentContext = null; traverseLoop: while (!traverserState.isEmpty()) { Object top = traverserState.pop(); if (top == TraverserState.Marker.END_LIST) { TraverserContext contextForLeave = (TraverserContext) traverserState.pop(); currentContext = contextForLeave; TraversalControl traversalControl = visitor.leave(contextForLeave); assertNotNull(traversalControl, "result of leave must not be null"); assertTrue(CONTINUE_OR_QUIT.contains(traversalControl), "result can only return CONTINUE or QUIT"); switch (traversalControl) { case QUIT: break traverseLoop; case CONTINUE: continue; default: assertShouldNeverHappen(); } } currentContext = (TraverserContext) top; if (currentContext.isVisited()) { TraversalControl traversalControl = visitor.backRef(currentContext); assertNotNull(traversalControl, "result of backRef must not be null"); assertTrue(CONTINUE_OR_QUIT.contains(traversalControl), "backRef can only return CONTINUE or QUIT"); if (traversalControl == QUIT) { break traverseLoop; } } else { TraversalControl traversalControl = visitor.enter(currentContext); assertNotNull(traversalControl, "result of enter must not be null"); this.traverserState.addVisited((T) currentContext.thisNode()); switch (traversalControl) { case QUIT: break traverseLoop; case ABORT: continue; case CONTINUE: traverserState.pushAll(currentContext, getChildren); continue; default: assertShouldNeverHappen(); } } } TraverserResult traverserResult = new TraverserResult(currentContext.getResult()); return traverserResult; }
Source:
default int getMastershipCount() { int count = 0; for (ExportStatsRow st : getStats(false)) { if ("TRUE".equalsIgnoreCase(st.m_exportingRole)) { count++; } } return count; }

Target:
default int getMastershipCount() { int count = 0; for (ExportStatsRow st : getStats(false)) { if (Boolean.parseBoolean(st.m_exportingRole)) { count++; } } return count; }
Source:
public String[] tensorflowNames() { return new String[] {"EnterZZZZ","ExposeZZZZ"}; }

Target:
public String[] tensorflowNames() { throw new NoOpNameFoundException("This operation has no TF counterpart"); }
Source:
public Tokenizer(Reader reader, int cacheBufferSize) { symbols = new UniqueList<TokenizerSymbol>(); token = new TokenizerToken(); upcomingToken = new TokenizerToken(); cacheBuffer = new char[cacheBufferSize]; setReader(reader); }

Target:
public Tokenizer(Reader reader, int cacheBufferSize) { symbols = new UniqueList(); token = new TokenizerToken(); upcomingToken = new TokenizerToken(); cacheBuffer = new char[cacheBufferSize]; setReader(reader); }
Source:
public void eventsShouldBeStreamedOnBatchSize() { final long timeout = TimeUnit.SECONDS.toMillis(1); final PartitionData pd = new PartitionData(null, 100L); for (int i = 0; i < 100; ++i) { pd.addEventFromKafka(i + 100L + 1, "test".getBytes()); } assertNull(pd.takeEventsToStream(currentTimeMillis(), 1000, timeout)); final SortedMap<Long, byte[]> eventsToStream = pd.takeEventsToStream(currentTimeMillis(), 99, timeout); assertNotNull(eventsToStream); assertEquals(99, eventsToStream.size()); }

Target:
public void eventsShouldBeStreamedOnBatchSize() { final long timeout = TimeUnit.SECONDS.toMillis(1); final PartitionData pd = new PartitionData(null, 100L); for (int i = 0; i < 100; ++i) { pd.addEventFromKafka(i + 100L + 1, "test".getBytes(UTF_8)); } assertNull(pd.takeEventsToStream(currentTimeMillis(), 1000, timeout)); final SortedMap<Long, byte[]> eventsToStream = pd.takeEventsToStream(currentTimeMillis(), 99, timeout); assertNotNull(eventsToStream); assertEquals(99, eventsToStream.size()); }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { Repository[] repos = getRepositories(event); if (repos.length == 0) return null; GitSynchronizeDataSet gsdSet = new GitSynchronizeDataSet(); for (Repository repo : repos) { try { gsdSet.add(new GitSynchronizeData(repo, HEAD, HEAD, true)); } catch (IOException e) { Activator.handleError(e.getMessage(), e, true); } } GitModelSynchronize.launch(gsdSet, getSelectedResources(event)); return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { Repository[] repos = getRepositories(event); if (repos.length == 0) return null; GitSynchronizeDataSet gsdSet = new GitSynchronizeDataSet(); for (Repository repo : repos) try { gsdSet.add(new GitSynchronizeData(repo, HEAD, HEAD, true)); } catch (IOException e) { Activator.handleError(e.getMessage(), e, true); } GitModelSynchronize.launch(gsdSet, getSelectedResources(event)); return null; }
Source:
public String init() { System.out.println("_YE_OLDE_QUERY_COUNTER_"); if ((session.getUser() != null) && (session.getUser().isAuthenticated()) && (session.getUser().isSuperuser())) { authUser = (AuthenticatedUser) session.getUser(); userListMaker = new UserListMaker(userService); runUserSearch(); } else { return permissionsWrapper.notAuthorized(); } return null; }

Target:
public String init() { if ((session.getUser() != null) && (session.getUser().isAuthenticated()) && (session.getUser().isSuperuser())) { authUser = (AuthenticatedUser) session.getUser(); userListMaker = new UserListMaker(userService); runUserSearch(); } else { return permissionsWrapper.notAuthorized(); } return null; }
Source:
public boolean testProperty(Random random, Entity entityIn) { if (entityIn instanceof IVehicleUser && (((IVehicleUser) entityIn).isRidingVehicle())) { if (((IVehicleUser) entityIn).getVehicle().isPresent()) { VehicleBase vehicle = ((IVehicleUser) entityIn).getVehicle().get(); String vehicleConfigName = vehicle.vehicleType.getConfigName(); return vehicleConfigName.contains(this.testVehicle); } } return false; }

Target:
public boolean testProperty(Random random, Entity entityIn) { if (entityIn instanceof IVehicleUser) { IVehicleUser vehicleUserEntity = (IVehicleUser) entityIn; if (vehicleUserEntity.isRidingVehicle() && vehicleUserEntity.getVehicle().isPresent()) { VehicleBase vehicle = vehicleUserEntity.getVehicle().get(); String vehicleConfigName = vehicle.vehicleType.getConfigName(); return vehicleConfigName.contains(testVehicle); } } return false; }
Source:
private void exportWithInvalidScaleLevel(Integer scaleLevel) throws Exception { String outputPath = "/" + TEMPORARY_PROJECT_NAME + "/" + IMAGE_FILE_NAME + ImageFileFormat.PNG.getName().toLowerCase(); try { ExportAction exportAction = new ExportAction(session, Collections.singletonList(getRepresentation()), new Path(outputPath), ImageFileFormat.PNG, false, true); exportAction.setDiagramScaleLevel(scaleLevel); fail("The export should throw an IllegalArgumentException because the scale level is invalid."); } catch (IllegalArgumentException iae) { assertEquals("The scale level must be a percentage (between 0 to 100).", iae.getMessage()); } catch (Exception e) { fail("The export should throw an IllegalArgumentException because the scale level is invalid."); } }

Target:
private void exportWithInvalidScaleLevel(Integer scaleLevel) throws Exception { String outputPath = "/" + TEMPORARY_PROJECT_NAME + "/" + IMAGE_FILE_NAME + ImageFileFormat.PNG.getName().toLowerCase(); String failureMessage = "The export should throw an IllegalArgumentException because the scale level is invalid."; try { ExportAction exportAction = new ExportAction(session, Collections.singletonList(getRepresentation()), new Path(outputPath), ImageFileFormat.PNG, false, true); exportAction.setDiagramScaleLevel(scaleLevel); fail(failureMessage); } catch (IllegalArgumentException iae) { assertEquals("The scale level must be a percentage (between 0 to 100).", iae.getMessage()); } catch (Exception e) { fail(failureMessage); } }
Source:
public ThriftIndexHandle( @JsonProperty("schemaTableName") SchemaTableName schemaTableName, @JsonProperty("tupleDomain") TupleDomain<ColumnHandle> tupleDomain) { this.schemaTableName = requireNonNull(schemaTableName, "schemaTableName is null"); this.tupleDomain = requireNonNull(tupleDomain, "tupleDomain is null"); this.session = Optional.empty(); }

Target:
public ThriftIndexHandle( @JsonProperty("schemaTableName") SchemaTableName schemaTableName, @JsonProperty("tupleDomain") TupleDomain<ColumnHandle> tupleDomain) { this(schemaTableName, tupleDomain, Optional.empty()); }
Source:
public static String getFieldName(AccessibleObject fieldOrMethod) { if (fieldOrMethod instanceof Field) { return ((Field) fieldOrMethod).getName(); } Method method = (Method) fieldOrMethod; String name = method.getName(); boolean hasValidParameterCount = method.getParameterCount() == 0 || isRequestScopeableMethod((Method) fieldOrMethod); if (name.startsWith("get") && hasValidParameterCount) { name = StringUtils.uncapitalize(name.substring("get".length())); } else if (name.startsWith("is") && hasValidParameterCount) { name = StringUtils.uncapitalize(name.substring("is".length())); } else { return null; } return name; }

Target:
public static String getFieldName(AccessibleObject fieldOrMethod) { if (fieldOrMethod instanceof Field) { return ((Field) fieldOrMethod).getName(); } Method method = (Method) fieldOrMethod; String name = method.getName(); boolean hasValidParameterCount = method.getParameterCount() == 0 || isRequestScopeableMethod(method); if (name.startsWith("get") && hasValidParameterCount) { return StringUtils.uncapitalize(name.substring("get".length())); } if (name.startsWith("is") && hasValidParameterCount) { return StringUtils.uncapitalize(name.substring("is".length())); } return null; }
Source:
public static StructuralNode getRootNode() { Model model = Model.getSingleton(); if (!Constant.isLowMemoryOptionSet()) { return new StructuralSiteNode(model.getSession().getSiteTree().getRootNode()); } Session session = Model.getSingleton().getSession(); RecordStructure rs; try { rs = model.getDb().getTableStructure().find(session.getSessionId(), ROOT, "Get"); if (rs != null) { return new StructuralTableNode(rs); } } catch (DatabaseException e) { log.error(e.getMessage(), e); } return null; }

Target:
public static StructuralNode getRootNode() { Model model = Model.getSingleton(); if (!Constant.isLowMemoryOptionSet()) { return new StructuralSiteNode(model.getSession().getSiteTree().getRoot()); } Session session = Model.getSingleton().getSession(); RecordStructure rs; try { rs = model.getDb().getTableStructure().find(session.getSessionId(), ROOT, HttpRequestHeader.GET); if (rs != null) { return new StructuralTableNode(rs); } } catch (DatabaseException e) { log.error(e.getMessage(), e); } return null; }
Source:
public void preparedStatementCacheMetrics(){ navigation.selectRow().invoke("View"); Application.waitUntilVisible(); MetricsAreaFragment metricsArea = dsPage.getPreparedStatementCacheMetricsArea(); double expectedHitCountPercentage = metricsArea.getPercentage(HIT_COUNT, ACCESS_COUNT); double expectedMissCountPercentage = metricsArea.getPercentage(MISS_COUNT, ACCESS_COUNT); MetricsFragment hitCountMetrics = metricsArea.getMetricsFragment(HIT_COUNT); MetricsFragment missCountMetrics = metricsArea.getMetricsFragment(MISS_COUNT); assertEquals(expectedHitCountPercentage, hitCountMetrics.getPercentage(), DELTA); assertEquals(expectedMissCountPercentage, missCountMetrics.getPercentage(), DELTA); }

Target:
public void preparedStatementCacheMetrics(){ MetricsAreaFragment metricsArea = dsPage.getPreparedStatementCacheMetricsArea(); double expectedHitCountPercentage = metricsArea.getPercentage(HIT_COUNT, ACCESS_COUNT); double expectedMissCountPercentage = metricsArea.getPercentage(MISS_COUNT, ACCESS_COUNT); MetricsFragment hitCountMetrics = metricsArea.getMetricsFragment(HIT_COUNT); MetricsFragment missCountMetrics = metricsArea.getMetricsFragment(MISS_COUNT); assertEquals(expectedHitCountPercentage, hitCountMetrics.getPercentage(), DELTA); assertEquals(expectedMissCountPercentage, missCountMetrics.getPercentage(), DELTA); }
Source:
public <S> LinkedHashSet<S> loadJavaServices(Class<S> serviceContract) { ServiceLoader<S> serviceLoader; if ( serviceLoaders.containsKey( serviceContract ) ) { serviceLoader = serviceLoaders.get( serviceContract ); } else { serviceLoader = ServiceLoader.load( serviceContract, aggregatedClassLoader ); serviceLoaders.put( serviceContract, serviceLoader ); } final LinkedHashSet<S> services = new LinkedHashSet<S>(); for ( S service : serviceLoader ) { services.add( service ); } return services; }

Target:
public <S> LinkedHashSet<S> loadJavaServices(Class<S> serviceContract) { ServiceLoader<S> serviceLoader = ServiceLoader.load( serviceContract, aggregatedClassLoader ); final LinkedHashSet<S> services = new LinkedHashSet<S>(); for ( S service : serviceLoader ) { services.add( service ); } return services; }
Source:
private String getFactoryMethodName(TypeName returnType, TypeElement factoryClass) { List<? extends Element> elements = factoryClass.getEnclosedElements(); for (Element element : elements) { if (element.getKind() != ElementKind.METHOD || !element.getModifiers().contains(Modifier.STATIC)) { continue; } ExecutableElement method = (ExecutableElement) element; if (methodTakesAndReturns(method, CURSOR, returnType)) { return method.getSimpleName().toString(); } } return null; }

Target:
private String getFactoryMethodName(TypeName returnType, TypeElement factoryClass) { List<? extends Element> elements = factoryClass.getEnclosedElements(); for (Element element : elements) { if (element.getKind() != ElementKind.METHOD || !element.getModifiers().contains(Modifier.STATIC)) { continue; } ExecutableElement method = (ExecutableElement) element; if (methodTakesAndReturns(method, CURSOR, returnType)) { return method.getSimpleName().toString(); } } throw new IllegalArgumentException(String.format("Class \"%s\" needs to define a " + "public static method taking a \"Cursor\" and returning \"%s\"", factoryClass.getSimpleName(), returnType.toString())); }
Source:
public Object processFetch(Environment context, PersistentResourceFetcher fetcher) { NonEntityDictionary nonEntityDictionary = fetcher.getNonEntityDictionary(); String fieldName = context.field.getName(); Object returnObject; if (KEY.equalsIgnoreCase(fieldName)) { returnObject = entry.getKey(); } else if (VALUE.equalsIgnoreCase(fieldName)) { returnObject = entry.getValue(); } else { throw new BadRequestException("Invalid field: '" + fieldName + "'. Maps only contain fields 'key' and 'value'"); } if (nonEntityDictionary.hasBinding(new ClassType(returnObject.getClass()))) { return new NonEntityContainer(returnObject); } return returnObject; }

Target:
public Object processFetch(Environment context, PersistentResourceFetcher fetcher) { NonEntityDictionary nonEntityDictionary = fetcher.getNonEntityDictionary(); String fieldName = context.field.getName(); Object returnObject; if (KEY.equalsIgnoreCase(fieldName)) { returnObject = entry.getKey(); } else if (VALUE.equalsIgnoreCase(fieldName)) { returnObject = entry.getValue(); } else { throw new BadRequestException("Invalid field: '" + fieldName + "'. Maps only contain fields 'key' and 'value'"); } if (nonEntityDictionary.hasBinding(EntityDictionary.getType(returnObject))) { return new NonEntityContainer(returnObject); } return returnObject; }
Source:
public JobModel getJobModel() { JavaSystemConfig systemConfig = new JavaSystemConfig(this.config); Map<String, SystemAdmin> systemAdminMap = systemConfig.getSystemAdmins(); SystemAdmins systemAdmins = new SystemAdmins(Util.javaMapAsScalaMap(systemAdminMap)); StreamMetadataCache streamMetadataCache = new StreamMetadataCache(Util.javaMapAsScalaMap(systemAdminMap), 5000, SystemClock.instance()); systemAdmins.start(); String containerId = Integer.toString(config.getInt(JobConfig.PROCESSOR_ID())); JobModel jobModel = JobModelManager.readJobModel(this.config, Collections.emptyMap(), null, streamMetadataCache, Collections.singletonList(containerId)); systemAdmins.stop(); return jobModel; }

Target:
public JobModel getJobModel() { SystemAdmins systemAdmins = new SystemAdmins(config); StreamMetadataCache streamMetadataCache = new StreamMetadataCache(systemAdmins, 5000, SystemClock.instance()); systemAdmins.start(); String containerId = Integer.toString(config.getInt(JobConfig.PROCESSOR_ID())); JobModel jobModel = JobModelManager.readJobModel(this.config, Collections.emptyMap(), null, streamMetadataCache, Collections.singletonList(containerId)); systemAdmins.stop(); return jobModel; }
Source:
public static int comp(String str1, String str2) { if (str1 == null) { return (str2 == null) ? 0 : -1; } else if (str2 == null) { return 1; } boolean isDigitTurn = false; int begSeq1 = 0, begSeq2 = 0, endSeq1, endSeq2; while ((endSeq1 = findEndOfSequence(str1, begSeq1, isDigitTurn)) != begSeq1) { if ((endSeq2 = findEndOfSequence(str2, begSeq2, isDigitTurn)) == begSeq2) { return 1; } String seq1 = str1.substring(begSeq1, endSeq1); String seq2 = str2.substring(begSeq2, endSeq2); int compRes = compareSequence(seq1, seq2, isDigitTurn); if (compRes != 0) { return compRes; } isDigitTurn = !isDigitTurn; begSeq1 = endSeq1; begSeq2 = endSeq2; } if (begSeq2 != str2.length()) { return -1; } return 0; }

Target:
public static int comp(String str1, String str2) { if (str1 == null) { return (str2 == null) ? 0 : -1; } else if (str2 == null) { return 1; } boolean digitTurn = false; int begSeq1 = 0; int begSeq2 = 0; while (begSeq1 != str1.length()) { if (begSeq2 == str2.length()) { return 1; } int endSeq1 = findEndOfSequence(str1, begSeq1, digitTurn); int endSeq2 = findEndOfSequence(str2, begSeq2, digitTurn); String seq1 = str1.substring(begSeq1, endSeq1); String seq2 = str2.substring(begSeq2, endSeq2); int compRes = compareSequence(seq1, seq2, digitTurn); if (compRes != 0) { return compRes; } digitTurn = !digitTurn; begSeq1 = endSeq1; begSeq2 = endSeq2; } if (begSeq2 != str2.length()) { return -1; } return 0; }