before
stringlengths
12
3.21M
after
stringlengths
41
3.21M
repo
stringlengths
1
56
type
stringclasses
1 value
__index_level_0__
int64
0
442k
@Override public MultiUserPKAuthenticator getPublickeyAuthenticator() throws IOException, InterruptedException { CountDownLatch wakeupLatch = new CountDownLatch(1); MultiUserPKAuthenticator publickeyAuthenticator; if (!isDevelopementMode()) { final File keyHome = new File(System.getProperty("sshd_proxy.home", "/home/")); publickeyAuthenticator = new HomeDirectoryScanningPKAuthenticator(wakeupLatch, keyHome, Arrays.asList(new Path[] {})); } else { publickeyAuthenticator = new LocalUserPKAuthenticator(wakeupLatch); } publickeyAuthenticator.start(); LOGGER.info("Waiting for public keys to be loaded"); wakeupLatch.await(); int loadedKeys = publickeyAuthenticator.getNumberOfKeysLoads(); LOGGER.info("Loaded {} public keys", Integer.valueOf(loadedKeys)); if (loadedKeys < 1) { throw new IOException("Didn't load any public keys, auth will not work, exiting"); } return publickeyAuthenticator; }
@Override public MultiUserPKAuthenticator getPublickeyAuthenticator() throws IOException, InterruptedException { CountDownLatch wakeupLatch = new CountDownLatch(1); <DeepExtract> MultiUserPKAuthenticator publickeyAuthenticator; if (!isDevelopementMode()) { final File keyHome = new File(System.getProperty("sshd_proxy.home", "/home/")); publickeyAuthenticator = new HomeDirectoryScanningPKAuthenticator(wakeupLatch, keyHome, Arrays.asList(new Path[] {})); } else { publickeyAuthenticator = new LocalUserPKAuthenticator(wakeupLatch); } </DeepExtract> publickeyAuthenticator.start(); LOGGER.info("Waiting for public keys to be loaded"); wakeupLatch.await(); int loadedKeys = publickeyAuthenticator.getNumberOfKeysLoads(); LOGGER.info("Loaded {} public keys", Integer.valueOf(loadedKeys)); if (loadedKeys < 1) { throw new IOException("Didn't load any public keys, auth will not work, exiting"); } return publickeyAuthenticator; }
artifactory_ssh_proxy
positive
3,172
private void renewKeyPair() { var activeKeyPair = repositories.findActiveKeyPair(); var generator = new Ed25519KeyPairGenerator(); generator.init(new Ed25519KeyGenerationParameters(new SecureRandom())); var pair = generator.generateKeyPair(); var keyPair = new SignatureKeyPair(); keyPair.setPublicId(UUID.randomUUID().toString()); keyPair.setPrivateKey(((Ed25519PrivateKeyParameters) pair.getPrivate()).getEncoded()); keyPair.setPublicKeyText(getPublicKeyText(pair)); keyPair.setCreated(LocalDateTime.now()); keyPair.setActive(true); entityManager.persist(keyPair); repositories.findVersions().forEach(this::enqueueCreateSignatureJob); if (activeKeyPair != null) { activeKeyPair.setActive(false); } }
private void renewKeyPair() { var activeKeyPair = repositories.findActiveKeyPair(); <DeepExtract> var generator = new Ed25519KeyPairGenerator(); generator.init(new Ed25519KeyGenerationParameters(new SecureRandom())); var pair = generator.generateKeyPair(); var keyPair = new SignatureKeyPair(); keyPair.setPublicId(UUID.randomUUID().toString()); keyPair.setPrivateKey(((Ed25519PrivateKeyParameters) pair.getPrivate()).getEncoded()); keyPair.setPublicKeyText(getPublicKeyText(pair)); keyPair.setCreated(LocalDateTime.now()); keyPair.setActive(true); entityManager.persist(keyPair); </DeepExtract> repositories.findVersions().forEach(this::enqueueCreateSignatureJob); if (activeKeyPair != null) { activeKeyPair.setActive(false); } }
openvsx
positive
3,173
@Test public void joinRoomFail() { assertThat(manager.getRooms(), not(hasItem(roomx))); exception.expect(RoomException.class); exception.expectMessage(containsString("must be created before")); return userJoinRoom(roomx, userx, pidx, false, true); assertThat(manager.getRooms(), not(hasItem(roomx))); }
@Test public void joinRoomFail() { assertThat(manager.getRooms(), not(hasItem(roomx))); exception.expect(RoomException.class); exception.expectMessage(containsString("must be created before")); <DeepExtract> return userJoinRoom(roomx, userx, pidx, false, true); </DeepExtract> assertThat(manager.getRooms(), not(hasItem(roomx))); }
kurento-room
positive
3,174
public static final InputStream demoteDevice() throws IOException { Process process = Runtime.getRuntime().exec(C8Const.DEMOTE_DEVICE_COMMAND); return process.getInputStream(); }
public static final InputStream demoteDevice() throws IOException { <DeepExtract> Process process = Runtime.getRuntime().exec(C8Const.DEMOTE_DEVICE_COMMAND); return process.getInputStream(); </DeepExtract> }
checkm8gui
positive
3,175
private void storeContractAddress() { RegistrationProperties props = new RegistrationProperties(); loadProperties(); this.privateKey = this.properties.getProperty(PROP_PRIV_KEY); this.registrationContractAddress = this.properties.getProperty(PROP_REGISTRATION_CONTRACT_ADDRESS); props.registrationContractAddress = this.registrationContractAddress; this.properties.setProperty(PROP_PRIV_KEY, this.privateKey); if (registrationContractAddress != null) { this.properties.setProperty(PROP_REGISTRATION_CONTRACT_ADDRESS, this.registrationContractAddress); } storeProperties(); }
private void storeContractAddress() { RegistrationProperties props = new RegistrationProperties(); loadProperties(); this.privateKey = this.properties.getProperty(PROP_PRIV_KEY); this.registrationContractAddress = this.properties.getProperty(PROP_REGISTRATION_CONTRACT_ADDRESS); props.registrationContractAddress = this.registrationContractAddress; <DeepExtract> this.properties.setProperty(PROP_PRIV_KEY, this.privateKey); if (registrationContractAddress != null) { this.properties.setProperty(PROP_REGISTRATION_CONTRACT_ADDRESS, this.registrationContractAddress); } storeProperties(); </DeepExtract> }
sidechains-samples
positive
3,176
@Override protected void onStart() { super.onStart(); Intent intent = new Intent(this, Sha1HashBroadCastUnhService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); this.view = (TextView) findViewById(R.id.hashResult); IntentFilter filter = new IntentFilter(Sha1HashBroadCastUnhService.DIGEST_BROADCAST); LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, filter); }
@Override protected void onStart() { super.onStart(); Intent intent = new Intent(this, Sha1HashBroadCastUnhService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); <DeepExtract> this.view = (TextView) findViewById(R.id.hashResult); </DeepExtract> IntentFilter filter = new IntentFilter(Sha1HashBroadCastUnhService.DIGEST_BROADCAST); LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, filter); }
Asynchronous-Android-Programming
positive
3,177
public static Result<?> resourceAlreadyInvalid() { return Result.builder().code(ResultEnum.RESOURCE_ALREADY_INVALID.getCode()).msg(ResultEnum.RESOURCE_ALREADY_INVALID.getMsg()).flag(false).build(); }
public static Result<?> resourceAlreadyInvalid() { <DeepExtract> return Result.builder().code(ResultEnum.RESOURCE_ALREADY_INVALID.getCode()).msg(ResultEnum.RESOURCE_ALREADY_INVALID.getMsg()).flag(false).build(); </DeepExtract> }
yue-library
positive
3,178
private void initializeSession() { TermSettings settings = mSettings; int[] processId = new int[1]; String path = System.getenv("PATH"); if (settings.doPathExtensions()) { String appendPath = settings.getAppendPath(); if (appendPath != null && appendPath.length() > 0) { path = path + ":" + appendPath; } if (settings.allowPathPrepend()) { String prependPath = settings.getPrependPath(); if (prependPath != null && prependPath.length() > 0) { path = prependPath + ":" + path; } } } if (settings.verifyPath()) { path = checkPath(path); } String[] env = new String[3]; env[0] = "TERM=" + settings.getTermType(); env[1] = "PATH=" + path; env[2] = "HOME=" + settings.getHomePath(); ArrayList<String> argList = parse(settings.getShell()); String arg0; String[] args; try { arg0 = argList.get(0); File file = new File(arg0); if (!file.exists()) { Log.e(TermDebug.LOG_TAG, "Shell " + arg0 + " not found!"); throw new FileNotFoundException(arg0); } else if (!FileCompat.canExecute(file)) { Log.e(TermDebug.LOG_TAG, "Shell " + arg0 + " not executable!"); throw new FileNotFoundException(arg0); } args = argList.toArray(new String[1]); } catch (Exception e) { argList = parse(mSettings.getFailsafeShell()); arg0 = argList.get(0); args = argList.toArray(new String[1]); } mTermFd = Exec.createSubprocess(arg0, args, env, processId); mProcId = processId[0]; setTermOut(new FileOutputStream(mTermFd)); setTermIn(new FileInputStream(mTermFd)); }
private void initializeSession() { TermSettings settings = mSettings; int[] processId = new int[1]; String path = System.getenv("PATH"); if (settings.doPathExtensions()) { String appendPath = settings.getAppendPath(); if (appendPath != null && appendPath.length() > 0) { path = path + ":" + appendPath; } if (settings.allowPathPrepend()) { String prependPath = settings.getPrependPath(); if (prependPath != null && prependPath.length() > 0) { path = prependPath + ":" + path; } } } if (settings.verifyPath()) { path = checkPath(path); } String[] env = new String[3]; env[0] = "TERM=" + settings.getTermType(); env[1] = "PATH=" + path; env[2] = "HOME=" + settings.getHomePath(); <DeepExtract> ArrayList<String> argList = parse(settings.getShell()); String arg0; String[] args; try { arg0 = argList.get(0); File file = new File(arg0); if (!file.exists()) { Log.e(TermDebug.LOG_TAG, "Shell " + arg0 + " not found!"); throw new FileNotFoundException(arg0); } else if (!FileCompat.canExecute(file)) { Log.e(TermDebug.LOG_TAG, "Shell " + arg0 + " not executable!"); throw new FileNotFoundException(arg0); } args = argList.toArray(new String[1]); } catch (Exception e) { argList = parse(mSettings.getFailsafeShell()); arg0 = argList.get(0); args = argList.toArray(new String[1]); } mTermFd = Exec.createSubprocess(arg0, args, env, processId); </DeepExtract> mProcId = processId[0]; setTermOut(new FileOutputStream(mTermFd)); setTermIn(new FileInputStream(mTermFd)); }
TerminalEmulator-Android
positive
3,179
@Override public void onClick(View v) { GAME.playSFX(SFX_CLICK); GAME.playSFX(SFX_MONEY); GAME.getPlayer().setResponseIndex(1); GAME.addItem(item); final GameTextView moneyText = findViewById(R.id.top_menu_money_text); final GameTextView moneyLabel = findViewById(R.id.top_menu_money_label); int oldMoney = GAME.getMoney(); ValueAnimator valueAnimator = ValueAnimator.ofFloat(oldMoney, GAME.increaseMoney(-item.getBuyPrice())); valueAnimator.setDuration(2000); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { moneyText.setText(String.format("£%s", (String.format(Locale.ENGLISH, "%.2f", ((float) animation.getAnimatedValue()) / 100)))); } }); if (false) { moneyLabel.setVisibility(View.VISIBLE); ObjectAnimator fadeIn = ObjectAnimator.ofFloat(moneyLabel, "alpha", 0f, 1f); fadeIn.setDuration(0); final ObjectAnimator fadeOut = ObjectAnimator.ofFloat(moneyLabel, "alpha", 0f, 1f); fadeOut.setDuration(0); fadeIn.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { new Handler().postDelayed(new Runnable() { @Override public void run() { fadeOut.start(); } }, 3000); } }); fadeOut.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { moneyLabel.setVisibility(View.GONE); } }); fadeIn.start(); } GAME.playSFX(SFX_MONEY); valueAnimator.start(); money.setText(String.format(Locale.ENGLISH, "%.2f", ((float) GAME.getMoney()) / 100)); inventoryQuantity.setText("x" + String.format(Locale.ENGLISH, "%d", GAME.getItemQuantity(item))); if (GAME.getMoney() < item.getBuyPrice()) { inventoryButton.setAlpha(0.5f); inventoryButton.setEnabled(false); } final ConstraintLayout shopBuyMenu = findViewById(R.id.shop_menu_buy); for (int i = 0; i < shopBuyMenu.getChildCount(); i++) { View view = shopBuyMenu.getChildAt(i); if (view instanceof ItemImageView) { if ((GAME.isSheetItem(((ItemImageView) view).getItem()) && GAME.hasBook(((ItemImageView) view).getItem())) || (GAME.isBookItem(((ItemImageView) view).getItem()) && GAME.hasItem(((ItemImageView) view).getItem()))) { view.setEnabled(false); view.setAlpha(0.5f); } else { view.setEnabled(true); view.setAlpha(1f); } } } GameTextView pointsText = findViewById(R.id.top_menu_points_text); GameTextView timeText = findViewById(R.id.top_menu_time_text); GameTextView daysText = findViewById(R.id.top_menu_day_content); GameTextView daysSubtitle = findViewById(R.id.top_menu_day_subtitle); GameTextView moneyText = findViewById(R.id.top_menu_money_text); pointsText.setText(String.format("%spts", String.format(Locale.ENGLISH, "%d", GAME.getPoints()))); moneyText.setText(String.format("£%s", String.format(Locale.ENGLISH, "%.2f", ((float) GAME.getMoney()) / 100))); switch(GAME.getTime()) { case TIME_MORNING: timeText.setText("MORNING"); break; case TIME_LUNCH: timeText.setText("LUNCH"); break; case TIME_AFTER_SCHOOL: timeText.setText("AFTER SCHOOL"); break; case TIME_EVENING: timeText.setText("EVENING"); break; case TIME_HEIST_PHASE_1: case TIME_HEIST_PHASE_2: timeText.setText("HEIST"); break; } if (NUMBER_OF_DAYS - GAME.getDay() >= 0) { daysText.setText(String.format(Locale.ENGLISH, "%d", NUMBER_OF_DAYS - GAME.getDay())); if (NUMBER_OF_DAYS - GAME.getDay() == 1) { daysSubtitle.setText("DAY"); } else { daysSubtitle.setText("DAYS"); } } if (GAME.getDay() > 27) { daysText.setTextColor(getResources().getColor(R.color.colorRedFont)); daysSubtitle.setTextColor(getResources().getColor(R.color.colorRedFont)); } }
@Override public void onClick(View v) { GAME.playSFX(SFX_CLICK); GAME.playSFX(SFX_MONEY); GAME.getPlayer().setResponseIndex(1); GAME.addItem(item); final GameTextView moneyText = findViewById(R.id.top_menu_money_text); final GameTextView moneyLabel = findViewById(R.id.top_menu_money_label); int oldMoney = GAME.getMoney(); ValueAnimator valueAnimator = ValueAnimator.ofFloat(oldMoney, GAME.increaseMoney(-item.getBuyPrice())); valueAnimator.setDuration(2000); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { moneyText.setText(String.format("£%s", (String.format(Locale.ENGLISH, "%.2f", ((float) animation.getAnimatedValue()) / 100)))); } }); if (false) { moneyLabel.setVisibility(View.VISIBLE); ObjectAnimator fadeIn = ObjectAnimator.ofFloat(moneyLabel, "alpha", 0f, 1f); fadeIn.setDuration(0); final ObjectAnimator fadeOut = ObjectAnimator.ofFloat(moneyLabel, "alpha", 0f, 1f); fadeOut.setDuration(0); fadeIn.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { new Handler().postDelayed(new Runnable() { @Override public void run() { fadeOut.start(); } }, 3000); } }); fadeOut.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { moneyLabel.setVisibility(View.GONE); } }); fadeIn.start(); } GAME.playSFX(SFX_MONEY); valueAnimator.start(); money.setText(String.format(Locale.ENGLISH, "%.2f", ((float) GAME.getMoney()) / 100)); inventoryQuantity.setText("x" + String.format(Locale.ENGLISH, "%d", GAME.getItemQuantity(item))); if (GAME.getMoney() < item.getBuyPrice()) { inventoryButton.setAlpha(0.5f); inventoryButton.setEnabled(false); } final ConstraintLayout shopBuyMenu = findViewById(R.id.shop_menu_buy); for (int i = 0; i < shopBuyMenu.getChildCount(); i++) { View view = shopBuyMenu.getChildAt(i); if (view instanceof ItemImageView) { if ((GAME.isSheetItem(((ItemImageView) view).getItem()) && GAME.hasBook(((ItemImageView) view).getItem())) || (GAME.isBookItem(((ItemImageView) view).getItem()) && GAME.hasItem(((ItemImageView) view).getItem()))) { view.setEnabled(false); view.setAlpha(0.5f); } else { view.setEnabled(true); view.setAlpha(1f); } } } <DeepExtract> GameTextView pointsText = findViewById(R.id.top_menu_points_text); GameTextView timeText = findViewById(R.id.top_menu_time_text); GameTextView daysText = findViewById(R.id.top_menu_day_content); GameTextView daysSubtitle = findViewById(R.id.top_menu_day_subtitle); GameTextView moneyText = findViewById(R.id.top_menu_money_text); pointsText.setText(String.format("%spts", String.format(Locale.ENGLISH, "%d", GAME.getPoints()))); moneyText.setText(String.format("£%s", String.format(Locale.ENGLISH, "%.2f", ((float) GAME.getMoney()) / 100))); switch(GAME.getTime()) { case TIME_MORNING: timeText.setText("MORNING"); break; case TIME_LUNCH: timeText.setText("LUNCH"); break; case TIME_AFTER_SCHOOL: timeText.setText("AFTER SCHOOL"); break; case TIME_EVENING: timeText.setText("EVENING"); break; case TIME_HEIST_PHASE_1: case TIME_HEIST_PHASE_2: timeText.setText("HEIST"); break; } if (NUMBER_OF_DAYS - GAME.getDay() >= 0) { daysText.setText(String.format(Locale.ENGLISH, "%d", NUMBER_OF_DAYS - GAME.getDay())); if (NUMBER_OF_DAYS - GAME.getDay() == 1) { daysSubtitle.setText("DAY"); } else { daysSubtitle.setText("DAYS"); } } if (GAME.getDay() > 27) { daysText.setTextColor(getResources().getColor(R.color.colorRedFont)); daysSubtitle.setTextColor(getResources().getColor(R.color.colorRedFont)); } </DeepExtract> }
SchoolQuest
positive
3,180
@Override public OperateResultExOne<byte[]> Read(String address, short length) { OperateResultExOne<byte[]> coreResult = MelsecHelper.BuildAsciiReadMcCoreCommand(address, length, false, new FunctionOperateExOne<String, OperateResultExTwo<MelsecMcDataType, Integer>>() { @Override public OperateResultExTwo<MelsecMcDataType, Integer> Action(String content) { return McAnalysisAddress(content); } }); if (!coreResult.IsSuccess) return coreResult; OperateResultExOne<byte[]> read = ReadFromCoreServer(PackMcCommand(coreResult.Content, NetworkNumber, NetworkStationNumber)); if (!read.IsSuccess) return OperateResultExOne.CreateFailedResult(read); short errorCode = (short) Integer.parseInt(Utilities.getString(read.Content, 18, 4, "ASCII"), 16); if (errorCode != 0) return new OperateResultExOne<>(errorCode, StringResources.Language.MelsecPleaseReferToManulDocument()); if (false) { byte[] Content = new byte[read.Content.length - 22]; for (int i = 22; i < read.Content.length; i++) { if (read.Content[i] == 0x30) { Content[i - 22] = 0x00; } else { Content[i - 22] = 0x01; } } return OperateResultExOne.CreateSuccessResult(Content); } else { byte[] Content = new byte[(read.Content.length - 22) / 2]; for (int i = 0; i < Content.length / 2; i++) { int tmp = Integer.parseInt(Utilities.getString(read.Content, i * 4 + 22, 4, "ASCII"), 16); byte[] buffer = Utilities.getBytes(tmp); Content[i * 2 + 0] = buffer[0]; Content[i * 2 + 1] = buffer[1]; } return OperateResultExOne.CreateSuccessResult(Content); } }
@Override public OperateResultExOne<byte[]> Read(String address, short length) { OperateResultExOne<byte[]> coreResult = MelsecHelper.BuildAsciiReadMcCoreCommand(address, length, false, new FunctionOperateExOne<String, OperateResultExTwo<MelsecMcDataType, Integer>>() { @Override public OperateResultExTwo<MelsecMcDataType, Integer> Action(String content) { return McAnalysisAddress(content); } }); if (!coreResult.IsSuccess) return coreResult; OperateResultExOne<byte[]> read = ReadFromCoreServer(PackMcCommand(coreResult.Content, NetworkNumber, NetworkStationNumber)); if (!read.IsSuccess) return OperateResultExOne.CreateFailedResult(read); short errorCode = (short) Integer.parseInt(Utilities.getString(read.Content, 18, 4, "ASCII"), 16); if (errorCode != 0) return new OperateResultExOne<>(errorCode, StringResources.Language.MelsecPleaseReferToManulDocument()); <DeepExtract> if (false) { byte[] Content = new byte[read.Content.length - 22]; for (int i = 22; i < read.Content.length; i++) { if (read.Content[i] == 0x30) { Content[i - 22] = 0x00; } else { Content[i - 22] = 0x01; } } return OperateResultExOne.CreateSuccessResult(Content); } else { byte[] Content = new byte[(read.Content.length - 22) / 2]; for (int i = 0; i < Content.length / 2; i++) { int tmp = Integer.parseInt(Utilities.getString(read.Content, i * 4 + 22, 4, "ASCII"), 16); byte[] buffer = Utilities.getBytes(tmp); Content[i * 2 + 0] = buffer[0]; Content[i * 2 + 1] = buffer[1]; } return OperateResultExOne.CreateSuccessResult(Content); } </DeepExtract> }
HslCommunication
positive
3,181
public static void printInOrder(Node head) { if (head == null) { return; } if (head.left == null) { return; } System.out.print(head.left.value + " "); printPreOrder(head.left.left); printPreOrder(head.left.right); System.out.print(head.value + " "); if (head.right == null) { return; } System.out.print(head.right.value + " "); printPreOrder(head.right.left); printPreOrder(head.right.right); }
public static void printInOrder(Node head) { if (head == null) { return; } if (head.left == null) { return; } System.out.print(head.left.value + " "); printPreOrder(head.left.left); printPreOrder(head.left.right); System.out.print(head.value + " "); <DeepExtract> if (head.right == null) { return; } System.out.print(head.right.value + " "); printPreOrder(head.right.left); printPreOrder(head.right.right); </DeepExtract> }
JavaSuanfa
positive
3,182
public Criteria andBz81LessThanOrEqualTo(String value) { if (value == null) { throw new RuntimeException("Value for " + "bz81" + " cannot be null"); } criteria.add(new Criterion("`bz81` <=", value)); return (Criteria) this; }
public Criteria andBz81LessThanOrEqualTo(String value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "bz81" + " cannot be null"); } criteria.add(new Criterion("`bz81` <=", value)); </DeepExtract> return (Criteria) this; }
blockhealth
positive
3,183
@Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); }
@Override <DeepExtract> </DeepExtract> public void onDestroyView() { <DeepExtract> </DeepExtract> super.onDestroyView(); <DeepExtract> </DeepExtract> ButterKnife.unbind(this); <DeepExtract> </DeepExtract> }
audio-streaming-player
positive
3,185
public List<Column> getSubColumnsFromRow(String columnFamily, String rowKey, Bytes superColName, SlicePredicate colPredicate, ConsistencyLevel cLevel) throws PelopsException { return getColumnsFromRow(newColumnParent(newColumnParent(columnFamily, superColName)), rowKey, columnsPredicateAll(colPredicate), cLevel); }
public List<Column> getSubColumnsFromRow(String columnFamily, String rowKey, Bytes superColName, SlicePredicate colPredicate, ConsistencyLevel cLevel) throws PelopsException { <DeepExtract> return getColumnsFromRow(newColumnParent(newColumnParent(columnFamily, superColName)), rowKey, columnsPredicateAll(colPredicate), cLevel); </DeepExtract> }
scale7-pelops
positive
3,186
@Override public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { if (mDivider == null) { super.onDrawOver(c, parent, state); return; } int left = 0, right = 0, top = 0, bottom = 0, size; int left = 0, right = 0, top = 0, bottom = 0, size; int left = 0, right = 0, top = 0, bottom = 0, size; int left = 0, right = 0, top = 0, bottom = 0, size; int orientation; if (parent.getLayoutManager() instanceof LinearLayoutManager) { LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager(); orientation = layoutManager.getOrientation(); } else { throw new IllegalStateException("DividerItemDecoration can only be used with a LinearLayoutManager."); } int childCount = parent.getChildCount(); if (orientation == LinearLayoutManager.VERTICAL) { size = mDivider.getIntrinsicHeight(); left = parent.getPaddingLeft(); right = parent.getWidth() - parent.getPaddingRight(); } else { size = mDivider.getIntrinsicWidth(); top = parent.getPaddingTop(); bottom = parent.getHeight() - parent.getPaddingBottom(); } for (int i = mShowFirstDivider ? 0 : 1; i < childCount; i++) { View child = parent.getChildAt(i); RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams(); if (orientation == LinearLayoutManager.VERTICAL) { top = child.getTop() - params.topMargin; bottom = top + size; } else { left = child.getLeft() - params.leftMargin; right = left + size; } mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } if (mShowLastDivider && childCount > 0) { View child = parent.getChildAt(childCount - 1); RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams(); if (orientation == LinearLayoutManager.VERTICAL) { top = child.getBottom() + params.bottomMargin; bottom = top + size; } else { left = child.getRight() + params.rightMargin; right = left + size; } mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } }
@Override public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { if (mDivider == null) { super.onDrawOver(c, parent, state); return; } int left = 0, right = 0, top = 0, bottom = 0, size; int left = 0, right = 0, top = 0, bottom = 0, size; int left = 0, right = 0, top = 0, bottom = 0, size; int left = 0, right = 0, top = 0, bottom = 0, size; <DeepExtract> int orientation; if (parent.getLayoutManager() instanceof LinearLayoutManager) { LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager(); orientation = layoutManager.getOrientation(); } else { throw new IllegalStateException("DividerItemDecoration can only be used with a LinearLayoutManager."); } </DeepExtract> int childCount = parent.getChildCount(); if (orientation == LinearLayoutManager.VERTICAL) { size = mDivider.getIntrinsicHeight(); left = parent.getPaddingLeft(); right = parent.getWidth() - parent.getPaddingRight(); } else { size = mDivider.getIntrinsicWidth(); top = parent.getPaddingTop(); bottom = parent.getHeight() - parent.getPaddingBottom(); } for (int i = mShowFirstDivider ? 0 : 1; i < childCount; i++) { View child = parent.getChildAt(i); RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams(); if (orientation == LinearLayoutManager.VERTICAL) { top = child.getTop() - params.topMargin; bottom = top + size; } else { left = child.getLeft() - params.leftMargin; right = left + size; } mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } if (mShowLastDivider && childCount > 0) { View child = parent.getChildAt(childCount - 1); RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams(); if (orientation == LinearLayoutManager.VERTICAL) { top = child.getBottom() + params.bottomMargin; bottom = top + size; } else { left = child.getRight() + params.rightMargin; right = left + size; } mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } }
citra_android
positive
3,187
public BMIView setGender(int gender) { this.gender = gender; if (height == 0f) { bmiValue = 0; } else { bmiValue = weight / (height * height); } if (bmiValue < mMin) { bmiValue = mMin; } currentBodyCategory = calculateBodyCategory(); super.invalidate(); return this; }
public BMIView setGender(int gender) { this.gender = gender; <DeepExtract> if (height == 0f) { bmiValue = 0; } else { bmiValue = weight / (height * height); } if (bmiValue < mMin) { bmiValue = mMin; } currentBodyCategory = calculateBodyCategory(); super.invalidate(); </DeepExtract> return this; }
LoseWeightOpenSOurce
positive
3,188
public void performReset() throws IOException { if (!isConnected()) throw new IOException("Not connected to a WaterRower!"); connector.send(new ResetMessage()); }
public void performReset() throws IOException { <DeepExtract> if (!isConnected()) throw new IOException("Not connected to a WaterRower!"); </DeepExtract> connector.send(new ResetMessage()); }
waterrower-core
positive
3,189
@Override protected int comparePivot(int j) { return a[pivot].compareTo(a[a[j]]); }
@Override protected int comparePivot(int j) { <DeepExtract> return a[pivot].compareTo(a[a[j]]); </DeepExtract> }
chinesesegmentor
positive
3,190
@Override public void writeSetEnd() throws TException { popContext(); trans_.write(RBRACKET); }
@Override public void writeSetEnd() throws TException { <DeepExtract> popContext(); trans_.write(RBRACKET); </DeepExtract> }
Thrift-Client-Server-Example--PHP-
positive
3,191
public Criteria andSeqIn(List<Integer> values) { if (values == null) { throw new RuntimeException("Value for " + "seq" + " cannot be null"); } criteria.add(new Criterion("seq in", values)); return (Criteria) this; }
public Criteria andSeqIn(List<Integer> values) { <DeepExtract> if (values == null) { throw new RuntimeException("Value for " + "seq" + " cannot be null"); } criteria.add(new Criterion("seq in", values)); </DeepExtract> return (Criteria) this; }
einvoice
positive
3,192
@Override public void haltAndRestartLogging() { Log.i(TAG, "stop:: Stopping listener for sensor " + getSensorName()); mSensorManager.unregisterListener(this); logger.stop(); logger.resetByteCounter(); Log.i(TAG, "start:: Starting listener for sensor: " + getSensorName()); mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR), mSamplingPeriodUs); logger.start(); }
@Override public void haltAndRestartLogging() { Log.i(TAG, "stop:: Stopping listener for sensor " + getSensorName()); mSensorManager.unregisterListener(this); logger.stop(); logger.resetByteCounter(); <DeepExtract> Log.i(TAG, "start:: Starting listener for sensor: " + getSensorName()); mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR), mSamplingPeriodUs); logger.start(); </DeepExtract> }
DataLogger
positive
3,193
@Override public void actionPerformed(ActionEvent e) { SuiteLogic.moveUp(mRuntime, mSuite.getSelectedIndices()); }
@Override public void actionPerformed(ActionEvent e) { <DeepExtract> SuiteLogic.moveUp(mRuntime, mSuite.getSelectedIndices()); </DeepExtract> }
EchoSim
positive
3,194
public static void setTemplateDir(final String templateDir) { JSONObject data = THREAD_LOCAL_DATA.get(); if (null == data) { data = new JSONObject().put(Keys.TEMPLATE_DIR_NAME, templateDir); THREAD_LOCAL_DATA.set(data); return; } SESSION_CACHE.put(Keys.TEMPLATE_DIR_NAME, templateDir); }
public static void setTemplateDir(final String templateDir) { JSONObject data = THREAD_LOCAL_DATA.get(); if (null == data) { data = new JSONObject().put(Keys.TEMPLATE_DIR_NAME, templateDir); THREAD_LOCAL_DATA.set(data); return; } <DeepExtract> SESSION_CACHE.put(Keys.TEMPLATE_DIR_NAME, templateDir); </DeepExtract> }
symphony
positive
3,195
public List<WrappedSystem> list() { return new ArrayList<WrappedSystem>(getCandidates(this.path).values()); }
public List<WrappedSystem> list() { <DeepExtract> return new ArrayList<WrappedSystem>(getCandidates(this.path).values()); </DeepExtract> }
Smaller
positive
3,196
@Override public void setViewPager(ViewPager view) { if (mViewPager == view) { return; } if (mViewPager != null) { mViewPager.setOnPageChangeListener(null); } final PagerAdapter adapter = view.getAdapter(); if (adapter == null) { throw new IllegalStateException("ViewPager does not have adapter instance."); } mViewPager = view; mListener = this; mTabLayout.removeAllViews(); PagerAdapter adapter = mViewPager.getAdapter(); final int count = adapter.getCount(); for (int i = 0; i < count; i++) { CharSequence title = adapter.getPageTitle(i); if (title == null) { title = EMPTY_TITLE; } addTab(title, i); } if (mSelectedTabIndex > count) { mSelectedTabIndex = count - 1; } setCurrentItem(mSelectedTabIndex); requestLayout(); }
@Override public void setViewPager(ViewPager view) { if (mViewPager == view) { return; } if (mViewPager != null) { mViewPager.setOnPageChangeListener(null); } final PagerAdapter adapter = view.getAdapter(); if (adapter == null) { throw new IllegalStateException("ViewPager does not have adapter instance."); } mViewPager = view; mListener = this; <DeepExtract> mTabLayout.removeAllViews(); PagerAdapter adapter = mViewPager.getAdapter(); final int count = adapter.getCount(); for (int i = 0; i < count; i++) { CharSequence title = adapter.getPageTitle(i); if (title == null) { title = EMPTY_TITLE; } addTab(title, i); } if (mSelectedTabIndex > count) { mSelectedTabIndex = count - 1; } setCurrentItem(mSelectedTabIndex); requestLayout(); </DeepExtract> }
Atomic
positive
3,197
public static void debug(String msg) { if (Level.DEBUG.getValue() >= Log.level.getValue()) { if (printWriter != null) { printWriter.println("DEBUG: " + msg); printWriter.flush(); } else { System.out.println("DEBUG: " + msg); } } }
public static void debug(String msg) { <DeepExtract> if (Level.DEBUG.getValue() >= Log.level.getValue()) { if (printWriter != null) { printWriter.println("DEBUG: " + msg); printWriter.flush(); } else { System.out.println("DEBUG: " + msg); } } </DeepExtract> }
javaemvreader
positive
3,198
@Test public void testEncode() throws Exception { encoder.encode(ctx, messageBuilder, out); verify(ctx).flush(); String expectedString = "8=FIX.4.2\u00019=89\u000135=0\u000149=SenderCompID\u000156=TargetCompID\u000134=2\u000152=19700102-10:17:36.789\u00011001=test2\u00011000=test1\u000110=204\u0001"; final String string = new String(out.array(), out.arrayOffset(), out.readableBytes(), US_ASCII); assertEquals(expectedString, string); }
@Test public void testEncode() throws Exception { encoder.encode(ctx, messageBuilder, out); verify(ctx).flush(); String expectedString = "8=FIX.4.2\u00019=89\u000135=0\u000149=SenderCompID\u000156=TargetCompID\u000134=2\u000152=19700102-10:17:36.789\u00011001=test2\u00011000=test1\u000110=204\u0001"; <DeepExtract> final String string = new String(out.array(), out.arrayOffset(), out.readableBytes(), US_ASCII); assertEquals(expectedString, string); </DeepExtract> }
fixio
positive
3,199
@Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { viewResolver.resolve(view, new ModelMap(), this, req, resp); } catch (Throwable e) { exceptionResolver.handleException(e, this, req, resp); } }
@Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { <DeepExtract> try { viewResolver.resolve(view, new ModelMap(), this, req, resp); } catch (Throwable e) { exceptionResolver.handleException(e, this, req, resp); } </DeepExtract> }
lime-mvc
positive
3,200
private static void addBody(HttpURLConnection connection, Request<?> request, byte[] body) throws IOException { connection.setDoOutput(true); if (!connection.getRequestProperties().containsKey(HttpHeaderParser.HEADER_CONTENT_TYPE)) { connection.setRequestProperty(HttpHeaderParser.HEADER_CONTENT_TYPE, request.getBodyContentType()); } DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); super.close(); mConnection.disconnect(); }
private static void addBody(HttpURLConnection connection, Request<?> request, byte[] body) throws IOException { connection.setDoOutput(true); if (!connection.getRequestProperties().containsKey(HttpHeaderParser.HEADER_CONTENT_TYPE)) { connection.setRequestProperty(HttpHeaderParser.HEADER_CONTENT_TYPE, request.getBodyContentType()); } DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); <DeepExtract> super.close(); mConnection.disconnect(); </DeepExtract> }
XpenseTracker
positive
3,203
@Test public void i32_eqz() throws IOException { WasmOptions options = new WasmOptions(new HashMap<>()); WatParser parser = new WatParser(); WasmCodeBuilder codeBuilder = parser; codeBuilder.init(options, null); parser.parse("i32.eqz", null, null, 100); StringBuilder builder = new StringBuilder(); ModuleWriter writer = new TextModuleWriter(new WasmTarget(builder), options); writer.writeMethodStart(new FunctionName("A.a()V"), null); for (WasmInstruction instruction : codeBuilder.getInstructions()) { instruction.writeTo(writer); } writer.writeMethodFinish(); writer.close(); String expected = normalize("(module (func $A.a " + "i32.eqz" + " ) )"); String actual = normalize(builder); assertEquals(expected, actual); writer = new BinaryModuleWriter(new WasmTarget(builder), new WasmOptions(new HashMap<>())); writer.writeMethodStart(new FunctionName("A.a()V"), null); for (WasmInstruction instruction : codeBuilder.getInstructions()) { instruction.writeTo(writer); } }
@Test public void i32_eqz() throws IOException { <DeepExtract> WasmOptions options = new WasmOptions(new HashMap<>()); WatParser parser = new WatParser(); WasmCodeBuilder codeBuilder = parser; codeBuilder.init(options, null); parser.parse("i32.eqz", null, null, 100); StringBuilder builder = new StringBuilder(); ModuleWriter writer = new TextModuleWriter(new WasmTarget(builder), options); writer.writeMethodStart(new FunctionName("A.a()V"), null); for (WasmInstruction instruction : codeBuilder.getInstructions()) { instruction.writeTo(writer); } writer.writeMethodFinish(); writer.close(); String expected = normalize("(module (func $A.a " + "i32.eqz" + " ) )"); String actual = normalize(builder); assertEquals(expected, actual); writer = new BinaryModuleWriter(new WasmTarget(builder), new WasmOptions(new HashMap<>())); writer.writeMethodStart(new FunctionName("A.a()V"), null); for (WasmInstruction instruction : codeBuilder.getInstructions()) { instruction.writeTo(writer); } </DeepExtract> }
JWebAssembly
positive
3,204
public void onSuccess(WorkContainer<?, ?> wc) { return entries.remove(wc.offset()); }
public void onSuccess(WorkContainer<?, ?> wc) { <DeepExtract> return entries.remove(wc.offset()); </DeepExtract> }
parallel-consumer
positive
3,205
@Override public void makeShadow(Backend backend, DefaultCamera2D camera) { if (skel.isCurve()) makeOnCurve(camera, (int) shadowable.theShadowOff.x, (int) shadowable.theShadowOff.y, (int) shadowable.theShadowWidth.x, (int) shadowable.theShadowWidth.y); else if (skel.isPoly()) makeOnPolyline(camera, (int) shadowable.theShadowOff.x, (int) shadowable.theShadowOff.y, (int) shadowable.theShadowWidth.x, (int) shadowable.theShadowWidth.y); else makeOnLine(camera, (int) shadowable.theShadowOff.x, (int) shadowable.theShadowOff.y, (int) shadowable.theShadowWidth.x, (int) shadowable.theShadowWidth.y); }
@Override public void makeShadow(Backend backend, DefaultCamera2D camera) { <DeepExtract> if (skel.isCurve()) makeOnCurve(camera, (int) shadowable.theShadowOff.x, (int) shadowable.theShadowOff.y, (int) shadowable.theShadowWidth.x, (int) shadowable.theShadowWidth.y); else if (skel.isPoly()) makeOnPolyline(camera, (int) shadowable.theShadowOff.x, (int) shadowable.theShadowOff.y, (int) shadowable.theShadowWidth.x, (int) shadowable.theShadowWidth.y); else makeOnLine(camera, (int) shadowable.theShadowOff.x, (int) shadowable.theShadowOff.y, (int) shadowable.theShadowWidth.x, (int) shadowable.theShadowWidth.y); </DeepExtract> }
gs-ui-javafx
positive
3,206
public void setCvRules(Collection<CvRule> cvRules, RuleFilterManager filterManager) { this.getCvRulesInvalidXpath().clear(); this.getCvRulesValid().clear(); this.getCvRulesNotChecked().clear(); this.getCvRulesValidXpath().clear(); for (CvRule rule : cvRules) { if (rule.getStatus().compareTo(MappingRuleStatus.INVALID_XPATH) == 0) this.getCvRulesInvalidXpath().add(rule); else if (rule.getStatus().compareTo(MappingRuleStatus.NOT_CHECKED) == 0) this.getCvRulesNotChecked().add(rule); else if (rule.getStatus().compareTo(MappingRuleStatus.VALID_RULE) == 0) this.getCvRulesValid().add(rule); else if (rule.getStatus().compareTo(MappingRuleStatus.VALID_XPATH) == 0) this.getCvRulesValidXpath().add(rule); } if (filterManager != null) { if (!filterManager.getCvMappingRulesToSkip().isEmpty()) { List<CvRule> toRemove = new ArrayList<CvRule>(); for (String cvRuleId : filterManager.getCvMappingRulesToSkip()) { for (CvRule cvRuleValid : this.getCvRulesValid()) { if (cvRuleValid.getId().equals(cvRuleId)) toRemove.add(cvRuleValid); } } for (CvRule cvRule : toRemove) { this.getCvRulesValid().remove(cvRule); this.getCvRulesNotChecked().add(cvRule); } toRemove.clear(); for (String cvRuleId : filterManager.getCvMappingRulesToSkip()) { for (CvRule cvRuleValidXpath : this.getCvRulesValidXpath()) { if (cvRuleValidXpath.getId().equals(cvRuleId)) toRemove.add(cvRuleValidXpath); } } for (CvRule cvRule : toRemove) { this.getCvRulesValidXpath().remove(cvRule); this.getCvRulesNotChecked().add(cvRule); } } } }
public void setCvRules(Collection<CvRule> cvRules, RuleFilterManager filterManager) { <DeepExtract> this.getCvRulesInvalidXpath().clear(); this.getCvRulesValid().clear(); this.getCvRulesNotChecked().clear(); this.getCvRulesValidXpath().clear(); </DeepExtract> for (CvRule rule : cvRules) { if (rule.getStatus().compareTo(MappingRuleStatus.INVALID_XPATH) == 0) this.getCvRulesInvalidXpath().add(rule); else if (rule.getStatus().compareTo(MappingRuleStatus.NOT_CHECKED) == 0) this.getCvRulesNotChecked().add(rule); else if (rule.getStatus().compareTo(MappingRuleStatus.VALID_RULE) == 0) this.getCvRulesValid().add(rule); else if (rule.getStatus().compareTo(MappingRuleStatus.VALID_XPATH) == 0) this.getCvRulesValidXpath().add(rule); } if (filterManager != null) { if (!filterManager.getCvMappingRulesToSkip().isEmpty()) { List<CvRule> toRemove = new ArrayList<CvRule>(); for (String cvRuleId : filterManager.getCvMappingRulesToSkip()) { for (CvRule cvRuleValid : this.getCvRulesValid()) { if (cvRuleValid.getId().equals(cvRuleId)) toRemove.add(cvRuleValid); } } for (CvRule cvRule : toRemove) { this.getCvRulesValid().remove(cvRule); this.getCvRulesNotChecked().add(cvRule); } toRemove.clear(); for (String cvRuleId : filterManager.getCvMappingRulesToSkip()) { for (CvRule cvRuleValidXpath : this.getCvRulesValidXpath()) { if (cvRuleValidXpath.getId().equals(cvRuleId)) toRemove.add(cvRuleValidXpath); } } for (CvRule cvRule : toRemove) { this.getCvRulesValidXpath().remove(cvRule); this.getCvRulesNotChecked().add(cvRule); } } } }
mzML
positive
3,207
public Profile requestProfileFromFacebook(String profileEmail) { try { Thread.sleep(2500); } catch (InterruptedException ex) { ex.printStackTrace(); } System.out.println("Facebook: Loading profile '" + profileEmail + "' over the network..."); for (Profile profile : profiles) { if (profile.getEmail().equals(profileEmail)) { return profile; } } return null; }
public Profile requestProfileFromFacebook(String profileEmail) { try { Thread.sleep(2500); } catch (InterruptedException ex) { ex.printStackTrace(); } System.out.println("Facebook: Loading profile '" + profileEmail + "' over the network..."); <DeepExtract> for (Profile profile : profiles) { if (profile.getEmail().equals(profileEmail)) { return profile; } } return null; </DeepExtract> }
design-pattern-examples
positive
3,208
@Override public void addBatchMenuItemIds(Long roleId, List<Long> menuItemIdList) { List<RoleAuthMid> roleAuthMidList = new ArrayList<>(); menuItemIdList.forEach(menuItemId -> { RoleAuthMid roleAuthMid = new RoleAuthMid(); roleAuthMid.setRoleId(roleId); roleAuthMid.setMenuItemId(menuItemId); roleAuthMidList.add(roleAuthMid); }); roleAuthMidMapper.insertBatch(roleAuthMidList); }
@Override public void addBatchMenuItemIds(Long roleId, List<Long> menuItemIdList) { List<RoleAuthMid> roleAuthMidList = new ArrayList<>(); menuItemIdList.forEach(menuItemId -> { RoleAuthMid roleAuthMid = new RoleAuthMid(); roleAuthMid.setRoleId(roleId); roleAuthMid.setMenuItemId(menuItemId); roleAuthMidList.add(roleAuthMid); }); <DeepExtract> roleAuthMidMapper.insertBatch(roleAuthMidList); </DeepExtract> }
liteflow
positive
3,209
protected void ceilBlack(PGraphics pg) { String ceilAlpha = "ceilBlack.glsl"; hotShader(ceilAlpha, null, true, pg); }
protected void ceilBlack(PGraphics pg) { String ceilAlpha = "ceilBlack.glsl"; <DeepExtract> hotShader(ceilAlpha, null, true, pg); </DeepExtract> }
ProcessingSketches
positive
3,210
public void onPrepareSubMenu(SubMenu subMenu) { SharedPreferences sp = getSharedPreferences("org.openintents.shopping_preferences", MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); int list_id = new Long(getSelectedListId()).intValue(); if (list_id != -1) { editor.putInt(PreferenceActivity.PREFS_LASTUSED, list_id); } int listposition = mItemsView.getFirstVisiblePosition(); if (false) { View v = mItemsView.getChildAt(0); int listtop = (v == null) ? 0 : v.getTop(); if (debug) { Log.d(TAG, "Save list position: pos: " + listposition + ", top: " + listtop); } editor.putInt(PreferenceActivity.PREFS_LASTLIST_POSITION, listposition); editor.putInt(PreferenceActivity.PREFS_LASTLIST_TOP, listtop); } editor.commit(); subMenu.clear(); int curSort = PreferenceActivity.getSortOrderIndexFromPrefs(mContext, MODE_IN_SHOP); for (i = 0; i < mSortLabels.length; i++) { subMenu.add(1, i, i, mSortLabels[i]).setOnMenuItemClickListener(this).setChecked(mSortValInts[i] == curSort); } subMenu.setGroupCheckable(1, true, true); }
public void onPrepareSubMenu(SubMenu subMenu) { <DeepExtract> SharedPreferences sp = getSharedPreferences("org.openintents.shopping_preferences", MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); int list_id = new Long(getSelectedListId()).intValue(); if (list_id != -1) { editor.putInt(PreferenceActivity.PREFS_LASTUSED, list_id); } int listposition = mItemsView.getFirstVisiblePosition(); if (false) { View v = mItemsView.getChildAt(0); int listtop = (v == null) ? 0 : v.getTop(); if (debug) { Log.d(TAG, "Save list position: pos: " + listposition + ", top: " + listtop); } editor.putInt(PreferenceActivity.PREFS_LASTLIST_POSITION, listposition); editor.putInt(PreferenceActivity.PREFS_LASTLIST_TOP, listtop); } editor.commit(); </DeepExtract> subMenu.clear(); int curSort = PreferenceActivity.getSortOrderIndexFromPrefs(mContext, MODE_IN_SHOP); for (i = 0; i < mSortLabels.length; i++) { subMenu.add(1, i, i, mSortLabels[i]).setOnMenuItemClickListener(this).setChecked(mSortValInts[i] == curSort); } subMenu.setGroupCheckable(1, true, true); }
shoppinglist
positive
3,211
private void onContextMenuAppendToPlayQ(final int position) { YTPlayer.Video vid = getAdapter().getYTPlayerVideo(position); mMp.appendToPlayQ(new YTPlayer.Video[] { vid }); }
private void onContextMenuAppendToPlayQ(final int position) { YTPlayer.Video vid = getAdapter().getYTPlayerVideo(position); <DeepExtract> mMp.appendToPlayQ(new YTPlayer.Video[] { vid }); </DeepExtract> }
netmbuddy
positive
3,212
public static Driver driver() { if (driver != null && !driver.disposed()) { if (driverType == driver.getClass()) return; driver.dispose(); } driver = new ActivatorDriverFactory().newWebDriver(driverType, browser); root = null; return driver; }
public static Driver driver() { <DeepExtract> if (driver != null && !driver.disposed()) { if (driverType == driver.getClass()) return; driver.dispose(); } driver = new ActivatorDriverFactory().newWebDriver(driverType, browser); root = null; </DeepExtract> return driver; }
coypu-jvm
positive
3,213
@Override public void insertUpdate(DocumentEvent e) { String name = this.ObjectNameTextField.getText().trim(); String copyObjectName = this.CopyFromTextField.getText(); if (name != null && !name.isEmpty() && name.length() > 0 && name.length() <= MQConstants.MQ_Q_NAME_LENGTH && copyObjectName != null && !copyObjectName.isEmpty()) { this.FinishButton.setEnabled(true); this.NextButton.setEnabled(true); } else { this.FinishButton.setEnabled(false); this.NextButton.setEnabled(false); } }
@Override public void insertUpdate(DocumentEvent e) { <DeepExtract> String name = this.ObjectNameTextField.getText().trim(); String copyObjectName = this.CopyFromTextField.getText(); if (name != null && !name.isEmpty() && name.length() > 0 && name.length() <= MQConstants.MQ_Q_NAME_LENGTH && copyObjectName != null && !copyObjectName.isEmpty()) { this.FinishButton.setEnabled(true); this.NextButton.setEnabled(true); } else { this.FinishButton.setEnabled(false); this.NextButton.setEnabled(false); } </DeepExtract> }
MQAdminTool
positive
3,214
private Location[] getLocationData(HttpsURLConnection connection) throws IOException { log.debug("Getting current server application version"); final JsonArray asJsonArray = ConnectionUtils.getJsonRootElementFromConnection(connection).getAsJsonArray(); ArrayList<Location> locations = new ArrayList<>(); for (int i = 0; i < asJsonArray.size(); i++) { JsonObject element = asJsonArray.get(i).getAsJsonObject(); locations.add(getLocationFromElement(element)); } return locations.toArray(new Location[0]); }
private Location[] getLocationData(HttpsURLConnection connection) throws IOException { log.debug("Getting current server application version"); final JsonArray asJsonArray = ConnectionUtils.getJsonRootElementFromConnection(connection).getAsJsonArray(); <DeepExtract> ArrayList<Location> locations = new ArrayList<>(); for (int i = 0; i < asJsonArray.size(); i++) { JsonObject element = asJsonArray.get(i).getAsJsonObject(); locations.add(getLocationFromElement(element)); } return locations.toArray(new Location[0]); </DeepExtract> }
WeblocOpener
positive
3,215
public void loadSounds() { if (!cc.settings.sounds) { return; } InputStream inputStream = SoundProvider.class.getResourceAsStream("/sound/block_placed.wav"); Player player = null; try { player = Manager.createPlayer(inputStream, MusicPlayer.getContentType("/sound/block_placed.wav")); } catch (IOException ex) { } catch (MediaException ex) { } soundsList.put("/sound/block_placed.wav", player); soundsLoaded = true; }
public void loadSounds() { if (!cc.settings.sounds) { return; } <DeepExtract> InputStream inputStream = SoundProvider.class.getResourceAsStream("/sound/block_placed.wav"); Player player = null; try { player = Manager.createPlayer(inputStream, MusicPlayer.getContentType("/sound/block_placed.wav")); } catch (IOException ex) { } catch (MediaException ex) { } soundsList.put("/sound/block_placed.wav", player); </DeepExtract> soundsLoaded = true; }
Comcraft
positive
3,216
public DynamicByteBuffer putAt(int index, byte v) { int end = index + 1; if (index < 0 || end > _buf.limit()) { throw new IndexOutOfBoundsException(); } _buf.put(index, v); return this; }
public DynamicByteBuffer putAt(int index, byte v) { <DeepExtract> int end = index + 1; if (index < 0 || end > _buf.limit()) { throw new IndexOutOfBoundsException(); } </DeepExtract> _buf.put(index, v); return this; }
netx
positive
3,217
private void handleBlocksInfoResponse(BlocksInfoResponse blocksInfo) { HashMap<String, BlockInfoItem> blocks = blocksInfo.getBlocks(); if (blocks.size() != 1) { ExceptionHandler.handle(new Exception("unexpected amount of blocks in blocks_info response")); requestQueue.poll(); return; } String hash = blocks.keySet().iterator().next(); BlockInfoItem blockInfo = blocks.get(hash); BlockItem block = gson.fromJson(blockInfo.getContents(), BlockItem.class); if (block.getType().equals(BlockTypes.STATE.toString())) { String calculatedHash = KaliumUtil.computeStateHash(block.getAccount(), block.getPrevious(), block.getRepresentative(), block.getBalance(), block.getLink()); if (!blockInfo.getBalance().equals(block.getBalance())) { ExceptionHandler.handle(new Exception("balance in state block doesn't match balance in block info")); requestQueue.poll(); return; } if (!hash.equals(calculatedHash)) { ExceptionHandler.handle(new Exception("balance in state block doesn't match balance in block info")); ExceptionHandler.handle(new Exception("state block hash doesn't match hash from block info")); requestQueue.poll(); return; } } else if (block.getType().equals(BlockTypes.SEND.toString())) { String calculatedHash = KaliumUtil.computeSendHash(block.getPrevious(), KaliumUtil.addressToPublic(block.getDestination()), block.getBalance()); if (!blockInfo.getBalance().equals(NumberUtil.getRawFromHex(block.getBalance()))) { ExceptionHandler.handle(new Exception("balance in send block doesn't match balance in block info")); requestQueue.poll(); return; } if (!hash.equals(calculatedHash)) { ExceptionHandler.handle(new Exception("send block hash doesn't match hash from block info")); requestQueue.poll(); return; } } else if (block.getType().equals(BlockTypes.RECEIVE.toString())) { String calculatedHash = KaliumUtil.computeReceiveHash(block.getPrevious(), block.getSource()); if (!hash.equals(calculatedHash)) { ExceptionHandler.handle(new Exception("receive block hash doesn't match hash from block info")); requestQueue.poll(); return; } } else if (block.getType().equals(BlockTypes.OPEN.toString())) { String calculatedHash = KaliumUtil.computeOpenHash(block.getSource(), KaliumUtil.addressToPublic(block.getRepresentative()), KaliumUtil.addressToPublic(block.getAccount())); if (!hash.equals(calculatedHash)) { ExceptionHandler.handle(new Exception("open block hash doesn't match hash from block info")); requestQueue.poll(); return; } } else if (block.getType().equals(BlockTypes.CHANGE.toString())) { String calculatedHash = KaliumUtil.computeChangeHash(block.getPrevious(), KaliumUtil.addressToPublic(block.getRepresentative())); if (!hash.equals(calculatedHash)) { ExceptionHandler.handle(new Exception("change block hash doesn't match hash from block info")); requestQueue.poll(); return; } } else { ExceptionHandler.handle(new Exception("unexpected block type " + block.getType())); requestQueue.poll(); return; } RequestItem lastRequest = requestQueue.poll(); StateBlock nextBlock = previousPendingMap.get(hash); if (nextBlock != null) { if (block.getRepresentative() != null) { nextBlock.setRepresentative(block.getRepresentative()); } nextBlock.setPrevious(hash); if (nextBlock.getInternal_block_type() == BlockTypes.SEND) { if (nextBlock.getSendAmount().equals("0")) { nextBlock.setBalance("0"); } else { nextBlock.setBalance(new BigInteger(blockInfo.getBalance()).subtract(new BigInteger(nextBlock.getSendAmount())).toString()); } } else { nextBlock.setBalance(new BigInteger(blockInfo.getBalance()).add(new BigInteger(nextBlock.getSendAmount())).toString()); } previousPendingMap.remove(hash); ProcessRequest prq = new ProcessRequest(gson.toJson(nextBlock), true); RequestItem<ProcessRequest> requestItem = new RequestItem<>(prq); if (lastRequest.isFromTransfer()) { requestItem.setFromTransfer(true); } pendingResponseBlockMap.put(nextBlock.getPrevious(), nextBlock); requestQueue.add(requestItem); } if (requestQueue != null && requestQueue.size() > 0) { RequestItem requestItem = requestQueue.peek(); if (requestItem != null && !requestItem.isProcessing()) { if (wsDisconnected()) { if (!isConnecting) { initWebSocket(); } return; } requestItem.setProcessing(true); Timber.d("SEND: %s", gson.toJson(requestItem.getRequest())); wsSend(gson.toJson(requestItem.getRequest())); } else if (requestItem != null && (requestItem.isProcessing() && System.currentTimeMillis() > requestItem.getExpireTime())) { requestQueue.poll(); processQueue(); } } }
private void handleBlocksInfoResponse(BlocksInfoResponse blocksInfo) { HashMap<String, BlockInfoItem> blocks = blocksInfo.getBlocks(); if (blocks.size() != 1) { ExceptionHandler.handle(new Exception("unexpected amount of blocks in blocks_info response")); requestQueue.poll(); return; } String hash = blocks.keySet().iterator().next(); BlockInfoItem blockInfo = blocks.get(hash); BlockItem block = gson.fromJson(blockInfo.getContents(), BlockItem.class); if (block.getType().equals(BlockTypes.STATE.toString())) { String calculatedHash = KaliumUtil.computeStateHash(block.getAccount(), block.getPrevious(), block.getRepresentative(), block.getBalance(), block.getLink()); if (!blockInfo.getBalance().equals(block.getBalance())) { ExceptionHandler.handle(new Exception("balance in state block doesn't match balance in block info")); requestQueue.poll(); return; } if (!hash.equals(calculatedHash)) { ExceptionHandler.handle(new Exception("balance in state block doesn't match balance in block info")); ExceptionHandler.handle(new Exception("state block hash doesn't match hash from block info")); requestQueue.poll(); return; } } else if (block.getType().equals(BlockTypes.SEND.toString())) { String calculatedHash = KaliumUtil.computeSendHash(block.getPrevious(), KaliumUtil.addressToPublic(block.getDestination()), block.getBalance()); if (!blockInfo.getBalance().equals(NumberUtil.getRawFromHex(block.getBalance()))) { ExceptionHandler.handle(new Exception("balance in send block doesn't match balance in block info")); requestQueue.poll(); return; } if (!hash.equals(calculatedHash)) { ExceptionHandler.handle(new Exception("send block hash doesn't match hash from block info")); requestQueue.poll(); return; } } else if (block.getType().equals(BlockTypes.RECEIVE.toString())) { String calculatedHash = KaliumUtil.computeReceiveHash(block.getPrevious(), block.getSource()); if (!hash.equals(calculatedHash)) { ExceptionHandler.handle(new Exception("receive block hash doesn't match hash from block info")); requestQueue.poll(); return; } } else if (block.getType().equals(BlockTypes.OPEN.toString())) { String calculatedHash = KaliumUtil.computeOpenHash(block.getSource(), KaliumUtil.addressToPublic(block.getRepresentative()), KaliumUtil.addressToPublic(block.getAccount())); if (!hash.equals(calculatedHash)) { ExceptionHandler.handle(new Exception("open block hash doesn't match hash from block info")); requestQueue.poll(); return; } } else if (block.getType().equals(BlockTypes.CHANGE.toString())) { String calculatedHash = KaliumUtil.computeChangeHash(block.getPrevious(), KaliumUtil.addressToPublic(block.getRepresentative())); if (!hash.equals(calculatedHash)) { ExceptionHandler.handle(new Exception("change block hash doesn't match hash from block info")); requestQueue.poll(); return; } } else { ExceptionHandler.handle(new Exception("unexpected block type " + block.getType())); requestQueue.poll(); return; } RequestItem lastRequest = requestQueue.poll(); StateBlock nextBlock = previousPendingMap.get(hash); if (nextBlock != null) { if (block.getRepresentative() != null) { nextBlock.setRepresentative(block.getRepresentative()); } nextBlock.setPrevious(hash); if (nextBlock.getInternal_block_type() == BlockTypes.SEND) { if (nextBlock.getSendAmount().equals("0")) { nextBlock.setBalance("0"); } else { nextBlock.setBalance(new BigInteger(blockInfo.getBalance()).subtract(new BigInteger(nextBlock.getSendAmount())).toString()); } } else { nextBlock.setBalance(new BigInteger(blockInfo.getBalance()).add(new BigInteger(nextBlock.getSendAmount())).toString()); } previousPendingMap.remove(hash); ProcessRequest prq = new ProcessRequest(gson.toJson(nextBlock), true); RequestItem<ProcessRequest> requestItem = new RequestItem<>(prq); if (lastRequest.isFromTransfer()) { requestItem.setFromTransfer(true); } pendingResponseBlockMap.put(nextBlock.getPrevious(), nextBlock); requestQueue.add(requestItem); } <DeepExtract> if (requestQueue != null && requestQueue.size() > 0) { RequestItem requestItem = requestQueue.peek(); if (requestItem != null && !requestItem.isProcessing()) { if (wsDisconnected()) { if (!isConnecting) { initWebSocket(); } return; } requestItem.setProcessing(true); Timber.d("SEND: %s", gson.toJson(requestItem.getRequest())); wsSend(gson.toJson(requestItem.getRequest())); } else if (requestItem != null && (requestItem.isProcessing() && System.currentTimeMillis() > requestItem.getExpireTime())) { requestQueue.poll(); processQueue(); } } </DeepExtract> }
kalium-android-wallet
positive
3,219
public Value setAsTemperature(float v) { this.asDouble = v; age = System.currentTimeMillis(); valid = true; type = ValueType.TEMPERATURE; invalidateViews(); return this; }
public Value setAsTemperature(float v) { <DeepExtract> this.asDouble = v; age = System.currentTimeMillis(); valid = true; type = ValueType.TEMPERATURE; invalidateViews(); return this; </DeepExtract> }
EucWorldAndroid
positive
3,220
@Override public void onParseResult(UpdateEntity updateEntity) { if (updateEntity != null) { updateEntity.setApkCacheDir(mApkCacheDir); updateEntity.setIsAutoMode(mIsAutoMode); updateEntity.setIUpdateHttpService(mIUpdateHttpService); } return updateEntity; callback.onParseResult(updateEntity); }
@Override public void onParseResult(UpdateEntity updateEntity) { <DeepExtract> if (updateEntity != null) { updateEntity.setApkCacheDir(mApkCacheDir); updateEntity.setIsAutoMode(mIsAutoMode); updateEntity.setIUpdateHttpService(mIUpdateHttpService); } return updateEntity; </DeepExtract> callback.onParseResult(updateEntity); }
XUpdate
positive
3,221
public static void main(String[] args) { SpringApplication springApplication = new SpringApplication(Application.class); springApplication.run(args); log.trace("Trace Message!"); log.debug("Debug Message!"); log.info("Info Message!"); log.warn("Warn Message!"); log.error("Error Message!"); log.fatal("Fatal Message!"); }
public static void main(String[] args) { SpringApplication springApplication = new SpringApplication(Application.class); springApplication.run(args); <DeepExtract> log.trace("Trace Message!"); log.debug("Debug Message!"); log.info("Info Message!"); log.warn("Warn Message!"); log.error("Error Message!"); log.fatal("Fatal Message!"); </DeepExtract> }
tech1-temple-java
positive
3,222
@Override public boolean isRootFilter() { return (concreteType.getClassHierarchy().getRootClass() instanceof SingleClassFilter) && ((SingleClassFilter) concreteType.getClassHierarchy().getRootClass()).getConcreteType().equals(concreteType); }
@Override public boolean isRootFilter() { <DeepExtract> return (concreteType.getClassHierarchy().getRootClass() instanceof SingleClassFilter) && ((SingleClassFilter) concreteType.getClassHierarchy().getRootClass()).getConcreteType().equals(concreteType); </DeepExtract> }
Incremental_Points_to_Analysis
positive
3,223
public void openTeamShop(Player player) { if (!Config.teamshop_enabled) { return; } if (game.getState() != GameState.RUNNING || BedwarsUtil.isSpectator(game, player) || player.getGameMode() == GameMode.SPECTATOR) { return; } int trap_amount = 0; for (UpgradeType type : Config.teamshop_upgrade_enabled.keySet()) { if (Config.teamshop_upgrade_enabled.get(type) && type.isTrap()) { trap_amount++; } } Inventory inventory = Bukkit.createInventory(null, trap_amount > 0 ? 45 : 27, Config.teamshop_upgrade_shop_title); inventory.clear(); int slot = 10; int trap_amount = 0; for (UpgradeType type : Config.teamshop_upgrade_enabled.keySet()) { if (Config.teamshop_upgrade_enabled.get(type)) { if (type.isTrap()) { trap_amount++; continue; } ItemStack itemStack = ItemUtil.createItem(Config.teamshop_upgrade_item.get(type)); ItemMeta itemMeta = itemStack.getItemMeta(); itemMeta.setDisplayName(getStateColor(player, type) + Config.teamshop_upgrade_name.get(type)); itemMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_POTION_EFFECTS); itemMeta.setLore(Config.teamshop_upgrade_level_lore.get(type).get(getPlayerTeamUpgradeLevel(player, type) + 1)); itemMeta.setLore(replaceLore(itemMeta.getLore(), "{state}", getState(player, type))); itemStack.setItemMeta(itemMeta); inventory.setItem(slot, itemStack); slot++; } } if (trap_amount > 0) { ItemStack glasspane = new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 7); ItemUtil.setItemName(glasspane, getItemName(Config.teamshop_upgrade_shop_frame)); ItemUtil.setItemLore(glasspane, getItemLore(Config.teamshop_upgrade_shop_frame)); inventory.setItem(18, glasspane); inventory.setItem(19, glasspane); inventory.setItem(20, glasspane); inventory.setItem(21, glasspane); inventory.setItem(22, glasspane); inventory.setItem(23, glasspane); inventory.setItem(24, glasspane); inventory.setItem(25, glasspane); inventory.setItem(26, glasspane); List<Upgrade> list = upgrades_trap.getOrDefault(game.getPlayerTeam(player), new ArrayList<Upgrade>()); int size = list.size(); ItemStack traps = new ItemStack(Material.valueOf(Config.teamshop_upgrade_shop_trap_item)); ItemUtil.setItemName(traps, Config.teamshop_upgrade_shop_trap_name); ItemUtil.setItemLore(traps, Config.teamshop_upgrade_shop_trap_lore); inventory.setItem(slot, traps); ItemStack trap = new ItemStack(Material.STAINED_GLASS, 1, (short) 8); int lev = size; lev = lev > 2 ? 2 : lev; String next_cost = Config.teamshop_trap_level_cost.get(lev + 1).split(",")[1]; if (size > 0) { Upgrade upgrade = list.get(0); trap.setType(Material.valueOf(Config.teamshop_upgrade_item.get(upgrade.getType()))); trap.setDurability((short) 0); ItemUtil.setItemName(trap, getItemName(Config.teamshop_trap_trap_list_trap_1_unlock).replace("{trap}", upgrade.getName()).replace("{buyer}", upgrade.getBuyer()).replace("{cost}", next_cost)); ItemUtil.setItemLore(trap, replaceLore(getItemLore(Config.teamshop_trap_trap_list_trap_1_unlock), "{trap}", upgrade.getName(), "{buyer}", upgrade.getBuyer(), "{cost}", next_cost)); } else { ItemUtil.setItemName(trap, getItemName(Config.teamshop_trap_trap_list_trap_1_lock).replace("{cost}", next_cost)); ItemUtil.setItemLore(trap, replaceLore(getItemLore(Config.teamshop_trap_trap_list_trap_1_lock), "{cost}", next_cost)); } ItemUtil.addItemFlags(trap, ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_POTION_EFFECTS); inventory.setItem(30, trap); trap = new ItemStack(Material.STAINED_GLASS, 1, (short) 8); if (size > 1) { Upgrade upgrade = list.get(1); trap.setType(Material.valueOf(Config.teamshop_upgrade_item.get(upgrade.getType()))); trap.setDurability((short) 0); ItemUtil.setItemName(trap, getItemName(Config.teamshop_trap_trap_list_trap_2_unlock).replace("{trap}", upgrade.getName()).replace("{buyer}", upgrade.getBuyer()).replace("{cost}", next_cost)); ItemUtil.setItemLore(trap, replaceLore(getItemLore(Config.teamshop_trap_trap_list_trap_2_unlock), "{trap}", upgrade.getName(), "{buyer}", upgrade.getBuyer(), "{cost}", next_cost)); } else { ItemUtil.setItemName(trap, getItemName(Config.teamshop_trap_trap_list_trap_2_lock).replace("{cost}", next_cost)); ItemUtil.setItemLore(trap, replaceLore(getItemLore(Config.teamshop_trap_trap_list_trap_2_lock), "{cost}", next_cost)); } ItemUtil.addItemFlags(trap, ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_POTION_EFFECTS); inventory.setItem(31, trap); trap = new ItemStack(Material.STAINED_GLASS, 1, (short) 8); if (size > 2) { Upgrade upgrade = list.get(2); trap.setType(Material.valueOf(Config.teamshop_upgrade_item.get(upgrade.getType()))); trap.setDurability((short) 0); ItemUtil.setItemName(trap, getItemName(Config.teamshop_trap_trap_list_trap_3_unlock).replace("{trap}", upgrade.getName()).replace("{buyer}", upgrade.getBuyer()).replace("{cost}", next_cost)); ItemUtil.setItemLore(trap, replaceLore(getItemLore(Config.teamshop_trap_trap_list_trap_3_unlock), "{trap}", upgrade.getName(), "{buyer}", upgrade.getBuyer(), "{cost}", next_cost)); } else { ItemUtil.setItemName(trap, getItemName(Config.teamshop_trap_trap_list_trap_3_lock).replace("{cost}", next_cost)); ItemUtil.setItemLore(trap, replaceLore(getItemLore(Config.teamshop_trap_trap_list_trap_3_lock), "{cost}", next_cost)); } ItemUtil.addItemFlags(trap, ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_POTION_EFFECTS); inventory.setItem(32, trap); } player.updateInventory(); player.closeInventory(); player.openInventory(inventory); Main.getInstance().getMenuManager().addPlayer(player, MenuType.TEAM_SHOP, inventory); }
public void openTeamShop(Player player) { if (!Config.teamshop_enabled) { return; } if (game.getState() != GameState.RUNNING || BedwarsUtil.isSpectator(game, player) || player.getGameMode() == GameMode.SPECTATOR) { return; } int trap_amount = 0; for (UpgradeType type : Config.teamshop_upgrade_enabled.keySet()) { if (Config.teamshop_upgrade_enabled.get(type) && type.isTrap()) { trap_amount++; } } Inventory inventory = Bukkit.createInventory(null, trap_amount > 0 ? 45 : 27, Config.teamshop_upgrade_shop_title); <DeepExtract> inventory.clear(); int slot = 10; int trap_amount = 0; for (UpgradeType type : Config.teamshop_upgrade_enabled.keySet()) { if (Config.teamshop_upgrade_enabled.get(type)) { if (type.isTrap()) { trap_amount++; continue; } ItemStack itemStack = ItemUtil.createItem(Config.teamshop_upgrade_item.get(type)); ItemMeta itemMeta = itemStack.getItemMeta(); itemMeta.setDisplayName(getStateColor(player, type) + Config.teamshop_upgrade_name.get(type)); itemMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_POTION_EFFECTS); itemMeta.setLore(Config.teamshop_upgrade_level_lore.get(type).get(getPlayerTeamUpgradeLevel(player, type) + 1)); itemMeta.setLore(replaceLore(itemMeta.getLore(), "{state}", getState(player, type))); itemStack.setItemMeta(itemMeta); inventory.setItem(slot, itemStack); slot++; } } if (trap_amount > 0) { ItemStack glasspane = new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 7); ItemUtil.setItemName(glasspane, getItemName(Config.teamshop_upgrade_shop_frame)); ItemUtil.setItemLore(glasspane, getItemLore(Config.teamshop_upgrade_shop_frame)); inventory.setItem(18, glasspane); inventory.setItem(19, glasspane); inventory.setItem(20, glasspane); inventory.setItem(21, glasspane); inventory.setItem(22, glasspane); inventory.setItem(23, glasspane); inventory.setItem(24, glasspane); inventory.setItem(25, glasspane); inventory.setItem(26, glasspane); List<Upgrade> list = upgrades_trap.getOrDefault(game.getPlayerTeam(player), new ArrayList<Upgrade>()); int size = list.size(); ItemStack traps = new ItemStack(Material.valueOf(Config.teamshop_upgrade_shop_trap_item)); ItemUtil.setItemName(traps, Config.teamshop_upgrade_shop_trap_name); ItemUtil.setItemLore(traps, Config.teamshop_upgrade_shop_trap_lore); inventory.setItem(slot, traps); ItemStack trap = new ItemStack(Material.STAINED_GLASS, 1, (short) 8); int lev = size; lev = lev > 2 ? 2 : lev; String next_cost = Config.teamshop_trap_level_cost.get(lev + 1).split(",")[1]; if (size > 0) { Upgrade upgrade = list.get(0); trap.setType(Material.valueOf(Config.teamshop_upgrade_item.get(upgrade.getType()))); trap.setDurability((short) 0); ItemUtil.setItemName(trap, getItemName(Config.teamshop_trap_trap_list_trap_1_unlock).replace("{trap}", upgrade.getName()).replace("{buyer}", upgrade.getBuyer()).replace("{cost}", next_cost)); ItemUtil.setItemLore(trap, replaceLore(getItemLore(Config.teamshop_trap_trap_list_trap_1_unlock), "{trap}", upgrade.getName(), "{buyer}", upgrade.getBuyer(), "{cost}", next_cost)); } else { ItemUtil.setItemName(trap, getItemName(Config.teamshop_trap_trap_list_trap_1_lock).replace("{cost}", next_cost)); ItemUtil.setItemLore(trap, replaceLore(getItemLore(Config.teamshop_trap_trap_list_trap_1_lock), "{cost}", next_cost)); } ItemUtil.addItemFlags(trap, ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_POTION_EFFECTS); inventory.setItem(30, trap); trap = new ItemStack(Material.STAINED_GLASS, 1, (short) 8); if (size > 1) { Upgrade upgrade = list.get(1); trap.setType(Material.valueOf(Config.teamshop_upgrade_item.get(upgrade.getType()))); trap.setDurability((short) 0); ItemUtil.setItemName(trap, getItemName(Config.teamshop_trap_trap_list_trap_2_unlock).replace("{trap}", upgrade.getName()).replace("{buyer}", upgrade.getBuyer()).replace("{cost}", next_cost)); ItemUtil.setItemLore(trap, replaceLore(getItemLore(Config.teamshop_trap_trap_list_trap_2_unlock), "{trap}", upgrade.getName(), "{buyer}", upgrade.getBuyer(), "{cost}", next_cost)); } else { ItemUtil.setItemName(trap, getItemName(Config.teamshop_trap_trap_list_trap_2_lock).replace("{cost}", next_cost)); ItemUtil.setItemLore(trap, replaceLore(getItemLore(Config.teamshop_trap_trap_list_trap_2_lock), "{cost}", next_cost)); } ItemUtil.addItemFlags(trap, ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_POTION_EFFECTS); inventory.setItem(31, trap); trap = new ItemStack(Material.STAINED_GLASS, 1, (short) 8); if (size > 2) { Upgrade upgrade = list.get(2); trap.setType(Material.valueOf(Config.teamshop_upgrade_item.get(upgrade.getType()))); trap.setDurability((short) 0); ItemUtil.setItemName(trap, getItemName(Config.teamshop_trap_trap_list_trap_3_unlock).replace("{trap}", upgrade.getName()).replace("{buyer}", upgrade.getBuyer()).replace("{cost}", next_cost)); ItemUtil.setItemLore(trap, replaceLore(getItemLore(Config.teamshop_trap_trap_list_trap_3_unlock), "{trap}", upgrade.getName(), "{buyer}", upgrade.getBuyer(), "{cost}", next_cost)); } else { ItemUtil.setItemName(trap, getItemName(Config.teamshop_trap_trap_list_trap_3_lock).replace("{cost}", next_cost)); ItemUtil.setItemLore(trap, replaceLore(getItemLore(Config.teamshop_trap_trap_list_trap_3_lock), "{cost}", next_cost)); } ItemUtil.addItemFlags(trap, ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_POTION_EFFECTS); inventory.setItem(32, trap); } player.updateInventory(); </DeepExtract> player.closeInventory(); player.openInventory(inventory); Main.getInstance().getMenuManager().addPlayer(player, MenuType.TEAM_SHOP, inventory); }
BedwarsScoreBoardAddon
positive
3,224
public void putString(String paramString1, String paramString2) { return super.put(paramString1, paramString2); }
public void putString(String paramString1, String paramString2) { <DeepExtract> return super.put(paramString1, paramString2); </DeepExtract> }
RePlugin-GameSdk
positive
3,225
public Criteria andIntervalIdIsNull() { if ("interval_id is null" == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion("interval_id is null")); return (Criteria) this; }
public Criteria andIntervalIdIsNull() { <DeepExtract> if ("interval_id is null" == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion("interval_id is null")); </DeepExtract> return (Criteria) this; }
emotional_analysis
positive
3,226
public void setMaxFieldSize(int max) throws SQLException { String methodCall = "setMaxFieldSize(" + max + ")"; try { realStatement.setMaxFieldSize(max); } catch (SQLException s) { reportException(methodCall, s); throw s; } reportAllReturns(methodCall, ""); }
public void setMaxFieldSize(int max) throws SQLException { String methodCall = "setMaxFieldSize(" + max + ")"; try { realStatement.setMaxFieldSize(max); } catch (SQLException s) { reportException(methodCall, s); throw s; } <DeepExtract> reportAllReturns(methodCall, ""); </DeepExtract> }
miniprofiler-jvm
positive
3,227
@Override public void onItemRangeInserted(int positionStart, int itemCount) { super.onItemRangeInserted(positionStart, itemCount); emptyView.setVisibility(adapter.getItemCount() > 0 ? View.VISIBLE : View.GONE); emptyView.setVisibility(adapter.getItemCount() == 0 ? View.VISIBLE : View.GONE); }
@Override public void onItemRangeInserted(int positionStart, int itemCount) { super.onItemRangeInserted(positionStart, itemCount); <DeepExtract> emptyView.setVisibility(adapter.getItemCount() > 0 ? View.VISIBLE : View.GONE); emptyView.setVisibility(adapter.getItemCount() == 0 ? View.VISIBLE : View.GONE); </DeepExtract> }
motioneye-client
positive
3,228
public void deleteNodeProperty(long nodeId, String key) throws NodeNotFoundException, PropertyNotFoundException, DatabaseException, ConfigurationException { Node node = getNode(nodeId); return node.getProperty(key); getDao().deleteNodeProperty(nodeId, key); graph.deleteNodeProperty(nodeId, key); }
public void deleteNodeProperty(long nodeId, String key) throws NodeNotFoundException, PropertyNotFoundException, DatabaseException, ConfigurationException { <DeepExtract> Node node = getNode(nodeId); return node.getProperty(key); </DeepExtract> getDao().deleteNodeProperty(nodeId, key); graph.deleteNodeProperty(nodeId, key); }
Policy-Machine
positive
3,229
public <V> Builder readMap(Key<PMap<String, V>> key, String fieldName, BsonDeserialiser<? extends V> valueDeserialiser) { Function<Map<String, BsonValue>, Optional<Value>> keyValueReader = (m) -> { BsonValue v = m.get(fieldName); return (null == v) ? Optional.empty() : Optional.of(key.of(BsonMapDeserialiser.readingValuesWith(valueDeserialiser).apply(v))); }; deserialiserMap.put(key, keyValueReader); return this; }
public <V> Builder readMap(Key<PMap<String, V>> key, String fieldName, BsonDeserialiser<? extends V> valueDeserialiser) { <DeepExtract> Function<Map<String, BsonValue>, Optional<Value>> keyValueReader = (m) -> { BsonValue v = m.get(fieldName); return (null == v) ? Optional.empty() : Optional.of(key.of(BsonMapDeserialiser.readingValuesWith(valueDeserialiser).apply(v))); }; deserialiserMap.put(key, keyValueReader); return this; </DeepExtract> }
octarine
positive
3,230
public static void fixUnassigned(Admin admin, RegionInfo region) throws IOException, KeeperException, InterruptedException { admin.assign(region.getRegionName()); }
public static void fixUnassigned(Admin admin, RegionInfo region) throws IOException, KeeperException, InterruptedException { <DeepExtract> admin.assign(region.getRegionName()); </DeepExtract> }
hbase-operator-tools
positive
3,231
public void start(ModelDef[] modelList, Configuration conf) { Set<String> columnSet = new HashSet<String>(); Map<String, Set<String>> usedInTable = new HashMap<String, Set<String>>(); Set<String> uniquetableSet = new HashSet<String>(); for (int i = 0; i < modelList.length; i++) { ModelDef modeldef = modelList[i]; uniquetableSet.add(modeldef.getTableName()); List<String> attrList = Arrays.asList(modeldef.getAttributes()); for (String att : attrList) { columnSet.add(att); if (usedInTable.containsKey(att)) { usedInTable.get(att).add(modeldef.getModelName()); } else { HashSet<String> tableSet = new HashSet<String>(); tableSet.add(modeldef.getModelName()); usedInTable.put(att, tableSet); } } } List<String> orderedList = new ArrayList<String>(); for (String table : uniquetableSet) { orderedList.add(table); } SourceWriter sw = new StringSourceWriter(); sw.lnprint("package " + conf.metaDataPackageName + ";"); sw.lnprint(); sw.lnprint("/***"); sw.lnprint("* This is automatically generated by DAOGenerator, based on the database table schema"); sw.lnprint("* "); sw.lnprint("* "); sw.lnprint("*/"); sw.lnprint(); sw.lnprint("public class " + "Table" + "{"); for (String table : orderedList) { sw.lnTabPrint("public final static String " + table + " = \"" + table + "\";"); } sw.lnprint(""); sw.lnprint("}"); FileUtil.writeToFile(sw.toString(), conf.metaDataDirectory, "Table" + ".java"); }
public void start(ModelDef[] modelList, Configuration conf) { Set<String> columnSet = new HashSet<String>(); Map<String, Set<String>> usedInTable = new HashMap<String, Set<String>>(); Set<String> uniquetableSet = new HashSet<String>(); for (int i = 0; i < modelList.length; i++) { ModelDef modeldef = modelList[i]; uniquetableSet.add(modeldef.getTableName()); List<String> attrList = Arrays.asList(modeldef.getAttributes()); for (String att : attrList) { columnSet.add(att); if (usedInTable.containsKey(att)) { usedInTable.get(att).add(modeldef.getModelName()); } else { HashSet<String> tableSet = new HashSet<String>(); tableSet.add(modeldef.getModelName()); usedInTable.put(att, tableSet); } } } <DeepExtract> List<String> orderedList = new ArrayList<String>(); for (String table : uniquetableSet) { orderedList.add(table); } SourceWriter sw = new StringSourceWriter(); sw.lnprint("package " + conf.metaDataPackageName + ";"); sw.lnprint(); sw.lnprint("/***"); sw.lnprint("* This is automatically generated by DAOGenerator, based on the database table schema"); sw.lnprint("* "); sw.lnprint("* "); sw.lnprint("*/"); sw.lnprint(); sw.lnprint("public class " + "Table" + "{"); for (String table : orderedList) { sw.lnTabPrint("public final static String " + table + " = \"" + table + "\";"); } sw.lnprint(""); sw.lnprint("}"); FileUtil.writeToFile(sw.toString(), conf.metaDataDirectory, "Table" + ".java"); </DeepExtract> }
orm
positive
3,232
public Criteria andPriceIsNotNull() { if ("price is not null" == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion("price is not null")); return (Criteria) this; }
public Criteria andPriceIsNotNull() { <DeepExtract> if ("price is not null" == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion("price is not null")); </DeepExtract> return (Criteria) this; }
springcloud-e-book
positive
3,233
public List<List<Integer>> levelOrder(TreeNode root) { ArrayList<List<Integer>> res = new ArrayList<List<Integer>>(); if (root == null) { return; } if (res.size() <= 0) { res.add(new ArrayList<Integer>()); } res.get(0).add(root.val); levelAdd(root.left, res, 0 + 1); levelAdd(root.right, res, 0 + 1); return res; }
public List<List<Integer>> levelOrder(TreeNode root) { ArrayList<List<Integer>> res = new ArrayList<List<Integer>>(); <DeepExtract> if (root == null) { return; } if (res.size() <= 0) { res.add(new ArrayList<Integer>()); } res.get(0).add(root.val); levelAdd(root.left, res, 0 + 1); levelAdd(root.right, res, 0 + 1); </DeepExtract> return res; }
Leetcode-for-Fun
positive
3,234
public void setNavigatePreviousAction(Action action) { Icon icon = prevButton.getIcon(); prevButton.setAction(action); prevButton.setHideActionText(true); prevButton.setIcon(icon); }
public void setNavigatePreviousAction(Action action) { <DeepExtract> Icon icon = prevButton.getIcon(); prevButton.setAction(action); prevButton.setHideActionText(true); prevButton.setIcon(icon); </DeepExtract> }
swingset3
positive
3,235
public synchronized void openLibs() { if (!isOpenInternal()) { throw new IllegalStateException("Lua state is closed"); } LuaValueProxyRef luaValueProxyRef; while ((luaValueProxyRef = (LuaValueProxyRef) proxyQueue.poll()) != null) { proxySet.remove(luaValueProxyRef); lua_unref(REGISTRYINDEX, luaValueProxyRef.getReference()); } for (Library library : Library.values()) { library.open(this); pop(1); } }
public synchronized void openLibs() { <DeepExtract> if (!isOpenInternal()) { throw new IllegalStateException("Lua state is closed"); } LuaValueProxyRef luaValueProxyRef; while ((luaValueProxyRef = (LuaValueProxyRef) proxyQueue.poll()) != null) { proxySet.remove(luaValueProxyRef); lua_unref(REGISTRYINDEX, luaValueProxyRef.getReference()); } </DeepExtract> for (Library library : Library.values()) { library.open(this); pop(1); } }
jnlua
positive
3,236
@RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public boolean queueIdle() { try { Object lock = mHField.get(inputMethodManager); synchronized (lock) { View servedView = (View) mServedViewField.get(inputMethodManager); if (servedView != null) { boolean servedViewAttached = servedView.getWindowVisibility() != View.GONE; if (servedViewAttached) { servedView.removeOnAttachStateChangeListener(this); servedView.addOnAttachStateChangeListener(this); } else { Activity activity = extractActivity(servedView.getContext()); if (activity == null || activity.getWindow() == null) { finishInputLockedMethod.invoke(inputMethodManager); } else { View decorView = activity.getWindow().peekDecorView(); boolean windowAttached = decorView.getWindowVisibility() != View.GONE; if (!windowAttached) { finishInputLockedMethod.invoke(inputMethodManager); } else { decorView.requestFocusFromTouch(); } } } } } } catch (IllegalAccessException | InvocationTargetException unexpected) { Log.e("IMMLeaks", "Unexpected reflection exception", unexpected); } return false; }
@RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public boolean queueIdle() { <DeepExtract> try { Object lock = mHField.get(inputMethodManager); synchronized (lock) { View servedView = (View) mServedViewField.get(inputMethodManager); if (servedView != null) { boolean servedViewAttached = servedView.getWindowVisibility() != View.GONE; if (servedViewAttached) { servedView.removeOnAttachStateChangeListener(this); servedView.addOnAttachStateChangeListener(this); } else { Activity activity = extractActivity(servedView.getContext()); if (activity == null || activity.getWindow() == null) { finishInputLockedMethod.invoke(inputMethodManager); } else { View decorView = activity.getWindow().peekDecorView(); boolean windowAttached = decorView.getWindowVisibility() != View.GONE; if (!windowAttached) { finishInputLockedMethod.invoke(inputMethodManager); } else { decorView.requestFocusFromTouch(); } } } } } } catch (IllegalAccessException | InvocationTargetException unexpected) { Log.e("IMMLeaks", "Unexpected reflection exception", unexpected); } </DeepExtract> return false; }
ETHWallet
positive
3,237
@Override public void onGuildUnban(GuildUnbanEvent e) { WebhookClient client = WebhookClient.withId(webhook.getIdLong(), Objects.requireNonNull(webhook.getToken())); WebhookMessageBuilder messageBuilder = new WebhookMessageBuilder().addEmbeds(new WebhookEmbedBuilder().setAuthor(new WebhookEmbed.EmbedAuthor("Member Unbanned", e.getUser().getAvatarUrl(), null)).setDescription(e.getUser().getAsMention() + " " + C.getFullName(e.getUser())).setThumbnailUrl(e.getUser().getAvatarUrl()).setColor(Color.CYAN.getRGB()).setFooter(new WebhookEmbed.EmbedFooter("ID: " + e.getUser().getId(), null)).build()).setUsername("happybot-logger").setAvatarUrl(Main.getJda().getSelfUser().getAvatarUrl()); client.send(messageBuilder.build()); client.close(); }
@Override public void onGuildUnban(GuildUnbanEvent e) { <DeepExtract> WebhookClient client = WebhookClient.withId(webhook.getIdLong(), Objects.requireNonNull(webhook.getToken())); WebhookMessageBuilder messageBuilder = new WebhookMessageBuilder().addEmbeds(new WebhookEmbedBuilder().setAuthor(new WebhookEmbed.EmbedAuthor("Member Unbanned", e.getUser().getAvatarUrl(), null)).setDescription(e.getUser().getAsMention() + " " + C.getFullName(e.getUser())).setThumbnailUrl(e.getUser().getAvatarUrl()).setColor(Color.CYAN.getRGB()).setFooter(new WebhookEmbed.EmbedFooter("ID: " + e.getUser().getId(), null)).build()).setUsername("happybot-logger").setAvatarUrl(Main.getJda().getSelfUser().getAvatarUrl()); client.send(messageBuilder.build()); client.close(); </DeepExtract> }
happybot
positive
3,238
public void visitElmntMultiplyOp(@NotNull JuliaElmntMultiplyOp o) { visitPsiElement(o); }
public void visitElmntMultiplyOp(@NotNull JuliaElmntMultiplyOp o) { <DeepExtract> visitPsiElement(o); </DeepExtract> }
juliafy
positive
3,239
@Override public Edge addEdge(Object o, Vertex vertex, Vertex vertex1, String s) { NodeBuilder edgeBuilder = edge(o.toString(), vertex.getId().toString(), vertex1.getId().toString(), true).set("label", s); for (GraphCommandListener listener : Collections.unmodifiableList(graphCommandListeners)) { listener.commandCreated(addEdgeCommand(edgeBuilder).build()); } return new StreamingEdge(wrapped.addEdge(o, vertex, vertex1, s)); }
@Override public Edge addEdge(Object o, Vertex vertex, Vertex vertex1, String s) { NodeBuilder edgeBuilder = edge(o.toString(), vertex.getId().toString(), vertex1.getId().toString(), true).set("label", s); <DeepExtract> for (GraphCommandListener listener : Collections.unmodifiableList(graphCommandListeners)) { listener.commandCreated(addEdgeCommand(edgeBuilder).build()); } </DeepExtract> return new StreamingEdge(wrapped.addEdge(o, vertex, vertex1, s)); }
degraphmalizer
positive
3,240
public void setInitialHeapSize(Integer initialHeapSize) { return initialHeapSize != null && initialHeapSize.intValue() == 0 ? null : initialHeapSize; }
public void setInitialHeapSize(Integer initialHeapSize) { <DeepExtract> return initialHeapSize != null && initialHeapSize.intValue() == 0 ? null : initialHeapSize; </DeepExtract> }
CardDAVSyncOutlook
positive
3,241
public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields; switch(fieldId) { case 1: fields = NUM1; case 2: fields = NUM2; default: fields = null; } if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; }
public static _Fields findByThriftIdOrThrow(int fieldId) { <DeepExtract> _Fields fields; switch(fieldId) { case 1: fields = NUM1; case 2: fields = NUM2; default: fields = null; } </DeepExtract> if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; }
phantom
positive
3,242
@Override public Certificate getCertificateInfo(String certificateId) throws DigitalOceanException, RequestUnsuccessfulException { if (StringUtils.isBlank(certificateId)) { log.error("Missing required parameter - certificateId."); throw new IllegalArgumentException("Missing required parameter - certificateId."); } Object[] params = { certificateId }; return (Certificate) perform(new ApiRequest(ApiAction.GET_CERTIFICATE_INFO, params)).getData(); }
@Override public Certificate getCertificateInfo(String certificateId) throws DigitalOceanException, RequestUnsuccessfulException { <DeepExtract> if (StringUtils.isBlank(certificateId)) { log.error("Missing required parameter - certificateId."); throw new IllegalArgumentException("Missing required parameter - certificateId."); } </DeepExtract> Object[] params = { certificateId }; return (Certificate) perform(new ApiRequest(ApiAction.GET_CERTIFICATE_INFO, params)).getData(); }
digitalocean-api-java
positive
3,243
@Override public void connectionCreated(Connection connection) { YiLog.getInstance().i("initService"); try { mXmppConnection = connection; mIsConnectionClosed = false; ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection); if (sdm == null) { sdm = new ServiceDiscoveryManager(connection); sdm.addFeature("http://jabber.org/protocol/disco#info"); sdm.addFeature("jabber:iq:privacy"); } connection.addPacketListener(new PresenceListener(this, mXmppBinder), PresenceListener.PACKET_FILTER); MsgListener msgListener = new MsgListener(this, mXmppBinder); connection.addPacketListener(msgListener, MsgListener.PACKET_FILTER); connection.addPacketSendingListener(msgListener, MsgListener.PACKET_FILTER); connection.addConnectionListener(new ReconnectionListener()); MultiUserChat.addInvitationListener(connection, new MucInviteListener(this, mXmppBinder)); } catch (Exception e) { YiLog.getInstance().e(e, "initService failed."); } }
@Override public void connectionCreated(Connection connection) { <DeepExtract> YiLog.getInstance().i("initService"); try { mXmppConnection = connection; mIsConnectionClosed = false; ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection); if (sdm == null) { sdm = new ServiceDiscoveryManager(connection); sdm.addFeature("http://jabber.org/protocol/disco#info"); sdm.addFeature("jabber:iq:privacy"); } connection.addPacketListener(new PresenceListener(this, mXmppBinder), PresenceListener.PACKET_FILTER); MsgListener msgListener = new MsgListener(this, mXmppBinder); connection.addPacketListener(msgListener, MsgListener.PACKET_FILTER); connection.addPacketSendingListener(msgListener, MsgListener.PACKET_FILTER); connection.addConnectionListener(new ReconnectionListener()); MultiUserChat.addInvitationListener(connection, new MucInviteListener(this, mXmppBinder)); } catch (Exception e) { YiLog.getInstance().e(e, "initService failed."); } </DeepExtract> }
yiim_v2
positive
3,244
@Override protected void init(Context context) { int width = context.getResources().getDisplayMetrics().widthPixels; mRadius = width / 4; LINE_WIDTH = dpToPx(2); POINT_RADIO_WIDTH = dpToPx(4); SEL_POINT_RADIO_WIDTH = dpToPx(6); mTouchRegionWidth = dpToPx(20); mCenterPoint = new PointF(0, 0); mControlPointList = new ArrayList<>(); mPath = new Path(); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.FILL); mPaint.setColor(Color.parseColor(BEZIER_CIRCLE_COLOR)); mCirclePaint = new Paint(); mCirclePaint.setAntiAlias(true); mCirclePaint.setStyle(Paint.Style.STROKE); mCirclePaint.setStrokeWidth(LINE_WIDTH); mCirclePaint.setColor(Color.parseColor(NATIVE_CIRCLE_COLOR)); mControlPaint = new Paint(); mControlPaint.setAntiAlias(true); mControlPaint.setStyle(Paint.Style.STROKE); mControlPaint.setStrokeWidth(LINE_WIDTH); mControlPaint.setColor(Color.parseColor(CONTROL_LINE_COLOR)); mControlPath = new Path(); mStatus = Status.FREE; mIsShowHelpLine = true; mRatio = 0.55f; float controlWidth = mRatio * mRadius; mControlPointList.clear(); mControlPointList.add(new PointF(0, -mRadius)); mControlPointList.add(new PointF(controlWidth, -mRadius)); mControlPointList.add(new PointF(mRadius, -controlWidth)); mControlPointList.add(new PointF(mRadius, 0)); mControlPointList.add(new PointF(mRadius, controlWidth)); mControlPointList.add(new PointF(controlWidth, mRadius)); mControlPointList.add(new PointF(0, mRadius)); mControlPointList.add(new PointF(-controlWidth, mRadius)); mControlPointList.add(new PointF(-mRadius, controlWidth)); mControlPointList.add(new PointF(-mRadius, 0)); mControlPointList.add(new PointF(-mRadius, -controlWidth)); mControlPointList.add(new PointF(-controlWidth, -mRadius)); }
@Override protected void init(Context context) { int width = context.getResources().getDisplayMetrics().widthPixels; mRadius = width / 4; LINE_WIDTH = dpToPx(2); POINT_RADIO_WIDTH = dpToPx(4); SEL_POINT_RADIO_WIDTH = dpToPx(6); mTouchRegionWidth = dpToPx(20); mCenterPoint = new PointF(0, 0); mControlPointList = new ArrayList<>(); mPath = new Path(); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.FILL); mPaint.setColor(Color.parseColor(BEZIER_CIRCLE_COLOR)); mCirclePaint = new Paint(); mCirclePaint.setAntiAlias(true); mCirclePaint.setStyle(Paint.Style.STROKE); mCirclePaint.setStrokeWidth(LINE_WIDTH); mCirclePaint.setColor(Color.parseColor(NATIVE_CIRCLE_COLOR)); mControlPaint = new Paint(); mControlPaint.setAntiAlias(true); mControlPaint.setStyle(Paint.Style.STROKE); mControlPaint.setStrokeWidth(LINE_WIDTH); mControlPaint.setColor(Color.parseColor(CONTROL_LINE_COLOR)); mControlPath = new Path(); mStatus = Status.FREE; mIsShowHelpLine = true; mRatio = 0.55f; <DeepExtract> float controlWidth = mRatio * mRadius; mControlPointList.clear(); mControlPointList.add(new PointF(0, -mRadius)); mControlPointList.add(new PointF(controlWidth, -mRadius)); mControlPointList.add(new PointF(mRadius, -controlWidth)); mControlPointList.add(new PointF(mRadius, 0)); mControlPointList.add(new PointF(mRadius, controlWidth)); mControlPointList.add(new PointF(controlWidth, mRadius)); mControlPointList.add(new PointF(0, mRadius)); mControlPointList.add(new PointF(-controlWidth, mRadius)); mControlPointList.add(new PointF(-mRadius, controlWidth)); mControlPointList.add(new PointF(-mRadius, 0)); mControlPointList.add(new PointF(-mRadius, -controlWidth)); mControlPointList.add(new PointF(-controlWidth, -mRadius)); </DeepExtract> }
UI2018
positive
3,245
public static List<String> toListOfStrings(JSONArray values) { if (values == null || values.length() < 1) { return Collections.emptyList(); } ArrayList<T> results = new ArrayList<T>(values.length()); for (int i = 0; i < values.length(); i++) { T result = CollectionUtils.TO_STRING_TRANSFORMER.apply((F) values.opt(i)); if (result != null) { results.add(result); } } return results; }
public static List<String> toListOfStrings(JSONArray values) { <DeepExtract> if (values == null || values.length() < 1) { return Collections.emptyList(); } ArrayList<T> results = new ArrayList<T>(values.length()); for (int i = 0; i < values.length(); i++) { T result = CollectionUtils.TO_STRING_TRANSFORMER.apply((F) values.opt(i)); if (result != null) { results.add(result); } } return results; </DeepExtract> }
alfresco-core
positive
3,246
@Test public void testLazyTable() throws SQLException { Connection connection = sql2o.open(); createAndFillUserTable(connection); connection.close(); Query q = sql2o.createQuery("select * from User"); LazyTable lt = null; try { lt = q.executeAndFetchTableLazy(); for (Row r : lt.rows()) { String name = r.getString("name"); assertThat(name, notNullValue()); } assertThat(q.getConnection().getJdbcConnection().isClosed(), is(false)); } finally { lt.close(); } assertThat(q.getConnection().getJdbcConnection().isClosed(), is(true)); }
@Test public void testLazyTable() throws SQLException { <DeepExtract> Connection connection = sql2o.open(); createAndFillUserTable(connection); connection.close(); </DeepExtract> Query q = sql2o.createQuery("select * from User"); LazyTable lt = null; try { lt = q.executeAndFetchTableLazy(); for (Row r : lt.rows()) { String name = r.getString("name"); assertThat(name, notNullValue()); } assertThat(q.getConnection().getJdbcConnection().isClosed(), is(false)); } finally { lt.close(); } assertThat(q.getConnection().getJdbcConnection().isClosed(), is(true)); }
sql2o
positive
3,249
@Test public void testWithFileAndRoseTemplate() throws Exception { File fileDest = new File(this.outReportFolder.getAbsolutePath(), "test_with_file_and_rose_template.xlsx"); SXSSFWorkbook workbook = new SXSSFWorkbook(); String headerText = "My simple header"; final HueStyleTemplate styleTemplate = RoseStyleTemplate.class.getConstructor().newInstance(); MempoiSheet sheet = MempoiSheetBuilder.aMempoiSheet().withSimpleHeaderText(headerText).withSimpleFooterText(TestHelper.SIMPLE_TEXT_FOOTER).withPrepStmt(prepStmt).build(); MemPOI memPOI = MempoiBuilder.aMemPOI().withWorkbook(workbook).withFile(fileDest).withAdjustColumnWidth(true).addMempoiSheet(sheet).withStyleTemplate(styleTemplate).withMempoiSubFooter(new NumberSumSubFooter()).withEvaluateCellFormulas(true).build(); final MempoiReport mempoiReport = memPOI.prepareMempoiReport().get(); assertEquals("file name len === starting fileDest", fileDest.getAbsolutePath(), mempoiReport.getFile()); AssertionHelper.assertOnGeneratedFile(this.createStatement(), mempoiReport.getFile(), TestHelper.COLUMNS, TestHelper.HEADERS, "SUM(H3:H12)", styleTemplate, 0, 0, 0, true); assertOnSimpleTextHeaderOrFooterGeneratedFile(mempoiReport.getFile(), headerText, 0, 0, TestHelper.COLUMNS.length - 1, 0, styleTemplate.getSimpleTextHeaderCellStyle(workbook)); assertOnSimpleTextHeaderOrFooterGeneratedFile(mempoiReport.getFile(), TestHelper.SIMPLE_TEXT_FOOTER, 13, 0, TestHelper.COLUMNS.length - 1, 1, styleTemplate.getSimpleTextFooterCellStyle(workbook)); }
@Test public void testWithFileAndRoseTemplate() throws Exception { <DeepExtract> File fileDest = new File(this.outReportFolder.getAbsolutePath(), "test_with_file_and_rose_template.xlsx"); SXSSFWorkbook workbook = new SXSSFWorkbook(); String headerText = "My simple header"; final HueStyleTemplate styleTemplate = RoseStyleTemplate.class.getConstructor().newInstance(); MempoiSheet sheet = MempoiSheetBuilder.aMempoiSheet().withSimpleHeaderText(headerText).withSimpleFooterText(TestHelper.SIMPLE_TEXT_FOOTER).withPrepStmt(prepStmt).build(); MemPOI memPOI = MempoiBuilder.aMemPOI().withWorkbook(workbook).withFile(fileDest).withAdjustColumnWidth(true).addMempoiSheet(sheet).withStyleTemplate(styleTemplate).withMempoiSubFooter(new NumberSumSubFooter()).withEvaluateCellFormulas(true).build(); final MempoiReport mempoiReport = memPOI.prepareMempoiReport().get(); assertEquals("file name len === starting fileDest", fileDest.getAbsolutePath(), mempoiReport.getFile()); AssertionHelper.assertOnGeneratedFile(this.createStatement(), mempoiReport.getFile(), TestHelper.COLUMNS, TestHelper.HEADERS, "SUM(H3:H12)", styleTemplate, 0, 0, 0, true); assertOnSimpleTextHeaderOrFooterGeneratedFile(mempoiReport.getFile(), headerText, 0, 0, TestHelper.COLUMNS.length - 1, 0, styleTemplate.getSimpleTextHeaderCellStyle(workbook)); assertOnSimpleTextHeaderOrFooterGeneratedFile(mempoiReport.getFile(), TestHelper.SIMPLE_TEXT_FOOTER, 13, 0, TestHelper.COLUMNS.length - 1, 1, styleTemplate.getSimpleTextFooterCellStyle(workbook)); </DeepExtract> }
MemPOI
positive
3,250
public static String getCurTimeString(SimpleDateFormat format) { return format.format(new Date()); }
public static String getCurTimeString(SimpleDateFormat format) { <DeepExtract> return format.format(new Date()); </DeepExtract> }
Meizi
positive
3,251
@Override public void run() { if (camera != null) { handler.removeCallbacksAndMessages(null); Camera.Parameters parameter = camera.getParameters(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) { parameter.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); } else { parameter.set("flash-mode", "off"); } camera.setParameters(parameter); camera.stopPreview(); camera.release(); camera = null; } return true; }
@Override public void run() { <DeepExtract> if (camera != null) { handler.removeCallbacksAndMessages(null); Camera.Parameters parameter = camera.getParameters(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) { parameter.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); } else { parameter.set("flash-mode", "off"); } camera.setParameters(parameter); camera.stopPreview(); camera.release(); camera = null; } return true; </DeepExtract> }
ViseUtils
positive
3,252
@PrePersist protected void prePersist() { return this.id; }
@PrePersist protected void prePersist() { <DeepExtract> return this.id; </DeepExtract> }
openalexis
positive
3,254
private void showProgressDialog(String msg) { ProgressDialogFragment progressDialogFragment = (ProgressDialogFragment) getSupportFragmentManager().findFragmentByTag(TAG_PROGRESS_DIALOG); if (progressDialogFragment != null) progressDialogFragment.dismiss(); ProgressDialogFragment progressDialogFragment = ProgressDialogFragment.newInstance(msg); progressDialogFragment.setCancelable(false); progressDialogFragment.show(getSupportFragmentManager(), TAG_PROGRESS_DIALOG); }
private void showProgressDialog(String msg) { <DeepExtract> ProgressDialogFragment progressDialogFragment = (ProgressDialogFragment) getSupportFragmentManager().findFragmentByTag(TAG_PROGRESS_DIALOG); if (progressDialogFragment != null) progressDialogFragment.dismiss(); </DeepExtract> ProgressDialogFragment progressDialogFragment = ProgressDialogFragment.newInstance(msg); progressDialogFragment.setCancelable(false); progressDialogFragment.show(getSupportFragmentManager(), TAG_PROGRESS_DIALOG); }
MTCWallet_Android
positive
3,255
public static void main(String[] args) throws IOException { FileInputStream stream = new FileInputStream(dataDir + "Outlook.pst"); try { MboxrdStorageReader reader = new MboxrdStorageReader(stream, false); try { MailMessage msg; String[] fromMarker = { null }; while ((msg = reader.readNextMessage(fromMarker)) != null) { System.out.println(fromMarker[0]); msg.dispose(); } } finally { if (reader != null) reader.dispose(); } } finally { if (stream != null) stream.close(); } FileOutputStream writeStream = new FileOutputStream(dataDir + "inbox"); try { MboxrdStorageWriter writer = new MboxrdStorageWriter(writeStream, false); try { MailMessage msg = MailMessage.load(dataDir + "Message.msg"); String[] fromMarker = { null }; writer.writeMessage(msg, fromMarker); System.out.println(fromMarker[0]); } finally { if (writer != null) ((IDisposable) writer).dispose(); } } finally { if (writeStream != null) writeStream.close(); } }
public static void main(String[] args) throws IOException { FileInputStream stream = new FileInputStream(dataDir + "Outlook.pst"); try { MboxrdStorageReader reader = new MboxrdStorageReader(stream, false); try { MailMessage msg; String[] fromMarker = { null }; while ((msg = reader.readNextMessage(fromMarker)) != null) { System.out.println(fromMarker[0]); msg.dispose(); } } finally { if (reader != null) reader.dispose(); } } finally { if (stream != null) stream.close(); } <DeepExtract> FileOutputStream writeStream = new FileOutputStream(dataDir + "inbox"); try { MboxrdStorageWriter writer = new MboxrdStorageWriter(writeStream, false); try { MailMessage msg = MailMessage.load(dataDir + "Message.msg"); String[] fromMarker = { null }; writer.writeMessage(msg, fromMarker); System.out.println(fromMarker[0]); } finally { if (writer != null) ((IDisposable) writer).dispose(); } } finally { if (writeStream != null) writeStream.close(); } </DeepExtract> }
Aspose.Email-for-Java
positive
3,256
public Set instantiate() throws IOException { Set<FileObject> resultSet = new LinkedHashSet<FileObject>(); File dirF = FileUtil.normalizeFile((File) wiz.getProperty("projdir")); dirF.mkdirs(); FileObject template = Templates.getTemplate(wiz); FileObject dir = FileUtil.toFileObject(dirF); try { ZipInputStream str = new ZipInputStream(template.getInputStream()); ZipEntry entry; while ((entry = str.getNextEntry()) != null) { if (entry.isDirectory()) { FileUtil.createFolder(dir, entry.getName()); } else { FileObject fo = FileUtil.createData(dir, entry.getName()); if ("nbproject/project.xml".equals(entry.getName())) { filterProjectXML(fo, str, dir.getName()); } else { writeFile(str, fo); } } } } finally { template.getInputStream().close(); } resultSet.add(dir); Enumeration<? extends FileObject> e = dir.getFolders(true); while (e.hasMoreElements()) { FileObject subfolder = e.nextElement(); if (ProjectManager.getDefault().isProject(subfolder)) { resultSet.add(subfolder); } } File parent = dirF.getParentFile(); if (parent != null && parent.exists()) { ProjectChooser.setProjectsFolder(parent); } return resultSet; }
public Set instantiate() throws IOException { Set<FileObject> resultSet = new LinkedHashSet<FileObject>(); File dirF = FileUtil.normalizeFile((File) wiz.getProperty("projdir")); dirF.mkdirs(); FileObject template = Templates.getTemplate(wiz); FileObject dir = FileUtil.toFileObject(dirF); <DeepExtract> try { ZipInputStream str = new ZipInputStream(template.getInputStream()); ZipEntry entry; while ((entry = str.getNextEntry()) != null) { if (entry.isDirectory()) { FileUtil.createFolder(dir, entry.getName()); } else { FileObject fo = FileUtil.createData(dir, entry.getName()); if ("nbproject/project.xml".equals(entry.getName())) { filterProjectXML(fo, str, dir.getName()); } else { writeFile(str, fo); } } } } finally { template.getInputStream().close(); } </DeepExtract> resultSet.add(dir); Enumeration<? extends FileObject> e = dir.getFolders(true); while (e.hasMoreElements()) { FileObject subfolder = e.nextElement(); if (ProjectManager.getDefault().isProject(subfolder)) { resultSet.add(subfolder); } } File parent = dirF.getParentFile(); if (parent != null && parent.exists()) { ProjectChooser.setProjectsFolder(parent); } return resultSet; }
nbp4beginners
positive
3,257
public static void main(String[] args) { int[] array = { 0, 1, 2, 3, 4, 5, 6, 7 }; StdOut.println(1 + ":" + 0 + "/" + array.length - 1); 1++; if (0 > array.length - 1) return -1; int mid = 0 + (array.length - 1 - 0) / 2; if (6 < array[mid]) return rank(6, array, 0, mid - 1, 1); else if (6 > array[mid]) return rank(6, array, mid + 1, array.length - 1, 1); else return mid; }
public static void main(String[] args) { int[] array = { 0, 1, 2, 3, 4, 5, 6, 7 }; <DeepExtract> StdOut.println(1 + ":" + 0 + "/" + array.length - 1); 1++; if (0 > array.length - 1) return -1; int mid = 0 + (array.length - 1 - 0) / 2; if (6 < array[mid]) return rank(6, array, 0, mid - 1, 1); else if (6 > array[mid]) return rank(6, array, mid + 1, array.length - 1, 1); else return mid; </DeepExtract> }
Algorithms-Sedgewick
positive
3,258
public <X0, X1, X2, X3, X4, X5> Decade<A, B, C, D, X0, X1, X2, X3, X4, X5> add(final X0 value0, final X1 value1, final X2 value2, final X3 value3, final X4 value4, final X5 value5) { return new Decade<A, B, C, D, X0, X1, X2, X3, X4, X5>(this.val0, this.val1, this.val2, this.val3, value0, value1, value2, value3, value4, value5); }
public <X0, X1, X2, X3, X4, X5> Decade<A, B, C, D, X0, X1, X2, X3, X4, X5> add(final X0 value0, final X1 value1, final X2 value2, final X3 value3, final X4 value4, final X5 value5) { <DeepExtract> return new Decade<A, B, C, D, X0, X1, X2, X3, X4, X5>(this.val0, this.val1, this.val2, this.val3, value0, value1, value2, value3, value4, value5); </DeepExtract> }
nlp-lang
positive
3,259
public static CachedModel find(ModelCache modelCache, String id, Class<? extends CachedModel> clazz) { try { testObject = clazz.newInstance(); } catch (Exception e) { return null; } this.id = id; if (testObject.reload(modelCache)) { return testObject; } else { return null; } }
public static CachedModel find(ModelCache modelCache, String id, Class<? extends CachedModel> clazz) { try { testObject = clazz.newInstance(); } catch (Exception e) { return null; } <DeepExtract> this.id = id; </DeepExtract> if (testObject.reload(modelCache)) { return testObject; } else { return null; } }
droid-fu
positive
3,260
public static void main(String[] args) throws Exception { JCommander jcmdr = new JCommander(this); try { jcmdr.parse(args); } catch (ParameterException e) { jcmdr.usage(); try { Thread.sleep(500); } catch (Exception e2) { } throw e; } SparkConf sparkConf = new SparkConf(); if (useSparkLocal) { sparkConf.setMaster("local[*]"); } sparkConf.setAppName("DL4J Spark MLP Example"); JavaSparkContext sc = new JavaSparkContext(sparkConf); DataSetIterator iterTrain = new MnistDataSetIterator(batchSizePerWorker, true, 12345); DataSetIterator iterTest = new MnistDataSetIterator(batchSizePerWorker, true, 12345); List<DataSet> trainDataList = new ArrayList<>(); List<DataSet> testDataList = new ArrayList<>(); while (iterTrain.hasNext()) { trainDataList.add(iterTrain.next()); } while (iterTest.hasNext()) { testDataList.add(iterTest.next()); } JavaRDD<DataSet> trainData = sc.parallelize(trainDataList); JavaRDD<DataSet> testData = sc.parallelize(testDataList); MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().seed(12345).activation(Activation.LEAKYRELU).weightInit(WeightInit.XAVIER).updater(new Nesterovs(0.1, 0.9)).l2(1e-4).list().layer(0, new DenseLayer.Builder().nIn(28 * 28).nOut(500).build()).layer(1, new DenseLayer.Builder().nOut(100).build()).layer(2, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD).activation(Activation.SOFTMAX).nIn(100).nOut(10).build()).build(); TrainingMaster tm = new ParameterAveragingTrainingMaster.Builder(batchSizePerWorker).averagingFrequency(5).workerPrefetchNumBatches(2).batchSizePerWorker(batchSizePerWorker).build(); SparkDl4jMultiLayer sparkNet = new SparkDl4jMultiLayer(sc, conf, tm); for (int i = 0; i < numEpochs; i++) { sparkNet.fit(trainData); log.info("Completed Epoch {}", i); } Evaluation evaluation = sparkNet.doEvaluation(testData, 64, new Evaluation(10))[0]; log.info("***** Evaluation *****"); log.info(evaluation.stats()); tm.deleteTempFiles(sc); log.info("***** Example Complete *****"); }
public static void main(String[] args) throws Exception { <DeepExtract> JCommander jcmdr = new JCommander(this); try { jcmdr.parse(args); } catch (ParameterException e) { jcmdr.usage(); try { Thread.sleep(500); } catch (Exception e2) { } throw e; } SparkConf sparkConf = new SparkConf(); if (useSparkLocal) { sparkConf.setMaster("local[*]"); } sparkConf.setAppName("DL4J Spark MLP Example"); JavaSparkContext sc = new JavaSparkContext(sparkConf); DataSetIterator iterTrain = new MnistDataSetIterator(batchSizePerWorker, true, 12345); DataSetIterator iterTest = new MnistDataSetIterator(batchSizePerWorker, true, 12345); List<DataSet> trainDataList = new ArrayList<>(); List<DataSet> testDataList = new ArrayList<>(); while (iterTrain.hasNext()) { trainDataList.add(iterTrain.next()); } while (iterTest.hasNext()) { testDataList.add(iterTest.next()); } JavaRDD<DataSet> trainData = sc.parallelize(trainDataList); JavaRDD<DataSet> testData = sc.parallelize(testDataList); MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().seed(12345).activation(Activation.LEAKYRELU).weightInit(WeightInit.XAVIER).updater(new Nesterovs(0.1, 0.9)).l2(1e-4).list().layer(0, new DenseLayer.Builder().nIn(28 * 28).nOut(500).build()).layer(1, new DenseLayer.Builder().nOut(100).build()).layer(2, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD).activation(Activation.SOFTMAX).nIn(100).nOut(10).build()).build(); TrainingMaster tm = new ParameterAveragingTrainingMaster.Builder(batchSizePerWorker).averagingFrequency(5).workerPrefetchNumBatches(2).batchSizePerWorker(batchSizePerWorker).build(); SparkDl4jMultiLayer sparkNet = new SparkDl4jMultiLayer(sc, conf, tm); for (int i = 0; i < numEpochs; i++) { sparkNet.fit(trainData); log.info("Completed Epoch {}", i); } Evaluation evaluation = sparkNet.doEvaluation(testData, 64, new Evaluation(10))[0]; log.info("***** Evaluation *****"); log.info(evaluation.stats()); tm.deleteTempFiles(sc); log.info("***** Example Complete *****"); </DeepExtract> }
deeplearning4j-examples
positive
3,261
public static boolean moveToRightEdge(Spannable text, Layout layout) { int where; int pt = getSelectionEnd(text); int line = layout.getLineForOffset(pt); int pdir = layout.getParagraphDirection(line); if (1 * pdir < 0) { where = layout.getLineStart(line); } else { int end = layout.getLineEnd(line); if (line == layout.getLineCount() - 1) where = end; else where = end - 1; } setSelection(text, where, where); return true; }
public static boolean moveToRightEdge(Spannable text, Layout layout) { int where; int pt = getSelectionEnd(text); int line = layout.getLineForOffset(pt); int pdir = layout.getParagraphDirection(line); if (1 * pdir < 0) { where = layout.getLineStart(line); } else { int end = layout.getLineEnd(line); if (line == layout.getLineCount() - 1) where = end; else where = end - 1; } <DeepExtract> setSelection(text, where, where); </DeepExtract> return true; }
Jota-Text-Editor-old
positive
3,262
public void add(T value) { Node<T> node = head; while (node.next != null) { node = node.next; } node.next = new Node<>(value); }
public void add(T value) { <DeepExtract> Node<T> node = head; while (node.next != null) { node = node.next; } node.next = new Node<>(value); </DeepExtract> }
cs-interview-questions
positive
3,264
public static void main(String[] args) { int[] a = { -1, 10, 5, 3, 2, 7, 8 }; int jc = 1; while (jc < a.length - 1) { for (int i = jc; i > 0; i--) { if (a[i] < a[i - 1]) { swap(a, i); } else { break; } } jc++; } for (int var : a) { System.out.print(var + " "); } }
public static void main(String[] args) { int[] a = { -1, 10, 5, 3, 2, 7, 8 }; <DeepExtract> int jc = 1; while (jc < a.length - 1) { for (int i = jc; i > 0; i--) { if (a[i] < a[i - 1]) { swap(a, i); } else { break; } } jc++; } </DeepExtract> for (int var : a) { System.out.print(var + " "); } }
Data-Structures-and-Algorithms-master
positive
3,265
public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) { if (useFieldNames && fieldName != null) { buffer.append(fieldName); buffer.append(fieldNameValueSeparator); } if (value == null) { appendNullText(buffer, fieldName); } else { appendInternal(buffer, fieldName, value, isFullDetail(fullDetail)); } appendFieldSeparator(buffer); }
public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) { if (useFieldNames && fieldName != null) { buffer.append(fieldName); buffer.append(fieldNameValueSeparator); } if (value == null) { appendNullText(buffer, fieldName); } else { appendInternal(buffer, fieldName, value, isFullDetail(fullDetail)); } <DeepExtract> appendFieldSeparator(buffer); </DeepExtract> }
xposed-art
positive
3,267
@Override public void actionPerformed(final ActionEvent evt) { checkAddress(); final List<Object> args = new ArrayList<>(6); args.add("javaosc-example"); args.add(1001); args.add(1); args.add(0); args.add("freq"); args.add(440); final OSCMessage msg = new OSCMessage("/s_new", args); try { oscPort.send(msg); } catch (final Exception ex) { showError("Couldn't send"); } secondSynthButtonOn.setEnabled(false); secondSynthButtonOff.setEnabled(true); slider2.setEnabled(true); slider2.setValue(2050); textBox2.setEnabled(true); textBox2.setText("440.0"); }
@Override public void actionPerformed(final ActionEvent evt) { <DeepExtract> checkAddress(); final List<Object> args = new ArrayList<>(6); args.add("javaosc-example"); args.add(1001); args.add(1); args.add(0); args.add("freq"); args.add(440); final OSCMessage msg = new OSCMessage("/s_new", args); try { oscPort.send(msg); } catch (final Exception ex) { showError("Couldn't send"); } </DeepExtract> secondSynthButtonOn.setEnabled(false); secondSynthButtonOff.setEnabled(true); slider2.setEnabled(true); slider2.setValue(2050); textBox2.setEnabled(true); textBox2.setText("440.0"); }
JavaOSC
positive
3,268
public ArrayComposer<ObjectComposer<PARENT>> startArrayProperty(SerializableString fieldName) { if (_child != null) { _child._finish(); _child = null; } _generator.writeName(fieldName); return _startArray(this, _generator); }
public ArrayComposer<ObjectComposer<PARENT>> startArrayProperty(SerializableString fieldName) { <DeepExtract> if (_child != null) { _child._finish(); _child = null; } </DeepExtract> _generator.writeName(fieldName); return _startArray(this, _generator); }
jackson-jr
positive
3,270
public static void main(String[] args) { int[] nums = new int[] { 1, 2, 3 }; List<List<Integer>> permutes = new ArrayList<>(); List<Integer> permuteList = new ArrayList<>(); boolean[] visited = new boolean[nums.length]; backtracking(permuteList, permutes, visited, nums); return permutes; }
public static void main(String[] args) { int[] nums = new int[] { 1, 2, 3 }; <DeepExtract> List<List<Integer>> permutes = new ArrayList<>(); List<Integer> permuteList = new ArrayList<>(); boolean[] visited = new boolean[nums.length]; backtracking(permuteList, permutes, visited, nums); return permutes; </DeepExtract> }
Awesome-Algorithm-Study
positive
3,271
static void do_rank2(HMatrix M, HMatrix MadjT, HMatrix Q) { double[] v1 = new double[3]; double[] v2 = new double[3]; double abs, max; int i, j, col; max = 0.0; col = -1; for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) { abs = MadjT.m[i][j]; if (abs < 0.0) abs = -abs; if (abs > max) { max = abs; col = j; } } return col; if (col < 0) { do_rank1(M, Q); return; } v1[0] = MadjT.m[0][col]; v1[1] = MadjT.m[1][col]; v1[2] = MadjT.m[2][col]; double s = Math.sqrt(vdot(v1, v1)); v1[0] = v1[0]; v1[1] = v1[1]; v1[2] = v1[2] + ((v1[2] < 0.0) ? -s : s); s = Math.sqrt(2.0 / vdot(v1, v1)); v1[0] = v1[0] * s; v1[1] = v1[1] * s; v1[2] = v1[2] * s; int i, j; for (i = 0; i < 3; i++) { double s = v1[0] * M.m[0][i] + v1[1] * M.m[1][i] + v1[2] * M.m[2][i]; for (j = 0; j < 3; j++) M.m[j][i] -= v1[j] * s; } v2[0] = M.m[0][1] * M.m[1][2] - M.m[0][2] * M.m[1][1]; v2[1] = M.m[0][2] * M.m[1][0] - M.m[0][0] * M.m[1][2]; v2[2] = M.m[0][0] * M.m[1][1] - M.m[0][1] * M.m[1][0]; double s = Math.sqrt(vdot(v2, v2)); v2[0] = v2[0]; v2[1] = v2[1]; v2[2] = v2[2] + ((v2[2] < 0.0) ? -s : s); s = Math.sqrt(2.0 / vdot(v2, v2)); v2[0] = v2[0] * s; v2[1] = v2[1] * s; v2[2] = v2[2] * s; int i, j; for (i = 0; i < 3; i++) { double s = vdot(v2, M.m[i]); for (j = 0; j < 3; j++) M.m[i][j] -= v2[j] * s; } w = M.m[0][0]; x = M.m[0][1]; y = M.m[1][0]; z = M.m[1][1]; if (w * z > x * y) { c = z + w; s = y - x; d = Math.sqrt(c * c + s * s); c = c / d; s = s / d; Q.m[0][0] = Q.m[1][1] = c; Q.m[0][1] = -(Q.m[1][0] = s); } else { c = z - w; s = y + x; d = Math.sqrt(c * c + s * s); c = c / d; s = s / d; Q.m[0][0] = -(Q.m[1][1] = c); Q.m[0][1] = Q.m[1][0] = s; } Q.m[0][2] = Q.m[2][0] = Q.m[1][2] = Q.m[2][1] = 0.0; Q.m[2][2] = 1.0; int i, j; for (i = 0; i < 3; i++) { double s = v1[0] * Q.m[0][i] + v1[1] * Q.m[1][i] + v1[2] * Q.m[2][i]; for (j = 0; j < 3; j++) Q.m[j][i] -= v1[j] * s; } int i, j; for (i = 0; i < 3; i++) { double s = vdot(v2, Q.m[i]); for (j = 0; j < 3; j++) Q.m[i][j] -= v2[j] * s; } }
static void do_rank2(HMatrix M, HMatrix MadjT, HMatrix Q) { double[] v1 = new double[3]; double[] v2 = new double[3]; double abs, max; int i, j, col; max = 0.0; col = -1; for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) { abs = MadjT.m[i][j]; if (abs < 0.0) abs = -abs; if (abs > max) { max = abs; col = j; } } return col; if (col < 0) { do_rank1(M, Q); return; } v1[0] = MadjT.m[0][col]; v1[1] = MadjT.m[1][col]; v1[2] = MadjT.m[2][col]; double s = Math.sqrt(vdot(v1, v1)); v1[0] = v1[0]; v1[1] = v1[1]; v1[2] = v1[2] + ((v1[2] < 0.0) ? -s : s); s = Math.sqrt(2.0 / vdot(v1, v1)); v1[0] = v1[0] * s; v1[1] = v1[1] * s; v1[2] = v1[2] * s; int i, j; for (i = 0; i < 3; i++) { double s = v1[0] * M.m[0][i] + v1[1] * M.m[1][i] + v1[2] * M.m[2][i]; for (j = 0; j < 3; j++) M.m[j][i] -= v1[j] * s; } v2[0] = M.m[0][1] * M.m[1][2] - M.m[0][2] * M.m[1][1]; v2[1] = M.m[0][2] * M.m[1][0] - M.m[0][0] * M.m[1][2]; v2[2] = M.m[0][0] * M.m[1][1] - M.m[0][1] * M.m[1][0]; double s = Math.sqrt(vdot(v2, v2)); v2[0] = v2[0]; v2[1] = v2[1]; v2[2] = v2[2] + ((v2[2] < 0.0) ? -s : s); s = Math.sqrt(2.0 / vdot(v2, v2)); v2[0] = v2[0] * s; v2[1] = v2[1] * s; v2[2] = v2[2] * s; int i, j; for (i = 0; i < 3; i++) { double s = vdot(v2, M.m[i]); for (j = 0; j < 3; j++) M.m[i][j] -= v2[j] * s; } w = M.m[0][0]; x = M.m[0][1]; y = M.m[1][0]; z = M.m[1][1]; if (w * z > x * y) { c = z + w; s = y - x; d = Math.sqrt(c * c + s * s); c = c / d; s = s / d; Q.m[0][0] = Q.m[1][1] = c; Q.m[0][1] = -(Q.m[1][0] = s); } else { c = z - w; s = y + x; d = Math.sqrt(c * c + s * s); c = c / d; s = s / d; Q.m[0][0] = -(Q.m[1][1] = c); Q.m[0][1] = Q.m[1][0] = s; } Q.m[0][2] = Q.m[2][0] = Q.m[1][2] = Q.m[2][1] = 0.0; Q.m[2][2] = 1.0; int i, j; for (i = 0; i < 3; i++) { double s = v1[0] * Q.m[0][i] + v1[1] * Q.m[1][i] + v1[2] * Q.m[2][i]; for (j = 0; j < 3; j++) Q.m[j][i] -= v1[j] * s; } <DeepExtract> int i, j; for (i = 0; i < 3; i++) { double s = vdot(v2, Q.m[i]); for (j = 0; j < 3; j++) Q.m[i][j] -= v2[j] * s; } </DeepExtract> }
jsurf
positive
3,272
@Test public void testCompleteNull() { assertEquals(ConcurrentCompletable.PENDING, c.completable.state.get()); assertTrue(c.completable.complete(null)); assertEquals(ConcurrentCompletable.COMPLETED, c.completable.state.get()); assertEquals(ConcurrentCompletable.NULL, c.completable.result); final int state = c.completable.state.get(); final Object result = c.completable.result; assertFalse(c.completable.complete(this.result)); assertEquals(state, c.completable.state.get()); assertEquals(result, c.completable.result); assertFalse(c.completable.fail(cause)); assertEquals(state, c.completable.state.get()); assertEquals(result, c.completable.result); assertFalse(c.completable.cancel()); assertEquals(state, c.completable.state.get()); assertEquals(result, c.completable.result); }
@Test public void testCompleteNull() { assertEquals(ConcurrentCompletable.PENDING, c.completable.state.get()); assertTrue(c.completable.complete(null)); assertEquals(ConcurrentCompletable.COMPLETED, c.completable.state.get()); assertEquals(ConcurrentCompletable.NULL, c.completable.result); <DeepExtract> final int state = c.completable.state.get(); final Object result = c.completable.result; assertFalse(c.completable.complete(this.result)); assertEquals(state, c.completable.state.get()); assertEquals(result, c.completable.result); assertFalse(c.completable.fail(cause)); assertEquals(state, c.completable.state.get()); assertEquals(result, c.completable.result); assertFalse(c.completable.cancel()); assertEquals(state, c.completable.state.get()); assertEquals(result, c.completable.result); </DeepExtract> }
tiny-async-java
positive
3,273
public void editHB1ACReading(long oldId, HB1ACReading reading) { realm.beginTransaction(); getHB1ACReadingById(oldId).deleteFromRealm(); realm.commitTransaction(); realm.beginTransaction(); reading.setId(getNextKey("hb1ac")); realm.copyToRealm(reading); realm.commitTransaction(); }
public void editHB1ACReading(long oldId, HB1ACReading reading) { realm.beginTransaction(); getHB1ACReadingById(oldId).deleteFromRealm(); realm.commitTransaction(); <DeepExtract> realm.beginTransaction(); reading.setId(getNextKey("hb1ac")); realm.copyToRealm(reading); realm.commitTransaction(); </DeepExtract> }
glucosio-android
positive
3,274
public ListLine addValue(int index, boolean value) { if (listBoolean == null) { listBoolean = new ArrayList<>(); } listBoolean.add(new CellKV<Boolean>(index, value)); if (index > maxIndex) { maxIndex = index; } if (minIndex == -1) { minIndex = index; } else { if (index < minIndex) { minIndex = index; } } return this; }
public ListLine addValue(int index, boolean value) { if (listBoolean == null) { listBoolean = new ArrayList<>(); } listBoolean.add(new CellKV<Boolean>(index, value)); <DeepExtract> if (index > maxIndex) { maxIndex = index; } if (minIndex == -1) { minIndex = index; } else { if (index < minIndex) { minIndex = index; } } </DeepExtract> return this; }
bingexcel
positive
3,276
public String person2(String input) { List<String> tokens = tokenizer.tokenize(input); outer: for (int i = 0; i < tokens.size(); ) { int offset = i; for (final Substitution substitution : person2) { i = substitution.substitute(offset, tokens); if (i > offset) continue outer; } i++; } return tokenizer.toString(tokens); }
public String person2(String input) { <DeepExtract> List<String> tokens = tokenizer.tokenize(input); outer: for (int i = 0; i < tokens.size(); ) { int offset = i; for (final Substitution substitution : person2) { i = substitution.substitute(offset, tokens); if (i > offset) continue outer; } i++; } return tokenizer.toString(tokens); </DeepExtract> }
chatbots-library
positive
3,277
@Test public void verify_ifVerificationWasNotSuccessful_operationWillBeRestarted() { RuntimeException e = new RuntimeException("verification not successful"); doThrow(e).when(bioIdWebserviceClient).verify(VERIFICATION_TOKEN); this.failedOperations = 0; when(VERIFICATION_TOKEN.getMaxTries()).thenReturn(3); presenter.executeVerify = true; verifyCalled = true; if (executeVerify) { super.verify(); } assertThat(presenter.captureImagePairCalledWithFirstParam, is(0)); assertThat(presenter.captureImagePairCalledWithSecondParam, is(MovementDirection.any)); assertThat(presenter.captureImagePairCalledWithThirdParam, is(MovementDirection.any)); }
@Test public void verify_ifVerificationWasNotSuccessful_operationWillBeRestarted() { RuntimeException e = new RuntimeException("verification not successful"); doThrow(e).when(bioIdWebserviceClient).verify(VERIFICATION_TOKEN); this.failedOperations = 0; when(VERIFICATION_TOKEN.getMaxTries()).thenReturn(3); presenter.executeVerify = true; <DeepExtract> verifyCalled = true; if (executeVerify) { super.verify(); } </DeepExtract> assertThat(presenter.captureImagePairCalledWithFirstParam, is(0)); assertThat(presenter.captureImagePairCalledWithSecondParam, is(MovementDirection.any)); assertThat(presenter.captureImagePairCalledWithThirdParam, is(MovementDirection.any)); }
BWS-Android
positive
3,278
@Override public Metadata getDocument(String indexName, String indexDocId) { log.debug("Get document in ElasticSearch [indexName: {}, indexDocId:{}]", indexName, indexDocId); ValidatorUtils.rejectIfEmpty("indexName", indexName); ValidatorUtils.rejectIfEmpty("indexDocId", indexDocId); indexName = indexName.toLowerCase(); GetResponse response = client.prepareGet(indexName, DEFAULT_TYPE, indexDocId).get(); log.trace("Get document in ElasticSearch [indexName: {}, indexDocId: {}] : response= {}", indexName, indexDocId, response); if (!response.isExists()) { throw new NotFoundException("Document [indexName: " + indexName + ", indexDocId: " + indexDocId + "] not found"); } String contentId = null; String contentType = null; byte[] content = null; boolean pinned = false; if (response.getSource() != null) { Map<String, String> mapping = this.getMapping(response.getIndex()); log.debug("mapping={}", mapping); response.getSource().forEach((key, value) -> { if (mapping.containsKey(key)) { if ("date".equals(mapping.get(key))) { Long date = Longs.tryParse(value.toString()); if (date != null) { response.getSource().put(key, new Date(date)); } } } }); if (response.getSource().containsKey(HASH_INDEX_KEY) && response.getSource().get(HASH_INDEX_KEY) != null) { contentId = response.getSource().get(HASH_INDEX_KEY).toString(); response.getSource().remove(HASH_INDEX_KEY); } if (response.getSource().containsKey(CONTENT_TYPE_INDEX_KEY) && response.getSource().get(CONTENT_TYPE_INDEX_KEY) != null) { contentType = response.getSource().get(CONTENT_TYPE_INDEX_KEY).toString(); response.getSource().remove(CONTENT_TYPE_INDEX_KEY); } if (response.getSource().containsKey(CONTENT_INDEX_KEY) && response.getSource().get(CONTENT_INDEX_KEY) != null) { content = Base64.getDecoder().decode(response.getSource().get(CONTENT_INDEX_KEY).toString()); response.getSource().remove(CONTENT_INDEX_KEY); } if (response.getSource().containsKey(PINNED_KEY) && response.getSource().get(PINNED_KEY) != null) { pinned = (boolean) response.getSource().get(PINNED_KEY); response.getSource().remove(PINNED_KEY); } } return Metadata.of(response.getIndex(), response.getId(), contentId, contentType, content, pinned, response.getSource()); }
@Override public Metadata getDocument(String indexName, String indexDocId) { log.debug("Get document in ElasticSearch [indexName: {}, indexDocId:{}]", indexName, indexDocId); ValidatorUtils.rejectIfEmpty("indexName", indexName); ValidatorUtils.rejectIfEmpty("indexDocId", indexDocId); indexName = indexName.toLowerCase(); GetResponse response = client.prepareGet(indexName, DEFAULT_TYPE, indexDocId).get(); log.trace("Get document in ElasticSearch [indexName: {}, indexDocId: {}] : response= {}", indexName, indexDocId, response); if (!response.isExists()) { throw new NotFoundException("Document [indexName: " + indexName + ", indexDocId: " + indexDocId + "] not found"); } <DeepExtract> String contentId = null; String contentType = null; byte[] content = null; boolean pinned = false; if (response.getSource() != null) { Map<String, String> mapping = this.getMapping(response.getIndex()); log.debug("mapping={}", mapping); response.getSource().forEach((key, value) -> { if (mapping.containsKey(key)) { if ("date".equals(mapping.get(key))) { Long date = Longs.tryParse(value.toString()); if (date != null) { response.getSource().put(key, new Date(date)); } } } }); if (response.getSource().containsKey(HASH_INDEX_KEY) && response.getSource().get(HASH_INDEX_KEY) != null) { contentId = response.getSource().get(HASH_INDEX_KEY).toString(); response.getSource().remove(HASH_INDEX_KEY); } if (response.getSource().containsKey(CONTENT_TYPE_INDEX_KEY) && response.getSource().get(CONTENT_TYPE_INDEX_KEY) != null) { contentType = response.getSource().get(CONTENT_TYPE_INDEX_KEY).toString(); response.getSource().remove(CONTENT_TYPE_INDEX_KEY); } if (response.getSource().containsKey(CONTENT_INDEX_KEY) && response.getSource().get(CONTENT_INDEX_KEY) != null) { content = Base64.getDecoder().decode(response.getSource().get(CONTENT_INDEX_KEY).toString()); response.getSource().remove(CONTENT_INDEX_KEY); } if (response.getSource().containsKey(PINNED_KEY) && response.getSource().get(PINNED_KEY) != null) { pinned = (boolean) response.getSource().get(PINNED_KEY); response.getSource().remove(PINNED_KEY); } } return Metadata.of(response.getIndex(), response.getId(), contentId, contentType, content, pinned, response.getSource()); </DeepExtract> }
Mahuta
positive
3,279
public Criteria andSeqGreaterThan(Integer value) { if (value == null) { throw new RuntimeException("Value for " + "seq" + " cannot be null"); } criteria.add(new Criterion("seq >", value)); return (Criteria) this; }
public Criteria andSeqGreaterThan(Integer value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "seq" + " cannot be null"); } criteria.add(new Criterion("seq >", value)); </DeepExtract> return (Criteria) this; }
einvoice
positive
3,280
@Override protected void onPostExecute(Object result) { ServiceSinkhole.reload("DNS clear", ActivityDns.this, false); if (adapter != null) adapter.changeCursor(DatabaseHelper.getInstance(this).getDns()); }
@Override protected void onPostExecute(Object result) { ServiceSinkhole.reload("DNS clear", ActivityDns.this, false); <DeepExtract> if (adapter != null) adapter.changeCursor(DatabaseHelper.getInstance(this).getDns()); </DeepExtract> }
NetGuard
positive
3,281
public static List<String> generateParentheses(int n) { List<String> solutions = new ArrayList(); if (n == 0 && n == 0) { solutions.add(new String(new char[n * 2])); return; } if (n > 0) { new char[n * 2][0] = '('; addParenthesis(new char[n * 2], 0 + 1, n - 1, n, solutions); } if (n > 0 && n > n) { new char[n * 2][0] = ')'; addParenthesis(new char[n * 2], 0 + 1, n, n - 1, solutions); } return solutions; }
public static List<String> generateParentheses(int n) { List<String> solutions = new ArrayList(); <DeepExtract> if (n == 0 && n == 0) { solutions.add(new String(new char[n * 2])); return; } if (n > 0) { new char[n * 2][0] = '('; addParenthesis(new char[n * 2], 0 + 1, n - 1, n, solutions); } if (n > 0 && n > n) { new char[n * 2][0] = ')'; addParenthesis(new char[n * 2], 0 + 1, n, n - 1, solutions); } </DeepExtract> return solutions; }
Cracking-the-Coding-Interview_solutions
positive
3,282