text stringlengths 14 410k | label int32 0 9 |
|---|---|
public synchronized boolean isValid(){
try {
MessageDigest hasher = MessageDigest.getInstance("SHA");
byte[] result = hasher.digest(this.getData());
hasher.reset();
if(result.length != hash.length){
System.err.println("Hash check for piece " + this.index + " failed with hash length mismatch.");
return false;
}
//System.out.println("hash-"+ (new String(hash)));
//System.out.println("newh-"+ (new String(result)));
for(int i = 0; i < result.length; i++){
if(result[i] != hash[i]){
System.err.println("Hash check for piece " + this.index + " failed at byte " + i + ".");
return false;
}
}
} catch (NoSuchAlgorithmException e) {
System.err.println("Unable to check hash of piece. Invalid Algorithm");
}
return true;
} | 4 |
public static void chooseBestHand(BlackjackPlayer player) {
int playerDefaultScore = player.getDefaultScore();
int playerChangedAceScore = player.getChangedAceScore();
System.out.println("The score with the ace value as 1: " + playerDefaultScore);
System.out.println("The score with the ace value as 11: " + playerChangedAceScore);
/* If the 'playerDefaultScore' is not greater than the 'playerChangedAceScore' and
* less than or equal to 21, then set it as the default score for this BlackjackPlayer
*/
if(playerDefaultScore > playerChangedAceScore && playerDefaultScore <= twentyOne) {
player.setDefaultScore(playerDefaultScore);
System.out.println("Chose the score with ace value as 1: " + playerDefaultScore);
}
// This means that the changedAceScore is closer to 21 than the defaultScore.
else if(playerChangedAceScore > playerDefaultScore && playerChangedAceScore <= twentyOne) {
player.setDefaultScore(playerChangedAceScore);
System.out.println("Chose the score with ace avlue as 11: " + playerChangedAceScore);
}
// Else at this point, just default.
else {
player.setDefaultScore(playerDefaultScore);
System.out.println("This is the chosen score: " + playerDefaultScore);
}
} | 4 |
private synchronized void seed() {
// Silently ignore if we're already seeding.
if (ClientState.SEEDING.equals(this.getState())) {
return;
}
logger.info("Download of " + this.torrent.getPieceCount() +
" pieces completed.");
if (this.seed == 0) {
logger.info("No seeding requested, stopping client...");
this.stop();
return;
}
this.setState(ClientState.SEEDING);
if (this.seed < 0) {
logger.info("Seeding indefinetely...");
return;
}
logger.info("Seeding for " + this.seed + " seconds...");
Timer seedTimer = new Timer();
seedTimer.schedule(new StopSeedingTask(this), this.seed*1000);
} | 3 |
public boolean isSpaceForCar(VehicleAcceptor r) {
List<Vehicle> cars = r.getCars();
if (cars == null) {
return true;
}
for (Vehicle c: cars) {
if (c.getBackPosition() <= this.getLength()) {
//System.out.println("Not Enough Room for " + this + " b/c " + c);
return false;
}
}
return true;
} | 3 |
@EventHandler
public void WitchWaterBreathing(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.getWitchConfig().getDouble("Witch.WaterBreathing.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getWitchConfig().getBoolean("Witch.WaterBreathing.Enabled", true) && damager instanceof Witch && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.WATER_BREATHING, plugin.getWitchConfig().getInt("Witch.WaterBreathing.Time"), plugin.getWitchConfig().getInt("Witch.WaterBreathing.Power")));
}
} | 6 |
@Override
public void run() {
while (!mainFrame.isGameOver()) {
try {
Thread.sleep(CYCLE_SLEEP_TIME);
if (!mainFrame.isPause()) {
cyclesCount++;
// move down if needed
int gravity = mainFrame.getLevel();
if (cyclesCount>=AUTO_MOVE_DOWN_MAX_CYCLES / gravity) {
cyclesCount = 0;
mainFrame.moveEvent(Move.DOWN);
}
}
} catch (InterruptedException e) {
System.out.println("Interrupted exception");
}
}
} | 4 |
private int calcPlusDef() {
if (plus <= 0 || plus > 15) {
return 0;
}
if (typ.equals(ItemTyp.PLATE)) {
return plus_plate[plus];
}
if (typ.equals(ItemTyp.HEAVY)) {
return plus_heavy[plus];
}
if (typ.equals(ItemTyp.LIGHT)) {
return plus_light[plus];
}
return plus_cloth[plus];
} | 5 |
private void FormaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FormaActionPerformed
// TODO add your handling code here:
if((Vias.getSelectedItem()!="Vias de administracion") && (Forma.getItemCount())!=0){
if(Forma.getSelectedItem().equals("Forma")){
Tipo.removeAllItems();
Tipo.addItem("Tipo");
}else{
Tipo.removeAllItems();
Tipo.addItem("Tipo");
for(String s: v){
Tipo.addItem(s);
}
}
}
}//GEN-LAST:event_FormaActionPerformed | 4 |
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Pair<?, ?>)) {
return false;
}
Pair<?, ?> otherPair = (Pair<?, ?>) obj;
return isEqualOrNulls(first, otherPair.getFirst())
&& isEqualOrNulls(second, otherPair.getSecond());
} | 8 |
public void invokeMain(String sClass, String[] args) throws Throwable {
Class<?> clazz = loadClass(sClass);
log("Launch: %s.main(); Loader: %s", sClass, clazz.getClassLoader());
Method method = clazz.getMethod("main", new Class<?>[] { String[].class });
boolean bValidModifiers = false;
boolean bValidVoid = false;
if (method != null) {
method.setAccessible(true); // Disable IllegalAccessException
int nModifiers = method.getModifiers(); // main() must be "public static"
bValidModifiers = Modifier.isPublic(nModifiers) &&
Modifier.isStatic(nModifiers);
Class<?> clazzRet = method.getReturnType(); // main() must be "void"
bValidVoid = (clazzRet == void.class);
}
if (method == null || !bValidModifiers || !bValidVoid) {
throw new NoSuchMethodException(
"The main() method in class \"" + sClass + "\" not found.");
}
// Invoke method.
// Crazy cast "(Object)args" because param is: "Object... args"
try {
method.invoke(null, (Object)args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
} // invokeMain() | 9 |
public static void main(String[] args) {
ExecutorImplClassDemo executorImplClassDemo = new ExecutorImplClassDemo();
CompoundExecutorDemo compoundExecutorDemo = new CompoundExecutorDemo(executorImplClassDemo);
ExecutorImplClassDemo.RunnableImpl runnable = new ExecutorImplClassDemo.RunnableImpl();
compoundExecutorDemo.execute(runnable);
try {
sleep(3000);//等程序执行完
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main print:" + runnable.getCount());
} | 1 |
void updateButtons(Set<Direction> valids)
{
for ( DirectionButton b: this.buttons.values() )
b.setVisible(false);
if ( ( valids == null ) || ( valids.isEmpty() ) )
{
this.setVisible(false);
return;
}
for ( Direction d: valids )
this.buttons.get(d).setVisible(true);
this.setVisible(true);
} | 4 |
public boolean isPressedOnce(int key) {
if (this.keys.containsKey(key) && this.keys.get(key)) {
if (!this.pressed.containsKey(key) || !this.pressed.get(key)) {
this.pressed.put(key, true);
return true;
}
}
return false;
} | 4 |
private boolean jj_3_16() {
if (jj_3R_34()) return true;
return false;
} | 1 |
private static int getBits(int i, BZip2BlockEntry blockEntry) {
int j;
do {
if (blockEntry.anInt577 >= i) {
int k = blockEntry.anInt576 >> blockEntry.anInt577 - i & (1 << i) - 1;
blockEntry.anInt577 -= i;
j = k;
break;
}
blockEntry.anInt576 = blockEntry.anInt576 << 8 | blockEntry.inputBuffer[blockEntry.offset] & 0xff;
blockEntry.anInt577 += 8;
blockEntry.offset++;
blockEntry.compressedSize--;
blockEntry.anInt566++;
if (blockEntry.anInt566 == 0)
blockEntry.anInt567++;
} while (true);
return j;
} | 3 |
public static void main(String[] args) throws Exception
{
HashMap<String, RawDesignMatrixParser> map = RawDesignMatrixParser.getByFullId();
List<String> bioinformaticsIds = RawDesignMatrixParser.getAllBioinformaticsIDs(map);
//for(String s : bioinformaticsIds)
// System.out.println(s);
List<String> taxaHeaders = RawDesignMatrixParser.getTaxaIds();
//for(String s : taxaHeaders)
// System.out.println(s);
List<String> mbqcIDs = RawDesignMatrixParser.getAllMBQCIDs(map);
List<String> wetlabIds = RawDesignMatrixParser.getAllWetlabIDs(map);
//System.out.println(wetlabIds);
HashMap<String, Double> avgVals = RawDesignMatrixParser.getTaxaAverages(map, taxaHeaders);
HashMap<String,String> kitMap = getManualKitManufacturer();
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(ConfigReader.getMbqcDir() +
File.separator + "af_out" + File.separator + "pValuesNAVsNonNA.txt")));
writer.write("bioinformaticsLab\tsequencingLab\textractionProtocol\tkitManufacturer\tseqPlusExtraction\ttaxa\tsampleSize\tpValue\tmeanDifference\tfoldChange\tavgTaxa\n");
for(String bio : bioinformaticsIds)
for( String wet : wetlabIds)
for(String taxa : taxaHeaders)
if( avgVals.get(taxa) >= 0.01 )
{
HashMap<String, List<RawDesignMatrixParser>> mbqcIDMap =
RawDesignMatrixParser.pivotBySampleID(map, bio, wet);
System.out.println(bio + "\t" + wet + "\t" + taxa );
List<String> extractionProtocols = getAllExtractionNotNA(mbqcIDMap);
for(String extraction : extractionProtocols)
{
String kit = kitMap.get(extraction);
if( kit == null)
throw new Exception("No " + extraction);
writer.write(bio + "\t" + wet + "\t" + extraction + "\t" + kit + "\t" + wet + "_" + extraction + "\t" +
taxa );
int taxaID = RawDesignMatrixParser.getTaxaID(taxaHeaders,taxa );
Holder h= getPValueForNAVsOther(map, mbqcIDs, wet, bio, taxaID, extraction,
mbqcIDMap);
writer.write("\t" + h.sampleSize + "\t");
if( h.pairedResults != null)
writer.write(h.pairedResults.getPValue() + "\t" + h.meanDifference + "\t" + h.foldChange + "\t");
else
writer.write("\t\t\t");
writer.write(avgVals.get(taxa) + "\n");
}
}
writer.flush(); writer.close();
} | 7 |
public void replace(FilterBypass filterBypass, int offset, int length, String string, AttributeSet attributeSet)
throws BadLocationException {
super.replace(filterBypass, offset, length, string, attributeSet);
Document doc = filterBypass.getDocument();
_preText = doc.getText(0, doc.getLength());
_firstSelectedIndex = -1;
for (int i = 0; i < getCompleterListSize(); i++) {
String objString = getCompleterObjectAt(i).toString();
if ((_case) ? objString.equals(_preText) : objString.equalsIgnoreCase(_preText)) {
_firstSelectedIndex = i;
if (_corrective)
filterBypass.replace(0, _preText.length(), objString, attributeSet);
break;
}
if (objString.length() <= _preText.length())
continue;
String objStringStart = objString.substring(0, _preText.length());
if ((_case) ? objStringStart.equals(_preText) : objStringStart.equalsIgnoreCase(_preText)) {
String objStringEnd = objString.substring(_preText.length());
if (_corrective)
filterBypass.replace(0, _preText.length(), objString, attributeSet);
else
filterBypass.insertString(_preText.length(), objStringEnd, attributeSet);
getTextField().select(_preText.length(), doc.getLength());
_firstSelectedIndex = i;
break;
}
}
} | 8 |
public void setTransforms(TransformsType value) {
this.transforms = value;
} | 0 |
@Override
public void show_TrisA(Integer value) {
PIC_Logger.logger.info("Showing Tris A");
int x=7;
for(int i = 0; i < 8; i++){
if( (value & (int)Math.pow(2, i)) == (int)Math.pow(2, i)){
regA.setValueAt("i", 0, x+1);
}
else{
regA.setValueAt("o", 0, x+1);
}
x--;
}
} | 2 |
String getSQLWhere() {
switch (relationship) {
case NOT_EQUALS: return columnName + " <> ?";
case GREATER_THAN: return columnName + " > ?";
case GREATER_THAN_OR_EQUALS: return columnName + " >= ?";
case LESS_THAN: return columnName + " < ?";
case LESS_THAN_OR_EQUALS: return columnName + " <= ?";
case LIKE: return columnName + " LIKE ?";
default: return columnName + " = ?";
}
} | 6 |
public Packet read() {
try {
ByteBuffer header = ByteBuffer.allocate(4);
int code = socket.read(header);
if (code == 4) {
header.flip();
short id = header.getShort();
short len = header.getShort();
ByteBuffer data = ByteBuffer.allocate(len);
socket.read(data);
data.flip();
Packet packet = PacketCodecs.CLIENT_SERVER.read(id, data);
if (packet != null) {
return packet;
} else {
System.out.println("[Server] failed to read full packet");
}
} else if (code >= 0) {
System.out.println("[Server] Malformed data received from " + socket.getRemoteAddress());
}
} catch (IOException e) {
System.err.println("Failed to read from " + getRemoteAddress() + ": " + e.getMessage());
try {
socket.close();
} catch (IOException e1) {
System.err.println("Failed to close socket from " + getRemoteAddress() + ": " + e1.getMessage());
}
}
return null;
} | 5 |
public static boolean testCollectionofMemberOfP(Stella_Object member, Surrogate type) {
{ Object old$ReversepolarityP$000 = Logic.$REVERSEPOLARITYp$.get();
Object old$Context$000 = Stella.$CONTEXT$.get();
try {
Native.setBooleanSpecial(Logic.$REVERSEPOLARITYp$, false);
Native.setSpecial(Stella.$CONTEXT$, Logic.getPropertyTestContext());
{ Proposition p = null;
Iterator iter000 = Logic.allTrueDependentPropositions(member, Logic.SGT_PL_KERNEL_KB_COLLECTIONOF, true);
while (iter000.nextP()) {
p = ((Proposition)(iter000.value));
if ((!p.deletedP()) &&
((((Boolean)(Logic.$REVERSEPOLARITYp$.get())).booleanValue() ? Proposition.falseP(p) : (Proposition.trueP(p) ||
Proposition.functionWithDefinedValueP(p))))) {
{ Stella_Object collection = p.arguments.last();
if ((!Stella_Object.eqlP(member, collection)) &&
LogicObject.collectionImpliesCollectionP(((LogicObject)(collection)), Logic.surrogateToDescription(type))) {
return (true);
}
}
}
}
}
return (false);
} finally {
Stella.$CONTEXT$.set(old$Context$000);
Logic.$REVERSEPOLARITYp$.set(old$ReversepolarityP$000);
}
}
} | 7 |
public String get_field( String section, String field )
throws NoSuchKeyException, NoSuchSectionException {
Hashtable s;
String t;
if(section==null) {
throw new NoSuchSectionException();
}
if(field==null) {
throw new NoSuchKeyException();
}
s = (Hashtable) sections.get(section);
if( s == null) {
throw new NoSuchSectionException("Section ["+section+"] not found");
}
t = (String) s.get(field);
if( t == null ) {
throw new NoSuchKeyException("Field ["+field+"] in section ["+section+"] not found");
}
return new String(t);
} | 4 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Rectangular that = (Rectangular) o;
if (length != that.length) return false;
return width == that.width;
} | 4 |
public float [] compute(float [] x)
{
if (x.length != n)
throw new IllegalArgumentException("BIJfft not properly initialized");
float[] xre = new float[n];
float[] xim = new float[n];
for (int i = 0; i < n; i++)
{
xre[i] = x[i];
xim[i] = 0;
}
int k = 0;
int localnu1 = nu1;
int localn2 = n2;
for (int l = 1; l <= nu; l++)
{
while (k < n)
{
for (int i = 1; i <= localn2; i++)
{
// Get the proper values from the sin and cos tables.
int p = bitrev (k >> localnu1);
float c = (float) C[p];
float s = (float) S[p];
double arg = 2 * Math.PI * p / n;
//if (c != (float) Math.cos (arg) || s != (float) Math.sin (arg))
// System.out.println("k="+k+" "+c+" "+(float) Math.cos (arg)+" "+s+" "+(float) Math.sin (arg));
c = (float) Math.cos (arg);
s = (float) Math.sin (arg);
float tr = xre[k+localn2]*c + xim[k+localn2]*s;
float ti = xim[k+localn2]*c - xre[k+localn2]*s;
xre[k+localn2] = xre[k] - tr;
xim[k+localn2] = xim[k] - ti;
xre[k] += tr;
xim[k] += ti;
k++;
}
k += localn2;
}
k = 0;
localnu1--;
localn2 = localn2/2;
}
k = 0;
int r;
while (k < n)
{
r = bitrev (k);
if (r > k)
{
float tr = xre[k];
float ti = xim[k];
xre[k] = xre[r];
xim[k] = xim[r];
xre[r] = tr;
xim[r] = ti;
}
k++;
}
float[] mag = new float[n/2];
mag[0] = (float) (Math.sqrt(xre[0]*xre[0] + xim[0]*xim[0]))/n;
for (int i = 1; i < n/2; i++)
mag[i]= 2 * (float) (Math.sqrt(xre[i]*xre[i] + xim[i]*xim[i]))/n;
return mag;
} | 8 |
protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) {
int b,c;
int[][] lookup = CHAR_TO_BYTE; // getfield bytecode optimization
int[] table;
int remaining = in.remaining();
while (remaining-- > 0) {
if (out.remaining() < 1)
return CoderResult.OVERFLOW; // we need exactly one byte per char
c = in.get();
table = lookup[c >>> 8];
b = table == null ? -1 : table[c & 0xFF];
if (b == -1) {
in.position(in.position() - 1);
return CoderResult.unmappableForLength(1);
}
out.put((byte)(b & 0xFF));
}
return CoderResult.UNDERFLOW;
} | 4 |
public RoomInfo(String mapName){
if(mapName.equals("Exterior1.tmx")){
upDoorPos = null;
downDoorPos = null;
leftDoorPos = new Vector2(1.25f,4.5f);
rightDoorPos = null;
upBoundry = 15f;
downBoundry = 1f;
leftBoundry = 1f;
rightBoundry = 19f;
}
else if(mapName.equals("BigRoom1.tmx")){
upDoorPos = null;
downDoorPos = new Vector2(8.5f,2.25f);
leftDoorPos = new Vector2(2.25f,11.5f);
rightDoorPos = new Vector2(21.85f,6.5f);
upBoundry = 14f;
downBoundry = 2f;
leftBoundry = 2f;
rightBoundry = 22f;
}
else if(mapName.equals("ForgeRoom.tmx")){
upDoorPos = new Vector2(5.5f,10.85f);
downDoorPos = new Vector2(6.5f,1.25f);
leftDoorPos = new Vector2(1.25f,7.5f);
rightDoorPos = new Vector2(10.85f,3.5f);
upBoundry = 11f;
downBoundry = 1f;
leftBoundry = 1f;
rightBoundry = 11f;
}
} | 3 |
@EventHandler(priority = EventPriority.LOW)
public void onExplosionEvent(final EntityExplodeEvent event) {
Location eventLocation = event.getLocation();
if (plugin.Blast_Mode.containsKey(eventLocation)) {
Integer BlastMode = plugin.Blast_Mode.get(eventLocation);
if (BlastMode == 0) {
// GET BLOCKS EFFECT BY AN EXPLOSION
List<Block> blockList = event.blockList();
int len = blockList.size();
// FOR EVERY BLOCK EFFECTED BY EXPLOSION
for(int i = 0; i < len; i++) {
// remove block from damage list
blockList.remove(i);
i--;
len--;
}
} else if (BlastMode == 1) {
// GET BLOCKS EFFECT BY AN EXPLOSION
List<Block> blockList = event.blockList();
int len = blockList.size();
// FOR EVERY BLOCK EFFECTED BY EXPLOSION
for(int i = 0; i < len; i++) {
// remove block from damage list
blockList.remove(i);
i--;
len--;
}
} else if (BlastMode == 2) {
// DO NOTHING
} else if (BlastMode == 3) {
// NO DAMAGE PLAYER and then...
event.setYield(0);
} else if (BlastMode == 4) {
event.setYield(0);
}
}
} | 8 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Serie.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Serie.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Serie.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Serie.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Serie().setVisible(true);
}
});
} | 6 |
Point3 getVelocityTo(Obstacle o) {
Point3 velocity = o.getPosition().minus(myBeing.getPosition());
velocity.normalize();
return velocity;
} | 0 |
public String getLinkName(Element tcElement){
if (tcElement.getName().equals("transitioncondition")){
Element source = (Element)tcElement.getParentElement();
return source.getAttributeValue("linkName");
}else{
return null;
}
} | 1 |
public void sendFirst() {
System.out.println("-- Alice --");
if (betray) {
System.out.println("ACHTUNG: Betrugsmodus aktiv!!!");
}
// Hard coded messages M_0 and M_1
BigInteger[] M = new BigInteger[2];
M[0] = new BigInteger("11111111111111111111111111111111111111111111111111111111111");
M[1] = new BigInteger("22222222222222222222222222222222222222222222222222222222222");
if (betray) {
M[1] = M[0];
}
// Hard coded ElGamal
BigInteger p_A = new BigInteger("7789788965135663714690749102453072297748091458564354001035945418057913886819451721947477667556269500246451521462308030406227237346483679855991947569361139");
BigInteger g_A = new BigInteger("6064211169633122201619014531987050083527855665630754543345421103270545526304595525644519493777291154802011605984321393354028831270292432551124003674426238");
BigInteger y_A = new BigInteger("3437627792030969437324738830672923365331058766427964788898937390314623633227168012908665090706697391878208866573481456022491841700034626290242749535475902");
// private:
BigInteger x_A = new BigInteger("3396148360179732969395840357777168909721385739804535508222449486018759668590512304433229713789117927644143586092277750293910884717312503836910153525557232");
// Objekt initialisieren mit priv key
ElGamal elGamal_A = new ElGamal(p_A, g_A, y_A, x_A);
BigInteger p = elGamal_A.p;
// Alice sendet ElGamal public key an Bob
Com.sendTo(1, elGamal_A.p.toString(16)); // S1
Com.sendTo(1, elGamal_A.g.toString(16)); // S2
Com.sendTo(1, elGamal_A.y.toString(16)); // S3
// Alice wählt zufällig zwei Nachrichten m_0, m_1 in Z_p, 1 <= m < p
BigInteger[] m = new BigInteger[2];
m[0] = BigIntegerUtil.randomBetween(ONE, p);
m[1] = BigIntegerUtil.randomBetween(ONE, p);
System.out.println("m_0: " + m[0]);
System.out.println("m_1: " + m[1]);
// Alice sendet m_0, m_1 an Bob
Com.sendTo(1, m[0].toString(16)); // S4
Com.sendTo(1, m[1].toString(16)); // S5
// Alice empfängt q
BigInteger q = new BigInteger(Com.receive(), 16); // R6
// Alice berechnet k_0', k_1', hier k_A[0] und k_A[1] genannt
BigInteger[] k_strich = new BigInteger[2];
for (int i = 0; i < 2; i++) {
k_strich[i] = elGamal_A.decipher((q.subtract(m[i])).mod(p.multiply(p))); // D_A((q-m_i) mod p^2)
}
System.out.println("k_strich[0]: " + k_strich[0]);
System.out.println("k_strich[1]: " + k_strich[1]);
// zufällig s wählen
int s = BigIntegerUtil.randomBetween(ZERO, TWO).intValue();
System.out.println("s: " + s);
BigInteger[] send = new BigInteger[2];
send[0] = M[0].add(k_strich[s]).mod(p);
send[1] = M[1].add(k_strich[s ^ 1]).mod(p);
System.out.println("send_0: " + send[0]);
System.out.println("send_1: " + send[1]);
int r = -1;
if (betray) { // try to find right r :D
r = BigIntegerUtil.randomBetween(ZERO, TWO).intValue();
System.out.println("guessed r: " + r);
}
// Signatur berechnen
BigInteger[] S = new BigInteger[2];
for (int i = 0; i < 2; i++) {
if (betray) {
if (i == r) { // gefälschte signatur
S[i] = BigIntegerUtil.randomBetween(BigIntegerUtil.TWO, p.multiply(p));
} else {
S[i] = elGamal_A.sign(k_strich[i]);
}
} else { // no betraying
S[i] = elGamal_A.sign(k_strich[i]);
}
}
System.out.println("S_0: " + S[0]);
System.out.println("S_1: " + S[1]);
// Alice sendet send_0, send_1, s, S[0], S[1]
Com.sendTo(1, send[0].toString(16)); // S7
Com.sendTo(1, send[1].toString(16)); // S8
Com.sendTo(1, s + ""); // S9
Com.sendTo(1, S[0].toString(16)); // S10
Com.sendTo(1, S[1].toString(16)); // S11
} | 7 |
public List<Turma> pesquisaTurmasDoProfessor(String matriculaProf)
throws ProfessorInexistenteException {
List<Turma> turmasDoProfessor = new ArrayList<Turma>();
boolean flag = false;
for (Professor prof : this.professores) {
if (prof.getMatricula().equals(matriculaProf)) {
turmasDoProfessor = prof.turmasAlocado;
flag = true;
break;
}
}
if (flag == false) {
throw new ProfessorInexistenteException("Professor Inexistente !!!");
}
return turmasDoProfessor;
} | 3 |
@RequestMapping(value = "del", method = RequestMethod.POST)
@ResponseBody
public Map del(@RequestParam int[] id) {
Map<String, Object> map = new HashMap<>();
List<String> l1 = new ArrayList<>();
List<String> l2 = new ArrayList<>();
List<String> l3 = new ArrayList<>();
for (int i = 0; i < id.length; i++) {
Course course = courseService.getById(id[i]);
if (course != null) {
if (course.getOptionMappingList().isEmpty()) {
l1.add(course.getCourseName());
courseService.delete(course);
} else {
l3.add(course.getCourseName());
}
} else {
l2.add(id[i] + "");
}
}
String s1 = Tools.toArrayString(l1);
String s2 = Tools.toArrayString(l2);
String s3 = Tools.toArrayString(l3);
map.put("success", true);
map.put("msg", "科目:" + s1 + ",删除成功!"
+ (s2.isEmpty() ? "" : ("\n科目:" + s2 + ",信息不存在,请刷新后重试。"))
+ (s3.isEmpty() ? "" : ("\n科目:" + s3 + ",存在子项,请清空子项后重试。")));
return map;
} | 5 |
public Item buildHouseplant(MOB mob, Room room)
{
final Item newItem=CMClass.getItem("GenItem");
newItem.setMaterial(RawMaterial.RESOURCE_GREENS);
switch(CMLib.dice().roll(1,7,0))
{
case 1:
newItem.setName(L("a potted rose"));
newItem.setDisplayText(L("a potted rose is here."));
newItem.setDescription("");
break;
case 2:
newItem.setName(L("a potted daisy"));
newItem.setDisplayText(L("a potted daisy is here."));
newItem.setDescription("");
break;
case 3:
newItem.setName(L("a potted carnation"));
newItem.setDisplayText(L("a potted white carnation is here"));
newItem.setDescription("");
break;
case 4:
newItem.setName(L("a potted sunflower"));
newItem.setDisplayText(L("a potted sunflowers is here."));
newItem.setDescription(L("Happy flowers have little yellow blooms."));
break;
case 5:
newItem.setName(L("a potted gladiola"));
newItem.setDisplayText(L("a potted gladiola is here."));
newItem.setDescription("");
break;
case 6:
newItem.setName(L("a potted fern"));
newItem.setDisplayText(L("a potted fern is here."));
newItem.setDescription(L("Like a tiny bush, this dark green plant is lovely."));
break;
case 7:
newItem.setName(L("a potted patch of bluebonnets"));
newItem.setDisplayText(L("a potted patch of bluebonnets is here."));
newItem.setDescription(L("Happy flowers with little blue and purple blooms."));
break;
}
newItem.setSecretIdentity(mob.Name());
newItem.setMiscText(newItem.text());
Druid_MyPlants.addNewPlant(mob, newItem);
room.addItem(newItem);
final Chant_SummonHouseplant newChant=new Chant_SummonHouseplant();
newItem.basePhyStats().setWeight(1);
newItem.basePhyStats().setLevel(10+newChant.getX1Level(mob));
newItem.setExpirationDate(0);
room.showHappens(CMMsg.MSG_OK_ACTION,CMLib.lang().L("Suddenly, @x1 appears here.",newItem.name()));
newChant.plantsLocationR=room;
newChant.littlePlantsI=newItem;
if(CMLib.law().doesOwnThisProperty(mob,room))
{
newChant.setInvoker(mob);
newChant.setMiscText(mob.Name());
newItem.addNonUninvokableEffect(newChant);
}
else
newChant.beneficialAffect(mob,newItem,0,(newChant.adjustedLevel(mob,0)*240)+450);
room.recoverPhyStats();
return newItem;
} | 8 |
private void removeUseless(Grammar g)
{
UselessProductionRemover remover = new UselessProductionRemover();
Grammar g2 = UselessProductionRemover
.getUselessProductionlessGrammar(g);
Production[] p1 = g.getProductions();
Production[] p2 = g2.getProductions();
if (p1.length > p2.length) {
GrammarEnvironment env=new GrammarEnvironment(new GrammarInputPane(g));
UselessPane up = new UselessPane(env, g);
UselessController controller=new UselessController(up, g);
controller.doAll();
g=controller.getGrammar();
}
initializeChomskyMap(g);
} | 1 |
public static void invokeQuizRemoving(int id) {
for (QuestPoint q : campaign.getQuizes()) {
if (q.getId() == id) {
campaign.removeQuiz(q);
campaign.deleteTrue();
ProjectOptionsView.updateView();
break;
}
}
} | 2 |
private void applyFileHandlers( Environment<String,BasicType> httpConfig )
throws ConfigurationException {
Environment<String,BasicType> httpSettings = httpConfig.getChild( Constants.KEY_HTTPCONFIG_FILEHANDLERS );
if( httpSettings == null ) {
this.getLogger().log( Level.INFO,
getClass().getName() + ".applyFileHandlers(...)",
"Param set for applyFileHandlers() has no '" + Constants.KEY_HTTPCONFIG_FILEHANDLERS + "' node. No settings loaded." );
return;
}
BasicType wrp_configFilename = httpSettings.get( Constants.KEY_HTTPCONFIG_FILEHANDLERS_FILE );
if( wrp_configFilename == null ) {
this.getLogger().log( Level.INFO,
getClass().getName() + ".applyFileHandlers(...)",
"HTTP settings have no '" + Constants.KEY_HTTPCONFIG_FILEHANDLERS_FILE + "' entity. No config file loaded." );
return;
}
String configFilename = CustomUtil.processCustomizedFilePath( wrp_configFilename.getString() );
if( configFilename == null || configFilename.length() == 0 ) {
this.getLogger().log( Level.INFO,
getClass().getName() + ".applyFileHandlers(...)",
"HTTP settings entity '" + Constants.KEY_HTTPCONFIG_FILEHANDLERS_FILE + "' is empty. No config file loaded." );
return;
}
this.getLogger().log( Level.INFO,
getClass().getName() + ".applyFileHandlers(...)",
"Loading file handlers from file '" + configFilename+ "' ... " );
// Load config
this.getHandler().initFileHandlers( new File(configFilename) );
} | 4 |
public static String filter(String str) {
String output = "";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
int asc = str.charAt(i);
if (asc != 10 && asc != 13) {
sb.append(str.subSequence(i, i + 1));
}
}
output = new String(sb);
return output;
} | 3 |
static Object newObject(String className) {
if (Functions.isEmpty(className)) return null;
Class<?> c;
try {
c = Class.forName(cn(className));
} catch (Throwable e) {
return null;
}
Object returnObject;
try {
returnObject = c.newInstance();
} catch (Throwable e) {
return null;
}
return returnObject;
} | 4 |
public static void main(String[] args) throws SlickException{
//establish game event factory
new ERGameEventFactory();
if(args.length==0){
args = new String[] {"-sc"};
}
if(args[0].equals("-s") || args[0].equals("-sc") ){//run the server on -s command
EmptyRoomServer server = new EmptyRoomServer();
server.start();
}
if (args[0].equals("-c") || args[0].equals("-sc") ){
EmptyRoomSimulation client;
if(args[0].equals("-c") && args.length>1){
client = new EmptyRoomSimulation(args[1]);
} else{
client = new EmptyRoomSimulation("localhost");
}
//make client in network game framework
client.start();
//SLICK
AppGameContainer app = new AppGameContainer(new EmptyRoom("", client));
app.setDisplayMode(800, 600, false);
app.setSmoothDeltas(true);
app.setTargetFrameRate(60);
app.setShowFPS(true);
System.out.println("STARTING APP");
app.start();
}
} | 7 |
@Override
protected void paintExpandControl(Graphics g, Rectangle clipBounds, Insets insets,
Rectangle bounds, TreePath path, int row, boolean isExpanded,
boolean hasBeenExpanded, boolean isLeaf) {
// if the given path is selected, then
boolean isPathSelected = tree.getSelectionModel().isPathSelected(path);
Icon expandIcon = isPathSelected ? fColorScheme.getSelectedExpandedIcon()
: fColorScheme.getUnselectedExpandedIcon();
Icon collapseIcon = isPathSelected ? fColorScheme.getSelectedCollapsedIcon()
: fColorScheme.getUnselectedCollapsedIcon();
Object categoryOrItem =
((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject();
boolean setIcon = !(categoryOrItem instanceof SourceListCategory)
|| ((SourceListCategory) categoryOrItem).isCollapsable();
setExpandedIcon(setIcon ? expandIcon : null);
setCollapsedIcon(setIcon ? collapseIcon : null);
super.paintExpandControl(g, clipBounds, insets, bounds, path, row, isExpanded, hasBeenExpanded, isLeaf);
} | 5 |
public PaymentEntity getPayment() {
return payment;
} | 0 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Subgoal subgoal = (Subgoal) o;
if (condition != null ? !condition.equals(subgoal.condition) : subgoal.condition != null) return false;
if (step != null ? !step.equals(subgoal.step) : subgoal.step != null) return false;
return true;
} | 7 |
int unpack(Buffer opb){
int vendorlen=opb.read(32);
if(vendorlen<0){
clear();
return (-1);
}
vendor=new byte[vendorlen+1];
opb.read(vendor, vendorlen);
comments=opb.read(32);
if(comments<0){
clear();
return (-1);
}
user_comments=new byte[comments+1][];
comment_lengths=new int[comments+1];
for(int i=0; i<comments; i++){
int len=opb.read(32);
if(len<0){
clear();
return (-1);
}
comment_lengths[i]=len;
user_comments[i]=new byte[len+1];
opb.read(user_comments[i], len);
}
if(opb.read(1)!=1){
clear();
return (-1);
}
return (0);
} | 5 |
public boolean clicked() {
if(key.isPressed() && !key.isHeld())
return true;
else
return false;
} | 2 |
public void update(int playerScores[]){
for(int i=0;i<playerScores.length;i++){
this.playerTotals[i] = playerScores[i];
this.l_playerTotals[i]
.setText(new Integer(playerScores[i]).toString());
}
p_playerScores.removeAll();
//figure out the order each players should be
//displayed based on score->>high to low.
int scoreOrder[] = new int[this.numPlayers];
boolean picked[] = new boolean[this.numPlayers];
for(int i=0;i<scoreOrder.length;i++){
picked[i] = false;
}
for(int i=0;i<scoreOrder.length;i++){
//get first non-'picked' element
int low = 0;
for(int j=0;j<scoreOrder.length;j++){
if(picked[j]==false){
low = j;
break;
}
}
//find lowest scored non-'picked' element
for(int j=0;j<scoreOrder.length;j++){
if((playerTotals[low]>=playerTotals[j])&&(picked[j]==false)){
low=j;
}
}
scoreOrder[i] = low;
picked[low] = true;
}
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.CENTER;
c.weightx = 1.0;
c.weighty = 1.0;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(5,0,5,0);
for(int i=(numPlayers-1);i>=0;i--){
c.gridy++;
p_playerScores.add(container[scoreOrder[i]],c);
}
c.weighty = .2;
c.insets = new Insets(1,0,1,0);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridy++;
p_playerScores.add(b_newGame,c);
c.gridy++;
p_playerScores.add(b_toMainMenu,c);
} | 9 |
public static Color clipcol(int r, int g, int b, int a) {
if (r < 0)
r = 0;
if (r > 255)
r = 255;
if (g < 0)
g = 0;
if (g > 255)
g = 255;
if (b < 0)
b = 0;
if (b > 255)
b = 255;
if (a < 0)
a = 0;
if (a > 255)
a = 255;
return (new Color(r, g, b, a));
} | 8 |
private boolean jj_2_16(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_16(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(15, xla); }
} | 1 |
private void checkFolder() {
File KeywordFolder;
boolean stateKeywordFolder;
KeywordFolder = new File("./KeyWord");
stateKeywordFolder = KeywordFolder.exists();
if(stateKeywordFolder == false ){
System.out.println("The 'KeyWord' folder do not exist,trying to create one...");
stateKeywordFolder = KeywordFolder.mkdir();
if( stateKeywordFolder == false ){
System.out.println("Unable to create the folder,please check disk ...");
System.exit(1);
}
}
} | 2 |
private String pedirPista() {
if(pistasAgotadas()){
pistasUsadas++;
return diccionario.getPistaPalabraEspecifica(palabraActualObjeto)+"\n";
}
else{
return "Se agoto el numero de pistas";
}
} | 1 |
private synchronized void unchokePeers(boolean optimistic) {
// Build a set of all connected peers, we don't care about peers we're
// not connected to.
TreeSet<SharingPeer> bound = new TreeSet<SharingPeer>(
this.getPeerRateComparator());
bound.addAll(this.connected.values());
if (bound.size() == 0) {
logger.trace("No connected peers, skipping unchoking.");
return;
} else {
logger.trace("Running unchokePeers() on " + bound.size() +
" connected peers.");
}
int downloaders = 0;
Set<SharingPeer> choked = new HashSet<SharingPeer>();
// We're interested in the top downloaders first, so use a descending
// set.
for (SharingPeer peer : bound.descendingSet()) {
if (downloaders < Client.MAX_DOWNLOADERS_UNCHOKE) {
// Unchoke up to MAX_DOWNLOADERS_UNCHOKE interested peers
if (peer.isChoking()) {
if (peer.isInterested()) {
downloaders++;
}
peer.unchoke();
}
} else {
// Choke everybody else
choked.add(peer);
}
}
// Actually choke all chosen peers (if any), except the eventual
// optimistic unchoke.
if (choked.size() > 0) {
SharingPeer randomPeer = choked.toArray(
new SharingPeer[0])[this.random.nextInt(choked.size())];
for (SharingPeer peer : choked) {
if (optimistic && peer == randomPeer) {
logger.debug("Optimistic unchoke of " + peer);
continue;
}
peer.choke();
}
}
} | 9 |
public static void main(String[] args) throws KeyStoreException {
PlayerRepository<Schema.Player> repository = JacksonPlayerRepository.create("/master.player.json");
Iterable<? extends Player> players = Iterables.transform(repository.getPlayers(),Schema.TRANSFORM);
players = Iterables.filter(players, Biography.HAS_BIO_FILTER);
final PlayerStore playerStore = FileBackedStore.create("");
PlayerStore.Reader in = playerStore.createReader();
IdReader idReader = new BioReader();
Map<String, Player> idMap = DatabaseFactory.createIdMap(players, idReader);
BootstrapMerge theMerge = new BootstrapMerge(idMap, idReader);
String updates[] =
{
"mlb.players.json"
, "espn.players.json"
, "lahman.players.json"
// TODO -- oliver has no DOB information in it.
// , "oliver.players.json"
, "rotoworld.players.json"
, "yahoo.players.json"
// , "baseballReference.players.json"
// , "biography.merged.json"
};
for (String updateDatabase : updates) {
Iterable<? extends Player> update = in.readPlayers(updateDatabase);
update = Iterables.filter(update, Biography.HAS_BIO_FILTER);
theMerge.merge(update);
}
PlayerStore.Writer out = playerStore.createWriter();
out.writePlayers("bootstrap.merged.json", theMerge.collectMasterDatabase());
out.writePlayers("bootstrap.missing.json", theMerge.collectMissingDatabase());
out.writePlayers("bootstrap.conflict.json", theMerge.collectConflictDatabase());
} | 3 |
public void compile(String directory, String fileName) {
fileName = FileUtil.quoteFileName(fileName);
ConsoleDialog console;
if (editor != null) {
console = new ConsoleDialog(editor, "Compiling", false);
} else {
console = new ConsoleDialog();
}
console.setSize(500, 400);
console.setText("Compiling...\n");
WindowUtil.centerShow(editor, console);
try {
StringBuffer command = new StringBuffer(compilerBinary).append(' ').append(compilerOptions).append(' ').append(compilerClassPath).append(' ').append(
fileName);
Logger.logMessage("Compile command: " + command);
ProcessBuilder pb = new ProcessBuilder(command.toString().split(" "));
pb.redirectErrorStream(true);
pb.directory(FileUtil.getCwd());
Process p = pb.start();
// The waitFor() must done after reading the input and error stream of the process
console.processStream(p.getInputStream());
p.waitFor();
if (p.exitValue() == 0) {
console.append("Compiled successfully.\n");
console.setTitle("Compiled successfully.");
} else {
console.append("Compile Failed (" + p.exitValue() + ")\n");
console.setTitle("Compile failed.");
}
} catch (IOException e) {
console.append("Unable to compile!\n");
console.append("Exception was: " + e.toString() + "\n");
console.append("Does " + compilerBinary + " exist?\n");
console.setTitle("Exception while compiling");
} catch (InterruptedException e) {
// Immediately reasserts the exception by interrupting the caller thread itself
Thread.currentThread().interrupt();
console.append("Compile interrupted.\n");
console.setTitle("Compile interrupted.");
}
Integer codesize = CodeSizeCalculator.getDirectoryCodeSize(new File(directory));
if (codesize != null) {
String weightClass = null;
if (codesize >= 1500) {
weightClass = "MegaBot (codesize >= 1500 bytes)";
} else if (codesize > 750) {
weightClass = "MiniBot (codesize < 1500 bytes)";
} else if (codesize > 250) {
weightClass = "MicroBot (codesize < 750 bytes)";
} else {
weightClass = "NanoBot (codesize < 250 bytes)";
}
StringBuilder sb = new StringBuilder();
sb.append("\n\n---- Codesize ----\n");
sb.append("Codesize: ").append(codesize).append(" bytes\n");
sb.append("Robot weight class: ").append(weightClass).append('\n');
console.append(sb.toString());
}
} | 8 |
public void processEvent(Event event)
{
if (event.getType() == Event.COMPLETION_EVENT)
{
System.out.println(_className + ": Receive a COMPLETION_EVENT, " + event.getHandle());
return;
}
System.out.println(_className + ".processEvent: Received Login Response... ");
if (event.getType() != Event.OMM_ITEM_EVENT)
{
System.out.println("ERROR: " + _className + " Received an unsupported Event type.");
_mainApp.cleanup(-1);
return;
}
OMMItemEvent ie = (OMMItemEvent)event;
OMMMsg respMsg = ie.getMsg();
if (respMsg.getMsgModelType() != RDMMsgTypes.LOGIN)
{
System.out.println("ERROR: " + _className + " Received a non-LOGIN model type.");
_mainApp.cleanup(-1);
return;
}
if (respMsg.isFinal())
{
System.out.println(_className + ": Login Response message is final.");
GenericOMMParser.parse(respMsg);
_mainApp.processLogin(false);
return;
}
if ((respMsg.getMsgType() == OMMMsg.MsgType.STATUS_RESP) && (respMsg.has(OMMMsg.HAS_STATE))
&& (respMsg.getState().getStreamState() == OMMState.Stream.OPEN)
&& (respMsg.getState().getDataState() == OMMState.Data.OK))
{
System.out.println(_className + ": Received Login STATUS OK Response");
GenericOMMParser.parse(respMsg);
_mainApp.processLogin(true);
}
else
{
System.out.println(_className + ": Received Login Response - "
+ OMMMsg.MsgType.toString(respMsg.getMsgType()));
GenericOMMParser.parse(respMsg);
}
} | 8 |
public Node mergeNodes(Node node1, Node node2) {
Node superNode = new Node(node1.getId() + "-" + node2.getId());
addNode(superNode);
List<Node> connectedNodes = new ArrayList<Node>();
for (Node node : getAdjacentNodes(node1)) {
if (!node.equals(node1) && !node.equals(node2)) {
connectedNodes.add(node);
}
}
for (Node node : getAdjacentNodes(node2)) {
if (!node.equals(node1) && !node.equals(node2)) {
connectedNodes.add(node);
}
}
Set<Edge> edgesToDelete = new HashSet<Edge>();
edgesToDelete.addAll(edgesByNode.get(node1));
edgesToDelete.addAll(edgesByNode.get(node2));
nodes.remove(node1);
nodes.remove(node2);
edgesByNode.remove(node1);
edgesByNode.remove(node2);
for (Edge edge : edgesToDelete) {
removeEdge(edge);
}
for (Node connectedNode : connectedNodes) {
addEdge(superNode, connectedNode);
}
return superNode;
} | 8 |
public static List<Apple> filterGreenApples(List<Apple> inventory) {
List<Apple> filteredApples = new ArrayList<>();
for (Apple apple : inventory) {
if(Apple.AppleColor.GREEN.equals(apple.getColor())) {
filteredApples.add(apple);
}
}
return filteredApples;
} | 2 |
public void check() {
if (chrlist == null)
return;
if (selbtn == null)
return;
if (chr == null) {
chr = chrlist.opts.get(0).name;
} else {
String nm = null;
for (Listbox.Option opt : chrlist.opts) {
if (opt.disp.equals(chr)) {
nm = opt.name;
break;
}
}
if (nm == null)
throw (new RobotException(this, "requested character not found: " + chr));
chr = nm;
}
chrlist.wdgmsg("chose", chr);
selbtn.wdgmsg("activate");
} | 6 |
@Test
public void parseTestInfo() {
String str = Utils.getFileContents(TEST_INFO);
JSONObject testInfoJO = null;
TestInfo ti_actual = new TestInfo();
TestInfo ti_expected = new TestInfo();
ti_expected.setId("411711");
ti_expected.setName("load_test");
ti_expected.setStatus(TestStatus.NotRunning);
// ti_expected.setNumberOfUsers(2760);
ti_expected.setNumberOfUsers(920);
ti_expected.setLocation("us-west-2");
Overrides overrides = new Overrides(0, -1, 0, 230);
ti_expected.setOverrides(overrides);
ti_expected.setType("jmeter");
try {
testInfoJO = new JSONObject(str);
ti_actual = TestInfoProcessor.parseTestInfo(testInfoJO);
} catch (JSONException e) {
BmLog.error("Failed to construct TestInfoJO from locations.txt: " + e);
}
Assert.assertEquals(ti_expected.getId(), ti_actual.getId());
Assert.assertEquals(ti_expected.getName(), ti_actual.getName());
Assert.assertEquals(ti_expected.getLocation(), ti_actual.getLocation());
Assert.assertEquals(ti_expected.getNumberOfUsers(), ti_actual.getNumberOfUsers());
Assert.assertEquals(ti_expected.getStatus(), ti_actual.getStatus());
Assert.assertEquals(ti_expected.getType(), ti_actual.getType());
} | 1 |
public void createClient() {
Socket socket;
BufferedReader in;
PrintWriter out;
try {
socket = new Socket(InetAddress.getLocalHost(),5000);
System.out.println("Demande de connexion ...");
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
w.write(String.valueOf(10));
w.flush();
System.out.println("Envoie de la valeur ...");
System.out.println("Attente de la reponse ...");
in = new BufferedReader (new InputStreamReader (socket.getInputStream()));
String message_distant = in.readLine();
int i = Integer.parseInt(message_distant);
System.out.println("value : " + i);
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} | 2 |
public boolean isTile(int x, int y)
{
return (x >= 0 && x < sea.length && y >= 0 && y < sea[0].length);
} | 3 |
@Override
public boolean isElementContentWhitespace() {
final String nodeValue = this.getNodeValue();
for (int i = 0, size = nodeValue.length(); i < size; i++) {
final char value = nodeValue.charAt(i);
if ((value > 0x20) || (value < 0x09)) return false;
if ((value != 0x0A) && (value != 0x0D)) return false;
}
return true;
} | 5 |
public NewAd() {
setSize(new Dimension(620, 620));
setResizable(false);
setTitle("Edit Ad");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(200, 200, 620, 620);
setIconImage(Toolkit.getDefaultToolkit().getImage("ICON2_Scaled.png"));
contentPane = new JPanel();
contentPane.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
contentPane.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
setContentPane(contentPane);
JLabel label = new JLabel("Ad ID");
label.setBounds(11, 34, 63, 14);
label.setHorizontalAlignment(SwingConstants.RIGHT);
JLabel label_1 = new JLabel("Title");
label_1.setBounds(11, 65, 63, 15);
label_1.setHorizontalAlignment(SwingConstants.RIGHT);
JLabel label_2 = new JLabel("Content");
label_2.setBounds(11, 93, 63, 14);
label_2.setHorizontalAlignment(SwingConstants.RIGHT);
JLabel label_3 = new JLabel("Columns");
label_3.setBounds(11, 205, 63, 20);
label_3.setHorizontalAlignment(SwingConstants.RIGHT);
JLabel label_4 = new JLabel("Name");
label_4.setBounds(16, 292, 63, 20);
label_4.setHorizontalAlignment(SwingConstants.RIGHT);
JLabel label_5 = new JLabel("Address");
label_5.setBounds(11, 325, 68, 15);
label_5.setHorizontalAlignment(SwingConstants.RIGHT);
JLabel label_6 = new JLabel("City");
label_6.setBounds(30, 357, 49, 14);
label_6.setHorizontalAlignment(SwingConstants.RIGHT);
JLabel label_7 = new JLabel("State");
label_7.setBounds(30, 395, 49, 14);
label_7.setHorizontalAlignment(SwingConstants.RIGHT);
JLabel label_8 = new JLabel("Zip Code");
label_8.setBounds(11, 430, 68, 20);
label_8.setHorizontalAlignment(SwingConstants.RIGHT);
txt_id = new JTextField();
txt_id.setHorizontalAlignment(SwingConstants.RIGHT);
txt_id.setBounds(78, 31, 86, 20);
txt_id.setEditable(false);
txt_id.setColumns(10);
txt_title = new JTextField();
txt_title.setBounds(78, 62, 189, 20);
txt_title.setColumns(10);
edit_content = new JEditorPane();
edit_content.setBounds(78, 93, 516, 106);
txt_columns = new JTextField();
txt_columns.setHorizontalAlignment(SwingConstants.RIGHT);
txt_columns.setBounds(78, 205, 32, 20);
txt_columns.setColumns(10);
JLabel lblRows = new JLabel("Rows");
lblRows.setBounds(114, 205, 50, 20);
txt_rows = new JTextField();
txt_rows.setHorizontalAlignment(SwingConstants.RIGHT);
txt_rows.setBounds(154, 205, 22, 20);
txt_rows.setEditable(false);
txt_rows.setColumns(10);
JLabel lblCost = new JLabel("Cost");
lblCost.setBounds(180, 205, 32, 20);
txt_cost = new JTextField();
txt_cost.setHorizontalAlignment(SwingConstants.RIGHT);
txt_cost.setBounds(216, 205, 55, 20);
txt_cost.setEditable(false);
txt_cost.setColumns(10);
JLabel lblType = new JLabel("Type");
lblType.setBounds(271, 205, 50, 20);
cmbo_type = new JComboBox<String>();
cmbo_type.setBounds(322, 205, 272, 20);
cmbo_type.setModel(new DefaultComboBoxModel<String>(new String[] {"01 - ANNOUNCEMENT_ENGAGEMENT", "02 - ANNOUNCEMENT_BIRTH", "03 - ANNOUNCEMENT_CELEBRATION", "04 - ANNOUNCEMENT_OTHER", "05 - PERSONAL", "06 - OBITUARY", "07 - HELP_WANTED_SKILLED", "08 - HELP_WANTED_UNSKILLED", "09 - PUBLIC_NOTICE", "10 - LOST_AND_FOUND_LOST", "11 - LOST_AND_FOUND_FOUND"}));
cmbo_type.setSelectedIndex(0);
JLabel lblDate = new JLabel("Date");
lblDate.setBounds(271, 65, 42, 14);
cmbo_month = new JComboBox<String>();
cmbo_month.setBounds(312, 62, 101, 20);
cmbo_month.setModel(new DefaultComboBoxModel<String>(new String[] {"Month...", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}));
cmbo_day = new JComboBox<String>();
cmbo_day.setBounds(419, 62, 71, 20);
cmbo_day.setModel(new DefaultComboBoxModel<String>(new String[] {"Day...", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"}));
cmbo_year = new JComboBox<String>();
cmbo_year.setBounds(496, 62, 98, 20);
cmbo_year.setModel(new DefaultComboBoxModel<String>(new String[] {"Year...","2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026", "2027", "2028", "2029", "2030"}));
JLabel lblAdInformation = new JLabel("Ad Information");
lblAdInformation.setBounds(252, 31, 111, 20);
JLabel lblBillingInformation = new JLabel("Billing Information");
lblBillingInformation.setHorizontalAlignment(SwingConstants.CENTER);
lblBillingInformation.setBounds(21, 248, 573, 14);
txt_name_billing = new JTextField();
txt_name_billing.setBounds(95, 292, 179, 20);
txt_name_billing.setColumns(10);
txt_address_billing = new JTextField();
txt_address_billing.setBounds(95, 322, 179, 20);
txt_address_billing.setColumns(10);
txt_city_billing = new JTextField();
txt_city_billing.setBounds(95, 354, 179, 20);
txt_city_billing.setColumns(10);
cmbo_state_billing = new JComboBox<String>();
cmbo_state_billing.setBounds(95, 392, 179, 20);
cmbo_state_billing.setModel(new DefaultComboBoxModel<String>(new String[] {"Select...", "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"}));
txt_zip_billing = new JTextField();
txt_zip_billing.setBounds(95, 430, 179, 20);
txt_zip_billing.setColumns(10);
JLabel lblCountry = new JLabel("Country");
lblCountry.setBounds(11, 469, 68, 14);
lblCountry.setHorizontalAlignment(SwingConstants.RIGHT);
cmbo_country_billing = new JComboBox<String>();
cmbo_country_billing.setBounds(95, 466, 179, 20);
cmbo_country_billing.setModel(new DefaultComboBoxModel<String>(new String[] {"Select...", "United States", "Canada", "----------------", "Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Antigua & Deps", "Argentina", "Armenia", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bhutan", "Bolivia", "Bosnia Herzegovina", "Botswana", "Brazil", "Brunei", "Bulgaria", "Burkina", "Burundi", "Cambodia", "Cameroon", "Cape Verde", "Central African Rep", "Chad", "Chile", "China", "Colombia", "Comoros", "Congo", "Congo {Democratic Rep}", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Fiji", "Finland", "France", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Greece", "Grenada", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Honduras", "Hungary", "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland {Republic}", "Israel", "Italy", "Ivory Coast", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea North", "Korea South", "Kosovo", "Kuwait", "Kyrgyzstan", "Laos", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Macedonia", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Mauritania", "Mauritius", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia", "Montenegro", "Morocco", "Mozambique", "Myanmar, {Burma}", "Namibia", "Nauru", "Nepal", "Netherlands", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Poland", "Portugal", "Qatar", "Romania", "Russian Federation", "Rwanda", "St Kitts & Nevis", "St Lucia", "Saint Vincent & the Grenadines", "Samoa", "San Marino", "Sao Tome & Principe", "Saudi Arabia", "Senegal", "Serbia", "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Sudan", "Spain", "Sri Lanka", "Sudan", "Suriname", "Swaziland", "Sweden", "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Togo", "Tonga", "Trinidad & Tobago", "Tunisia", "Turkey", "Turkmenistan", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "Uruguay", "Uzbekistan", "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Yemen", "Zambia", "Zimbabwe"}));
JSeparator separator_1 = new JSeparator();
separator_1.setBounds(21, 582, 70, 0);
separator_1.setOrientation(SwingConstants.VERTICAL);
JLabel lblPhoneNumber = new JLabel("Phone Number");
lblPhoneNumber.setBounds(282, 295, 104, 15);
lblPhoneNumber.setHorizontalAlignment(SwingConstants.RIGHT);
txt_phone_billing = new JTextField();
txt_phone_billing.setText("1234567890");
txt_phone_billing.setBounds(391, 292, 205, 20);
txt_phone_billing.setHorizontalAlignment(SwingConstants.LEFT);
txt_phone_billing.setColumns(10);
JLabel lblCardNumber = new JLabel("Card Number");
lblCardNumber.setBounds(282, 322, 104, 20);
lblCardNumber.setHorizontalAlignment(SwingConstants.RIGHT);
txt_ccn_billing = new JTextField();
txt_ccn_billing.setBounds(391, 322, 205, 20);
txt_ccn_billing.setColumns(10);
JLabel lblExpDate = new JLabel("Exp. Date");
lblExpDate.setBounds(282, 354, 104, 20);
lblExpDate.setHorizontalAlignment(SwingConstants.RIGHT);
cmbo_month_billing = new JComboBox<String>();
cmbo_month_billing.setBounds(391, 354, 102, 20);
cmbo_month_billing.setModel(new DefaultComboBoxModel<String>(new String[] {"Month...", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"}));
JLabel lblCvv = new JLabel("CVV2");
lblCvv.setHorizontalAlignment(SwingConstants.RIGHT);
lblCvv.setBounds(282, 392, 104, 20);
txt_cvv2_billing = new JTextField();
txt_cvv2_billing.setBounds(391, 392, 205, 20);
txt_cvv2_billing.setColumns(10);
cmbo_year_billing = new JComboBox<String>();
cmbo_year_billing.setBounds(494, 354, 102, 20);
cmbo_year_billing.setModel(new DefaultComboBoxModel<String>(new String[] {"Year...", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026", "2027", "2028", "2029", "2030"}));
btn_save = new JButton("Save");
btn_save.setBounds(258, 542, 101, 29);
btn_save.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent m) {
save_ad();
}
});
btn_update = new JButton("Calculate Cost");
btn_update.setBounds(83, 542, 101, 29);
btn_update.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent m) {
DecimalFormat df = new DecimalFormat("#0.00");
String num_columns = txt_columns.getText();
String content = edit_content.getText();
double total_rows = 0;
if (num_columns.compareToIgnoreCase("") != 0 || content.compareToIgnoreCase("") != 0) {
total_rows = (double) content.length() / (Double.valueOf(num_columns) * 20.0);
txt_rows.setText(String.valueOf((int)Math.ceil(total_rows)));
}
/*Columns 1 2 3 4
Base cost (title and 2 lines) $4.00 $5.50 $6.50 $8.00
Each additional line $0.50 $0.75 $1.50 $3.00 */
double cost = 0.0;
double cost_per_line_extra =0.0;
switch (Integer.valueOf(num_columns)) {
case 1:
cost = 4.00;
cost_per_line_extra = 0.5;
break;
case 2:
cost = 5.50;
cost_per_line_extra = 0.75;
break;
case 3:
cost = 6.50;
cost_per_line_extra = 1.50;
break;
case 4:
cost = 8.00;
cost_per_line_extra = 3.00;
break;
default:
cost = 0.0;
break;
}
if (total_rows > 2) {
cost += (total_rows - 2)*cost_per_line_extra;
}
txt_cost.setText("$" + df.format(cost));
}
});
btn_cancel = new JButton("Cancel");
btn_cancel.setBounds(433, 542, 115, 29);
btn_cancel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
int n = JOptionPane.showConfirmDialog(null, "Discard changes and cancel?", "Discard Changes",JOptionPane.YES_NO_OPTION);
if (n == 0) {
//yes
dispose();
}
}
});
separator = new JSeparator();
separator.setBounds(11, 236, 634, 6);
contentPane.setLayout(null);
contentPane.add(separator);
contentPane.add(lblBillingInformation);
contentPane.add(btn_update);
contentPane.add(btn_save);
contentPane.add(label);
contentPane.add(txt_id);
contentPane.add(lblAdInformation);
contentPane.add(label_1);
contentPane.add(label_2);
contentPane.add(label_3);
contentPane.add(txt_title);
contentPane.add(lblDate);
contentPane.add(txt_columns);
contentPane.add(lblRows);
contentPane.add(txt_rows);
contentPane.add(lblCost);
contentPane.add(txt_cost);
contentPane.add(lblType);
contentPane.add(cmbo_month);
contentPane.add(cmbo_day);
contentPane.add(cmbo_year);
contentPane.add(cmbo_type);
contentPane.add(edit_content);
contentPane.add(separator_1);
contentPane.add(label_6);
contentPane.add(txt_city_billing);
contentPane.add(label_7);
contentPane.add(cmbo_state_billing);
contentPane.add(label_4);
contentPane.add(txt_name_billing);
contentPane.add(label_5);
contentPane.add(txt_address_billing);
contentPane.add(label_8);
contentPane.add(lblCountry);
contentPane.add(cmbo_country_billing);
contentPane.add(txt_zip_billing);
contentPane.add(lblCardNumber);
contentPane.add(lblPhoneNumber);
contentPane.add(lblExpDate);
contentPane.add(lblCvv);
contentPane.add(txt_cvv2_billing);
contentPane.add(cmbo_month_billing);
contentPane.add(cmbo_year_billing);
contentPane.add(txt_ccn_billing);
contentPane.add(txt_phone_billing);
contentPane.add(btn_cancel);
chck_paid = new JCheckBox("Paid");
chck_paid.setHorizontalAlignment(SwingConstants.RIGHT);
chck_paid.setBounds(278, 466, 316, 20);
contentPane.add(chck_paid);
txt_id.setText(String.valueOf(AdsList.num_ads+1));
} | 8 |
private Collection<String> loadPrimaryColumns(String tableName) {
LinkedList<String> returnValue = new LinkedList<String>();
ResultSet rs = null;
try {
DatabaseMetaData metadata = connection.getMetaData();
SQLDatatbaseType sqlDatatbaseType = SQLDatatbaseType.getType(metadata.getURL());
/**
* Specificité Oracle : Il y a des schema et pas de catalog Specificité
* SQLServer : Il y a des catalogs et pas de schema
*/
String catalog, schema, table;
switch (sqlDatatbaseType) {
case SQLSERVER:
/*
* ==SQLServer== il est important que l'url de SQLServer contienne la
* base jdbc:microsoft:sqlserver://MY_SQLSERVE:1433;DatabaseName=MYDB
*/
if (StringUtils.isEmpty(schemaName)) {
catalog = null;
schema = null;
table = tableName.toUpperCase();
} else {
catalog = null;
schema = schemaName;
table = tableName.toUpperCase();
}
break;
case ORACLE:
/*
* ==Oracle== Il est important que l'importation se fasse avec le
* propriétaire du schema.
*/
if (StringUtils.isEmpty(schemaName)) {
catalog = null;
schema = metadata.getUserName();
table = tableName.toUpperCase();
} else {
catalog = null;
schema = schemaName;
table = tableName.toUpperCase();
}
break;
case DB2AS400:
/*
* ==DB2 AS400== Il est important que l'importation se fasse avec le
* propriétaire du schema.
*/
if (StringUtils.isEmpty(schemaName)) {
catalog = null;
schema = null;
table = tableName.toUpperCase();
} else {
catalog = null;
schema = schemaName;
table = tableName.toUpperCase();
}
break;
default:
catalog = null;
schema = schemaName;
table = tableName;
break;
}
rs = metadata.getPrimaryKeys(catalog, schema, table);
try {
while (rs.next()) {
String chaine = rs.getString("COLUMN_NAME").toUpperCase();
if (!returnValue.contains(chaine)) {
returnValue.add(chaine);
}
}
} finally {
rs.close();
}
rs = null;
} catch (java.sql.SQLException sqle) {
LOGGER.log(Level.SEVERE, "", sqle);
}
return returnValue;
} | 9 |
private void load() {
long startTime = System.currentTimeMillis();
logger.info("Starting reload of soft state...");
// the next version of the soft state
final Map<KeyRegistrationRecord, Set<KeyRegistrationRecord>> topology = new ConcurrentHashMap<KeyRegistrationRecord, Set<KeyRegistrationRecord>>();
final Map<String, KeyRegistrationRecord> key_to_record = new ConcurrentHashMap<String, KeyRegistrationRecord>();
final Map<Long, KeyRegistrationRecord> id_to_record = new ConcurrentHashMap<Long, KeyRegistrationRecord>();
final List<KeyRegistrationRecord> peers = Collections.synchronizedList(new ArrayList<KeyRegistrationRecord>());
final Map<String, Integer> ips_to_key_counts = Collections.synchronizedMap(new HashMap<String, Integer>());
(new SQLStatementProcessor<Void>("SELECT public_key, nick, created_by_account, registration_ip, registration_timestamp, last_refresh_timestamp, db_id FROM registered_keys ORDER BY key_hash ASC") {
Void process(PreparedStatement s) throws SQLException {
ResultSet rs = s.executeQuery();
while( rs.next() ) {
KeyRegistrationRecord fr = new KeyRegistrationRecord( rs.getString("public_key"), rs.getString("nick"), new Date(rs.getTimestamp("registration_timestamp").getTime()),
new Date(rs.getTimestamp("last_refresh_timestamp").getTime()), rs.getString("registration_ip"),
rs.getLong("created_by_account"), rs.getLong("db_id") );
peers.add(fr);
key_to_record.put(fr.getBase64PublicKey(), fr);
id_to_record.put(fr.getID(), fr);
topology.put(fr, Collections.synchronizedSet(new HashSet<KeyRegistrationRecord>()));
}
return null;
}
}).doit();
(new SQLStatementProcessor<Void>("SELECT registration_ip, COUNT(*) FROM registered_keys GROUP BY registration_ip") {
Void process(PreparedStatement s) throws SQLException {
ResultSet rs = s.executeQuery();
while( rs.next() ) {
String reg_ip = rs.getString(1);
Integer count = rs.getInt(2);
ips_to_key_counts.put(reg_ip, count);
logger.finest("ip: " + reg_ip + " registered " + count);
}
return null;
}
}).doit();
// (new SQLStatementProcessor<Void>("SELECT username, registered_keys FROM valid_accounts") {
// Void process(PreparedStatement s) throws SQLException {
// ResultSet rs = s.executeQuery();
// while( rs.next() ) {
// String reg_username = rs.getString(1);
// Integer count = rs.getInt(2);
//
// logger.finest("user: " + reg_username + " registered " + count);
// }
// return null;
// }
// }).doit();
(new SQLStatementProcessor<Void>("SELECT * FROM topology") {
Void process(PreparedStatement s) throws SQLException {
ResultSet rs = s.executeQuery();
while( rs.next() ) {
KeyRegistrationRecord a = id_to_record.get(rs.getLong("A_id"));
KeyRegistrationRecord b = id_to_record.get(rs.getLong("B_id"));
if( a == null ) {
logger.severe("Null soft state key registration record for ID: " + rs.getLong("A_id"));
continue;
}
if( b == null ) {
logger.severe("Null soft state key registration record for ID: " + rs.getLong("B_id"));
}
createFriendLink(topology, a, b, false);
}
return null;
}
}).doit();
synchronized(CommunityDAO.this) {
CommunityDAO.this.key_to_record = key_to_record;
CommunityDAO.this.id_to_record = id_to_record;
CommunityDAO.this.topology = topology;
CommunityDAO.this.peers = peers;
CommunityDAO.this.ips_to_key_counts = ips_to_key_counts;
}
logger.info("db sync took: " + (System.currentTimeMillis() - startTime) + " for " + peers.size());
} | 5 |
public EditorPane(RegularExpression expression) {
// super(new BorderLayout());
this.expression = expression;
field.setText(expression.asString());
field.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
updateExpression();
}
});
field.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
updateExpression();
}
public void removeUpdate(DocumentEvent e) {
updateExpression();
}
public void changedUpdate(DocumentEvent e) {
updateExpression();
}
});
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.gridwidth = GridBagConstraints.REMAINDER;
add(new JLabel("Edit the regular expression below:"), c);
add(field, c);
} | 0 |
public static void main(String[] args) {
Client client = null;
try {
Socket socket = new Socket(host, port);
client = new Client(socket);
} catch (UnknownHostException ex) {
System.out.println("Don't know about server " + host + ":" + port);
System.exit(-1);
} catch (IOException ex) {
System.out.println("Could't get I/O for "
+ "the connection to: " + host + ":" + port);
System.exit(-1);
}
MessagesListener messagesListener = new MessagesListener(client);
messagesListener.start();
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(
System.in));
try {
while(client.isConnected()) {
String s = stdIn.readLine();
if(s.toLowerCase().equals("exit")) {
messagesListener.disable();
client.println(farewellMessage);
client.disconnect();
} else {
client.println(s);
}
}
} catch(IOException e) {
System.out.println("IOE");
System.exit(-1);
} catch(NullPointerException e) {
System.out.println("NullPointerException cuz you've pressed ^C");
System.exit(-1);
}
try {
stdIn.close();
} catch (IOException e) {
}
} | 7 |
private int c2I(char c) {
int x = 0;
switch (c) {
case 'A': x = 0;
break;
case 'C': x = 1;
break;
case 'G': x = 2;
break;
case 'T': x = 3;
break;
default: x = 0;
System.out.println("Couldn't convert char "+c+" to index");
break;
}
return x;
} // Method - charToIndex | 4 |
public Perlin(int width, int height) {
random = new int[512];
Random r = new Random();
for (int i=0;i<512;i++) {
random[i] = r.nextInt(256);
}
data = new int[width][height];
for (int i=0;i<width;i++) {
for (int j=0;j<height;j++) {
data[i][j] = (int) (255*(noise(10.0*i/width,10.0*j/height,0)-1)/(2));
}
}
double minValue = 0;
double maxValue = 0;
for (int i=0;i<width;i++) {
for (int j=0;j<height;j++) {
minValue = Math.min(data[i][j], minValue);
maxValue = Math.max(data[i][j], maxValue);
}
}
for (int i=0;i<width;i++) {
for (int j=0;j<height;j++) {
data[i][j] = (int) (255*(data[i][j]-minValue)/(maxValue-minValue));
}
}
} | 7 |
public boolean Salvar(FormasPagamento obj){
PreparedStatement comando;
try{
if(obj.getId() == 0){
comando = banco.getConexao()
.prepareStatement("INSERT INTO tipos_pagamento "
+ "(nome,ativo) VALUES (?,?)");
comando.setString(1, obj.getNome());
comando.setInt(2, obj.getAtivo());
comando.executeUpdate();
comando.getConnection().commit();
}else {
comando = banco.getConexao()
.prepareStatement("UPDATE tipos_pagamento SET nome = ?, "
+ "ativo = ? WHERE id = ?");
comando.setString(1, obj.getNome());
comando.setInt(2, obj.getAtivo());
comando.setInt(3, obj.getId());
comando.executeUpdate();
comando.getConnection().commit();
}
return true;
}catch(SQLException ex){
ex.printStackTrace();
return false;
}
} | 2 |
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
HttpSession mensaje = request.getSession(true);
ResultSet respuesta=null;
PrintWriter out = response.getWriter();
//Declaro variables
String user_id = request.getParameter("user_id");
String nombre = request.getParameter("nombre");
String img_url = request.getParameter("img_url");
String tipo_primer = request.getParameter("tipo_primer");
BD bd = new BD();
bd.conectar();
ResultSet rs = bd.rawQuery("select * from guerrero where id_maestro ='"+user_id+"' and nombre='"+nombre+"'");
if(rs.next()){
mensaje.setAttribute("mensaje", "Ya tienes un guerrero con ese nombre");
response.sendRedirect("/Tarea1/Paginas/add_guerrero.jsp");
return;
}
if(tipo_primer.compareTo("none") == 0){
bd.regGuerrero(user_id,"1",nombre,img_url);
response.sendRedirect("/Tarea1/Paginas/p_usuario.jsp");
}else if(tipo_primer.compareTo("fuerte") == 0){
bd.regGuerrero(user_id,"4",nombre,img_url);
rs = bd.rawQuery("select id_guerrero from guerrero where id_maestro ='"+user_id+"' and nombre='"+nombre+"'");
rs.next();
String guerrero_id = rs.getString("id_guerrero");
bd.regHabilidad(guerrero_id, "AtaqueF", "2", "1");
bd.regHabilidad(guerrero_id, "DefensaF", "5", "2");
response.sendRedirect("/Tarea1/Paginas/p_usuario.jsp");
}else if(tipo_primer.compareTo("agil") == 0){
bd.regGuerrero(user_id,"3",nombre,img_url);
rs = bd.rawQuery("select id_guerrero from guerrero where id_maestro ='"+user_id+"' and nombre='"+nombre+"'");
rs.next();
String guerrero_id = rs.getString("id_guerrero");
bd.regHabilidad(guerrero_id, "AtaqueA", "5", "1");
bd.regHabilidad(guerrero_id, "DefensaA", "2", "2");
response.sendRedirect("/Tarea1/Paginas/p_usuario.jsp");
}
} catch (SQLException ex) {
Logger.getLogger(agregarGuerrero.class.getName()).log(Level.SEVERE, null, ex);
}
} | 5 |
public void updateStates() {
for (Player p : players) {
if (p != null && !p.dead) {
p.update();
}
}
for (Attack a : attacks) {
if (a != null) {
a.update();
int y = a.getLoc().getY();
int x = a.getLoc().getX();
if (y < 0 || y > StartUp.height || x < 0 || x > StartUp.width) {
attacks.remove(a);
}
}
}
} | 9 |
public void addNeuron(ArrayList<Connection> connects,Neuron neuron){
// THIS SHOULD NEVER RUN
if(connects.isEmpty()){
mutate();
return;
}
int connectionNum=rng.getInt(connects.size(),null,false);
Connection connection=connects.get(connectionNum);
//hack to make sure not inserting node into connection to self
int cnt=0;
while(connection.getGiveNeuron()==connection.getRecieveNeuron()){
cnt++;
connectionNum=rng.getInt(connects.size(),null,false);
connection=connects.get(connectionNum);
if(cnt==200)
new CMDTester(this);
}
Neuron otherNeuron=null;
if(connection.getGiveNeuron()==neuron)
otherNeuron=connection.getRecieveNeuron();
else
otherNeuron=connection.getGiveNeuron();
Neuron newNeuron=new Neuron_Add();
if(usingSpeciation){
newNeuron.setInitIn(neuron.getInnovationNum());
newNeuron.setInitOut(otherNeuron.getInnovationNum());
tracker.defineNeuron(newNeuron);
}
else
newNeuron.setInnovationNum(nodeCnt++);
if(connection.getGiveNeuron()==neuron){
makeConnection(neuron,newNeuron);
makeConnection(newNeuron,otherNeuron);
}else{
makeConnection(otherNeuron,newNeuron);
makeConnection(newNeuron,neuron);
}
neurons.add(newNeuron);
nodes.add(newNeuron);
} | 6 |
public void jugarAjedrez(){
iniciarElTablero();
imprimirArreglo();
int aband;
setTurno1();
do {
try{
System.out.println("Es el turno del jugador "+getTurno());
System.out.print("Ingrese la Fila: ");
fils=lea.nextInt();
System.out.print("Ingrese la Columna: ");
cols=lea.nextInt();
if (fils==-1&&cols==-1){
System.out.print("Deseas abandonar la partida? 1.Si/2.NO : ");
aband=lea.nextInt();
if(aband==1){
System.out.println("La partida ha sido habandonada por el jugador: "+getTurno());
if(getTurno()==1)
System.out.println("El jugador 1 ha ganado");
else
System.out.println("El jugador 2 ha ganado");
aband=0;
juegoTerminado=true;
}
}
seleccionarFicha(fils, cols, getTurno());
}catch(InputMismatchException e){
System.out.println("Ingresaste mal las conrdenadas, repite tu turno.");
lea.next();
}catch(Exception e){
System.out.println("las cordenadas ingresadas son incorrectas!");
}
} while (juegoTerminado=false);
} | 7 |
public JSONObject toJson() {
JSONObject rtn = new JSONObject();
try
{
rtn.put("type", this.getClass().getSimpleName());
rtn.put("value", this.getValueForOutput());
} catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return rtn;
} | 1 |
public Profile getProfile(String asAttendeeNumber) {
if (asAttendeeNumber == null || asAttendeeNumber.trim().length() == 0) {
throw new IllegalArgumentException("attendee num parameter is null");
}
return get(Profile.class, REST_URL_PROFILE + encode(asAttendeeNumber));
} | 2 |
public void onStop() throws JFException {
} | 0 |
public String getDescription() {
if(description==null)
return super.toString();
return description;
} | 1 |
public void setUnblocked(Account account){ account.setUnblocked(); } | 0 |
public ArrayList<Team> getAllTeams(Connection con) {
ArrayList<Team> arrayTeams = new ArrayList();
String SQLString = "SELECT * "
+ "FROM Teams ";
PreparedStatement statment = null;
try {
statment = con.prepareStatement(SQLString);
ResultSet rs = statment.executeQuery();
while (rs.next()) {
arrayTeams.add(new Team(rs.getInt(1), rs.getInt(2), rs.getInt(3)));
}
} catch (SQLException e) {
System.out.println("Error in TeamMapper - getAllTeams " + e);
} finally {
try {
statment.close();
} catch (SQLException e) {
System.out.println("Error in TeamMapper - getAllOrders.finally " + e);
}
}
return arrayTeams;
} | 3 |
public static IntersectData colliders( Collider collider1, Collider collider2 )
{
if ( collider1 == null || collider2 == null )
return null;
if ( collider1.getType() == ColliderType.SPHERE && collider2.getType() == ColliderType.SPHERE )
return ( (SphereCollider) collider1 ).intersect( (SphereCollider) collider2 );
if ( collider1.getType() == ColliderType.PLAN && collider2.getType() == ColliderType.SPHERE )
return planSphere( (PlanCollider) collider1, (SphereCollider) collider2 );
if ( collider1.getType() == ColliderType.SPHERE && collider2.getType() == ColliderType.PLAN )
return planSphere( (PlanCollider) collider2, (SphereCollider) collider1 );
return null;
} | 8 |
public void drawMap(Graphics graphics){
if (this.background != null){
graphics.drawImage(background, this.position.x, this.position.y, null);
}
if ((grid != null) && (showGrid)){
grid.paintComponent(graphics);
}
if (showGridEditor){
// private ArrayList<MapObstacle> obstacles = new ArrayList<MapObstacle>();
// private ArrayList<MapPortal> portals = new ArrayList<MapPortal>();
// private ArrayList<Point> items = new ArrayList<Point>();
for (MapObstacle obstacle : obstacles) {
Point systemCoordinate = grid.getCellPosition(obstacle.getLocation());
systemCoordinate.x += (grid.getCellWidth() / 4);
systemCoordinate.y += (grid.getCellHeight() * 3 / 4) ;
graphics.drawString("O", systemCoordinate.x, systemCoordinate.y);
}
for (MapPortal portal : portals) {
Point systemCoordinate = grid.getCellPosition(portal.getLocation());
systemCoordinate.x += (grid.getCellWidth() / 4);
systemCoordinate.y += (grid.getCellHeight() * 3 / 4) ;
graphics.drawString("P", systemCoordinate.x, systemCoordinate.y);
}
for (MapItem item : items) {
Point systemCoordinate = grid.getCellPosition(item.getLocation());
systemCoordinate.x += (grid.getCellWidth() / 4);
systemCoordinate.y += (grid.getCellHeight() * 3 / 4) ;
graphics.drawString("I", systemCoordinate.x, systemCoordinate.y);
}
}
} | 7 |
private Resource parseText(String lineOfText) {
boolean done = false; // Indicates the end of parsing
String token; // String token parsed from the line of text
int tokenCount = 0; // Number of tokens parsed
int frontIndex = 0; // Front index or character position
int backIndex = 0; // Rear index or character position
// Create a Resource object to record all of the info parsed from
// the line of text
Resource resource = new Resource();
while (!done) {
backIndex = lineOfText.indexOf(' ', frontIndex);
if (backIndex == -1) {
done = true;
token = lineOfText.substring(frontIndex);
} else {
token = lineOfText.substring(frontIndex, backIndex);
}
switch (tokenCount) {
case 0: // Resource ID
resource.setID(token);
frontIndex = backIndex + 1;
tokenCount++;
break;
case 1: // Resource's last name
resource.setLastName(token);
frontIndex = backIndex + 1;
tokenCount++;
break;
case 2: // Resource's First name
resource.setFirstName(token);
frontIndex = backIndex + 1;
tokenCount++;
break;
case 3: // Resource role (see this file's header)
resource.setRole(token);
frontIndex = backIndex + 1;
tokenCount++;
break;
default:
// This is where the projects are added to the list of projects
// previously assigned to this resource. Note that there are
// no details other than the project ID.
if(token != null && !token.isEmpty()) {
Project previouslyAssignedProject = projectReader.getListOfProjects().findProjectByID(token);
if (previouslyAssignedProject == null) {
resource.getPreviouslyAssignedProjectList().addProject(new Project(token));
} else {
resource.getPreviouslyAssignedProjectList().addProject(previouslyAssignedProject);
}
}
//resource.getPreviouslyAssignedProjectList().addProject(new Project(token));
frontIndex = backIndex + 1;
break;
} // end switch
} // end while
return (resource);
} // parseText | 9 |
public Image getImage(final double W, final double H) {
final int WIDTH = (int) W;
final int HEIGHT = (int) H;
WritableImage DESTINATION = new WritableImage(WIDTH, HEIGHT);
final int[] IN_PIXELS = new int[WIDTH];
final int[] OUT_PIXELS = new int[WIDTH];
randomNumbers = new Random(0);
final int ALPHA = color & 0xff000000;
final int RED = (color >> 16) & 0xff;
final int GREEN = (color >> 8) & 0xff;
final int BLUE = color & 0xff;
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
int tr = RED;
int tg = GREEN;
int tb = BLUE;
if (shine != 0) {
int f = (int) (255 * shine * Math.sin((double) x / WIDTH * Math.PI));
tr += f;
tg += f;
tb += f;
}
if (monochrome) {
int n = (int) (255 * (2 * randomNumbers.nextFloat() - 1) * amount);
IN_PIXELS[x] = ALPHA | (clamp(tr + n) << 16) | (clamp(tg + n) << 8) | clamp(tb + n);
} else {
IN_PIXELS[x] = ALPHA | (random(tr) << 16) | (random(tg) << 8) | random(tb);
}
}
if (radius != 0) {
blur(IN_PIXELS, OUT_PIXELS, WIDTH, radius);
setRGB(DESTINATION, 0, y, OUT_PIXELS);
} else {
setRGB(DESTINATION, 0, y, IN_PIXELS);
}
}
return DESTINATION;
} | 5 |
public void setQty(int newQty) {
qty = newQty;
if (qty < 1) {
itemType = null;
qty = 0;
}
} | 1 |
@Override
public void run() {
long last = System.currentTimeMillis();
while (running) {
long now = System.currentTimeMillis();
long delta = now - last;
update(delta);
render();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
last = now;
}
} | 2 |
public JSONObject increment(String key) throws JSONException {
Object value = this.opt(key);
if (value == null) {
this.put(key, 1);
} else if (value instanceof Integer) {
this.put(key, ((Integer) value).intValue() + 1);
} else if (value instanceof Long) {
this.put(key, ((Long) value).longValue() + 1);
} else if (value instanceof Double) {
this.put(key, ((Double) value).doubleValue() + 1);
} else if (value instanceof Float) {
this.put(key, ((Float) value).floatValue() + 1);
} else {
throw new JSONException("Unable to increment [" + quote(key) + "].");
}
return this;
} | 5 |
public void adjustSize(int width, int height) {
saving = true;
if(width > bi.getWidth() || height > bi.getHeight()) {
BufferedImage tempBi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = tempBi.createGraphics();
this.paint(g);
g.dispose();
bi = tempBi;
} else {
BufferedImage tempBi = bi.getSubimage(0, 0, width, height);
bi = tempBi;
}
saving = false;
this.setPreferredSize(new Dimension(width, height));
} | 2 |
@Override
protected void createReaderWriter() throws JoeException {
ourReaderWriter = new PdbTMReaderWriter() ;
if (ourReaderWriter == null) {
throw new JoeException(UNABLE_TO_CREATE_OBJECT) ;
}
} | 1 |
private Set<Card> FourFlushWithWheelStraight() {
return convertToCardSet("JD,4S,8S,3S,5S,AC,2H");
} | 0 |
public void dispatchEvent(Event event) {
if (!listeners.containsKey(event.getClass())) return;
Class<? extends Event> clazz = event.getClass();
while (clazz != null) {
for (Listener listener : listeners.get(event.getClass())) {
listener.onEvent(event);
}
clazz = (Class<? extends Event>) clazz.getSuperclass();
}
} | 5 |
public int getInt(String o) {
String i = ", ";
if (o.equals("avatarid"))
i = "}";
String v = Pattern.compile(o + ": ").split(line)[1];
return Integer.parseInt(v.substring(0, v.indexOf(i)));
} | 1 |
public void addCarriage(RollingStock newCarriage) throws TrainException {
if (train.isEmpty()) {
if (newCarriage instanceof Locomotive) {
train.add(newCarriage);
} else {
throw new TrainException(
"Invalid train configuration: Locomotive must be the first carriage.");
}
} else if (passengersOnTrain > NO_PASSENGERS) {
throw new TrainException(
"There are passengers on the train. No carriage shunting operations may be performed.");
} else if (newCarriage instanceof Locomotive) {
throw new TrainException(
"Invalid train configuration: There can only be one locomotive per train.");
} else if (newCarriage instanceof PassengerCar) {
// If there's no freight cars already attached
if (!freightCarsExist) {
train.add(newCarriage);
trainSeatsAbility += ((PassengerCar) newCarriage)
.numberOfSeats();
} else {
throw new TrainException(
"Invalid train configuration: Freight cars already exist.");
}
} else if (newCarriage instanceof FreightCar) {
freightCarsExist = true;
train.add(newCarriage);
} else {
throw new TrainException(
"Invalid train configuration: Unacceptable carriage name.");
}
} | 7 |
public static void main(String [] args) {
int[] d;
d = new int[10001]; // we'll ignore d[0];
for (int i = 1; i<10001; i++) {
// compute d(i)
int divisorSum = 0 ;
for (int j = 1; j<=1 + i/2; j++) {
if (i%j == 0) {
divisorSum += j;
}
}
d[i]=divisorSum;
}
int amicableSum = 0;
for (int a=1; a<=10000; a++) {
int b = d[a];
if (a<b) { // careful to not double count a,b and b,a
if (b>=1 && b<=10000) {
if (d[b] == a) {
amicableSum += (a+b);
System.out.println("Pair: " + a + ", b: " + b);
}
}
}
}
System.out.println(amicableSum);
} | 8 |
private void rapatrierFormations() {
ArrayList<Formation> formations = new ArrayList<Formation>();
String req = "";
req = "select * from Formation";
ResultSet res = null;
try {
res = gestionUniversite.Connexion.getInstance().getStatement().executeQuery(req);
while (res.next()) {
String code = res.getString("code");
String nom = res.getString("nom");
String nomSalleCM = res.getString("nomSalleCM");
String nomSalleTD = res.getString("nomSalleTD");
Salle salleCM = universite.getSalle(nomSalleCM);
Salle salleTD = universite.getSalle(nomSalleTD);
Formation formation = new Formation(nom, code, salleCM, salleTD);
formations.add(formation);
}
//res = gestionUniversite.Connexion.getInstance().getStatement().executeQuery(req);
} catch (SQLException ex) {
Logger.getLogger(ModeleApplication.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (res != null) {
try {
res.close();
} catch (SQLException ex) {
Logger.getLogger(ModeleApplication.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
this.universite.setLesFormations(formations);
for (Formation formation : formations) {
formation.setModules(this.reconstruireModules(formation.getCode()));
formation.setSuccessor(this.universite);
}
} | 5 |
private void initialize()
{
setForeground(Color.white);
setOpaque(false);
setContentAreaFilled(false);
setBorderPainted(false);
if (name != null)
{
this.setText(name);
this.setToolTipText(name);
}
setVerticalTextPosition(SwingConstants.BOTTOM);
setHorizontalTextPosition(SwingConstants.CENTER);
setPreferredSize(Utils.ICON_DIMENSION);
setMaximumSize(Utils.ICON_DIMENSION);
setMinimumSize(Utils.ICON_DIMENSION);
addMouseListener(new FileListListener(this));
if (this.getIcon() == null)
{
setIcon(Utils.getUnknownIcon());
if (medias.size() > 0)
downloadIcon();
}
} | 3 |
public RegularGrammar getRegularGrammar() {
return (RegularGrammar) getGrammar(RegularGrammar.class);
} | 0 |
@Override
public void keyPressed(KeyEvent e) {
int keys = e.getKeyCode();
if (keys == KeyEvent.VK_ESCAPE) {
mainMenuObj.setMx(WINDOW_WIDTH);
currentMode = mode1;
ticTacToeFunctionsObj.clearPlayerScores(ticTacToePlayerObj);
for (int i = 0; i < 10; i++) {
ticTacToeFunctionsObj.wipeBoard(ticTacToeboardObj, ticTacToePlayerObj, squareStore);
}
ticTacToePlayerObj.setTurn(1);
goFunctionsObj.resetBoard(goBoardObj, goSettingObj, goSquareStore);
}
if (currentMode == null ? mode5 == null : currentMode.equals(mode5)) {
if (keys == KeyEvent.VK_ENTER) {
goSettingObj.buildBoard();
currentMode = mode6;
}
}
} | 5 |
public String getBestScore() {
String res = "";
Collections.sort(scores);
res = scores.get(scores.size()-1);
return res;
} | 0 |
public Copyable getVersion(Transaction me, ContentionManager manager) {
while (true) {
if (me != null && me.getStatus() == Status.ABORTED) {
throw new AbortedException();
}
switch (writer.getStatus()) {
case ACTIVE:
if (manager == null) {
throw new PanicException("Transactional/Non-Tranactional race");
}
manager.resolveConflict(me, writer);
continue;
case COMMITTED:
return newVersion;
case ABORTED:
return oldVersion;
default:
throw new PanicException("Unexpected transaction state: " + writer.getStatus());
}
}
} | 7 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.