method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
b08aed58-5016-4971-adb9-1e779d77d134 | 0 | public boolean[][] getBooleans() {
return grid;
} |
f363a4c4-9645-41c2-abde-85befbd86752 | 3 | public boolean checkPermission(CommandSender sender) {
if ((this.permission == null) || (this.permission.length() == 0) || (sender.hasPermission(this.permission))) {
return true;
}
sender.sendMessage(ChatColor.RED + "Insufficient permissions");
sender.sendMessage(ChatColor.RED + "Requires " + permission);
return false;
} |
bfb826f2-6650-4766-9f5a-a156888e97d7 | 4 | @Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null) {
return false;
}
if (getClass() != other.getClass()) {
return false;
}
State that = (State) other;
return colorToPlay == that.colorToPlay
&& Arrays.deepEquals(squares, that.squares);
} |
ed3e1c43-c37c-4dcf-a61f-96fd30771690 | 1 | public Svd (Matrix[] toBeSvdMat, boolean codeCbCr) {
svdResult = new SingularValueDecomposition[3];
matU = new Matrix[3];
matV = new Matrix[3];
matS = new Matrix[3];
svdResult[0] = new SingularValueDecomposition(toBeSvdMat[0]);
matU[0] = svdResult[0].getU();
matV[0] = svdResult[0].getV();
matS[0] = svdResult[0].getS();
if (codeCbCr) {
svdResult[1] = new SingularValueDecomposition(toBeSvdMat[1]);
matU[1] = svdResult[1].getU();
matV[1] = svdResult[1].getV();
matS[1] = svdResult[1].getS();
svdResult[2] = new SingularValueDecomposition(toBeSvdMat[2]);
matU[2] = svdResult[2].getU();
matV[2] = svdResult[2].getV();
matS[2] = svdResult[2].getS();
}
} |
d58f3e13-8616-4e23-944e-a10c82be95fa | 3 | public OverviewPane(Gui gui) {
this.gui = gui;
try {
font = Font.createFont(Font.TRUETYPE_FONT, OverviewItem.class.getResourceAsStream("/font/arvo.ttf")).deriveFont(Font.PLAIN,
24f);
} catch (Exception e) {
font = new Font(Font.SERIF, Font.PLAIN, 24);
}
listPane = new JPanel();
listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS));
hackListComp = this;
JPanel wrapperPanel = new JPanel();
wrapperPanel.add(listPane);
JScrollPane scrollPane = new JScrollPane(wrapperPanel);
this.setLayout(new BorderLayout());
this.add(process, BorderLayout.NORTH);
this.add(scrollPane, BorderLayout.CENTER);
process.setFont(font);
process.setOpaque(true);
process.setBackground(new Color(225, 225, 225));
process.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(180, 180, 180)));
listPane.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3)
showPopup(listPane.getComponentAt(e.getPoint()), e.getPoint());
}
});
new Timer().schedule(new TimerTask() {
@Override
public void run() {
try {
synchronized (LOCK_MODEL) {
reorderModelList();
}
refreshAll();
} catch (Throwable e) {
e.printStackTrace();
}
}
}, 5000, 5000);
} |
bd6baefe-db1f-464a-9caa-7c667d4868b5 | 0 | public void depositar(double valor)
{
this.saldo += valor ;
} |
9666d30d-05f3-4992-95ef-39dd3a0e9c3c | 6 | @EventHandler
public void MagmaCubeNausea(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getMagmaCubeConfig().getDouble("MagmaCube.Nausea.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getMagmaCubeConfig().getBoolean("MagmaCube.Nausea.Enabled", true) && damager instanceof MagmaCube && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, plugin.getMagmaCubeConfig().getInt("MagmaCube.Nausea.Time"), plugin.getMagmaCubeConfig().getInt("MagmaCube.Nausea.Power")));
}
} |
3218e5f3-8296-4505-b667-589e98e49538 | 4 | @Override
public void draw(GL2 gl) {
if(skyTexture == null) {
loadTexture(textureToLoad);
}
if(parentPanel != null) {
GLU glu = GLU.createGLU(gl);
if(skyTexture != null) {
skyTexture.enable(gl);
skyTexture.bind(gl);
}
GLUquadric quadric = glu.gluNewQuadric();
// Erzeugen damit Texture gerundet gemapt werden kann
glu.gluQuadricTexture(quadric, true);
glu.gluQuadricOrientation(quadric, GLU.GLU_INSIDE);
/* auskommentiert, da dies leider Fehler verusacht*//*gl.glDisable(GL2.GL_DEPTH_TEST);
gl.glDepthMask(false);*/
gl.glPushMatrix();
// Rotieren, damit der Begin der Kugel oben ist
gl.glRotatef(90f, 1, 0, 0);
// Schneide ab der Mitte durch
double[] clipPlane2 = {0.0f, 0.0f, -1.0f, 0.5f};
gl.glClipPlane(GL2.GL_CLIP_PLANE2, clipPlane2, 0);
gl.glEnable(GL2.GL_CLIP_PLANE2);
// Zeichnen der Spehere, ausschalten vom clipping
glu.gluSphere(quadric, 20, 200, 15);
gl.glDisable(GL2.GL_CLIP_PLANE2);
if(skyTexture != null) {
skyTexture.disable(gl);
}
gl.glPopMatrix();
// s.o.
//gl.glEnable(GL2.GL_DEPTH_TEST);
//gl.glDepthMask(true);
}
} |
f4948431-2d89-4185-9a36-f85c1e50bad9 | 3 | private static boolean isFX2 (Device dev)
{
DeviceDescriptor desc;
if (dev == null)
return false;
desc = dev.getDeviceDescriptor ();
// Only the cypress development platform uses these IDs
if (desc.getVendorId () == 0x04b4 && desc.getProductId () == 0x8613)
return true;
// Other products will have IDs in (eep)rom ...
return false;
} |
dc64ae64-5bd4-4c94-9099-54a903262b76 | 3 | private static void inputCheck(int port, int windowSizeN, int timeout) {
if (port > 65535 || port < 1024) {
System.err.println("Port number must be in between 1024 and 65535");
System.exit(1);
}
if (windowSizeN < 0) {
System.err.println("Window size must be larger than 0");
System.exit(1);
}
} |
2e9a1bf6-6c96-48bb-87f1-a54215d110a8 | 4 | public boolean isInPanesSelector(int mouseX, int mouseY){
if (mouseX > 800 && mouseX < 1280){
if (mouseY > 0 && mouseY < 288){
return true;
}
}
return false;
} |
d0e890e5-a969-41a6-a320-26e9a26662e7 | 2 | public void testAddPartialConverterSecurity() {
if (OLD_JDK) {
return;
}
try {
Policy.setPolicy(RESTRICT);
System.setSecurityManager(new SecurityManager());
ConverterManager.getInstance().addPartialConverter(StringConverter.INSTANCE);
fail();
} catch (SecurityException ex) {
// ok
} finally {
System.setSecurityManager(null);
Policy.setPolicy(ALLOW);
}
assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length);
} |
d9b194ed-28cf-4f41-aa78-002c9f3424d7 | 7 | public static final String trimTrailingZeroes(String text, boolean localized) {
if (text == null) {
return null;
}
int dot = text.indexOf(localized ? LOCALIZED_DECIMAL_SEPARATOR.charAt(0) : '.');
if (dot == -1) {
return text;
}
int pos = text.length() - 1;
if (dot == pos) {
return text;
}
while (pos > dot && text.charAt(pos) == '0') {
pos--;
}
if (dot == pos) {
pos--;
}
return text.substring(0, pos + 1);
} |
c4a01280-62ec-4630-aef7-92e3f34eed30 | 5 | public TetrisTormays(Tetrimino tetrimino, Pelialue pelialue)
{
tormaykset = new ArrayList<Tormays>();
if(tetrimino.palikkakokoelma().lisattyja() <= 0)
return;
try {
for(Palikka palikka : tetrimino.palikkakokoelma().palikat())
{
if(palikka == null)
continue;
if(pelialue.alue().onSisalla(palikka.sijainti()))
tarkistaTormaakoPalikkaPelialueeseen(palikka, tetrimino, pelialue);
else
tormaykset.add(new AlueTormays(palikka, pelialue.alue()));
}
} catch(ConcurrentModificationException e) {}
} |
537dcfcb-d1b4-41b3-9f1e-398f63d5525f | 1 | public TabContainer(int width, int height) {
super(JTabbedPane.BOTTOM);
setBorder( BorderFactory.createEmptyBorder(-2, -1, 1, -3) );
GUI.setPreferredSize(this, width, height);
addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
AbstractTab tab = (AbstractTab) getSelectedComponent();
if (tab != null)
tab.setFocus();
}
});
} |
e3e9d9df-d02c-4c2e-b130-b4a50bc5930c | 1 | public int beforeBind() throws RemoteException
{
/*
* The ID to this server, it will compose the serviceName, like this:
* ServiceID
*/
int nid = nextServerID();
try
{
System.out.println("Server " + RemoteServer.getClientHost() + " asked a ID, sending " + nid);
}
catch (ServerNotActiveException e)
{
System.err.println("Controller.beforeBind() catch ServerNotActiveException");
e.printStackTrace();
}
return nid;
} |
70848de7-b388-4ce8-86d5-583936e46b9e | 1 | public List<CategorieType> getCategorie() {
if (categorie == null) {
categorie = new ArrayList<CategorieType>();
}
return this.categorie;
} |
ab83eedd-eb6d-4f48-809f-ed083f5a47c8 | 2 | public void setCommissionRate(double rate) {
if (rate > 0.0 && rate < 1.0)
commissionRate = rate;
else
throw new IllegalArgumentException(
"Commission rate must be > 0.0 and < 1.0");
} |
b5f8077d-164b-43fe-9466-37efeb443766 | 1 | public static double getBalance(String uid) {
if(checkUserExistance(uid))
{
UserStorageAccess xmlAccessor = new UserStorageAccess();
return xmlAccessor.getUserBalance(uid);
}else
{
return 0;
}
} |
5d5d9a7c-cbea-429a-85bc-6a7cb61785b3 | 3 | void doPermute(char[] in, StringBuffer outputString, boolean[] used, int inputLength, int level) {
// System.out.println(outputString.toString());
// System.out.print("used: ");
// for (boolean c : used) {
// System.out.print(c + ",");
// }
// System.out.println();
//
if (level == inputLength) {
System.out.println(outputString.toString());
return;
}
for (int i = 0; i < inputLength; ++i) {
if (used[i])
continue;
outputString.append(in[i]);
used[i] = true;
doPermute(in, outputString, used, inputLength, level + 1);
used[i] = false;
outputString.setLength(outputString.length() - 1);
}
} |
b0f53e20-f5b6-4a0d-b91d-46c4c323eaae | 8 | public boolean mobs(MOB mob, List<String> commands)
{
if(commands.size()<3)
{
mob.tell(L("You have failed to specify the proper fields.\n\rThe format is DESTROY MOB [MOB NAME]\n\r"));
mob.location().showOthers(mob,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> flub(s) a powerful spell."));
return false;
}
String mobID=CMParms.combine(commands,2);
boolean allFlag=commands.get(2).equalsIgnoreCase("all");
if(mobID.toUpperCase().startsWith("ALL.")){ allFlag=true; mobID="ALL "+mobID.substring(4);}
if(mobID.toUpperCase().endsWith(".ALL")){ allFlag=true; mobID="ALL "+mobID.substring(0,mobID.length()-4);}
MOB deadMOB=mob.location().fetchInhabitant(mobID);
boolean doneSomething=false;
while(deadMOB!=null)
{
if(!deadMOB.isMonster())
{
mob.tell(L("@x1 is a PLAYER!!\n\r",deadMOB.name()));
if(!doneSomething)
mob.location().showOthers(mob,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> flub(s) a powerful spell."));
return false;
}
doneSomething=true;
mob.location().showHappens(CMMsg.MSG_OK_VISUAL,L("@x1 vanishes in a puff of smoke.",deadMOB.name()));
Log.sysOut("Mobs",mob.Name()+" destroyed mob "+deadMOB.Name()+".");
deadMOB.destroy();
mob.location().delInhabitant(deadMOB);
deadMOB=mob.location().fetchInhabitant(mobID);
if(!allFlag)
break;
}
if(!doneSomething)
{
mob.tell(L("I don't see '@x1 here.\n\r",mobID));
mob.location().showOthers(mob,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> flub(s) a powerful spell."));
return false;
}
return true;
} |
6e0216f4-a83c-4dcf-a2b7-21dd538bdb70 | 5 | public String RecieveMessages(){
byte[] data = null;
try {
int length = inputStream.read();
data = new byte[length];
length = 0;
if (length != data.length)
{
int ch = inputStream.read(data,0, data.length);
if (ch == -1)
{
throw new IOException("Can't read data");
}
}
}
catch (IOException e)
{
System.err.println(e);
}
catch (NegativeArraySizeException xd){
System.err.println(xd);
}
catch (Exception err){
System.err.println("Entro a este final catch.");
}
String x= new String(data);
return x;
} |
52247969-3953-4ebf-9e57-a9fc40ef4152 | 3 | @Override
public void takeTurn(GameBoard currentBoard) {
Random rand = new Random();
int randomlySelectedRow = 0;
int tokensInRow = 0;
ArrayList<Integer> validRowNumbers = new ArrayList<Integer>();
int[] validRowNumberValues = { 1, 2, 3 };
for(int i: validRowNumberValues){
validRowNumbers.add(i);
}
boolean selectionNotValid = true;
while(selectionNotValid){
randomlySelectedRow = validRowNumbers.get(rand.nextInt(validRowNumbers.size()));
tokensInRow = currentBoard.getCurrentState().checkRow(randomlySelectedRow);
selectionNotValid = (tokensInRow > 0)?false:validRowNumbers.remove((Object)randomlySelectedRow);
}
int randTokenAmount = rand.nextInt(tokensInRow) + 1;
TurnAction action = new TurnAction();
action.setTargetRow(randomlySelectedRow);
action.setTokenAmount(randTokenAmount);
System.out.println("Computer chose row " + (randomlySelectedRow) + ".\n"
+ "Computer has removed " + randTokenAmount + " from that row.");
System.out.println(currentBoard.toString());
currentBoard.MakeMove(action);
} |
aaad32fa-0675-4b21-8931-4476d8d35d77 | 4 | public synchronized boolean startsWith(byte[] seq)
{
if (seq.length > buffer.length)
throw new IllegalArgumentException();
if (seq.length > bsize)
return false;
for (int i = 0; i < seq.length; ++i)
{
if (seq[i] != buffer[(offset + i) % buffer.length])
return false;
}
return true;
} |
42adaab5-9a5e-4307-886b-06a4ba624dee | 9 | public static double sinh(double x) {
boolean negate = false;
if (x != x) {
return x;
}
// sinh[z] = (exp(z) - exp(-z) / 2
// for values of z larger than about 20,
// exp(-z) can be ignored in comparison with exp(z)
if (x > 20) {
if (x >= LOG_MAX_VALUE) {
// Avoid overflow (MATH-905).
final double t = exp(0.5 * x);
return (0.5 * t) * t;
} else {
return 0.5 * exp(x);
}
} else if (x < -20) {
if (x <= -LOG_MAX_VALUE) {
// Avoid overflow (MATH-905).
final double t = exp(-0.5 * x);
return (-0.5 * t) * t;
} else {
return -0.5 * exp(-x);
}
}
if (x == 0) {
return x;
}
if (x < 0.0) {
x = -x;
negate = true;
}
double result;
if (x > 0.25) {
double hiPrec[] = new double[2];
exp(x, 0.0, hiPrec);
double ya = hiPrec[0] + hiPrec[1];
double yb = -(ya - hiPrec[0] - hiPrec[1]);
double temp = ya * HEX_40000000;
double yaa = ya + temp - temp;
double yab = ya - yaa;
// recip = 1/y
double recip = 1.0/ya;
temp = recip * HEX_40000000;
double recipa = recip + temp - temp;
double recipb = recip - recipa;
// Correct for rounding in division
recipb += (1.0 - yaa*recipa - yaa*recipb - yab*recipa - yab*recipb) * recip;
// Account for yb
recipb += -yb * recip * recip;
recipa = -recipa;
recipb = -recipb;
// y = y + 1/y
temp = ya + recipa;
yb += -(temp - ya - recipa);
ya = temp;
temp = ya + recipb;
yb += -(temp - ya - recipb);
ya = temp;
result = ya + yb;
result *= 0.5;
}
else {
double hiPrec[] = new double[2];
expm1(x, hiPrec);
double ya = hiPrec[0] + hiPrec[1];
double yb = -(ya - hiPrec[0] - hiPrec[1]);
/* Compute expm1(-x) = -expm1(x) / (expm1(x) + 1) */
double denom = 1.0 + ya;
double denomr = 1.0 / denom;
double denomb = -(denom - 1.0 - ya) + yb;
double ratio = ya * denomr;
double temp = ratio * HEX_40000000;
double ra = ratio + temp - temp;
double rb = ratio - ra;
temp = denom * HEX_40000000;
double za = denom + temp - temp;
double zb = denom - za;
rb += (ya - za*ra - za*rb - zb*ra - zb*rb) * denomr;
// Adjust for yb
rb += yb*denomr; // numerator
rb += -ya * denomb * denomr * denomr; // denominator
// y = y - 1/y
temp = ya + ra;
yb += -(temp - ya - ra);
ya = temp;
temp = ya + rb;
yb += -(temp - ya - rb);
ya = temp;
result = ya + yb;
result *= 0.5;
}
if (negate) {
result = -result;
}
return result;
} |
869e47a6-e93d-498a-83b4-afd841a79d6e | 3 | public static boolean isUnix()
{
String OS = System.getProperty("os.name").toLowerCase();
return (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("") >= 0 || OS.indexOf("aix") >= 0);
} |
93f845aa-7c0b-4351-94b8-3202244b4d19 | 4 | public static String qualifyPatternString( String pattern )
{
pattern = StringTool.strip( pattern, "*" );
pattern = StringTool.strip( pattern, "_(" ); // width placeholder
pattern = StringTool.strip( pattern, "_)" ); // width placeholder
pattern = StringTool.strip( pattern, "_" );
pattern = pattern.replaceAll( "\"", "" );
pattern = StringTool.strip( pattern, "?" );
// there are more bracketed expressions to deal with
// see http://office.microsoft.com/en-us/excel-help/creating-international-number-formats-HA001034635.aspx?redir=0
//pattern = StringTool.strip(pattern, "[Red]"); // [Black] [h] [hhh] [=1] [=2]
//pattern = StringTool.strip(pattern, "Red]");
// TODO: implement locale-specific entries: [$-409] [$-404] ... ********************
// pattern= pattern.replaceAll("\\[.+?\\]", "");
/* if (s.length > 1) {
System.out.println(s[0]);
java.util.regex.Pattern p = java.util.regex.Pattern.compile("\\[(.*?)\\]");
java.util.regex.Matcher m = p.matcher(pattern);
while(m.find()) {
System.out.println(m.group(1));
}
}*/
String[] s = pattern.split( "\\[" );
if( s.length > 1 )
{
pattern = "";
for( String value : s )
{
int zz = value.indexOf( "]" );
if( zz != -1 )
{
String term = value.substring( 1, zz ); // skip first $
if( term.indexOf( "-" ) != -1 )
{ // extract character TODO: locale specifics
pattern += term.substring( 0, term.indexOf( "-" ) );
}
}
pattern += value.substring( zz + 1 );
}
}
return pattern;
} |
1b0d1e68-e5d5-41d1-ad54-2d1ee74f8603 | 9 | public static void update() {
if (nextWave <= 0) {
if (monsters.size() > 0) {
new Thread() {
@Override
public void run() {
EnumMap<Monster, Integer> monsters = WaveManager.monsters.clone();
WaveManager.monsters.clear();
int leftLength = 0;
int rightLength = 0;
int space = Tile.SIZE * 2 - wave;
space = space < Tile.SIZE ? Tile.SIZE : space;
for (Monster monster : monsters.keySet()) {
for (int i = 0; i < monsters.get(monster); i++) {
try {
boolean left = Math.random() < 0.5;
int x = left ? -leftLength * space : Game.world.width + rightLength * space;
Entity e = (Entity) monster.getCreatureClass().getConstructor(int.class, int.class).newInstance(x, 0);
int y = Game.world.height / 2 - e.getBump(false).y + e.getBump(false).height;
e.setY(y);
Game.world.addEntity2(e, false);
if (left) leftLength++;
else rightLength++;
} catch (Exception e1) {
e1.printStackTrace();
}
}
leftLength /= 2;
rightLength /= 2;
}
}
}.start();
} else {
if (stageClear()) generateNextWave();
}
}
} |
ee3ada30-0aac-4b64-bad7-8431b1314810 | 2 | public static Color get(ChatColor color) {
for (TeamColor enumm : TeamColor.class.getEnumConstants()) {
if (enumm.toString().equals(color.toString())) {
return enumm.getColor();
}
}
return null;
} |
d8f03272-04e9-4af4-a7c7-2e6dcd15eae7 | 7 | private void triFusion(int debut, int fin) {
// tableau o� va aller la fusion
int[] tFusion = new int[fin - debut + 1];
int milieu = (debut + fin) / 2;
// Indices des �l�ments � comparer
int i1 = debut,
i2 = milieu + 1;
// indice de la prochaine case du tableau tFusion � remplir
int iFusion = 0;
while (i1 <= milieu && i2 <= fin) {
if (t[i1] < t[i2]) {
tFusion[iFusion++] = t[i1++];
}
else {
tFusion[iFusion++] = t[i2++];
}
}
if (i1 > milieu) {
// la 1�re tranche est �puis�e
for (int i = i2; i <= fin; ) {
tFusion[iFusion++] = t[i++];
}
}
else {
// la 2�me tranche est �puis�e
for (int i = i1; i <= milieu; ) {
tFusion[iFusion++] = t[i++];
}
}
// Copie tFusion dans t
for (int i = 0, j = debut; i <= fin - debut; ) {
t[j++] = tFusion[i++];
}
} |
7bab29bd-c32a-404e-9df8-65957d0a0ea8 | 2 | protected void verifySize() throws MatrixError {
if (width < 1)
throw new MatrixError("Width of matrix must be greater than 1");
if (height < 1)
throw new MatrixError("Height of matrix must be greater than 1");
} |
8e474ab6-e934-4028-83a8-d069e4ec2953 | 8 | void setExampleWidgetSize () {
int size = SWT.DEFAULT;
if (preferredButton == null) return;
if (preferredButton.getSelection()) size = SWT.DEFAULT;
if (tooSmallButton.getSelection()) size = TOO_SMALL_SIZE;
if (smallButton.getSelection()) size = SMALL_SIZE;
if (largeButton.getSelection()) size = LARGE_SIZE;
Control [] controls = getExampleControls ();
for (int i=0; i<controls.length; i++) {
GridData gridData = new GridData(size, size);
gridData.grabExcessHorizontalSpace = fillHButton.getSelection();
gridData.grabExcessVerticalSpace = fillVButton.getSelection();
gridData.horizontalAlignment = fillHButton.getSelection() ? SWT.FILL : SWT.LEFT;
gridData.verticalAlignment = fillVButton.getSelection() ? SWT.FILL : SWT.TOP;
controls [i].setLayoutData (gridData);
}
tabFolderPage.layout (controls);
} |
411d86dc-dac6-4493-ac1c-efb983b8c790 | 0 | public boolean isOutgoing() {
return !isIncoming();
} |
e563d9ac-aade-4d60-a0df-6df32c09e117 | 6 | public String toJSONString()
{
StringBuilder json = new StringBuilder();
json.append( "{" );
if ( className !=null && className.length()>0 )
{
json.append( "\"class\":\"" );
json.append( className );
json.append( "\"," );
}
if ( id != 0 )
{
json.append( "\"id\":\"t" );
String idStr = Integer.toString(id);
json.append( idStr );
json.append("\",");
}
json.append( "\"segments\":[" );
for ( int i=0;i<segments.size();i++ )
{
TextSegment s = segments.get(i);
if ( s.length()> 0 )
{
json.append( s.toJSONString() );
if ( i<segments.size()-1 )
json.append(", ");
}
}
json.append( "]}" );
return json.toString();
} |
91d6b371-2efa-44fc-8456-940f570545b6 | 8 | private boolean r_prelude() {
int among_var;
int v_1;
// repeat, line 36
replab0: while (true) {
v_1 = cursor;
lab1: do {
// (, line 36
// [, line 37
bra = cursor;
// substring, line 37
among_var = find_among(a_0, 3);
if (among_var == 0) {
break lab1;
}
// ], line 37
ket = cursor;
switch (among_var) {
case 0:
break lab1;
case 1:
// (, line 38
// <-, line 38
slice_from("a~");
break;
case 2:
// (, line 39
// <-, line 39
slice_from("o~");
break;
case 3:
// (, line 40
// next, line 40
if (cursor >= limit) {
break lab1;
}
cursor++;
break;
}
continue replab0;
} while (false);
cursor = v_1;
break replab0;
}
return true;
} |
63142afc-ab7a-4c62-b282-e8c4181fab3f | 0 | public double getRelativeX() {return pos.getX();} |
2083e597-d13e-4910-b32d-0c16c5ae9dfd | 6 | private void setMainPanel() {
//getsections according to examId
getSections(examId);
sectionChosen = new JCheckBox[sections.size()];
sectionLabels = new JLabel[sections.size()];
//set editbuttons, editbuttons and sectionlabels
for (int i = 1; i < sections.size() + 1; i++) {
Section section = sections.get(i - 1);
String sectionTimeLimit = new SimpleDateFormat("HH:mm:ss").format(section.getTimeLimit());
sectionLabels[i - 1] = new JLabel("Section " + i + " " + section.getSection_Name());
//Edit Button
//Checkboxes
sectionChosen[i - 1] = new JCheckBox();
sectionChosen[i - 1].setName(section.getSection_ID() + "");
sectionChosen[i - 1].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JCheckBox cbLog = (JCheckBox) e.getSource();
if (cbLog.isSelected()) {
for (int i = 0; i < sectionChosen.length; i++) {
if (!(sectionChosen[i] == e.getSource())) {
sectionChosen[i].setEnabled(false);
}
}
} else {
for (int i = 0; i < sectionChosen.length; i++) {
sectionChosen[i].setEnabled(true);
}
}
}
});
}
//p2.setLayout(new GridLayout(sections.size(),3));
//setlayout
GroupLayout groupLayout;
GroupLayout.ParallelGroup horizontalGroup_P;
GroupLayout.SequentialGroup verticalGroup_S;
groupLayout = new GroupLayout(mainPanel);
groupLayout.setAutoCreateContainerGaps(true);
groupLayout.setAutoCreateGaps(true);
horizontalGroup_P = groupLayout.createParallelGroup();
verticalGroup_S = groupLayout.createSequentialGroup();
for (int i = 0; i < sections.size(); i++) {
// mainPanel.add(sectionLabels[i]);
// mainPanel.add(buttons[i]);
// mainPanel.add(deleteButtons[i]);
horizontalGroup_P.addGroup(groupLayout.createSequentialGroup()
.addComponent(sectionChosen[i])
.addComponent(sectionLabels[i])
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE));
verticalGroup_S.addGroup(groupLayout.createParallelGroup()
.addComponent(sectionChosen[i])
.addComponent(sectionLabels[i]));
}
groupLayout.setHorizontalGroup(horizontalGroup_P);
groupLayout.setVerticalGroup(verticalGroup_S);
mainPanel.setLayout(groupLayout);
mainPanel.revalidate();
//p2.repaint();
} |
16e9835a-7f43-4f40-b117-1afc1956fd08 | 8 | public static int overallMines(MineGen theGrid, int gridX, int gridY) {
// This method receives the coordinates of the square that is on the overall grid
// and returns the number of its closest mines.
int a = gridX;
int b = gridY;
int mineCount = 0;
if (theGrid.hasMine(b, a + 1))
mineCount++;
if (theGrid.hasMine(b, a - 1))
mineCount++;
if (theGrid.hasMine(b + 1, a))
mineCount++;
if (theGrid.hasMine(b - 1, a))
mineCount++;
if (theGrid.hasMine(b + 1, a + 1))
mineCount++;
if (theGrid.hasMine(b - 1, a + 1))
mineCount++;
if (theGrid.hasMine(b + 1, a - 1))
mineCount++;
if (theGrid.hasMine(b - 1, a - 1))
mineCount++;
return mineCount;
} |
82882691-f313-442b-898a-bf75831d9c3b | 4 | public void encryptFile(String filePath, byte[][][] subKeys) {
System.out.println();
System.out.println("Encrypting");
try {
final File inputFile = new File(filePath);
final File outputFile = new File(filePath + ".des");
final InputStream inputStream = new BufferedInputStream(new FileInputStream(inputFile));
final OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
final long nbBytesFile = inputFile.length();
final long nbTotalBlocks = (long) Math.ceil(nbBytesFile / (double) BLOCK_SIZE_IN_BYTES);
final int nbBytesPaddingNeeded = (int) (BLOCK_SIZE_IN_BYTES - (nbBytesFile % BLOCK_SIZE_IN_BYTES));
final byte header = (byte) nbBytesPaddingNeeded;
outputStream.write(header);
byte[] block = new byte[BLOCK_SIZE_IN_BYTES];
int bytesRead = 0;
for (long nbBlocks = 1; nbBlocks <= nbTotalBlocks; nbBlocks++) {
bytesRead = inputStream.read(block);
//System.out.println("Encrypting block " + nbBlocks);
byte[] encryptedBlock = DesAlgorithm.encryptBlock(block, subKeys);
// schrijf geencrypteerd blok weg naar output bestand
outputStream.write(encryptedBlock);
block = new byte[BLOCK_SIZE_IN_BYTES];
}
inputStream.close();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} |
71be2ac2-66db-4354-b756-587a248b3bd7 | 2 | @Override
public Entity createEntity() {
Entity enemyEntity = new Entity(entityManager,
entityManager.createEntity(), new Spatial(0, 0,
enemyGraphic.getWidth(), enemyGraphic.getHeight()),
new Draw(enemyGraphic, DrawOrder.ENEMY),
new MinimapDrawn(0xFFFFFF),
// random AI, just for testing
new NameTag("enemy"), new AI("player",
Math.random() > 0.5 ? AI.AIState.FLEE : AI.AIState.ROAM, AI.AIState.ROAM, AI.AIState.SEEK),
new Collide(),
new Velocity(5, 2),
new Shoot(new BulletTemplate(), 0, 0, 7,
5000, 1, 1000),
new Health(500),
new HealthBar());
// Randomly add a shield to an enemy
if (Math.random() > 0.5) {
Entity shield = new TankShieldTemplate().createEntity();
enemyEntity.addComponentNoRefresh(new Children(shield));
}
return enemyEntity;
} |
68940647-caae-4c29-8f57-2d662c59b52d | 5 | public static Vector getOffset(BlockFace facing)
{
if (facing == null)
return new Vector((int)(Smelter.WIDTH / 2), (int)(-Smelter.HEIGHT / 2), 0);
if (facing.equals(BlockFace.NORTH))
{
return new Vector((int)(Smelter.WIDTH / 2), (int)(-Smelter.HEIGHT / 2), 0);
}
else if (facing.equals(BlockFace.EAST))
{
return new Vector(0, (int)(-Smelter.HEIGHT / 2), (int)(-Smelter.WIDTH / 2));
}
else if (facing.equals(BlockFace.SOUTH))
{
return new Vector((int)(-Smelter.WIDTH / 2), (int)(-Smelter.HEIGHT / 2), 0);
}
else if (facing.equals(BlockFace.WEST))
{
return new Vector(0, (int)(-Smelter.HEIGHT / 2), (int)(Smelter.WIDTH / 2));
}
else
{
return null;
}
} |
a98824eb-70c5-414a-bdba-bb2ee6f24039 | 1 | private void buildComponents(Container window) {
if (window instanceof Frame)
frame = (Frame) window;
window.setFont(new Font("dialog", Font.PLAIN, 10));
classpathField = new TextField(50);
classField = new TextField(50);
sourcecodeArea = new TextArea(20, 80);
errorArea = new TextArea(3, 80);
verboseCheck = new Checkbox("verbose", true);
prettyCheck = new Checkbox("pretty", true);
startButton = new Button("start");
saveButton = new Button("save");
// /#ifdef AWT10
// / saveButton.disable();
// /#else
saveButton.setEnabled(false);
// /#endif
sourcecodeArea.setEditable(false);
errorArea.setEditable(false);
Font monospaced = new Font("monospaced", Font.PLAIN, 10);
sourcecodeArea.setFont(monospaced);
errorArea.setFont(monospaced);
GridBagLayout gbl = new GridBagLayout();
window.setLayout(gbl);
GridBagConstraints labelConstr = new GridBagConstraints();
GridBagConstraints textConstr = new GridBagConstraints();
GridBagConstraints areaConstr = new GridBagConstraints();
GridBagConstraints checkConstr = new GridBagConstraints();
GridBagConstraints buttonConstr = new GridBagConstraints();
labelConstr.fill = GridBagConstraints.NONE;
textConstr.fill = GridBagConstraints.HORIZONTAL;
areaConstr.fill = GridBagConstraints.BOTH;
checkConstr.fill = GridBagConstraints.NONE;
buttonConstr.fill = GridBagConstraints.NONE;
labelConstr.anchor = GridBagConstraints.EAST;
textConstr.anchor = GridBagConstraints.CENTER;
checkConstr.anchor = GridBagConstraints.WEST;
buttonConstr.anchor = GridBagConstraints.CENTER;
labelConstr.anchor = GridBagConstraints.EAST;
textConstr.gridwidth = GridBagConstraints.REMAINDER;
textConstr.weightx = 1.0;
areaConstr.gridwidth = GridBagConstraints.REMAINDER;
areaConstr.weightx = 1.0;
areaConstr.weighty = 1.0;
// /#ifdef AWT10
// / Label label = new Label("class path: ");
// / gbl.setConstraints(label, labelConstr);
// / window.add(label);
// / gbl.setConstraints(classpathField, textConstr);
// / window.add(classpathField);
// / label = new Label("class name: ");
// / gbl.setConstraints(label, labelConstr);
// / window.add(label);
// / gbl.setConstraints(classField, textConstr);
// / window.add(classField);
// / gbl.setConstraints(verboseCheck, checkConstr);
// / window.add(verboseCheck);
// / gbl.setConstraints(prettyCheck, checkConstr);
// / window.add(prettyCheck);
// / labelConstr.weightx = 1.0;
// / label = new Label();
// / gbl.setConstraints(label, labelConstr);
// / window.add(label);
// / gbl.setConstraints(startButton, buttonConstr);
// / window.add(startButton);
// / buttonConstr.gridwidth = GridBagConstraints.REMAINDER;
// / gbl.setConstraints(saveButton, buttonConstr);
// / window.add(saveButton);
// / gbl.setConstraints(sourcecodeArea, areaConstr);
// / window.add(sourcecodeArea);
// / areaConstr.gridheight = GridBagConstraints.REMAINDER;
// / areaConstr.weighty = 0.0;
// / gbl.setConstraints(errorArea, areaConstr);
// / window.add(errorArea);
// /#else
window.add(new Label("class path: "), labelConstr);
window.add(classpathField, textConstr);
window.add(new Label("class name: "), labelConstr);
window.add(classField, textConstr);
window.add(verboseCheck, checkConstr);
window.add(prettyCheck, checkConstr);
labelConstr.weightx = 1.0;
window.add(new Label(), labelConstr);
window.add(startButton, buttonConstr);
buttonConstr.gridwidth = GridBagConstraints.REMAINDER;
window.add(saveButton, buttonConstr);
window.add(sourcecodeArea, areaConstr);
areaConstr.gridheight = GridBagConstraints.REMAINDER;
areaConstr.weighty = 0.0;
window.add(errorArea, areaConstr);
startButton.addActionListener(this);
saveButton.addActionListener(this);
// /#endif
errStream = new PrintWriter(new AreaWriter(errorArea));
decompiler.setErr(errStream);
} |
0424df99-08f6-457f-b663-47632a14b9b2 | 6 | @Override
public void mouseReleased(MouseEvent e) {
try {
int[] koords = haeKoordinaatit(e.getSource());
if (koords != null) {
int mouseEvent = e.getButton();
switch (mouseEvent) {
case 1:
avaaYksi(koords[0], koords[1]);
break;
case 2:
avaaMonta(koords[0], koords[1]);
break;
case 3:
asetaLippu(koords[0], koords[1]);
break;
}
}
if (e.getSource() == mykistysNappi) {
mykistaAanet();
}
} catch (Exception ex) {
kasittelePoikkeus(ex);
}
} |
0ea158b3-935d-490b-b730-795a4fd431eb | 8 | @Override
public void renameRooms(Area A, String oldName, List<Room> allMyDamnRooms)
{
final List<Room> onesToRenumber=new Vector<Room>();
for(Room R : allMyDamnRooms)
{
synchronized(("SYNC"+R.roomID()).intern())
{
R=getRoom(R);
R.setArea(A);
if(oldName!=null)
{
if(R.roomID().toUpperCase().startsWith(oldName.toUpperCase()+"#"))
{
Room R2=A.getRoom(A.Name()+"#"+R.roomID().substring(oldName.length()+1));
if(R2 == null)
R2=getRoom(A.Name()+"#"+R.roomID().substring(oldName.length()+1));
if((R2==null)||(!R2.roomID().startsWith(A.Name()+"#")))
{
final String oldID=R.roomID();
R.setRoomID(A.Name()+"#"+R.roomID().substring(oldName.length()+1));
CMLib.database().DBReCreate(R,oldID);
}
else
onesToRenumber.add(R);
}
else
CMLib.database().DBUpdateRoom(R);
}
}
}
if(oldName!=null)
{
for(final Room R: onesToRenumber)
{
final String oldID=R.roomID();
R.setRoomID(A.getNewRoomID(R,-1));
CMLib.database().DBReCreate(R,oldID);
}
}
} |
c0b59491-4ed8-4eb0-9729-ad6ddc947c43 | 2 | public static byte get(byte[] header, byte[] data, int i) {
if (i < header.length) {
return header[i];
}
if (i - header.length < data.length) {
return data[i - header.length];
}
return (byte) 0x00;
} |
4f2b9f04-8fc8-4eab-894e-2315f99d6659 | 4 | private void calcSum(int p, int currentFrame) {
for (int f = 1; f <= currentFrame; f++) {
scoreBoard[p][2][f] = scoreBoard[p][2][f-1] + scoreBoard[p][0][f] + scoreBoard[p][1][f];
if (scoreBoard[p][0][f] == 10){
if(scoreBoard[p][0][f+1] == 10){
scoreBoard[p][2][f] = scoreBoard[p][2][f]+scoreBoard[p][0][f+1]+scoreBoard[p][0][f+2];
}else{
scoreBoard[p][2][f] = scoreBoard[p][2][f]+scoreBoard[p][0][f+1]+scoreBoard[p][1][f+1];
}
}else if (scoreBoard[p][0][f]+scoreBoard[p][1][f]==10){
scoreBoard[p][2][f] = scoreBoard[p][2][f] + scoreBoard[p][0][f + 1];
}
}
} |
4dd7573f-af2d-4fa3-a183-4d443279a4b3 | 8 | public void getEventStream(CallBack callback) throws MalformedURLException, IOException {
HttpRequest request = generateRequest("/eventstream",
new TreeMap<String, String>(), false);
ApiResponse response = null;
response = streamApi(request);
BufferedReader br = new BufferedReader(new InputStreamReader(response
.getResponse().asStream()));
StringBuffer buffer = new StringBuffer();
char[] tmp = new char[1];
while (true) {
try {
if (br.ready()) {
@SuppressWarnings("unused")
int count = br.read(tmp, 0, 1);
buffer.append(tmp);
if (buffer.toString().contains("\r\n")
&& !buffer.toString().isEmpty()) {
if (buffer.toString().equalsIgnoreCase("\r\n")) {
// Flush the buffer because we don't want \r\n
buffer = new StringBuffer();
}
// can only handle single level json objects
while (buffer.indexOf("}") != -1) {
String json = buffer.substring(0,
buffer.indexOf("}") + 1);
callback.onData(gson.fromJson(json, Event.class));
buffer = new StringBuffer(buffer.substring(json
.length()));
}
}
}
} catch (JsonParseException jsone) {
System.err
.println("Could not parse JSON " + jsone.getMessage());
System.out.println("clearing buffer");
buffer = new StringBuffer();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
} |
36c054e7-6cfd-4528-83f7-3703ac67b359 | 1 | public NodeList getNodeList(String tagName) throws ParserConfigurationException, SAXException, IOException{
// Sucht nach die tagName tags
if(current==null){
return xmlFile.getElementsByTagName(tagName);
}
return current.getElementsByTagName(tagName);
} |
dd128697-5f9a-4f4b-aff5-21c39d89145d | 4 | public Principal authenticate(final String username, final String credentials) {
logger.info("authenticate called for user: " + username );
CommunityAccount purported = (new SQLStatementProcessor<CommunityAccount>("SELECT * FROM valid_accounts WHERE username = ?") {
CommunityAccount process( PreparedStatement s ) throws SQLException {
s.setString(1, username);
ResultSet rs = s.executeQuery();
if( rs.next() ) {
return accountFromResultSet(con, rs);
}
return null;
}
}).doit();
if( purported == null ) {
logger.warning("Unknown user: " + username + " / returning null.");
return null;
}
try {
if( Arrays.equals(getPasswordHash(credentials.toString()),
TypeUtil.fromHexString(purported.getHash().substring("MD5:".length()))) ) {
logger.finest("Passwords match for: " + username);
return purported;
}
} catch (IOException e) {
logger.warning(e.toString());
e.printStackTrace();
}
logger.fine("Password did not match for user: " + username);
return null;
} |
cbcabe8f-e27e-4e38-a33c-1820d3de07eb | 0 | public HashMap<String, HostInfo> getHosts(){
return this.hosts;
} |
77d4a20c-55dd-47ba-8e9d-cdfbf3bb242b | 0 | public void warn(String message) {
log(Level.WARNING, message);
} |
961efacf-2dc3-4552-ac60-dcf61fed817d | 4 | protected Boolean process(String command){
File script;
String suffix = ".sh";
if(SystemUtils.IS_OS_WINDOWS){
suffix = ".bat";
}
if((script= setData(command, suffix))==null){
return false;
}
script.setExecutable(true);
//starts and wait for the process
ProcessBuilder pb = new ProcessBuilder("."+File.separator+script.getName());
pb.directory(new File(script.getAbsolutePath().replace(
script.getName(), File.separator)));
try {
Process p = pb.start();
p.waitFor();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ( (line = br.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();
log.info(result);
} catch (IOException | InterruptedException e) {
LogHandler.writeStackTrace(log, e, Level.SEVERE);
return false;
}
//deletes the script
script.delete();
return true;
} |
c19a83d7-07b9-4aa9-9627-4b0c59088e85 | 4 | public static byte[] InputStreamToByte(InputStream in)
{
int BUFFER_SIZE = 4096;
ByteArrayOutputStream outStream = null;
byte[] data = new byte[4096];
int count = -1;
try
{
outStream = new ByteArrayOutputStream();
while ((count = in.read(data, 0, BUFFER_SIZE)) != -1)
{
outStream.write(data, 0, count);
}
return outStream.toByteArray();
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
finally
{
if (null != outStream)
{
try
{
outStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
} |
a4676657-9a8c-46bb-a6a4-6072f2bec6c2 | 2 | public void go(){
// 1 получить json с инстаграмма
while(run){
try {
process(getRecent());
Thread.sleep(timeout);
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date today = Calendar.getInstance().getTime();
System.out.println(df.format(today));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} |
bdbf18ff-21e1-4018-9a83-6934a3906804 | 1 | public static void doTowers(PrintWriter out,int topN, char from, char inter, char to) {
if (topN == 1){
out.println("Ring 1 from " + from + " to " + to);
}else {
doTowers(out,topN - 1, from, to, inter);
out.println("Ring " + topN + " from " + from + " to " + to);
doTowers(out,topN - 1, inter, from, to);
}
} |
af3efe34-279d-4681-a5b3-081a6053c106 | 7 | public static byte[] getMacAddress() {
if(cachedMacAddress != null && cachedMacAddress.length >= 10) {
return cachedMacAddress;
}
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while(networkInterfaces.hasMoreElements()) {
NetworkInterface network = networkInterfaces.nextElement();
byte[] mac = network.getHardwareAddress();
if(mac != null && mac.length > 0) {
cachedMacAddress = new byte[mac.length * 10];
for(int i = 0; i < cachedMacAddress.length; i++) {
cachedMacAddress[i] = mac[i - (Math.round(i / mac.length) * mac.length)];
}
return cachedMacAddress;
}
}
} catch (SocketException e) {
// Logger.logWarn("Failed to get MAC address, using default logindata key", e);
}
return new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
} |
7d2a69e5-f66d-4357-abdc-0ccd7d1d5d0f | 0 | public Integer interpret(Context ctx) {
// this 为调用interpret 方法的Variable 对象
return ctx.LookupValue(this);
} |
0126b6de-35a9-46fc-822c-e317af37d960 | 9 | private SolveStateEnum solve() {
try {
boolean run1 = true;
while (run1 && solveState != SolveStateEnum.ERROR) {
int starCount = getStarCountInRiddle();
checkByBlock();
if (starCount <= getStarCountInRiddle()) {
solveState = SolveStateEnum.MUST_GUESS;
run1 = false;
}
// moegliche Loesung gefunden
if (getStarCountInRiddle() == 0) {
// direkte Loesung, da vorher nicht geraten wurde
if (stacks == null || stacks.size() == 0) {
solveState = SolveStateEnum.SOLVED;
run1 = false;
if (isSolutionOk()) {
solutionsFromGuising.add(matrix);
} else {
solveState = SolveStateEnum.ERROR;
}
// andere Moeglichkeiten beim Raten testen!
} else {
run1 = false;
if (isSolutionOk()) {
solutionsFromGuising.add(matrix);
solveState = SolveStateEnum.FOUND_SOLUTION_WITH_STACK;
} else {
solveState = SolveStateEnum.ERROR;
}
}
}
}
} catch (Exception e) {
// e.printStackTrace();
solveState = SolveStateEnum.ERROR;
}
return solveState;
} |
a54c6d6f-9610-4108-a197-5530169ded24 | 3 | public int overColumnDivider(int x) {
int divider = getColumnDividerWidth();
int count = mColumns.size() - 1;
int pos = 0;
for (int i = 0; i < count; i++) {
TreeColumn column = mColumns.get(i);
pos += column.getWidth();
if (x >= pos - HIT_SLOP && x <= pos + HIT_SLOP) {
return i;
}
pos += divider;
}
return -1;
} |
ecab70f4-7b3e-48fa-8a6c-b82f667e56fe | 0 | @Test
public void testStartPlagiatsSearchInt()
{
assertEquals(0, 0);
} |
4a7d9d7f-8919-4e0a-997c-05b2ec40d4ec | 1 | public ArrayList<AbilityType> getAbilities() {
ArrayList<AbilityType> abilities = new ArrayList<AbilityType>();
for (int c = 0; c < activeEnchants.size(); c++) {
abilities.add(ActiveWeaponEnchant.getAbility(activeEnchants.get(c)));
}
return abilities;
} |
6601573d-84ce-40fd-b28b-761e3ec27a23 | 5 | @Override
public void handleCollision(Actor other) {
if(other instanceof Projectile){
hitPoints -= ((Projectile) other).getDamage();
} else if ( other instanceof Asteroid || other instanceof actor.ship.Ship){
// Don't collide with our siblings
if(other.getParentId() != null && other.getParentId().equals(getParentId()))
return;
// "Die" for our next update
hitPoints = 0;
}
} |
a2a8bc76-f40c-492b-a64f-11974309cc2c | 7 | public void testSetValue() {
Integer scalar = 0;
List<Integer> list = Arrays.asList(1, 2, 3);
ListELResolver resolver = new ListELResolver();
ListELResolver resolverReadOnly = new ListELResolver(true);
// base == null --> unresolved
context.setPropertyResolved(false);
resolver.setValue(context, null, "foo", -1);
assertFalse(context.isPropertyResolved());
// base is scalar --> unresolved
context.setPropertyResolved(false);
resolver.setValue(context, scalar, "foo", -1);
assertFalse(context.isPropertyResolved());
// base is array, property == 1 --> ok
context.setPropertyResolved(false);
resolver.setValue(context, list, 1, 999);
assertEquals(999, list.get(1).intValue());
assertTrue(context.isPropertyResolved());
// base is array, bad property --> exception
try {
resolver.setValue(context, list, null, 999);
fail();
} catch (IllegalArgumentException e) {
// fine
}
try {
resolver.setValue(context, list, "foo", 999);
fail();
} catch (IllegalArgumentException e) {
// fine
}
try {
resolver.setValue(context, list, -1, 999);
fail();
} catch (PropertyNotFoundException e) {
// fine
}
try {
resolver.setValue(context, list, list.size(), 999);
fail();
} catch (PropertyNotFoundException e) {
// fine
}
// base is array, property == 1, value == null --> ok
context.setPropertyResolved(false);
resolver.setValue(context, list, 1, null);
assertNull(list.get(1));
assertTrue(context.isPropertyResolved());
// base is array, property == 1, bad value --> exception
try {
resolver.setValue(context, list, 1, "foo");
fail();
} catch (ClassCastException e) {
// fine, according to the spec...
} catch (IllegalArgumentException e) {
// violates the spec, but we'll accept this...
}
// read-only resolver
try {
resolverReadOnly.setValue(context, list, 1, 999);
fail();
} catch (PropertyNotWritableException e) {
// fine
}
} |
0b601bf3-bf7f-481f-bb9b-68a0d3aff989 | 5 | public double getLatticeAngle(double arcFraction) {
if (arcLattice == null) {
generateArcLattice();
}
if (arcFraction < 0) {
return 0;
}
double hemispherePortion = (int)(arcFraction / 0.5) * Math.PI;
double remainderArcLength = (arcFraction % 0.5) * latticeArcLength;
int startI = 0, endI = arcLattice.length - 1, middleI;
while (endI - startI > 1) {
middleI = (endI - startI)/2 + startI;
if (remainderArcLength >= arcLattice[middleI]) {
startI = middleI;
continue;
}
if (remainderArcLength <= arcLattice[middleI]) {
endI = middleI;
continue;
}
}
double remainderPortion = ((remainderArcLength - arcLattice[startI])/(arcLattice[endI] - arcLattice[startI]) + startI)*ARC_ANGLE;
return (hemispherePortion + remainderPortion) % (Math.PI * 2);
} |
c93cc54c-49ff-4f4f-bb29-6199b7a60486 | 3 | private static String constructNEPerson(String input, String verb) throws InvalidFormatException, IOException
{
if (!verb.equals("") && !verb.equals("is"))
{
return "Did you " + verb + " " + nameFinderChatbot.findNames(input)[0] + "?";
}
else if (verb.equals("is"))
return "Nice to meet you " + nameFinderChatbot.findNames(input)[0] + ".";
else
return "Are you " + nameFinderChatbot.findNames(input)[0] + "?";
} |
33ea9733-91d4-459f-a6e6-d5da02716bb4 | 5 | public int CheckAdd() throws SQLException
{
int NbreAjout=0;
ResultSet R=M.exec("SELECT value FROM variable WHERE ID=1");
if(R!=null && R.absolute(1))
{
int x=R.getInt("Value");
ResultSet RS=M.exec("SELECT COUNT(*)FROM message");
if (RS!=null && RS.absolute(1)) {
int y=RS.getInt("COUNT(*)");
if(x<y)
{
NbreAjout=y-x;
}
}
}
return NbreAjout;
} |
534b4acb-16da-4600-b974-223bb94b7cbb | 4 | @Override
public void run() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(this.port);
//If no haertbeat from worker process ... then timeout.
serverSocket.setSoTimeout(ACCEPT_TIMEOUT);
while(true) {
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
//Should this part be in a separate thread using thread pool or
//can add retries in RegistryClient as that is the only place through
//which clients will interact with the RegistryServer.
ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
WorkerHeartbeat hb = (WorkerHeartbeat)ois.readObject();
//System.out.println("Received heartbeat from worker");
WorkerHeartbeatResponse response = handleHeartbeat(hb);
ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());
oos.writeObject(response);
oos.flush();
ois.close();
oos.close();
clientSocket.close();
} catch (InterruptedIOException timeout) {
startTaskRunner();
} catch (Exception exc) {
exc.printStackTrace();
} finally {
}
}
} catch (Exception e) {
e.printStackTrace();
}
} |
9434e50c-3c0e-449d-afd4-4fdafa0fe515 | 7 | private Mode extractRuleMode() throws XMLStreamException, ParserException {
String modeName = "";
boolean isModeNegation = false;
Tag startTag = currTag;
if (Tag.NOT.equals(currTag)) isModeNegation = true;
do {
int event = reader.next();
switch (event) {
case XMLStreamConstants.START_ELEMENT:
currTag = getXmlTag(reader.getLocalName());
break;
case XMLStreamConstants.END_ELEMENT:
if (startTag.equals(currTag)) return new Mode(modeName.trim(), isModeNegation);
break;
case XMLStreamConstants.CHARACTERS:
if (Tag.MODE.equals(currTag)) {
modeName += reader.getText();
}
break;
}
} while (reader.hasNext());
throw new ParserException(ErrorMessage.IO_UNEXPECTED_END_OF_FILE);
} |
a9f625c0-ab93-4fd3-adbb-42882f05ccad | 6 | public boolean canPlaceRoad(EdgeLocation edgeLoc) {
if (!playingRoadBuildingCard) {
if (presenter.getState().getStatus().equals("FirstRound") || presenter.getState().getStatus().equals("SecondRound")) {
return presenter.canPlaceRoad(edgeLoc, true);
}
else {
return presenter.canPlaceRoad(edgeLoc, false);
}
}
else {
if (numRoadsPlaced == 0) {
return presenter.canPlaceRoad(edgeLoc, true);
}
else {
if (edgeLoc.getHexLoc().getX() == 1 && edgeLoc.getHexLoc().getY() == -2)
return presenter.getClientModel().canPlayRoadBuilding(presenter.getPlayerInfo().getIndex(), edgeLoc1, edgeLoc);
else
return presenter.getClientModel().canPlayRoadBuilding(presenter.getPlayerInfo().getIndex(), edgeLoc1, edgeLoc);
}
}
} |
7d367aca-afdd-4de2-afd7-0326c603c82f | 8 | @Override
public void run() {
boolean stop = false;
while (!isInterrupted() && !stop) try {
Thread.sleep(1000);
if (appBehaviorObserver == null) continue;
ResourcePrincipal[] tmp = bean.getApplications();
Set<ResourcePrincipal> newSet = new HashSet<ResourcePrincipal>(tmp.length);
for (int i = 0; i < tmp.length; i++) {
if (!principals.contains(tmp[i])) appBehaviorObserver.newApp(tmp[i]);
else appBehaviorObserver.informationChange(tmp[i]);
newSet.add(tmp[i]);
}
for (ResourcePrincipal rp : principals)
if (!newSet.contains(rp))
appBehaviorObserver.removeApp(rp);
principals = newSet;
stop = appBehaviorObserver.isStopped();
} catch (InterruptedException e) {
e.printStackTrace();
}
} |
027819ae-8da9-4e85-8490-30f3e6fe5c33 | 9 | public void execute(final JGraphLayout layout) {
if (graph != null && graph.isEnabled() && graph.isMoveable()
&& layout != null) {
final JGraphFacade facade = createFacade(graph);
final ProgressMonitor progressMonitor = (layout instanceof JGraphLayout.Stoppable) ? createProgressMonitor(
graph, (JGraphLayout.Stoppable) layout)
: null;
new Thread() {
public void run() {
synchronized (this) {
try {
// Executes the layout and checks if the user has
// clicked
// on cancel during the layout run. If no progress
// monitor
// has been displayed or cancel has not been pressed
// then
// the result of the layout algorithm is processed.
layout.run(facade);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
boolean ignoreResult = false;
if (progressMonitor != null) {
ignoreResult = progressMonitor
.isCanceled();
progressMonitor.close();
}
if (!ignoreResult) {
// Processes the result of the layout
// algorithm
// by creating a nested map based on the
// global
// settings and passing the map to a
// morpher
// for the graph that should be changed.
// The morpher will animate the change
// and then
// invoke the edit method on the graph
// layout
// cache.
Map map = facade.createNestedMap(true,
(flushOriginCheckBox
.isSelected()) ? true
: false);
morpher.morph(graph, map);
graph.requestFocus();
}
}
});
} catch (Exception e) {
e.printStackTrace();
JOptionPane
.showMessageDialog(graph, e.getMessage());
}
}
}
}.start(); // fork
}
} |
010b3e3c-9ba5-4393-98a5-cd0d5e0c4ba6 | 9 | public static void openURL(String url) {
try { //attempt to use Desktop library from JDK 1.6+
Class<?> d = Class.forName("java.awt.Desktop");
d.getDeclaredMethod("browse", new Class[]{java.net.URI.class}).invoke(
d.getDeclaredMethod("getDesktop").invoke(null),
new Object[]{java.net.URI.create(url)});
//above code mimicks: java.awt.Desktop.getDesktop().browse()
} catch (Exception ignore) { //library not available or failed
String osName = System.getProperty("os.name");
try {
if (osName.startsWith("Mac OS")) {
Class.forName("com.apple.eio.FileManager").getDeclaredMethod(
"openURL", new Class[]{String.class}).invoke(null,
new Object[]{url});
} else if (osName.startsWith("Windows"))
Runtime.getRuntime().exec(
"rundll32 url.dll,FileProtocolHandler " + url);
else { //assume Unix or Linux
String browser = null;
for (String b : browsers)
if (browser == null && Runtime.getRuntime().exec(new String[]
{"which", b}).getInputStream().read() != -1)
Runtime.getRuntime().exec(new String[]{browser = b, url});
if (browser == null)
throw new Exception(Arrays.toString(browsers));
}
} catch (Exception e) {
}
}
} |
79a49f21-538a-494a-8583-6bcc43d9f4e9 | 2 | private void dfs(Digraph G, int v)
{
marked[v] = true;
preOrder.add(v);
for (int w : G.adj(v))
if (!marked[w])
dfs(G, w);
postOrder.add(v);
reversePostOrder.push(v);
} |
2eb37a19-99b3-4804-a3b7-4d6e5fc9a869 | 9 | @EventHandler
public void onMove(PlayerMoveEvent e) {
Location locFrom = e.getFrom();
Location locTo = e.getTo();
Player p = e.getPlayer();
Benutzer b = this.plugin.alleBenutzer.get(p.getName());
for (Map.Entry<String, Gebiet> mapGebiet : this.plugin.alleGebiete.entrySet()) {
Gebiet g = mapGebiet.getValue();
if (g.isInside(locTo) && !g.isInside(locFrom)){
// Gebiet Enter
if (g.checkEnterAllowed(b, p)){
g.onEnter(b, p);
} else {
p.teleport(locFrom);
p.sendMessage("Du darfst dieses Gebiet nicht betreten");
}
} else if (!g.isInside(locTo) && g.isInside(locFrom)) {
// Gebiet Leave
if (g.checkLeaveAllowed(b, p)){
g.onLeave(b, p);
} else {
p.teleport(locFrom);
p.sendMessage("Du darfst dieses Gebiet nicht verlassen");
}
} else if (g.isInside(locTo) && g.isInside(locFrom)) {
// Im Gebiet
} else {
// Nicht im Gebiet
}
}
} |
d7899017-d537-464f-8ef3-f7e8e0e6fcf8 | 7 | public UserView() {
frame = this;
this.setTitle("Library");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPanel = new JPanel();
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPanel.setLayout(new BorderLayout(0,0));
setContentPane(contentPanel);
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
int index = tabbedPane.getSelectedIndex();
if(index == 0){
frame.setSize(getMaximumSize());
}
else if(index == 1){
frame.setSize(400,250);
}
else if(index == 2 || index == 4){
frame.setSize(700,600);
}
else if(index == 3){
frame.setSize(400,400);
}
}
});
contentPanel.add(tabbedPane, BorderLayout.CENTER);
/*
* Search panel
*/
JPanel searchPanel = new JPanel();
tabbedPane.addTab("Search", null, searchPanel, null);
JPanel searchOptoinsPanel = new JPanel();
searchOptoinsPanel.setBorder(BorderFactory.createTitledBorder("Enter criteria"));
searchPanel.add(searchOptoinsPanel);
JPanel selectOptionsPanel = new JPanel();
selectOptionsPanel.setBorder(BorderFactory.createTitledBorder("Search or reset"));
searchPanel.add(selectOptionsPanel);
JPanel messageBoardpanel = new JPanel();
messageBoardpanel.setBorder(BorderFactory.createTitledBorder("Messages"));
searchPanel.add(messageBoardpanel);
JLabel infoLabel = new JLabel("Click on a book/row to chek it out");
infoLabel.setAlignmentX(LEFT_ALIGNMENT);
messageBoardpanel.add(infoLabel);
errorMessageLabel = new JLabel("");
errorMessageLabel.setAlignmentY(RIGHT_ALIGNMENT);
messageBoardpanel.add(errorMessageLabel);
JPanel tablePanel = new JPanel();
tablePanel.setBorder(BorderFactory.createTitledBorder("Table"));
tablePanel.setLayout(new BorderLayout(0,0));
searchPanel.add(tablePanel);
/*
* Set up table
*/
Object[] coulmnNames = {"Book ID", "Title", "Author", "Branch ID","Total copies","Available"};
serachTableModel = new DefaultTableModel(coulmnNames,0 );
searchTable = new JTable(serachTableModel) {
private static final long serialVersionUID = 1L;
public boolean isCellEditable(int row, int column) {
return false;
};
};
JScrollPane searchScrollPane = new JScrollPane(searchTable);
tablePanel.add(searchScrollPane);
searchButton = new JButton("Search");
selectOptionsPanel.add(searchButton);
JButton resetButton = new JButton("Reset fields");
selectOptionsPanel.add(resetButton);
//set box layout for vertical alignment of search options, buttons and table output
searchPanel.setLayout(new BoxLayout(searchPanel,BoxLayout.Y_AXIS));
JLabel bookIDLabel = new JLabel("Book ID");
searchOptoinsPanel.add(bookIDLabel);
bookIDTextField = new JTextField();
searchOptoinsPanel.add(bookIDTextField);
bookIDTextField.setColumns(10);
JLabel titleLabel = new JLabel("Title");
searchOptoinsPanel.add(titleLabel);
titleTextField = new JTextField();
searchOptoinsPanel.add(titleTextField);
titleTextField.setColumns(10);
normalSearchPanel = new JPanel();
searchOptoinsPanel.add(normalSearchPanel);
JLabel authorNameLabel = new JLabel("Author Name");
normalSearchPanel.add(authorNameLabel);
authorNameTextField = new JTextField();
normalSearchPanel.add(authorNameTextField);
authorNameTextField.setColumns(10);
detailedSearchPanel = new JPanel();
searchOptoinsPanel.add(detailedSearchPanel);
detailedSearchPanel.setVisible(false);
JLabel authorFirstNameLabel = new JLabel("First Name");
detailedSearchPanel.add(authorFirstNameLabel);
authorFirstNameTextField = new JTextField();
detailedSearchPanel.add(authorFirstNameTextField);
authorFirstNameTextField.setColumns(10);
JLabel authorMiddleInitialLabel = new JLabel("Initial");
detailedSearchPanel.add(authorMiddleInitialLabel);
authorMiddleInitialTextField = new JTextField();
detailedSearchPanel.add(authorMiddleInitialTextField);
authorMiddleInitialTextField.setColumns(10);
JLabel authorLastNameLabel = new JLabel("Last Name");
detailedSearchPanel.add(authorLastNameLabel);
authorLastNameTextField = new JTextField();
detailedSearchPanel.add(authorLastNameTextField);
authorLastNameTextField.setColumns(10);
detailedSelectionCheckBox = new JCheckBox("Detailed");
searchOptoinsPanel.add(detailedSelectionCheckBox);
detailedSelectionCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
if(normalSearchPanel.isVisible()){
normalSearchPanel.setVisible(false);
detailedSearchPanel.setVisible(true);
}
else if(detailedSearchPanel.isVisible()){
normalSearchPanel.setVisible(true);
detailedSearchPanel.setVisible(false);
}
}
});
searchButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
resizeColumnWidth(searchTable);
}
});
resetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
resetText();
}
});
/*
* Check out panel
*/
JPanel checkOutPanel = new JPanel();
tabbedPane.addTab("Check Out", null, checkOutPanel, null);
checkOutPanel.setLayout(new BorderLayout());
JPanel checkoutOptionsPanel = new JPanel();
//checkoutOptionsPanel.setLayout(new BoxLayout(checkoutOptionsPanel,BoxLayout.Y_AXIS ));
checkOutPanel.add(checkoutOptionsPanel);
checkoutOptionsPanel.setLayout(new GridLayout(5, 6, 0, 0));
JLabel bookIDCheckOutLabel = new JLabel("Book ID");
checkoutOptionsPanel.add(bookIDCheckOutLabel);
bookIDCheckoutTextField = new JTextField();
bookIDCheckoutTextField.setSize(new Dimension(this.getWidth(),2));
checkoutOptionsPanel.add(bookIDCheckoutTextField);
bookIDCheckoutTextField.setColumns(10);
JLabel branchIDCheckoutLabel = new JLabel("Branch ID");
checkoutOptionsPanel.add(branchIDCheckoutLabel);
branchIDCheckoutTextField = new JTextField();
branchIDCheckoutTextField.setSize(new Dimension(this.getWidth(),1));
checkoutOptionsPanel.add(branchIDCheckoutTextField);
branchIDCheckoutTextField.setColumns(10);
JLabel cardNoCheckoutLabel = new JLabel("Card Number");
checkoutOptionsPanel.add(cardNoCheckoutLabel);
cardNumberCheckoutTextField = new JTextField();
cardNumberCheckoutTextField.setSize(new Dimension(this.getWidth(),1));
checkoutOptionsPanel.add(cardNumberCheckoutTextField);
cardNumberCheckoutTextField.setColumns(10);
JPanel checkOutButtonPanel1 = new JPanel();
checkoutOptionsPanel.add(checkOutButtonPanel1);
checkOutButtonPanel1.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
checkOutButton = new JButton("Check Out");
checkOutButtonPanel1.add(checkOutButton);
JButton checkOutResetButton = new JButton("Reset");
checkOutButtonPanel1.add(checkOutResetButton);
JPanel checkOutInfoPanel = new JPanel();
checkoutOptionsPanel.add(checkOutInfoPanel);
checkOutInfoPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
checkOutInfoLabel = new JLabel("");
checkOutInfoPanel.add(checkOutInfoLabel);
checkOutResetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
resetText();
}
});
/*
* Check In panel
*/
JPanel checkInPanel = new JPanel();
tabbedPane.addTab("Check In", null, checkInPanel, null);
checkInPanel.setLayout(new BoxLayout(checkInPanel,BoxLayout.Y_AXIS));
JPanel checkInFieldsPanel = new JPanel();
checkInPanel.add(checkInFieldsPanel);
checkInFieldsPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel checkInCardNoLabel = new JLabel("Card Number");
checkInFieldsPanel.add(checkInCardNoLabel);
checkInCardNoTextField = new JTextField();
checkInFieldsPanel.add(checkInCardNoTextField);
checkInCardNoTextField.setColumns(10);
JLabel checkInBookIDLabel = new JLabel("Book ID");
checkInFieldsPanel.add(checkInBookIDLabel);
checkInBookIDTextField = new JTextField();
checkInFieldsPanel.add(checkInBookIDTextField);
checkInBookIDTextField.setColumns(10);
JLabel checkInBorrowerNameLabel = new JLabel("Borrower");
checkInFieldsPanel.add(checkInBorrowerNameLabel);
checkInBorrowerNameTextField = new JTextField();
checkInFieldsPanel.add(checkInBorrowerNameTextField);
checkInBorrowerNameTextField.setColumns(10);
JPanel checkInSearchButtonsPanel = new JPanel();
checkInPanel.add(checkInSearchButtonsPanel);
checkInSearchButtonsPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
checkInSearchButton = new JButton("Search");
checkInSearchButtonsPanel.add(checkInSearchButton);
JButton checkInResetButton = new JButton("Reset");
checkInSearchButtonsPanel.add(checkInResetButton);
checkInInfoLabel = new JLabel("Select value from table, select date and check in");
checkInSearchButtonsPanel.add(checkInInfoLabel);
JScrollPane checkInscrollPane = new JScrollPane();
checkInPanel.add(checkInscrollPane);
Object[] checkInColumnNames = {"Loan ID","Book ID", "Branch_ID", "Card Number", "Borrower Name"};
checkInTableModel = new DefaultTableModel(checkInColumnNames,0 );
checkInTable = new JTable(checkInTableModel);
checkInscrollPane.setViewportView(checkInTable);
JPanel dateSelectPanel = new JPanel();
checkInPanel.add(dateSelectPanel);
dateSelectPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel checkInDateInLabel = new JLabel("Select Check in Date:");
dateSelectPanel.add(checkInDateInLabel);
JPanel checkInButtonsPanel = new JPanel();
checkInPanel.add(checkInButtonsPanel);
checkInButtonsPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
Calendar now = Calendar.getInstance();
String months[] ={"01","02","03","04","05","06","07","08","09","10","11","12"};
monthCombo = new JComboBox<String>(months);
monthCombo.setSelectedIndex(now.get(Calendar.MONTH));
dateSelectPanel.add(monthCombo);
String Dates[] ={"01","02","03","04","05","06","07","08","09","10","11","12",
"13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31"};
dateCombo = new JComboBox<String>(Dates);
dateCombo.setSelectedIndex(now.get(Calendar.DAY_OF_MONTH)-1);
dateSelectPanel.add(dateCombo);
Integer years[] ={2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019,2020,2021,2022,2023,2024,2025};
yearCombo = new JComboBox<Integer>(years);
yearCombo.setSelectedItem(now.get(Calendar.YEAR));
dateSelectPanel.add(yearCombo);
checkInButton = new JButton("Check In");
checkInButtonsPanel.add(checkInButton);
checkInSearchButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
resizeColumnWidth(checkInTable);
checkInInfoLabel.setText("Select value from table, select date and check in");
}
});
checkInResetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
resetText();
}
});
/*
* Borrower panel
*/
JPanel borrowerPanel = new JPanel();
tabbedPane.addTab("Borrower", null, borrowerPanel, null);
borrowerPanel.setLayout(new GridLayout(8, 2, 0, 0));
JLabel borrowerFnameLabel = new JLabel(" First Name");
borrowerPanel.add(borrowerFnameLabel);
borrowerFnameTextField = new JTextField();
borrowerPanel.add(borrowerFnameTextField);
borrowerFnameTextField.setColumns(10);
JLabel borrowerLastNameLabel = new JLabel(" Last Name");
borrowerPanel.add(borrowerLastNameLabel);
borrowerlnameTextField = new JTextField();
borrowerPanel.add(borrowerlnameTextField);
borrowerlnameTextField.setColumns(10);
JLabel borrowerAddressLabel = new JLabel(" Address");
borrowerPanel.add(borrowerAddressLabel);
borrowerAddressTextField = new JTextField();
borrowerPanel.add(borrowerAddressTextField);
borrowerAddressTextField.setColumns(10);
JLabel borrowerPhoneLabel = new JLabel(" Phone Number");
borrowerPanel.add(borrowerPhoneLabel);
borrowerPhoneNumberTextField = new JTextField();
borrowerPanel.add(borrowerPhoneNumberTextField);
borrowerPhoneNumberTextField.setColumns(10);
JLabel borrowerStateLabel = new JLabel(" State");
borrowerPanel.add(borrowerStateLabel);
borrowerStateTextField = new JTextField();
borrowerPanel.add(borrowerStateTextField);
borrowerStateTextField.setColumns(10);
JLabel borrowerCityLabel = new JLabel(" City");
borrowerPanel.add(borrowerCityLabel);
borrowerCityTextField = new JTextField();
borrowerPanel.add(borrowerCityTextField);
borrowerCityTextField.setColumns(10);
borrowerInfoLabel1 = new JLabel("");
borrowerPanel.add(borrowerInfoLabel1);
JLabel borrowerInfoLabel2 = new JLabel("");
borrowerPanel.add(borrowerInfoLabel2);
borrowerAddUserButton = new JButton("Add");
borrowerPanel.add(borrowerAddUserButton);
JButton borrowerResetButton = new JButton("Reset");
borrowerPanel.add(borrowerResetButton);
borrowerResetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
resetText();
}
});
/*
* Fines table
*/
JPanel finesPanel = new JPanel();
tabbedPane.addTab("Fines", null, finesPanel, null);
finesPanel.setLayout(new BoxLayout(finesPanel, BoxLayout.Y_AXIS));
JPanel finesOptionsPanel = new JPanel();
finesPanel.add(finesOptionsPanel);
finesOptionsPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
getFinesButton = new JButton("Get Fines / Refresh");
finesOptionsPanel.add(getFinesButton);
AllFInesCheckBox = new JCheckBox("Show only unpaid");
finesOptionsPanel.add(AllFInesCheckBox);
setVisible(true);
JPanel fineTablePane = new JPanel();
finesPanel.add(fineTablePane);
Object[] finesColumnNames = {"Card Number","Fine Amount", "Paid/Not paid"};
finesTableModel = new DefaultTableModel(finesColumnNames,0 );
finesInTable = new JTable(finesTableModel);
JScrollPane finesScrollPane = new JScrollPane(finesInTable);
fineTablePane.add(finesScrollPane);
JPanel fineOptionsPanel = new JPanel();
finesPanel.add(fineOptionsPanel);
payFineButton = new JButton("Pay Fine");
fineOptionsPanel.add(payFineButton);
fineInfoLabel = new JLabel("make a selection and hit pay fine");
fineOptionsPanel.add(fineInfoLabel);
} |
283703c7-c6e5-44a8-bb6e-011f5ec6927b | 3 | public ArrayList<Local> listar(long pesquisaId) throws Exception
{
String sql = "SELECT * FROM pesquisalocal WHERE id1 = ?";
ArrayList<Local> listaLocal = new ArrayList<Local>();
if (pesquisaId > 0)
{
try
{
PreparedStatement stmt = ConnectionFactory.getConnection().prepareStatement(sql);
stmt.setLong(1, pesquisaId);
ResultSet rs = stmt.executeQuery();
LocalDAO ldao = new LocalDAO();
while (rs.next())
{
Local local = ldao.listar(" WHERE id = " + rs.getLong("id2")).get(0);
listaLocal.add(local);
}
rs.close();
}
catch (SQLException e)
{
throw e;
}
}
return listaLocal;
} |
ebfc4c88-3850-4a42-99fa-709f31502b33 | 6 | @Override
public final String getSqlPredicat() {
if (this.isPolesCollision()) {
return null;
}
final List ranges = (List) computeRange();
final List<Double[]> raRanges = (List<Double[]>) ranges.get(0);
final double[] decRange = (double[]) ranges.get(1);
String predicatDefinition;
if (isNorthPoleCollision()) {
LOG.log(Level.FINEST, "North collision case");
predicatDefinition = String.format(" AND (spoly_overlap_polygon(%s,'{(%sd,%sd),(%sd,%sd),(%sd,%sd)}')", geomCol, 0.0, decRange[0], 45.0, 90.0, 90.0, decRange[0]);
predicatDefinition = predicatDefinition.concat(String.format(" OR spoly_overlap_polygon(%s,'{(%sd,%sd),(%sd,%sd),(%sd,%sd)}')", geomCol, 90.0, decRange[MIN], 135.0, 90.0, 180.0, decRange[MIN]));
predicatDefinition = predicatDefinition.concat(String.format(" OR spoly_overlap_polygon(%s,'{(%sd,%sd),(%sd,%sd),(%sd,%sd)}')", geomCol, 180.0, decRange[MIN], 225.0, 90.0, 270.0, decRange[MIN]));
predicatDefinition = predicatDefinition.concat(String.format(" OR spoly_overlap_polygon(%s,'{(%sd,%sd),(%sd,%sd),(%sd,%sd)}'))", geomCol, 270.0, decRange[MIN], 325.0, 90.0, 360.0, decRange[MIN]));
LOG.log(Level.FINEST, predicatDefinition);
} else if (isSouthPoleCollision()) {
LOG.log(Level.FINEST, "South collision case");
predicatDefinition = String.format(" AND (spoly_overlap_polygon(%s,'{(%sd,%sd),(%sd,%sd),(%sd,%sd)}')", geomCol, 0.0, decRange[MAX], 45.0, -90.0, 90.0, decRange[MAX]);
predicatDefinition = predicatDefinition.concat(String.format(" OR spoly_overlap_polygon(%s,'{(%sd,%sd),(%sd,%sd),(%sd,%sd)}')", geomCol, 90.0, decRange[MAX], 135.0, -90.0, 180.0, decRange[MAX]));
predicatDefinition = predicatDefinition.concat(String.format(" OR spoly_overlap_polygon(%s,'{(%sd,%sd),(%sd,%sd),(%sd,%sd)}')", geomCol, 180.0, decRange[MAX], 225.0, -90.0, 270.0, decRange[MAX]));
predicatDefinition = predicatDefinition.concat(String.format(" OR spoly_overlap_polygon(%s,'{(%sd,%sd),(%sd,%sd),(%sd,%sd)}'))", geomCol, 270.0, decRange[MAX], 325.0, -90.0, 360.0, decRange[MAX]));
LOG.log(Level.FINEST, predicatDefinition);
} else if (isRing()) {
LOG.log(Level.FINEST, "Ring case");
predicatDefinition = String.format(" AND (spoly_overlap_polygon(%s,'{(%sd,%sd),(%sd,%sd),(%sd,%sd), (%sd,%sd)}')", geomCol, 0.0, decRange[MIN], 90.0, decRange[MIN], 90.0, decRange[MAX], 0.0, decRange[MAX]);
predicatDefinition = predicatDefinition.concat(String.format(" OR spoly_overlap_polygon(%s,'{(%sd,%sd),(%sd,%sd),(%sd,%sd), (%sd,%sd)}')", geomCol, 90.0, decRange[MIN], 180.0, decRange[MIN], 180.0, decRange[MAX], 90.0, decRange[MAX]));
predicatDefinition = predicatDefinition.concat(String.format(" OR spoly_overlap_polygon(%s,'{(%sd,%sd),(%sd,%sd),(%sd,%sd), (%sd,%sd)}')", geomCol, 180.0, decRange[MIN], 270.0, decRange[MIN], 270.0, decRange[MAX], 180.0, decRange[MAX]));
predicatDefinition = predicatDefinition.concat(String.format(" OR spoly_overlap_polygon(%s,'{(%sd,%sd),(%sd,%sd),(%sd,%sd), (%sd,%sd)}'))", geomCol, 270.0, decRange[MIN], 0.0, decRange[MIN], 0.0, decRange[MAX], 270.0, decRange[MAX]));
LOG.log(Level.FINEST, predicatDefinition);
} else if (raRanges.size() == 1 && isLargePolygon()) {
LOG.log(Level.FINEST, "Large polygon case");
final Double[] raRange1 = raRanges.get(0);
final double mean = (raRange1[MIN] + raRange1[MAX]) / 2.0;
raRanges.add(new Double[]{mean, raRange1[MAX]});
raRanges.set(0, new Double[]{raRange1[MIN], mean});
predicatDefinition = buildMultiPolygon(raRanges, decRange);
LOG.log(Level.FINEST, predicatDefinition);
} else {
LOG.log(Level.FINEST, "other case");
predicatDefinition = buildMultiPolygon(raRanges, decRange);
LOG.log(Level.FINEST, predicatDefinition);
}
return predicatDefinition;
} |
168148f7-3b39-4027-aec3-e7769c4571ad | 8 | @Override
public int castingQuality(MOB mob, Physical target)
{
if((mob!=null)&&(target!=null))
{
if(anyWeapons(mob))
return Ability.QUALITY_INDIFFERENT;
if(mob.rangeToTarget()>0)
return Ability.QUALITY_INDIFFERENT;
if(CMLib.flags().isSitting(mob))
return Ability.QUALITY_INDIFFERENT;
if(mob.charStats().getBodyPart(Race.BODY_ARM)<=1)
return Ability.QUALITY_INDIFFERENT;
if(target.basePhyStats().weight()>(mob.basePhyStats().weight()*2))
return Ability.QUALITY_INDIFFERENT;
if(target.fetchEffect(ID())!=null)
return Ability.QUALITY_INDIFFERENT;
}
return super.castingQuality(mob,target);
} |
b54d2b89-752e-4f79-8e1e-210e236c5954 | 7 | static final void getClientSignature(ByteBuffer buffer, byte i) {
anInt8248++;
byte[] is = new byte[24];
if (i == 55) {
if (Class374.randomDatBufferedFile != null) {
try {
Class374.randomDatBufferedFile.method789(0L, (byte) -120);
Class374.randomDatBufferedFile.method784(-89, is);
int i_170_;
for (i_170_ = 0; (i_170_ ^ 0xffffffff) > -25; i_170_++) {
if (is[i_170_] != 0)
break;
}
if ((i_170_ ^ 0xffffffff) <= -25)
throw new IOException();
} catch (Exception exception) {
for (int i_171_ = 0; (i_171_ ^ 0xffffffff) > -25; i_171_++)
is[i_171_] = (byte) -1;
}
}
buffer.putBytes(24, 0, is);
}
} |
68291ef1-36bc-4597-a92b-5545dba201c0 | 9 | public String[][] cantidadCitasMedico (String mes,String ano ){
String sql_consult;
String fecha_ini, fecha_fin;
String [] [] resultado = null;
String dia_final;
int mes_entero = Integer.parseInt(mes);
switch (mes_entero)
{
case 2 : dia_final = "28"; break;
case 4 : dia_final = "30"; break;
case 6 : dia_final = "30"; break;
case 9 : dia_final = "30"; break;
case 11 : dia_final = "30"; break;
default : dia_final= "31"; break;
}
fecha_ini = ano +"-"+ mes + "-01";
fecha_fin = ano+ "-" + mes + "-" + dia_final;
sql_consult = "SELECT DISTINCT C.id_medico, P.nombre, Count (id_paciente) nombre FROM " +
"Persona as P, Cita as C WHERE C.id_medico = P.id AND C.estado = 'Programada' " +
"AND fecha BETWEEN ' " +fecha_ini +"' AND ' " +fecha_fin + "'GROUP BY C.id_medico , P.nombre";
System.out.println(sql_consult);
try{
Statement statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet table = statement.executeQuery(sql_consult);
int i = 0;
table.last();
int filas = table.getRow();
if (filas !=0) {resultado = new String [filas][3];}
table.first();
table.previous();
while (table.next ())
{
resultado [i][0] = table.getString(1);
resultado [i][1] = table.getString(2);
resultado [i][2] = Integer.toString(table.getInt(3));
}
}
catch(SQLException e){
System.out.println(e);
resultado = new String [1][1];
resultado [0][0] = null;
}
catch(Exception e){
System.out.println(e);
resultado = new String [1][1];
resultado [0][0] = null;
}
return resultado;
} |
f2516e9e-351c-4c10-a9b5-aebbf02155b7 | 1 | private int getNumeroInstruccion (String nombre) {
int procACargar = 0;
while (!procedimientos.get(procACargar).getNombre().equals(nombre))
procACargar++;
return procedimientos.get(procACargar).getQuadruploInicio();
} |
e105f889-02f3-4560-93f5-c26da82b3979 | 3 | public void print(PrintStream out) {
out.println("Settings");
for (Setting setting : map.values()) {
if (setting instanceof AlgFileSetting)
continue;
if (setting.getLocked()) {
out.println(" " + setting.getName() + ": " + setting.getString());
} else {
out.println(" " + setting.getName() + ": [" + setting.getString() + "]");
}
}
} |
e3aa5090-e675-42c1-b4ae-13cb9e7654f3 | 6 | public static void main(String[] args)throws IOException
{
double finalAnswer=-99999;
double finalcurvePoints=0;
double finalPeriod=0;
double finalPercDif=0;
double finalminSRDif=0;
double finalTP=0;
double[] PortfolioValue=new double[60*260];
double[] BaseValue=new double[60*260];
final XYSeriesCollection dataset = new XYSeriesCollection();
for(int curvePoints =10;curvePoints<=10;curvePoints++){ //4
for(int period=10;period<=10;period++){ //2
for(int difPercenti=34;difPercenti<=34;difPercenti++){ //28
for(int minSRDif=37;minSRDif<=37;minSRDif++){ //34
for(int TPi=14;TPi<=14;TPi++){ //32
double difPercent=(double)difPercenti/100;
double minSRDifin=(double)minSRDif/1000;
double TP=(double)TPi/1000;
double answer=OptimiseParameters(minSRDifin,curvePoints,period,difPercent, TP,PortfolioValue,BaseValue,dataset);
System.err.println(answer);
if(finalAnswer<answer){
finalminSRDif=minSRDifin;
finalAnswer=answer;
finalcurvePoints=curvePoints;
finalPeriod=period;
finalPercDif=difPercent;
finalTP=TP;
}
}
}
}
}
}
System.out.println("The best parameters are : ");
System.out.println("period : "+finalPeriod);
System.out.println("curvePoints : "+finalcurvePoints);
System.out.println("PercentDifferenceNeeded : "+finalPercDif);
System.out.println("finalminSRDif : "+finalminSRDif);
System.out.println("TP : "+finalTP);
System.out.println("The best effective annual return for these parameters is : "+finalAnswer);
} |
f62ddb13-3241-405e-a948-29b167f24eae | 4 | public void run() {
// Сначала нужно проинициализировть данные откуда то
// Создать мир
this.init();
long startTime;
long currentTime;
startTime = System.currentTimeMillis();
while (true) {
// Допустим, я не хочу чтобы игра просчитывалась чаще чем 60 раз в секунду.
// Вообщем 17 миллисекунд на проход
currentTime = System.currentTimeMillis();
if ((currentTime - startTime) < MIN_ITERATION_TIME) {
try {
Thread.sleep(MIN_ITERATION_TIME - (currentTime - startTime));
} catch (Exception ex) {
}
}
startTime = System.currentTimeMillis();
gameTime = startTime;
// Тут выполняется цикл обсчёта игры
// Игра в целом состоит из ряда игровых зон
// Так же из объектов перемещающихся между игорвыми зонами
// Происходящее в одной игровой зоне МОЖЕТ влиять на происходящее в другой.
// Напрмер - потерян ретранслятор, тогда в другой системе корабли теряют управление.
// Каждая игровая зона обсчитывается в своём потоке.(?)
Iterator it = areas.entrySet().iterator();
while (it.hasNext()) {
Map.Entry m = (Map.Entry) it.next();
GameArea area = (GameArea) m.getValue();
area.update();
}
}
} |
5a8f0a41-becf-40fb-8cc3-cfbe34b87b3d | 8 | public Object calculate(SecuredTaskBean task) throws GranException {
HashMap<String, SecuredUDFValueBean> m = task.getUDFValues();
SecuredUDFValueBean ci = m.get(INCIDENT_PRODUCT_UDFID);
List<String> bf = new ArrayList<String>();
if (ci != null) {
Object value = ci.getValue();
if (value != null) {
List<SecuredTaskBean> productsInvolved = (List<SecuredTaskBean>) value;
if (!productsInvolved.isEmpty()) {
for (SecuredTaskBean product : productsInvolved) {
HashMap<String, SecuredUDFValueBean> udfValues = product.getUDFValues();
SecuredUDFValueBean replacement = udfValues.get(PRODUCT_REPLACEMENT_UDFID);
Object replacementValue = replacement.getValue();
if (replacementValue!=null){
List<SecuredTaskBean> newCI = (List<SecuredTaskBean>) replacementValue;
if (!newCI.isEmpty())
for (SecuredTaskBean c : newCI)
if (c.getStatusId().equals(PRODUCT_STATE_IN_USE))
bf.add("#"+c.getNumber());
}
}
}
}
return bf;
}
else return null;
} |
3228c9e6-2997-4665-8656-d8c1bceacb66 | 7 | public byte[] HandleRevealMessage(byte[] data)
{
RevealationMessage message = new RevealationMessage(ByteBuffer.wrap(data));
switch(message._revealationApi)
{
case (byte) 0xE3:
// ECM/Appliance Info
return HandleDeviceInformation(message._transactionId,message._revealationOpcode,message._revealationApi , "WPR33336L6L");
case (byte) 0xE4: // Reveal Subscription
return HandleRevealSubscriptionCommands(message._transactionId,message._revealationApi,message._revealationOpcode);
case (byte) 0xE5: // ECM Cache
break;
case (byte) 0xE6: // Reveal Interface
break;
case (byte) 0xE7: // Energy Measurements
break;
case (byte) 0xE8: //Date/Time Api
return HandleDateTimeCommands(message._transactionId,message._revealationApi,message._revealationOpcode);
case (byte) 0xE9: //Reset ECM Api
break;
default: break;
}
return null;
} |
0fbf20d6-8152-4a1b-a5ce-3f40c027016e | 4 | private void lol() {
Calendar cal = new GregorianCalendar(TimeZone.getDefault());
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
if (month == 3 && day == 1) {
xAuthLog.warning("Your trial version of xAuth expires today!");
xAuthLog.warning("Purchase the full version on Steam for $19.99.");
} else if (month == 3 && day == 2)
xAuthLog.info("April Fools!! xAuth will always be free!");
} |
214aa4ac-8b9f-4f6f-947b-a0f37f760156 | 0 | private void jButton0MouseMouseClicked(MouseEvent event) {
SelectFrame lf = new SelectFrame();
lf.setDefaultCloseOperation(SelectFrame.EXIT_ON_CLOSE);
lf.setTitle("SELECT");
lf.getContentPane().setPreferredSize(lf.getSize());
lf.pack();
lf.setLocationRelativeTo(null);
lf.setVisible(true);
this.dispose();
} |
397313a1-c0cf-45aa-b6bc-051023a5f922 | 4 | @Override
public String toString()
{
StringBuilder sb = new StringBuilder();
for (int y = 0; y < board.length; y++)
{
for (int x = 0; x < board[y].length; x++)
{
if (x > 0)
{
sb.append( ' ' );
}
sb.append( board[y][x] ? 'O' : '-' );
}
sb.append( '\n' );
}
return sb.toString();
} |
e8210518-7bb6-4061-8a5f-d6932603428a | 3 | private void setupFromQuestion(BonusQuestion bq) {
tfPromptInput.setText(bq.getPrompt());
if (bq.getBonusType() == BonusQuestion.BONUS_TYPE.MULTI) {
rbMultChoice.setSelected(true);
String[] choice = bq.getChoices();
for (int i = 0; i < tfMultiList.size(); i++) {
tfMultiList.get(i).setText(choice[i]);
// set the correct answer to be selected
if (choice[i].equals(bq.getAnswer()))
rbAnsList.get(i).setSelected(true);
}
} else { // its a short answer then
rbShortAnswer.setSelected(true);
tfShortAnswer.setText(bq.getAnswer());
}
cardsQPanel.show(pnlQuestionEdit, STEP_1);
setEnableNewQPanel(true);
} |
6990382a-9324-4960-b2bb-20ab08e588ac | 3 | @Override
public boolean equals(Object object){
if(!(object instanceof Move)){
return false;
}
Move move = (Move)object;
boolean equals = getColumn() == move.getColumn();
equals = equals && getRow() == move.getRow();
equals = equals && getPlayer() == move.getPlayer();
return equals;
} |
ddce3a14-a75d-42d9-a4c7-be18495dd8a5 | 2 | HospitalPart getHospitalizeRoom() {
double t = nextRand();
if ( t < 0.5 )
return HospitalPart.SURGERY;
else if ( t < 0.75 )
return HospitalPart.ICU;
else
return HospitalPart.CCU;
} |
39116dc9-89df-4333-9728-26ff1d3babea | 6 | public boolean canSplit2()
{
//Whoa... This gets complicated if I have to
//take into acount the "don't care" of transparent colors...
int[] data = new int[min.length];
boolean[] seen = new boolean[min.length];
for (MultiColor c : freqTable.keySet())
if (inside(c))
for (int i = 0; i < min.length; i++)
if (c.data[i] != -1)
if (!seen[i]) //First val we see
{
seen[i] = true;
data[i] = c.data[i];
} else if (data[i] != c.data[i])
return true;
return false;
} |
55f43adc-b768-4649-8245-e70f8ac4a3d3 | 4 | boolean isUnzipAddDirectory(String targetPath, String fileName) throws RemoteException {
// result:Used to store the result information of the command execution
ArrayList<String> result = new ArrayList<String>(0);
// errorResult:Used to store the error information of the command
// execution
ArrayList<String> errorResult = new ArrayList<String>(0);
String cmd = "cd " + targetPath + " && zipinfo -1 " +fileName;
this.reauthInfo.execCommand(conncontroller, cmd, result, errorResult);
if (result.isEmpty())
return false;
else
{
for(int i=0;i<result.size();i++)
{
if(result.get(i).contains("/"))
{
if(!result.get(i).startsWith(fileName.substring(0,fileName.indexOf(".zip"))))
{
return true;
}
}
}
return false;
}
} |
278c0b84-1b36-4af1-93b4-ec31163c1427 | 4 | public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (!plugin.hasPerm(sender, "reply", false)) {
sender.sendMessage(ChatColor.YELLOW
+ "You do not have permission to use /" + label);
return true;
}
Player player = (Player) sender;
String msg = plugin.message(args);
String[] replyArray = CraftEssence.reply.toArray(new String[] {});
for (String list : replyArray) {
String[] split = list.split(":");
if (split[1].equalsIgnoreCase(player.getName().toLowerCase())) {
Player sendTo = plugin.playerMatch(split[0]);
CraftEssence.reply.add(player.getName().toLowerCase() + ":"
+ sendTo.getName().toLowerCase());
sendTo.sendMessage(ChatColor.YELLOW + "[From -> "
+ player.getDisplayName() + "] " + ChatColor.WHITE
+ msg);
player.sendMessage(ChatColor.YELLOW + "[To -> "
+ sendTo.getDisplayName() + "] " + ChatColor.WHITE
+ msg);
UserTable ut = plugin.getDatabase().find(UserTable.class)
.where().ieq("userName", sendTo.getName()).findUnique();
if (ut.isAfk())
player.sendMessage(ChatColor.YELLOW + sendTo.getName()
+ " is currently afk.");
// CraftEssence.reply.remove(sendTo.getName().toLowerCase() +
// ":" + player.getName().toLowerCase());
}
}
return true;
} |
f5034aac-559d-483a-bac3-b81231d54ab9 | 3 | public void keyTyped(KeyEvent pEvent) {
char key = pEvent.getKeyChar();
String strKey = TableViewAdapter.removeSpecialCharacter(new Character(key).toString());
if (System.currentTimeMillis() - mPreviousTime < RESET_TIME) {
mTextToFind = mTextToFind + strKey;
}
else {
mTextToFind = strKey;
}
mPreviousTime = System.currentTimeMillis();
for (int i = 1; i < getRowCount(); i++) {
int row = (i + getSelectedRow()) % getRowCount();
if (TableViewAdapter.removeSpecialCharacter(getSelectedColumnObject().getValue(
((TableViewAdapter) getModel()).getNewRow(row)).toString()).startsWith(mTextToFind)) {
setRowSelectionInterval(row, row);
scrollToSelection();
i = getRowCount();
}
}
} |
bcdfc71c-acb7-4661-897a-dbb8f482fd8e | 9 | @Override
@SuppressWarnings("SleepWhileInLoop")
public void run() {
try {
int countSent = 0;
int countUnsent = 0;
String from = null;
String date = null;
String body = null;
for (int i = 0; i < selectedDocNames.size(); i++) {
WriteSMSToDocFile wsmstdf = new WriteSMSToDocFile();
jdre.getjLabelResendEmail().setText("<html>Reseding <em>" + i + "</em> of <em>" + selectedDocNames.size() + "</em> unsent Message documents. Please wait..");
jdre.getjTextAreaResendEmails().append("Generating doc\t : " + selectedDocNames.get(i) + "\n");
wsmstdf.setDocument(selectedDocNames.get(i));
switch (emailCase) {
case 0: {
from = view.getjTableWhatsappMsgs().getValueAt(convertIntegers(resendUnSentDocs)[i], 1).toString();
date = view.getjTableWhatsappMsgs().getValueAt(convertIntegers(resendUnSentDocs)[i], 2).toString();
body = view.getjTableWhatsappMsgs().getValueAt(convertIntegers(resendUnSentDocs)[i], 3).toString();
break;
}
case 1: {
from = view.getjTableWhatsappMsgs().getValueAt(convertIntegers(resendUnSentDocs)[i], 1).toString();
date = view.getjTableWhatsappMsgs().getValueAt(convertIntegers(resendUnSentDocs)[i], 2).toString();
body = view.getjTableWhatsappMsgs().getValueAt(convertIntegers(resendUnSentDocs)[i], 3).toString();
break;
}
case 2: {
from = view.getjTableWhatsappMsgs().getValueAt(convertIntegers(resendSentDocs)[i], 1).toString();
date = view.getjTableWhatsappMsgs().getValueAt(convertIntegers(resendSentDocs)[i], 2).toString();
body = view.getjTableWhatsappMsgs().getValueAt(convertIntegers(resendSentDocs)[i], 3).toString();
break;
}
case 3: {
from = view.getjTableWhatsappMsgs().getValueAt(convertIntegers(resendMixedDocs)[i], 1).toString();
date = view.getjTableWhatsappMsgs().getValueAt(convertIntegers(resendMixedDocs)[i], 2).toString();
body = view.getjTableWhatsappMsgs().getValueAt(convertIntegers(resendMixedDocs)[i], 3).toString();
break;
}
}
wsmstdf.setParagraph(from, date, body);
wsmstdf.doWritting();
jdre.getjTextAreaResendEmails().append("Generating ok? \t : Generation successful.\n");
jdre.getjTextAreaResendEmails().append("ReEmailing doc \t : " + selectedDocNames.get(i) + "\n");
Email email = new Email("targetingInbox@targeting.com", "localhbbost", selectedDocNames.get(i));
if (email.sendEmail()) {
jdre.getjTextAreaResendEmails().append("ReEmailing ok? \t : Re-emailing successful.\n");
new DatabaseHandle().updateEmailStatus(selectedDocNames.get(i), 1);
jdre.getjTextAreaResendEmails().append("DB Updated ok? \t : Database update successful\n");
countSent++;
} else {
jdre.getjTextAreaResendEmails().append("ReEmailing ok? \t : Re-emailing Unsuccessful.\n");
countUnsent++;
}
if (Utils.deleteTempFile(selectedDocNames.get(i))) {
jdre.getjTextAreaResendEmails().append("Delete doc ok? \t : Deleting temp doc successful.\n");
}
jdre.getjTextAreaResendEmails().append("------------------------------------------------\n");
if (i == selectedDocNames.size() - 1) {
jdre.getjTextAreaResendEmails().append("Done resending emails."
+ "\n---------------------------"
+ "\n- Total sent \t : " + countSent + "\t-"
+ "\n- Total failed \t : " + countUnsent + "\t-"
+ "\n---------------------------");
jdre.getjLabelResendEmail().setIcon(new javax.swing.ImageIcon(getClass().getResource("/smsapp/resources/ok_16.png")));
jdre.getjLabelResendEmail().setText("Done resending " + countSent + " of " + selectedDocNames.size() + " SMS documents emails.");
jdre.getjButtonCancel().setText("Close");
// resetTable(dtm, view.getjTableWhatsappMsgs());
// getSMSMessages();
}
Thread.sleep(1000);
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
} |
e6f3e7d4-adb2-422a-8d68-4e4f8e583673 | 1 | public Row getByKey(String tableName, String key) throws DataBaseTableException {
Table table = tableHashMap.get(tableName);
if (table == null) {
throw new DataBaseTableException("no such table");
}
return table.get(key);
} |
6a39e99f-71ec-488a-853b-c7145552803d | 7 | public Metadata readNextMetadata() throws IOException {
Metadata metadata = null;
boolean isLast = (bitStream.readRawUInt(Metadata.STREAM_METADATA_IS_LAST_LEN) != 0);
int type = bitStream.readRawUInt(Metadata.STREAM_METADATA_TYPE_LEN);
int length = bitStream.readRawUInt(Metadata.STREAM_METADATA_LENGTH_LEN);
if (type == Metadata.METADATA_TYPE_STREAMINFO) {
streamInfo = new StreamInfo(bitStream, length, isLast);
metadata = streamInfo;
pcmProcessors.processStreamInfo((StreamInfo)metadata);
} else if (type == Metadata.METADATA_TYPE_SEEKTABLE) {
metadata = new SeekTable(bitStream, length, isLast);
} else if (type == Metadata.METADATA_TYPE_APPLICATION) {
metadata = new Application(bitStream, length, isLast);
} else if (type == Metadata.METADATA_TYPE_PADDING) {
metadata = new Padding(bitStream, length, isLast);
} else if (type == Metadata.METADATA_TYPE_VORBIS_COMMENT) {
metadata = new VorbisComment(bitStream, length, isLast);
} else if (type == Metadata.METADATA_TYPE_CUESHEET) {
metadata = new CueSheet(bitStream, length, isLast);
} else if (type == Metadata.METADATA_TYPE_PICTURE) {
metadata = new Picture(bitStream, length, isLast);
} else {
metadata = new Unknown(bitStream, length, isLast);
}
frameListeners.processMetadata(metadata);
//if (isLast) state = DECODER_SEARCH_FOR_FRAME_SYNC;
return metadata;
} |
6ba442f5-088d-476c-85c4-b148aa8f6de2 | 1 | public boolean getCopyEnabled() {
return this instanceof ClipboardInterface && copyEnabled;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.