method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
3c58c2d0-87c7-4b13-8f5f-c2fabc0a44f3 | 0 | public void setInstallDate(String installDate) {
this.installdate = installDate;
setDirty();
} |
47ea8769-7deb-4b5e-8932-09d6cb91ae71 | 8 | private boolean isNumberDouble(String input) {
boolean res = true;
int i = 0;
if(input == null || input.isEmpty() || input.endsWith(".") || !input.contains("."))
res = false;
else{
i = 0;
while(i < input.length() && res){
if(!Character.isDigit(input.charAt(i)) && (input.charAt(i) != '.'))
res = false;
i++;
}
}
return res;
} |
5a4359f8-e571-464c-a61c-c9369239d5c1 | 1 | public void playGameAsHost(ArrayList<User> gameUsers, HostGameTask hgt)
throws InterruptedException, IOException, InvalidKeySpecException,
NoSuchAlgorithmException, NoSuchPaddingException,
NoSuchProviderException, InvalidKeyException, BadPaddingException,
IllegalBlockSizeException {
EncryptedDeck encDeck;
RSAService rsaService = new RSAService();
// if more types of poker were added this would be a parameter and
// SwingUI would instantiate it
GamePlay thGamePlay = new TexasHoldEmGamePlay();
thGamePlay.init();
gameUser.setDecryptionKey(rsaService.getD());
// broadcast p and q
comServ.broadcastPQ(rsaService.getP(), rsaService.getQ(),
gameUsers.size());
System.out.println(rsaService.getP().toString() + "\n"
+ rsaService.getQ().toString());
// create and encrypt the deck
encDeck = createDeck(rsaService);
try {
thGamePlay.hostGamePlay(rsaService, comServ, gameUser, gameUsers,
sig, encDeck, hgt);
} catch (Exception e) {
System.err.println("Error in host gameplay.");
System.exit(0);
}
comServ.shutdown();
return;
} |
bafb6567-4b36-4a4d-a4a3-df64ae726553 | 4 | @EventHandler
public void onInventoryClose(InventoryCloseEvent e)
{
if (e.getInventory().getName().equals(Message.REWARD_CLAIM_INVENTORY_NAME.toString()))
{
for (ItemStack itemStack : e.getInventory().getContents())
if (itemStack != null)
e.getPlayer().getWorld().dropItemNaturally(e.getPlayer().getLocation(), itemStack);
}
if (e.getInventory().getName().equals(Message.REWARD_EDIT_INVENTORY_NAME.toString()))
{
cm.getMain().getLM().storeEdits(e.getInventory());
}
} |
4a157f57-3c0b-45d9-9194-4d4c712988a0 | 0 | @Override
public void clearObservers() {
readers.clear();
} |
2a34df17-4d8f-4f6e-98c9-993f52a03154 | 0 | public void setGoToList(ArrayList<String> goToList) {
this.goToList = goToList;
} |
a034c140-0d39-4c19-baa8-589bce19fb25 | 6 | @Override
public boolean validCapture(Point startPosition, Point endPosition){
Point difference = new Point();
difference.setLocation(endPosition.getX() - startPosition.getX(), endPosition.getY() - startPosition.getY());
if(this.getColor() && (Math.abs(difference.getX()) == 1 && (difference.getY() == 1))){
return true;
}
else if(!this.getColor() && (Math.abs(difference.getX()) == 1 && (difference.getY() == -1))){
return true;
}
return false;
} |
97d25429-7933-4bb2-a770-d18b7ccc776e | 9 | @Override
public void bindTexture(TextureManager textureManager) {
// If skin changed, or if no skin texture is yet loaded...
if (skinBitmap != newSkinBitmap || textureId < 0) {
synchronized (this) {
if (skinBitmap != newSkinBitmap || textureId < 0) {
if (skinBitmap != null) {
// Unload the old texture
textureManager.unloadTexture(textureId);
}
if (newSkinBitmap == null) {
// Load default skin
if (isInteger(modelName)) {
textureId = textureManager.load(Textures.TERRAIN);
} else if (Model.HUMANOID.equals(modelName)) {
textureId = textureManager.load(Textures.MOB_HUMANOID);
} else {
textureId = textureManager.load(Textures.forModel(modelName));
}
} else {
// Load custom skin
hasHair = Model.HUMANOID.equals(modelName) && checkForHat(newSkinBitmap);
textureId = textureManager.load(newSkinBitmap);
}
skinBitmap = newSkinBitmap;
}
}
}
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureId);
} |
1a1e74cb-d978-49f6-86dc-79b2077ae7be | 3 | public void run() {
long time = System.currentTimeMillis();
while ( true ) {
long thisTime = System.currentTimeMillis();
if ( thisTime - time < FPS_TIME ) {
continue;
}
int len = SceneDirector.getLength();
int last = len - 1;
for ( int i = 0; i < len; i++ ) {
Scene scene = SceneDirector.getScene( i );
scene.getKeyEvent().updateKeyEvent( gameWindow.getPressKey(), gameWindow.getReleaseKey() );
scene.processUpdaste( ( i < last ) );
scene.getKeyEvent().disposeKeyEvent();
}
gameWindow.getGamePanel().repaint();
gameWindow.disposeKey();
time = thisTime;
}
} |
2e43fcdb-ac0f-4f91-8cb9-a637925c2f39 | 5 | @Override
public int getSamples(byte[] buffer) {
byte[] cvBuffer = null;
provider.getSamples(buffer);
if(attenuationCv != null) {
cvBuffer = new byte[buffer.length];
attenuationCv.getSamples(cvBuffer);
}
int index = 0;
for(int i = 0; i < buffer.length / 2; i++) {
// If there is cv input then apply that to the attenuationRatio
if(cvBuffer != null) {
short cvSample = SampleConverter.toSample(cvBuffer, index);
double cvValue = SampleConverter.getSampleValue(cvSample) * 2;
if(cvValue < 0.0) {
cvValue *= -1;
}
// Apply modulation value to sample
if(attenuationBaseRatio * cvValue <= 1.0) {
attenuationRatio = attenuationBaseRatio * cvValue;
}
}
short sample = SampleConverter.toSample(buffer, index);
sample = attenuate(sample);
// Store the processed sample back to the buffer.
buffer[index++] = (byte)(sample >> 8);
buffer[index++] = (byte)(sample & 0xFF);
}
return buffer.length;
} |
d9e5cd8a-0bd6-47bf-a284-dc79e14de4a0 | 2 | private boolean doConditionalAction(GenericLittleMan<?> littleMan) {
boolean isComplete2 = littleManConditionalAction.doAction(littleMan);
if (isComplete2) {
resetConditionalActionStep();
}
return isComplete2;
} |
43586ed0-f5fb-4996-9404-a487a6eac0ed | 4 | public List<String> getCyclingPeptideStrings(int stringLength, String peptide) {
List<String> peptideMassList = new ArrayList();
for (int i = 0; i < peptide.length(); i++) {
StringBuilder stringBuilder = new StringBuilder();
if ((stringLength + 1) == peptide.length()) {
stringBuilder.append(peptide);
if (!frequentWords.alreadyExistsInList(peptideMassList, stringBuilder.toString())) {
peptideMassList.add(stringBuilder.toString());
}
} else {
if ((i + stringLength + 1) > peptide.length()) {
int rest = i + stringLength + 1 - peptide.length();
int available = peptide.length() - i;
stringBuilder.append(peptide.substring(i, i + available));
stringBuilder.append(peptide.substring(0, rest));
peptideMassList.add(stringBuilder.toString());
} else {
stringBuilder.append(peptide.substring(i, i + stringLength + 1));
peptideMassList.add(stringBuilder.toString());
}
}
}
return peptideMassList;
} |
3681ca2a-f842-47ae-b35b-182c121db61c | 8 | private Component cycle(Component currentComponent, int delta) {
int index = -1;
loop : for (int i = 0; i < m_Components.length; i++) {
Component component = m_Components[i];
for (Component c = currentComponent; c != null; c = c.getParent()) {
if (component == c) {
index = i;
break loop;
}
}
}
// try to find enabled component in "delta" direction
int initialIndex = index;
while (true) {
int newIndex = indexCycle(index, delta);
if (newIndex == initialIndex) {
break;
}
index = newIndex;
//
Component component = m_Components[newIndex];
if (component.isEnabled() && component.isVisible() && component.isFocusable()) {
return component;
}
}
// not found
return currentComponent;
} |
e68598f6-6441-4833-9e0f-58649411eb33 | 7 | @Override
public void executeMsg(Environmental host, CMMsg msg)
{
if((msg.sourceMinor()==CMMsg.TYP_SPEAK)
&&(!noRecurse)
&&(affected instanceof MOB)
&&(msg.amISource((MOB)affected))
&&(msg.source().location()!=null)
&&(msg.source().charStats().getMyRace().bodyMask()[Race.BODY_MOUTH]>=0))
{
noRecurse=true;
final MOB invoker=(invoker()!=null) ? invoker() : msg.source();
try{CMLib.combat().postDamage(invoker,msg.source(),this,msg.source().maxState().getHitPoints()/20,CMMsg.MASK_ALWAYS|CMMsg.TYP_CAST_SPELL,Weapon.TYPE_SLASHING,L("The blades in <T-YOUPOSS> mouth <DAMAGE> <T-HIM-HER>!"));
}finally{noRecurse=false;}
}
super.executeMsg(host,msg);
} |
ee9ef829-7f44-48c9-9140-a4a95f8c6cb4 | 0 | @Override
public void reset() {
super.reset();
weight = 0;
gravityForce.set(0, 0, 0);
setTotalForce(gravityForce);
} |
dc500d55-371b-4748-ab9e-5faa2c7f45e2 | 8 | public void doAddUser(){
if( (newName.getText().length() > 0 && newSurname.getText().length() > 0 && newFisCod.getText().length() > 0 &&
newUserName.getText().length() > 0 && newPwd.getText().length() > 0 && confNewPwd.getText().length() > 0) && (confNewPwd.getText().equals(newPwd.getText()) ) ){ //TODO eventualmente piccolo avviso nel caso le password divergono
User temp = SystemController.currentUser.createUser();
temp.setName(newName.getText());
temp.setSurname(newSurname.getText());
temp.setFiscalCode(newFisCod.getText());
temp.setUsername(newUserName.getText());
temp.setPassword(GuiController.SHA1(newPwd.getText().getBytes()));
temp.setAdmin(false);
temp.setSubstituteOf("0");
temp.sendData();
sLab.setVisible(true);
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(addUser.class.getName()).log(Level.SEVERE, null, ex);
}
sLab.setVisible(false);
//TODO repaint dell lista utenti e metti un indietro
GuiController.showMainPanel();
}
} |
d9f2a7e4-b860-4bce-810f-3b54f8772407 | 4 | void onFocusOut () {
hasFocus = false;
if (itemsCount == 0) {
redraw ();
return;
}
if (focusItem != null) {
redrawItem (focusItem.index, true);
}
if ((getStyle () & (SWT.HIDE_SELECTION | SWT.MULTI)) == (SWT.HIDE_SELECTION | SWT.MULTI)) {
for (int i = 0; i < selectedItems.length; i++) {
redrawItem (selectedItems [i].index, true);
}
}
} |
e9634cbc-1679-41b5-a1aa-fa66ab3d796a | 1 | public void run() {
if (drawFlames) {
processFlameDrawing();
} else {
super.run();
}
} |
230f2f04-b389-4640-897f-0bf914f6e3c0 | 9 | public void nondeterministicPreCanonicalization(NamedGraph g) throws Exception{
//Get triples
ArrayList<Triple> triples=g.getTriples();
//Get C14N Predicate
String c14n=Ontology.getC14NPredicate();
//Count and substitute blank nodes
substituteBlankNodes(triples);
//Perform a one-step deterministic labeling (Step A)
lookupTable = new HashMap<String,Integer>();
counter=new GenSymCounter(bnCount);
oneStepDeterministicLabelling(g);
canonicalizeGraphNames(g);
canonicalizeReifications(g);
//Stop if there are no hard to label nodes (Step B)
if ( bnCount==0 ){
return;
}
//Delete triples with predicate "c14n:true" (Step C)
for(Triple t:triples) {
if (t.getPredicate().equals(c14n)){
triples.remove(t);
}
}
//Perform another one-step deterministic labeling (Step D)
substituteBlankNodes(triples);
oneStepDeterministicLabelling(g);
canonicalizeGraphNames(g);
canonicalizeReifications(g);
//Handle remaining hard to label nodes by adding new nodes (Step E)
lookupTable.clear();
counter.reset();
ArrayList<Triple> newTriples = new ArrayList<Triple>();
for(Triple t:triples) {
//Object and subject replacement - two iterations in while loop:
// 1) pos = Triple.object
// 2) pos = Triple.subject
int pos = Triple.object;
while (true){
if (t.getByIndex(pos).equals("~")){
//Get original blank node identifier from annotation
String bnName = t.getAnnotation();
//Is blank node in lookup table?
Integer lookupName = lookupTable.get(bnName);
if (lookupName == null){
//No, generate a new triple
newTriples.add( new Triple(bnName, c14n, "\""+counter.getNewSym()+"\"") );
lookupTable.put("x",counter.getCurrentValue());
}
}
//Replace subject after object or end loop if subject has been replaced already
if (pos == Triple.object){
pos = Triple.subject;
}else{
break;
}
}
}
for (Triple addNew:newTriples){
triples.add(addNew);
}
canonicalizeGraphNames(g);
canonicalizeReifications(g);
//Perform another one-step deterministic labeling (Step F)
lookupTable.clear();
counter.reset();
substituteBlankNodes(triples);
oneStepDeterministicLabelling(g);
canonicalizeGraphNames(g);
canonicalizeReifications(g);
//Sort sub graphs
Collections.sort(g.getChildren());
} |
6ad91d2f-92ff-47fd-8ead-f505499f0c2d | 6 | private void setParam() {
if (anon) {
try {
ctx.init(null, null, null);
} catch(KeyManagementException e) {
throw new AuthFailureException(e.getMessage());
}
} else {
try {
TrustManager[] myTM = new TrustManager[] {
new MyX509TrustManager()
};
ctx.init(null, myTM, null);
} catch(java.security.GeneralSecurityException e) {
throw new AuthFailureException(e.getMessage());
}
}
SSLSocketFactory sslfactory = ctx.getSocketFactory();
engine = ctx.createSSLEngine(client.getServerName(),
client.getServerPort());
engine.setUseClientMode(true);
if (anon) {
String[] supported;
ArrayList<String> enabled = new ArrayList<String>();
supported = engine.getSupportedCipherSuites();
for (int i = 0; i < supported.length; i++)
if (supported[i].matches("TLS_DH_anon.*"))
enabled.add(supported[i]);
engine.setEnabledCipherSuites(enabled.toArray(new String[0]));
} else {
engine.setEnabledCipherSuites(engine.getSupportedCipherSuites());
}
engine.setEnabledProtocols(new String[]{"SSLv3", "TLSv1"});
} |
5a19ef73-4e7e-4642-917c-5e4dde905ad8 | 6 | public void setRAMBufferSizeMB(double mb) {
if (mb > 2048.0) {
throw new IllegalArgumentException("ramBufferSize " + mb + " is too large; should be comfortably less than 2048");
}
if (mb != DISABLE_AUTO_FLUSH && mb <= 0.0)
throw new IllegalArgumentException(
"ramBufferSize should be > 0.0 MB when enabled");
if (mb == DISABLE_AUTO_FLUSH && getMaxBufferedDocs() == DISABLE_AUTO_FLUSH)
throw new IllegalArgumentException(
"at least one of ramBufferSize and maxBufferedDocs must be enabled");
docWriter.setRAMBufferSizeMB(mb);
if (infoStream != null)
message("setRAMBufferSizeMB " + mb);
} |
8e1dc220-26e2-49b1-a2c3-9336c3697a86 | 7 | @Override
@SuppressWarnings({ "nls", "boxing" })
protected void initialize(Class<?> type, Object oldInstance,
Object newInstance, Encoder enc) {
// Call the initialization of the super type
super.initialize(type, oldInstance, newInstance, enc);
// Continue only if initializing the "current" type
if (type != oldInstance.getClass()) {
return;
}
JTabbedPane pane = (JTabbedPane) oldInstance;
int count = pane.getTabCount();
for (int i = 0; i < count; i++) {
Expression getterExp = new Expression(pane.getComponentAt(i), pane,
"getComponentAt", new Object[] { i });
try {
// Calculate the old value of the property
Object oldVal = getterExp.getValue();
// Write the getter expression to the encoder
enc.writeExpression(getterExp);
// Get the target value that exists in the new environment
Object targetVal = enc.get(oldVal);
// Get the current property value in the new environment
Object newVal = null;
try {
JTabbedPane newJTabbedPane = (JTabbedPane) newInstance;
newVal = new Expression(newJTabbedPane.getComponent(i),
newJTabbedPane, "getComponentAt",
new Object[] { i }).getValue();
} catch (ArrayIndexOutOfBoundsException ex) {
// The newInstance has no elements, so current property
// value remains null
}
/*
* Make the target value and current property value equivalent
* in the new environment
*/
if (null == targetVal) {
if (null != newVal) {
// Set to null
Statement setterStm = new Statement(oldInstance, "addTab",
new Object[] { pane.getTitleAt(i), oldVal });
enc.writeStatement(setterStm);
}
} else {
Statement setterStm = new Statement(oldInstance, "addTab",
new Object[] { pane.getTitleAt(i), oldVal });
enc.writeStatement(setterStm);
}
} catch (Exception ex) {
enc.getExceptionListener().exceptionThrown(ex);
}
}
} |
d5c08f70-d595-4300-a04a-6cdb5bde4dbe | 5 | public int isMissingMeta(File mp3){
try {
String title, artist, bpm;
AudioFile f = AudioFileIO.read(mp3);
Tag tag = f.getTag();
if(tag == null){
return 9;//No tag what a drag.
}
artist = tag.getFirst(FieldKey.ARTIST);
title = tag.getFirst(FieldKey.TITLE);
bpm = tag.getFirst(FieldKey.BPM);
int ret = 0;
if(artist.equals("")){
ret = ret + 2;//2+3 = 5, 2+4 = 6, 3+4 =7,
}
if(title.equals("")){
ret = ret + 3;
}
if(bpm.equals("")){
ret = ret + 4;
}
return ret;
}catch(Exception e){
return 0;
}
} |
bb44e54a-9005-4918-862a-2df1ec8cbbd0 | 1 | public static void asm_andwf(Integer befehl, Prozessor cpu) {
Integer w = cpu.getW();
Integer f = getOpcodeFromToBit(befehl, 0, 6);
Integer erg = w & cpu.getSpeicherzellenWert(f);
if(getOpcodeFromToBit(befehl, 7, 7) == 1) {
cpu.setSpeicherzellenWert(f, erg, true);
}
else {
cpu.setW(erg, true);
}
cpu.incPC();
} |
426a077f-a9e8-4515-9a06-55780b4172f5 | 4 | @EventHandler
public void onPlayerLogin(final PlayerLoginEvent event) {
String player = event.getPlayer().getName();
/**
* Check if the player is banned.
*
* Kick with the appropriate message if so.
*/
if (this.plugin.isBanned(player)) {
event.setKickMessage(this.plugin.buildKickMessage(this.plugin.why(player)));
event.setResult(PlayerLoginEvent.Result.KICK_BANNED);
return;
}
/**
* Check if any of the player's previous names where banned while they were
* using it.
*/
Map<Integer, String> history = this.plugin.getNameHistory(event.getPlayer().getUniqueId());
for (int ts : history.keySet()) {
String previousName = history.get(ts);
if (this.plugin.isBanned(previousName)) {
Event previousEvent = this.plugin.getActiveEvent(previousName);
if (this.plugin.hadNameAtTime(event.getPlayer().getUniqueId(), previousName, previousEvent.getTime())) {
event.setKickMessage(this.plugin.buildKickMessage(this.plugin.why(previousName)));
event.setResult(PlayerLoginEvent.Result.KICK_BANNED);
return;
}
}
}
/**
* Start the player's task.
*
* This will make sure the player is kicked if a temporary unban expires, or
* if a ban is added externally.
*/
this.taskMap.put(
player,
this.plugin.getServer().getScheduler().scheduleSyncRepeatingTask(this.plugin,new PlayerTask(this.plugin,player),20 * 60,20 * 60)
);
} |
88c73377-917a-4560-add1-a0498c8b4447 | 2 | public void paint(Graphics g) {
super.paint(g);
for(int i = 0; i < area.entities.size(); i++) {
area.entities.get(i).render(g);
}
if(area.isEmpty(hold))
hold.render(g);
else
g.drawImage(Images.cross, (int)hold.x - 16 - View.x, (int)hold.y - 16 - View.y, null);
g.setColor(new Color(192, 192, 192));
g.fillRect(0,0,800, 30);
g.setColor(Color.WHITE);
g.setFont(new Font("Sans-Serif", Font.PLAIN, 14));
g.drawImage(Images.logs, 700, -2, null);
g.drawString(String.valueOf(Resources.wood), 740, 20);
g.drawImage(Images.slave, 610, 7, null);
g.drawString(String.valueOf(Resources.population) + " / " + String.valueOf(Resources.maxpop), 645, 20);
g.dispose();
} |
eaa1c48d-d5de-40ad-9d70-54f68fce7799 | 4 | public static Rectangle stringToRectangle(String s, Rectangle defaultValue)
{
if (s == null) return defaultValue;
String[] sa = s.split(" +");
if (sa.length != 4) return defaultValue;
int[] ia = new int[4];
for (int i = 0; i < 4; i++)
try
{
ia[i] = Integer.parseInt(sa[i]);
}
catch (NumberFormatException e)
{
return defaultValue;
}
return new Rectangle(ia[0],ia[1],ia[2],ia[3]);
} |
ade5ab7f-71ca-4387-aeed-fe4c7d5f030a | 6 | public boolean equals( Object other ) {
if ( _set.equals( other ) ) {
return true; // comparing two trove sets
} else if ( other instanceof Set ) {
Set that = ( Set ) other;
if ( that.size() != _set.size() ) {
return false; // different sizes, no need to compare
} else { // now we have to do it the hard way
Iterator it = that.iterator();
for ( int i = that.size(); i-- > 0; ) {
Object val = it.next();
if ( val instanceof Byte ) {
byte v = ( ( Byte ) val ).byteValue();
if ( _set.contains( v ) ) {
// match, ok to continue
} else {
return false; // no match: we're done
}
} else {
return false; // different type in other set
}
}
return true; // all entries match
}
} else {
return false;
}
} |
67447bc7-5e1c-4ea3-999f-b51eed9ac79d | 9 | public static void init(){
if(initialized) {System.err.println("Init done"); return; }
//System.err.println("Doing init");
initialized=true;
t = get_t();
// Get OS if that is important
if(isWindows()){
_SYS = OS.WIN;
}else if(isMac()){
_SYS = OS.MAC;
}else if(isUnix()){
_SYS = OS.LIN;
}else{
_SYS = OS.ALT;
}
// Load main properites
Properties props = new Properties();
//try retrieve data from file
try {
props.load(new FileInputStream(propertiesBase));
mainDB = props.getProperty("mainDB");
_repository = props.getProperty("Repository");
if(_repository.contains("$CURRENTDIR$")){
_repository = _repository.replace("$CURRENTDIR$", _currentDir);
}
LoadFromRepo = Integer.parseInt(props.getProperty("loadFromRepo")) == 1 ? true : false;
RECOMPUTE_SCENARIOS = Integer.parseInt(props.getProperty("recomputeScenarios")) == 1 ? true : false;
StrategyDB = _repository + "\\" + props.getProperty("StrategyDB");
// LoadFromDB = Integer.parseInt(props.getProperty("loadFromDB")) == 1 ? true : false;
// StoreInDB = Integer.parseInt(props.getProperty("storeInDB")) == 1 ? true : false;
// LoadFromRepo = Integer.parseInt(props.getProperty("loadFromRepo")) == 1 ? true : false;
_JPPF_EXEC = Integer.parseInt(props.getProperty("useJPPF")) == 1 ? true : false;
}catch(Exception e){
e.printStackTrace();
logger.error("Fatal Error: Problem loading properties - init():" + e);
System.exit(1);
}
//System.err.println("_repository:" + _repository);
} |
7692c454-7a39-48a4-89ad-24ff3c76e32b | 2 | protected boolean ready() throws IOException {
if (reader == null) return false; // No reader? then we are not ready
if (nextLine != null) return true; // Next line is null? then we have to try to read a line (to see if one is available)
readLine();
return nextLine != null; // Line was read from the file? Then we are ready.
} |
2a24f56a-b84e-46aa-9644-2f0a70a6503c | 3 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Salesman other = (Salesman) obj;
if (!Objects.equals(this.salesman, other.salesman)) {
return false;
}
return true;
} |
c6bec9e4-0dd9-4767-bfc0-2b4a75381650 | 2 | @Override
public boolean canMove(Board board, Field currentField, Field emptyField) {
return validSetupForMove(currentField, emptyField) && currentField.inDiagonalPathWith(emptyField) && board.clearPathBetween(currentField, emptyField);
} |
60542d4b-3f73-4018-9efd-dce59d1bb148 | 5 | public static ArrayList<Planet> forPlanet(SimulatedPlanetWars simpw){
ArrayList<Planet> asw = new ArrayList<Planet>(2);
// Find the biggest fleet to attack with
int maxShips = 0;
for (Planet p : simpw.MyPlanets()){
if (p.NumShips() > maxShips){
maxShips = p.NumShips();
asw.add(0,p);
}
}
// Find the destination with best distance to be captured (distance help to be sure to capture the planet on neutral ones)
int maxDist = 0;
for (Planet p : simpw.NotMyPlanets()){
int dist = (int) Helper.distance(asw.get(0),p);
if (dist > maxDist && Helper.WillCapture(asw.get(0),p)) {
maxDist = dist;
asw.add(1,p);
}
}
return asw;
} |
06345d72-4a0e-496a-a016-bbd8149c49ee | 9 | static void checkMethodDesc(final String desc) {
if (desc == null || desc.length() == 0) {
throw new IllegalArgumentException(
"Invalid method descriptor (must not be null or empty)");
}
if (desc.charAt(0) != '(' || desc.length() < 3) {
throw new IllegalArgumentException("Invalid descriptor: " + desc);
}
int start = 1;
if (desc.charAt(start) != ')') {
do {
if (desc.charAt(start) == 'V') {
throw new IllegalArgumentException("Invalid descriptor: "
+ desc);
}
start = checkDesc(desc, start, false);
} while (start < desc.length() && desc.charAt(start) != ')');
}
start = checkDesc(desc, start + 1, true);
if (start != desc.length()) {
throw new IllegalArgumentException("Invalid descriptor: " + desc);
}
} |
d7a4e1a6-d8b4-4fa6-b1fe-dc7595dd79f7 | 2 | public CourseDatabaseManager() {
try {
Class.forName(driver);
conn = (Connection) DriverManager
.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
e415725f-c347-4233-a36e-fd49d9bfee23 | 6 | @Override
public int compare( Method a, Method b )
{
int c0 = a.getName().compareTo( b.getName() );
if (c0 != 0)
{
return c0;
}
Class<?>[] pa = a.getParameterTypes();
Class<?>[] pb = b.getParameterTypes();
int c1 = pa.length - pb.length;
if (c1 != 0)
{
return c1;
}
for (int i = 0; i < pa.length; i++)
{
String pac = pa[i].getCanonicalName();
String pbc = pb[i].getCanonicalName();
int c2 = pac.compareTo( pbc );
if (c2 != 0)
{
return c2;
}
}
return 0;
} |
f38c3e6f-4725-4079-8955-ec382382162b | 8 | private void drawSetupMode(Graphics2D g) {
switch (setupMode) {
case 1:
if(!numAIChosen){
drawString(g, "Number of AI: ", 30, 25, 645, Color.BLACK);
}else{
drawString(g, "Number of players: ", 30, 25, 645, Color.BLACK);
}
break;
case 2:
drawString(g, "Player " + (turn + 1), 40, 25, 625, Color.BLACK);
drawString(g, "Choose a colour", 30, 30, 645, Color.BLACK);
break;
case 3:
drawDice(g);
break;
case 4:
drawTurn(g);
drawClaimTerritories(g);
break;
case 5:
drawTurn(g);
drawDeploySetupTroops(g);
break;
case -1:
drawPlayersConnected(g);
break;
case -2:
drawString(g, "Waiting for the host to begin the game", 30, 30, 645, Color.BLACK);
break;
}
} |
8c9a443f-5d67-4ddf-8ad6-b1b8ed2b6baa | 1 | @Override
public void exception(String msg, Throwable t) {
StringBuilder message = new StringBuilder();
message.append("An exception occured in the garbage collector!").append("\r\n");
message.append("\t").append("reason: ").append(msg).append(".");
if (t != null)
log.log(Level.SEVERE, message.toString(), t);
else
log.log(Level.SEVERE, message.toString());
} |
bf0bf7db-2ace-4a44-8949-ee660b5fcc7c | 4 | public double teaTypeSplitInfo() {
double result = 0.0;
double blackTeaSize = 0.0;
double whiteTeaSize = 0.0;
double greenTeaSize = 0.0;
for (Tea t : trainingSet) {
if (t.getTeaType().equals(Tea.BLACK_TEA)) {
blackTeaSize++;
}
if (t.getTeaType().equals(Tea.GREEN_TEA)) {
whiteTeaSize++;
}
if (t.getTeaType().equals(Tea.WHITE_TEA)) {
greenTeaSize++;
}
}
result = (-1.0*blackTeaSize / (double)trainingSet.size()) * log2(blackTeaSize/(double)trainingSet.size());
result+= (-1.0*whiteTeaSize / (double)trainingSet.size()) * log2(whiteTeaSize/(double)trainingSet.size());
result+= (-1.0*greenTeaSize / (double)trainingSet.size()) * log2(greenTeaSize/(double)trainingSet.size());
return result;
} |
4b97b8ad-e5f6-4d80-ba44-60cc7a80fe1b | 3 | public Gezin(int gezinsNr, Persoon ouder1, Persoon ouder2) {
if (ouder1 == null) {
throw new RuntimeException("Eerste ouder mmag niet null zijn");
}
if (ouder1 == ouder2) {
throw new RuntimeException("ouders hetzelfde");
}
this.gezinsNr = gezinsNr++;
this.ouder1 = ouder1;
this.ouder2 = ouder2;
kinderen = new ArrayList<Persoon>();
ouder1.wordtOuderIn(this);
if (ouder2 != null) {
ouder2.wordtOuderIn(this);
}
} |
68171b49-5d6e-47e5-a7a1-8b723fbe2fe8 | 9 | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Thai thai = (Thai) o;
if (age != thai.age) return false;
if (dumb != thai.dumb) return false;
if (name != null ? !name.equals(thai.name) : thai.name != null) return false;
if (town != null ? !town.equals(thai.town) : thai.town != null) return false;
return true;
} |
c7f4b734-d9b3-4370-9cb7-2bf97fda15a0 | 0 | public String getAssignee() {
return assignee;
} |
5e2b9efd-493f-466b-9f48-7fe936b8b6b9 | 5 | private static Move BackwardLeftCaptureForBlack(int r, int c, Board board){
Move backwardLeftCapture = null;
if(r<Board.rows-2 && c<Board.cols-2 && (
board.cell[r+1][c+1].equals(CellEntry.white)
|| board.cell[r+1][c+1].equals(CellEntry.whiteKing)
)
&& board.cell[r+2][c+2].equals(CellEntry.empty)
)
{
backwardLeftCapture = new Move(r,c,r+2,c+2);
//System.out.println("Backward Left Capture for Black");
}
return backwardLeftCapture;
} |
a8f69de2-bc3d-4f4b-a8df-d24f898c83b8 | 9 | public void setAction(final Action newAction)
{
final Action oldAction = getAction();
if (oldAction != null)
{
removeActionListener(oldAction);
oldAction.removePropertyChangeListener(getPropertyChangeHandler());
final Object o = oldAction.getValue(ActionDowngrade.ACCELERATOR_KEY);
if (o instanceof KeyStroke && o != null)
{
final KeyStroke k = (KeyStroke) o;
unregisterKeyboardAction(k);
}
}
this.action = newAction;
if (this.action != null)
{
addActionListener(newAction);
newAction.addPropertyChangeListener(getPropertyChangeHandler());
setText((String) (newAction.getValue(Action.NAME)));
setToolTipText((String) (newAction.getValue(Action.SHORT_DESCRIPTION)));
setIcon((Icon) newAction.getValue(Action.SMALL_ICON));
setEnabled(this.action.isEnabled());
Object o = newAction.getValue(ActionDowngrade.MNEMONIC_KEY);
if (o != null)
{
if (o instanceof Character)
{
final Character c = (Character) o;
setMnemonic(c.charValue());
}
else if (o instanceof Integer)
{
final Integer c = (Integer) o;
setMnemonic(c.intValue());
}
}
o = newAction.getValue(ActionDowngrade.ACCELERATOR_KEY);
if (o instanceof KeyStroke && o != null)
{
final KeyStroke k = (KeyStroke) o;
registerKeyboardAction(newAction, k, WHEN_IN_FOCUSED_WINDOW);
}
}
} |
1eb669ae-c9f4-41f4-8578-7985c9d313bd | 7 | public void listen() {
SSLSocket s = null;
SSLServerSocket serverSocket = null;
try {
System.out.println(DropboxConstants.SERVER_PORT);
//serverSocket = new ServerSocket(DropboxConstants.SERVER_PORT);
serverSocket = (SSLServerSocket)this.sslserversocketfactory.createServerSocket(DropboxConstants.SERVER_PORT);
while(true) {
try {
s = (SSLSocket) serverSocket.accept();
String ip = s.getInetAddress().getHostAddress();
if(!this.clientkeys.containsKey(ip)) {
System.out.println("A new client comes in, pick up keys for him");
Keys keys = this.clientKeyQueue.poll();
this.clientkeys.put(ip, keys);
}
PublicKey pubKey = this.clientkeys.get(ip).keyPair.getPublic();
SecretKey encryptionKey = this.clientkeys.get(ip).secretKey;
SynchronizationService service = new SynchronizationService(s, pubKey, encryptionKey);
threadService.submit(service);
}
catch(Exception ex) {
System.out.println("Socket Error or File Processing Error!");
Logger.getLogger(DropboxServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
catch(IOException ex) {
System.out.println("DropboxConstants.SERVER_PORT has already in use");
Logger.getLogger(DropboxServer.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
try {
if(serverSocket != null)
serverSocket.close();
if(s != null)
s.close();
} catch (IOException ex) {
Logger.getLogger(DropboxServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
} |
43990349-23f8-41c1-961c-15e2b744f2e1 | 3 | public boolean verificationComptabilite(String cheminAccesATester){
boolean aRetourner = false;
try{
Image img = ImageIO.read(new File(cheminAccesATester));
BufferedImage envTest = (BufferedImage)img;
int nbrPixel = envTest.getHeight()*envTest.getWidth();
if( (nbrPixel/3) >= GestionFichier.fichierEnFlux(this.lettre.getLettre()).length+tailleTotalReserver ){
String[] tmpString = cheminAccesATester.split("\\.");
if (tmpString.length ==2 ){
aRetourner = true;
}else{
System.out.println("le nom de l'enveloppe doit contenir l'extension pr�c�der d'un points");
}
}else{
System.out.print("la lettre est trop grande par rapport a l'enveloppe");
}
}catch(Exception e){
System.out.println("l'enveloppe d�signer n'est pas une image ou la lettre n'existe pas");
System.out.println(e);
}
return aRetourner;
} |
91a38220-0585-4f63-81c8-22b5c0418c15 | 6 | @Override
public XValue invoke(XRuntime runtime, XExec exec, int id, XValue thiz, XValue[] params, List<XValue> list, Map<String, XValue> map) {
switch (id) {
case 0:
return thiz;
case 1:
return add(runtime, thiz, params[0]);
case 2:
return indexOf(runtime, thiz, params[0]);
case 3:
return substring(runtime, thiz, params[0], params[1]);
case 4:
return length(runtime, thiz);
case 5:
return charAt(runtime, thiz, params[0]);
default:
break;
}
return super.invoke(runtime, exec, id, thiz, params, list, map);
} |
148e29f7-30c7-4741-8c70-5c8a27307040 | 0 | @Override
public void openFrame(JInternalFrame f) {
//System.out.println("openFrame");
super.openFrame(f);
updateDesktopSize(false);
} |
b41706c9-a5ea-47f9-a9d0-0ce707b56d00 | 5 | @Override
public int hashCode() {
int result = id;
result = 31 * result + (begdate != null ? begdate.hashCode() : 0);
result = 31 * result + (begtime != null ? begtime.hashCode() : 0);
result = 31 * result + (enddate != null ? enddate.hashCode() : 0);
result = 31 * result + (endtime != null ? endtime.hashCode() : 0);
result = 31 * result + (status != null ? status.hashCode() : 0);
return result;
} |
98a624ee-96d7-4a06-b3bd-81c462f4a475 | 1 | public String getAttributeEnumeration(String name, String aname)
{
Object attribute[] = getAttribute(name, aname);
if (attribute == null) {
return null;
} else {
return (String) attribute[3];
}
} |
e6d2ca87-26c9-452f-840b-bd4c0ab61f73 | 0 | @Override
public String adiciona(HttpServletRequest request,
HttpServletResponse response) {
HttpSession session = request.getSession();
session.removeAttribute("usuarioLogado");
return "/WEB-INF/paginas/logout.html";
} |
ef687f73-b198-4b62-8997-c33e0f40a2e1 | 3 | @EventHandler(priority = EventPriority.MONITOR)
public void onPlayerChat(PlayerChatEvent e)
{
IrcClient client = Parent.Manager.getCurrentClient();
for(String s : client.getMcEcho_ActiveChannels())
{
try{ client.PrivMsg(s, IrcColor.formatMCMessage(ChatManagerUtils.ParseMessage(e.getPlayer(), e.getMessage())), false); }
catch(NoClassDefFoundError ex){ ex.printStackTrace(); }
catch(Exception ex){ }
}
} |
8cd8a721-21c4-44f5-b865-47d55bffd7b0 | 4 | private static void editInfo() {
MainMenuUI mainMenu = new MainMenuUI();
int option = mainMenu.editInformation();
switch (option) {
case 1:
editProduct();
break;
case 2:
editCategory();
break;
case 3:
editUser();
break;
case 0:
break;
default:
mainMenu.showOptionNotValid();
}
} |
41dae649-51ab-449c-a443-b34e436e45d7 | 2 | private void convertFrequencies() {
for (Entry<Double, Long> ent : frequencies.entrySet()) {
if (freq_s.containsKey(ent.getValue())) {
freq_s.put(ent.getValue(), freq_s.get(ent.getValue())+ent.getKey());
}else{
freq_s.put(ent.getValue(),ent.getKey());
}
}
} |
9ea3c1cb-7b78-4f15-b467-238e2082cd88 | 0 | public static void main(String[] args)
{
System.out.println(HanziToPinYinHead.getFirstLetter("I love u"));
System.out.println(HanziToPinYinHead.getFirstLetter("我爱北京天安门 匡乔顺龙万友谊栾"));
System.out.println(HanziToPinYinHead.getFirstLetter("I love 北京天安门"));
} |
fc0518d0-1a42-43e0-a9b9-fb74f1314385 | 1 | public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int tests = sc.nextInt();
String[] input = new String[tests];
for(int i = 0 ;i<tests;i++){
input[i] = sc.next();
}
solve(input);
sc.close();
} |
8ffd091d-d811-4112-b97c-cf004b622985 | 8 | public static String getTipoVariavel (String ip, String comunidade, String objeto) throws IOException, NoSuchObjectException, NoSuchInstanceException {
// Inicia sessaso SNMP
TransportMapping transport = new DefaultUdpTransportMapping();
Snmp snmp = new Snmp(transport);
transport.listen();
// Configura o endereco
Address endereco = new UdpAddress(ip + "/" + porta);
// Configura target
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(comunidade));
target.setAddress(endereco);
target.setRetries(2);
target.setTimeout(1500);
target.setVersion(SnmpConstants.version2c);
// Cria PDU (SNMP Protocol Data Unit)
PDU pdu = new PDU();
pdu.add(new VariableBinding(new OID(objeto)));
pdu.setType(PDU.GET);
// Envia PDU
ResponseEvent responseEvent = snmp.send(pdu, target);
if(responseEvent != null) {
// Extrai a resposta PDU (pode ser null se ocorreu timeout)
PDU responsePDU = responseEvent.getResponse();
if(responsePDU != null) {
int errorStatus = responsePDU.getErrorStatus();
int errorIndex = responsePDU.getErrorIndex();
String errorStatusText = responsePDU.getErrorStatusText();
if (errorStatus == PDU.noError) {
Vector <VariableBinding> tmpv = (Vector <VariableBinding>) responsePDU.getVariableBindings();
if(tmpv != null) {
for(int k=0; k <tmpv.size();k++) {
VariableBinding vb = (VariableBinding) tmpv.get(k);
if (vb.isException()) {
String errorString = vb.getVariable().getSyntaxString();
System.out.println("Error:"+errorString);
if(errorString.equals("NoSuchObject"))
throw new NoSuchObjectException("No Such Object: " + objeto);
if(errorString.equals("NoSuchInstance"))
throw new NoSuchInstanceException("No Such Instance: " + objeto);
}
else {
Variable var = vb.getVariable();
OctetString oct = new OctetString(var.toString());
String sVar = oct.toString();
snmp.close();
return vb.getVariable().getSyntaxString();
}
}
}
}
else {
System.out.println("Erro: GET Request Falhou");
System.out.println("Status do Erro = " + errorStatus);
System.out.println("Index do Erro = " + errorIndex);
System.out.println(errorStatusText);
}
}
else {
System.out.println("Resultado vazio");
throw new NullPointerException("Null Response");
}
}
else {
throw new RuntimeException("GET Request Timed Out");
}
return "";
} |
52cbd7db-eee3-4ede-aedd-539da15c1deb | 1 | public static void main(String[] args) {
int arr2[]={1,11,111,2,334,45454,56,56,45};
quick n1=new quick();
n1.sort(arr2);
for(int i=0;i<arr2.length;i++)
{
System.out.println(arr2[i]);
}
} |
5de64d70-00b3-4d62-aa90-6f19210c2544 | 5 | @Override
public void rotate(int angle) {
Tile[][] trans;
int xtrans = 0, ytrans = 0;
switch (angle) {
case ROTATE_90:
trans = new Tile[bounds.width][bounds.height];
xtrans = bounds.height - 1;
break;
case ROTATE_180:
trans = new Tile[bounds.height][bounds.width];
xtrans = bounds.width - 1;
ytrans = bounds.height - 1;
break;
case ROTATE_270:
trans = new Tile[bounds.width][bounds.height];
ytrans = bounds.width - 1;
break;
default:
System.out.println("Unsupported rotation (" + angle + ")");
return;
}
double ra = Math.toRadians(angle);
int cos_angle = (int)Math.round(Math.cos(ra));
int sin_angle = (int)Math.round(Math.sin(ra));
for (int y = 0; y < bounds.height; y++) {
for (int x = 0; x < bounds.width; x++) {
int xrot = x * cos_angle - y * sin_angle;
int yrot = x * sin_angle + y * cos_angle;
trans[yrot + ytrans][xrot + xtrans] = getTileAt(x+bounds.x, y+bounds.y);
}
}
bounds.width = trans[0].length;
bounds.height = trans.length;
map = trans;
} |
e4e34bdd-9256-4e1d-81f8-82ef5672c82e | 0 | public boolean isLive() {
return isLive;
} |
b1b31c23-d18c-42b1-a2a2-eefde3cadf28 | 8 | public String genStream(linkedList add)
{
//Generate the key
String myStream;
myStream = glbKey;
char temp = 0;
//Generate type character
if (blIsBase)
temp = (char) (temp|2);
//Generate server active bit
if(canServer)
temp = (char) (temp|4);
//Generate the willing to connect bit
if(add!= null)
{
if(coolDownConnect>10)
if(canConnection(add))
{
temp = (char) (temp|16);
//System.out.println("Trying my damndest!");
}
else if(iNetProt != null)
{
//System.out.println("Failure");
if ((add.getAddress().toString()).equals(iNetProt.getPartnerIP().toString()))
temp = (char) (temp|16);
}
//else
//System.out.println("Failure");
}
myStream = myStream+temp;
//Generate IP Address
myStream = myStream+getMyParsedIP().toString();
//Generate Name
if(!myName.equals("null"))
myStream = myStream + ":" + myName;
return myStream;
} |
112fa0da-295e-4bf1-bdc7-90644f50cf3e | 3 | public void start()
{
mRunning = mGenerate = true;
while (mRunning)
{
while (mGenerate)
generate();
render();
mViewer.repaint();
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
mViewer.stopWindow();
} |
4193e47f-4cfa-4c20-ac43-87617ac14a3c | 6 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
InternalStorage other = (InternalStorage) obj;
if (capacity != other.capacity)
return false;
if (dataTransferRate != other.dataTransferRate)
return false;
if (type != other.type)
return false;
return true;
} |
199cd03e-ec18-4dd6-a7d1-651d4044fbe7 | 9 | public static int getWidth(String s)
{
int curLine = 0;
int maxLine = 0;
char[] chars = s.toLowerCase().toCharArray();
for(char c : chars)
{
if(c == 'i' || c == 'l' || c == 't' || c == 'v')
{
curLine += 7;
}
else if(c == '.' || c == ',')
{
curLine += 2;
}
else if(c == '\n')
{
if(curLine > maxLine)
{
maxLine = curLine;
}
curLine = 0;
}
else
{
curLine += 8;
}
}
return maxLine;
} |
5b27cefb-b296-4d60-8e6b-7734e6642416 | 3 | public WeaponPanel(String name) {
setSize(new Dimension(585, 300));
setLayout(null);
try {
this.sprite = new EditSprite(System.getProperty("resources") + "/sprites/" + name + ".png");
maxDir = this.sprite.getMaxDir();
maxFrame = this.sprite.getMaxFrame();
} catch(Exception e) {
sprite = null;
}
panel = new JPanel();
panel.setBounds(0, 0, 585, 300);
add(panel);
panel.setLayout(null);
scrollPane = new JScrollPane();
scrollPane.setBounds(12, 13, 325, 245);
panel.add(scrollPane);
spritePanel = new SpritePanel();
spritePanel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
rectToDraw.setFrame(e.getX(), e.getY(), rectToDraw.width, rectToDraw.height);
}
@Override
public void mouseReleased(MouseEvent e) {
rectToDraw.setFrameFromDiagonal(rectToDraw.x, rectToDraw.y, e.getX(), e.getY());
hitboxes[frameComboBox.getSelectedIndex()] = new Rectangle(rectToDraw.x - ((frameComboBox.getSelectedIndex() % maxFrame) * sprite.getSprite().getWidth() / maxFrame),
rectToDraw.y - ((frameComboBox.getSelectedIndex() / maxDir) * sprite.getSprite().getHeight() / maxDir), rectToDraw.width, rectToDraw.height);
spritePanel.repaint();
}
});
spritePanel.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
rectToDraw.setFrameFromDiagonal(rectToDraw.x, rectToDraw.y, e.getX(), e.getY());
spritePanel.repaint();
}
});
spritePanel.setPreferredSize(new Dimension(322, 242));
scrollPane.setViewportView(spritePanel);
JLabel label = new JLabel("Swing Time");
label.setBounds(366, 16, 62, 16);
panel.add(label);
totalText = new JTextField();
totalText.setEditable(false);
totalText.setBounds(440, 13, 116, 22);
panel.add(totalText);
totalText.setColumns(10);
timeComboBox = new JComboBox<String>();
timeComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
timeSpinner.setValue(swingTimes[timeComboBox.getSelectedIndex()]);
}
});
timeComboBox.setModel(buildSwingBox());
timeComboBox.setBounds(366, 45, 103, 22);
panel.add(timeComboBox);
timeSpinner = new JSpinner();
timeSpinner.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
swingTimes[timeComboBox.getSelectedIndex()] = (Float) timeSpinner.getValue();
float total = 0;
for(int x = 0; x<swingTimes.length; x++) {
total += swingTimes[x];
}
totalText.setText(total + " seconds");
}
});
timeSpinner.setBounds(481, 47, 75, 20);
panel.add(timeSpinner);
timeSpinner.setModel(new SpinnerNumberModel(new Float(0), new Float(0), null, new Float(1)));
if(swingTimes.length > 0)
timeSpinner.setValue(swingTimes[0]);
JSeparator separator = new JSeparator();
separator.setBounds(366, 80, 207, 1);
panel.add(separator);
JLabel label_1 = new JLabel("Frame Box");
label_1.setBounds(366, 94, 55, 16);
panel.add(label_1);
frameComboBox = new JComboBox<String>();
frameComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rectToDraw.setFrame(hitboxes[frameComboBox.getSelectedIndex()].x + ((frameComboBox.getSelectedIndex() % maxFrame) * sprite.getSprite().getWidth() / maxFrame),
hitboxes[frameComboBox.getSelectedIndex()].y + ((frameComboBox.getSelectedIndex() / maxDir) * sprite.getSprite().getHeight() / maxDir),
hitboxes[frameComboBox.getSelectedIndex()].width, hitboxes[frameComboBox.getSelectedIndex()].height);
spritePanel.repaint();
}
});
frameComboBox.setModel(buildFrameBox());
frameComboBox.setBounds(366, 123, 103, 22);
panel.add(frameComboBox);
} |
f7350cf8-db00-4faa-b038-e3e1f405d4d0 | 8 | public static void update(String eDatabase, String table,String column, String VALUES, String where){
Connection gCon = null; // general connection to MYSQL
Connection eCon = null; // connection to database
Statement eStatement = null; // statements for the eDatabase
try{
// Register JDBC driver
Class.forName(DBConfig.driver);
// Connect and initialize statements for General MYSQL and eDatabase
System.out.println("Connecting to MYSQL...");
gCon = DriverManager.getConnection(DBConfig.url, DBConfig.user, DBConfig.password);
eCon = DriverManager.getConnection(DBConfig.url + eDatabase, DBConfig.user, DBConfig.password);
eStatement = eCon.createStatement();
if (!DatabaseProcess.checkDBExists(gCon,eDatabase)) {
Exception e = new Exception("Requested database "+eDatabase+" doesn't exist");
throw(e);
}
System.out.println("UPDATE "+table + " SET "+column +" = " +VALUES+" " +"WHERE " + where +";");
eStatement.executeUpdate("UPDATE "+table+" set "+column+" = "+VALUES+" WHERE "+where+" ; ");
// Handle possible errors
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if((eStatement!=null)) {
eStatement.close();
}
}catch(SQLException se2){
}// nothing we can do
try{
if(eCon !=null || gCon != null ) {
eCon.close();
gCon.close();
}
}
catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
} |
555e01f9-cf57-423d-8937-c17df45d47e0 | 8 | @Override
public void handleGridEvent(GridEvent e) {
if(e.getSource().equals(builder)) {
if(admode.equals(AddDelMode.Add)){
if(mode.equals(EditorMode.Background)) {
builder.setBackgroundAtSelector(splitter.getSelectorPoint());
} else if(mode.equals(EditorMode.Object)) {
builder.setObjectAtSelector(splitter.getSelectorPoint());
}
}else if(admode.equals(AddDelMode.Del)){
if(mode.equals(EditorMode.Background)) {
builder.delBackgroundAtSelector();
} else if(mode.equals(EditorMode.Object)) {
builder.delObjectAtSelector();
}
}
} else if(e.getSource().equals(splitter)) {
}
} |
5a765209-14b9-42f8-a2bb-5ca7b01d4b9b | 0 | public DatagramPacket GetPacket()
{
return dPacket;
} |
cee01959-30fe-4644-8824-f84eabd13b00 | 9 | static int process(String line) {
String[] splts = line.trim().split(" ");
int n = Integer.parseInt(splts[0]), m = Integer.parseInt(splts[1]);
long c = Long.parseLong(splts[2]);
if(n == 0 && m == 0 && c == 0)
return 0;
long[] cons = new long[n];
boolean[] state = new boolean[n];
long p = 0;
for(int i = 0; i < n; i++) {
cons[i] = Long.parseLong(readLine().trim());
}
long max = 0;
boolean f = false;
for(int i = 0; i < m; i++) {
int dev = Integer.parseInt(readLine().trim()) - 1;
if(f)
continue;
if(state[dev]) {
p -= cons[dev];
}
else {
p += cons[dev];
}
max = Math.max(max, p);
if(p > c)
f = true;
state[dev] = !state[dev];
}
System.out.println("Sequence "+(++ind));
if(p > c) {
System.out.println("Fuse was blown.");
}
else {
System.out.println("Fuse was not blown.");
System.out.println("Maximal power consumption was "+max+" amperes.");
}
System.out.println();
return 1;
} |
21e00c5d-b0d4-4a5c-aa3b-30627a4d9f21 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ClaveDeReferenciable other = (ClaveDeReferenciable) obj;
if (end == null) {
if (other.end != null)
return false;
} else if (!end.equals(other.end))
return false;
if (start == null) {
if (other.start != null)
return false;
} else if (!start.equals(other.start))
return false;
return true;
} |
31fdad45-970f-450d-ae43-5f7f9a7a1bc0 | 8 | public static int createTexturedDisplayList(Model m) {
int displayList = glGenLists(1);
glNewList(displayList, GL_COMPILE);
{
glBegin(GL_TRIANGLES);
for (Model.Face face : m.getFaces()) {
if (face.hasTextureCoordinates()) {
glMaterial(GL_FRONT, GL_DIFFUSE, BufferTools.asFlippedFloatBuffer(face.getMaterial()
.diffuseColour[0], face.getMaterial().diffuseColour[1],
face.getMaterial().diffuseColour[2], 1));
glMaterial(GL_FRONT, GL_AMBIENT, BufferTools.asFlippedFloatBuffer(face.getMaterial()
.ambientColour[0], face.getMaterial().ambientColour[1],
face.getMaterial().ambientColour[2], 1));
glMaterialf(GL_FRONT, GL_SHININESS, face.getMaterial().specularCoefficient);
}
if (face.hasNormals()) {
Vector3f n1 = m.getNormals().get(face.getNormalIndices()[0] - 1);
glNormal3f(n1.x, n1.y, n1.z);
}
if (face.hasTextureCoordinates()) {
Vector2f t1 = m.getTextureCoordinates().get(face.getTextureCoordinateIndices()[0] - 1);
glTexCoord2f(t1.x, t1.y);
}
Vector3f v1 = m.getVertices().get(face.getVertexIndices()[0] - 1);
glVertex3f(v1.x, v1.y, v1.z);
if (face.hasNormals()) {
Vector3f n2 = m.getNormals().get(face.getNormalIndices()[1] - 1);
glNormal3f(n2.x, n2.y, n2.z);
}
if (face.hasTextureCoordinates()) {
Vector2f t2 = m.getTextureCoordinates().get(face.getTextureCoordinateIndices()[1] - 1);
glTexCoord2f(t2.x, t2.y);
}
Vector3f v2 = m.getVertices().get(face.getVertexIndices()[1] - 1);
glVertex3f(v2.x, v2.y, v2.z);
if (face.hasNormals()) {
Vector3f n3 = m.getNormals().get(face.getNormalIndices()[2] - 1);
glNormal3f(n3.x, n3.y, n3.z);
}
if (face.hasTextureCoordinates()) {
Vector2f t3 = m.getTextureCoordinates().get(face.getTextureCoordinateIndices()[2] - 1);
glTexCoord2f(t3.x, t3.y);
}
Vector3f v3 = m.getVertices().get(face.getVertexIndices()[2] - 1);
glVertex3f(v3.x, v3.y, v3.z);
}
glEnd();
}
glEndList();
return displayList;
} |
d3cbca5e-a8aa-4f41-b152-0b372e6d90cd | 4 | public static void moveRightText(OutlinerCellRendererImpl textArea, JoeTree tree, OutlineLayoutManager layout) {
Node currentNode = textArea.node;
if (textArea.getCaretPosition() == textArea.getText().length()) {
// Get Next Node
Node nextNode = tree.getNextNode(currentNode);
if (nextNode == null) {
tree.setCursorPosition(tree.getCursorPosition()); // Makes sure we reset the mark
return;
}
// Update Preferred Caret Position
tree.getDocument().setPreferredCaretPosition(0);
// Record the EditingNode and CursorPosition
tree.setEditingNode(nextNode);
tree.setCursorPosition(0);
// Clear Text Selection
textArea.setCaretPosition(0);
textArea.moveCaretPosition(0);
// Redraw and Set Focus
if (nextNode.isVisible()) {
layout.setFocus(nextNode,OutlineLayoutManager.TEXT);
} else {
layout.draw(nextNode,OutlineLayoutManager.TEXT);
}
} else {
// Update Preferred Caret Position
tree.getDocument().setPreferredCaretPosition(textArea.getCaretPosition() + 1);
// Record the CursorPosition only since the EditingNode should not have changed
int newCaretPosition = textArea.getCaretPosition() + 1;
textArea.setCaretPosition(newCaretPosition);
textArea.moveCaretPosition(newCaretPosition);
tree.setCursorPosition(newCaretPosition);
// Redraw and Set Focus if this node is currently offscreen
if (!currentNode.isVisible()) {
layout.draw(currentNode,OutlineLayoutManager.TEXT);
}
}
// Freeze Undo Editing
UndoableEdit.freezeUndoEdit(currentNode);
} |
7a64297d-62d5-4769-b966-51edf5fa474f | 0 | @Before
public void setUp() throws Exception
{
// set up the Players with predefined behaviour.
_paperPlayer = new Player("Paperman");
_paperPlayer.setDrawOutput(Output.Paper);
_rockPlayer = new Player("Rocker");
_rockPlayer.setDrawOutput(Output.Rock);
_scissorPlayer = new Player("Cutter");
_scissorPlayer.setDrawOutput(Output.Scissors);
} |
0b60f7ad-43ac-43d9-8e69-dea931fb3713 | 0 | @XmlElementDecl(namespace = "http://www.w3.org/2000/09/xmldsig#", name = "SPKISexp", scope = SPKIDataType.class)
public JAXBElement<byte[]> createSPKIDataTypeSPKISexp(byte[] value) {
return new JAXBElement<byte[]>(_SPKIDataTypeSPKISexp_QNAME, byte[].class, SPKIDataType.class, ((byte[]) value));
} |
5658e4d1-8a0d-44f9-8a06-75479f1bab1a | 6 | private void checkPermissions() {
String name = player.getStatus();
if (name.equals("Create")) {
permitGoverning(false);
permitNationName(false);
permitTravel(false);
permitPropose(false);
permitCoup(false);
permitNewGov(false);
permitJoin(false);
permitVoteTaxes(false);
permitElection(false);
}
if (name.equals("Nomad")) {
permitGoverning(false);
permitPropose(true);
permitCoup(false);
permitTravel(true);
if (player.isOn().getNation() != null) {
permitJoin(true);
updateCitizen(false);
}
}else if (name.equals("Citizen")) {
permitGoverning(false);
permitPropose(false);
permitNationName(true);
permitTravel(true);
updateCitizen(false);
//UPDATE TO DISALLOW COUP IF IN DEMO, ALLOW COUP IF IN DICT *******
}else if (name.equals("President")) {
permitTravel(true);
permitGoverning(true);
permitPropose(false);
permitCoup(false);
permitNationName(true);
updateCitizen(false);
}else if (name.equals("Dictator")) {
permitTravel(true);
permitGoverning(true);
permitPropose(false);
permitCoup(false);
permitNationName(true);
updateCitizen(false);
}
} |
f8e30e21-8d81-4a2a-81be-cd52a11e4180 | 7 | public void paint(Graphics2D g) {
g.setColor(foregroundColor);
g.setFont(xLabelFont);
if (recalculateBounds) {
initializeBounds(g);
}
// if (allowMouseDragSelection && mouseIsBeingDragged) {
// int xStart = round(mouseDragStart.x*xFactor);
// int xEnd = round(mouseDragEnd.x*xFactor);
// int rectL = Math.min(xStart, xEnd);
// int wid = Math.abs(xStart-xEnd);
// g.setColor(selectionRegionColor);
// g.fillRect(rectL, round(graphAreaTop), wid, round(graphAreaHeight));
// g.setColor(Color.GRAY);
// g.drawRect(rectL, round(graphAreaTop), wid, round(graphAreaHeight));
// }
if (allowMouseDragSelection && isRangeSelected && leftMarkerPos != rightMarkerPos) {
g.setColor(selectionRegionColor);
g.fillRect(leftMarkerPos, round(graphAreaTop), rightMarkerPos-leftMarkerPos, round(graphAreaHeight));
g.setColor(Color.gray);
g.drawLine(leftMarkerPos, round(graphAreaTop), leftMarkerPos, round(graphAreaTop+graphAreaHeight));
g.drawLine(rightMarkerPos, round(graphAreaTop), rightMarkerPos, round(graphAreaTop+graphAreaHeight));
double dataRX = figureXtoDataX(rightMarkerPos);
String drxStr = StringUtilities.format(dataRX);
double dataLX = figureXtoDataX(leftMarkerPos);
String dlxStr = StringUtilities.format(dataLX);
g.setColor(Color.gray);
g.setFont(mouseDragNumberFont);
g.drawString(drxStr, rightMarkerPos, round(graphAreaTop+graphAreaHeight+10));
g.drawString(dlxStr, leftMarkerPos-g.getFontMetrics().stringWidth(dlxStr), round(graphAreaTop+graphAreaHeight+10));
}
if (drawMousePosTick) {
g.setColor(Color.LIGHT_GRAY);
g.setStroke(normalStroke);
//System.out.println("Drawing mouse pos. tick 1");
g.drawLine(round(graphAreaLeft-yTickWidth*xFactor), mousePos.y, round(graphAreaLeft), mousePos.y);
//System.out.println("Drawing mouse pos. tick 2");
g.drawLine(mousePos.x, round(xAxisPos), mousePos.x, Math.max(round(xAxisPos+2),round(xAxisPos+xTickWidth*yFactor)));
}
if (isYSelected) {
g.setStroke(highlightStroke);
g.setColor(highlightColor);
paintYAxis(g);
}
g.setStroke(normalStroke);
g.setColor(Color.black);
paintYAxis(g);
if (isXSelected) {
g.setStroke(highlightStroke);
g.setColor(highlightColor);
paintXAxis(g);
}
g.setStroke(normalStroke);
g.setColor(Color.black);
paintXAxis(g);
} |
5682893b-961b-4c64-bbb4-ce735dfc3a0e | 9 | public void warn(Event event) {
switch (event.getTypeEvent()) {
case BUMP:
if (state == State.START)
state = State.PLUCK_BUMPED;
else
ignore();
break;
case USECLAWS_END:
if (state == State.PLUCK_BUMPED)
state = State.PLUCK_CAUGHT;
else
ignore();
break;
case ROTATE_END:
if (state == State.PLUCK_CAUGHT)
state = State.ROBOT_ROTATED;
else
ignore();
break;
case GOFORWARD_END:
// ne devrais jamais se produire
ignore();
break;
case CHILDBEHAVIOR_END:
if (state == State.ROBOT_ROTATED)
state = State.PLUCK_SCORED;
else
ignore();
break;
default:
ignore();
break;
}
} |
439d0ac5-9752-4e4d-ad92-e99d8122e5bf | 6 | @Override
public Sentence doProcess(Sentence st) {
String prevTag = null;
boolean changed = false;
Eojeol[] eojeolSet = st.getEojeols();
for (int i = 0; i < eojeolSet.length; i++) {
String[] tags = eojeolSet[i].getTags();
prevTag = "";
changed = false;
for (int j = 0; j < tags.length; j++) {
tags[j] = TagMapper.getKaistTagOnLevel(tags[j], TAG_LEVEL);
if (tags[j].equals(prevTag)) {
changed = true;
}
prevTag = tags[j];
}
if (changed) {
tagList.clear();
morphemeList.clear();
String[] morphemes = eojeolSet[i].getMorphemes();
for (int j = 0; j < tags.length - 1; j++) {
if (tags[j].equals(tags[j+1])) {
morphemes[j+1] = morphemes[j] + morphemes[j+1];
} else {
tagList.add(tags[j]);
morphemeList.add(morphemes[j]);
}
}
tagList.add(tags[tags.length - 1]);
morphemeList.add(morphemes[morphemes.length - 1]);
eojeolSet[i] = new Eojeol(morphemeList.toArray(new String[0]), tagList.toArray(new String[0]));
}
}
st.setEojeols(eojeolSet);
return st;
} |
124d317e-08b6-4e19-bbf4-31b2953ee8e9 | 8 | private double get_w_value(int idx, int label_idx) {
if (idx < 0 || idx > nr_feature) {
return 0;
}
if (solverType.isSupportVectorRegression()) {
return w[idx];
} else {
if (label_idx < 0 || label_idx >= nr_class) {
return 0;
}
if (nr_class == 2 && solverType != SolverType.MCSVM_CS) {
if (label_idx == 0) {
return w[idx];
} else {
return -w[idx];
}
} else {
return w[idx * nr_class + label_idx];
}
}
} |
6620a822-64f2-475f-beb4-9ba88bf82d5a | 6 | public static Creature parseFile(File f){
Creature result = null;
try {
Scanner sc = new Scanner(f);
String name = sc.nextLine();
int level = Integer.parseInt(sc.nextLine());
int initiative = Integer.parseInt(sc.nextLine());
int speed = Integer.parseInt(sc.nextLine());
String[] abbs = sc.nextLine().split(" ");
int[] abbInts = new int[6];
for(int i = 0; i < 6; i++){
abbInts[i] = Integer.parseInt(abbs[i]);
}
String[] mods = sc.nextLine().split(" ");
int[] modsInts = new int[6];
for(int i = 0; i < 6; i++){
modsInts[i] = Integer.parseInt(mods[i]);
}
String[] defs = sc.nextLine().split(" ");
int[] defsInts = new int[4];
for(int i = 0; i < 4; i++){
defsInts[i] = Integer.parseInt(defs[i]);
}
int hp = Integer.parseInt(sc.nextLine());
List<Weapon> weapons = new ArrayList<>();
while(sc.hasNextLine()){
String wname = sc.nextLine();
Weapon w = WeaponParser.weaponMap.get(wname);
if(w != null){
weapons.add(w);
}
}
StandardCreature creature = new StandardCreature(name, level, abbInts, modsInts, defsInts, hp, weapons, initiative, speed);
result = creature;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
} |
85309848-1dd6-4836-9233-30c3097a9a8d | 3 | public static String formatTime(long time) {
time /= 1000;
String seconds = Long.toString(time % 60) + "s";
if (time < 60) {
return seconds;
}
String minutes = Long.toString((time % 3600) / 60) + "m ";
if (time < 3600) {
return minutes + seconds;
}
String hours = Long.toString((time % 86400) / 3600) + "h ";
if (time < 86400) {
return hours + minutes + seconds;
}
String days = Long.toString(time / 86400) + "d ";
return days + hours + minutes + seconds;
} |
7de61799-3673-406e-a0b2-c486ecb4fb46 | 7 | public static void insertPrimitiveSuper(Surrogate newsuper, List supers) {
{ boolean foundP000 = false;
{ Surrogate sup = null;
Cons iter000 = supers.theConsList;
loop000 : for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
sup = ((Surrogate)(iter000.value));
if (Surrogate.subtypeOfP(newsuper, sup)) {
foundP000 = true;
break loop000;
}
}
}
if (!(foundP000)) {
{ Surrogate subsumedsuper = null;
loop001 : for (;;) {
{
{ Surrogate value000 = null;
{ Surrogate sup = null;
Cons iter001 = supers.theConsList;
loop002 : for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) {
sup = ((Surrogate)(iter001.value));
if (Surrogate.subtypeOfP(sup, newsuper)) {
value000 = sup;
break loop002;
}
}
}
subsumedsuper = value000;
}
if (!(subsumedsuper != null)) {
break loop001;
}
}
supers = ((List)(supers.remove(subsumedsuper)));
}
supers.insert(newsuper);
}
}
}
} |
83a4c369-b86f-4d9a-9c98-3a65f07ceadf | 6 | private int hexDigit(int value){
if(value>='0' && value<='9')
return (value-'0');
else if(value>='a' && value<='f')
return (value-'a')+10;
else if(value>='A' && value<='F')
return (value-'A')+10;
else
return -1;
} |
c90ef79a-7acd-44bb-8993-3d470876200a | 6 | private void parseArgs(String[] args) {
if (args != null && args.length > 0) {
for (String arg : args) {
if (arg.startsWith("-") && arg.lastIndexOf("=") != -1) { // -config="server.config"
arg = arg.substring(1, arg.length());
String[] keyValuePair = arg.split("=");
if (keyValuePair.length == 2) {
log("adding arg to map, key: '" + keyValuePair[0] + "' value: '" + keyValuePair[1] + "'");
argMap.put(keyValuePair[0], keyValuePair[1]);
} else {
log("arg contains multiple '=', arg: " + arg);
}
} else {
log("arg does not starts with '-' and does not contains '=', arg: " + arg);
}
}
} else {
log("no args, using defaults");
}
} |
af0ffb1e-d5a2-4e2b-a5e1-199048ce3a1c | 2 | @Override
public double getMissingMoney(double priceInEuros) {
if (priceInEuros < 0)
throw new IllegalArgumentException("ERR00034452b");
if (priceInEuros > totalAmountInEuros)
return priceInEuros - totalAmountInEuros;
else
return 0;
} |
02834d6c-0eba-4667-bb69-a6a118b4bac9 | 9 | protected void openDocument() throws XPathException {
if (writer==null) {
makeWriter();
}
if (characterSet==null) {
characterSet = UTF8CharacterSet.getInstance();
}
// Write a BOM if requested
String encoding = outputProperties.getProperty(OutputKeys.ENCODING);
if (encoding==null || encoding.equalsIgnoreCase("utf8")) {
encoding = "UTF-8";
}
String byteOrderMark = outputProperties.getProperty(SaxonOutputKeys.BYTE_ORDER_MARK);
if ("yes".equals(byteOrderMark) && (
"UTF-8".equalsIgnoreCase(encoding) ||
"UTF-16LE".equalsIgnoreCase(encoding) ||
"UTF-16BE".equalsIgnoreCase(encoding))) {
try {
writer.write('\uFEFF');
} catch (java.io.IOException err) {
// Might be an encoding exception; just ignore it
}
}
started = true;
} |
9ba9bd38-1abd-4bc7-89b8-9f0e1276e771 | 7 | private static int resolveFirstDayOfWeek(String firstDayOfWeek) {
if (firstDayOfWeek.equalsIgnoreCase("sunday")) {
return SUNDAY;
}
else if (firstDayOfWeek.equalsIgnoreCase("monday")) {
return MONDAY;
}
else if (firstDayOfWeek.equalsIgnoreCase("tuesday")) {
return TUESDAY;
}
else if (firstDayOfWeek.equalsIgnoreCase("wednesday")) {
return WEDNESDAY;
}
else if (firstDayOfWeek.equalsIgnoreCase("thursday")) {
return THURSDAY;
}
else if (firstDayOfWeek.equalsIgnoreCase("friday")) {
return FRIDAY;
}
else if (firstDayOfWeek.equalsIgnoreCase("saturday")) {
return SATURDAY;
}
throw new IllegalArgumentException("Never heard for this day of week: " + firstDayOfWeek);
} |
85b9c34b-f790-4dad-89f7-880139cbb146 | 4 | private void readParameterAnnotations(int v, final String desc,
final char[] buf, final boolean visible, final MethodVisitor mv) {
int i;
int n = b[v++] & 0xFF;
// workaround for a bug in javac (javac compiler generates a parameter
// annotation array whose size is equal to the number of parameters in
// the Java source file, while it should generate an array whose size is
// equal to the number of parameters in the method descriptor - which
// includes the synthetic parameters added by the compiler). This work-
// around supposes that the synthetic parameters are the first ones.
int synthetics = Type.getArgumentTypes(desc).length - n;
AnnotationVisitor av;
for (i = 0; i < synthetics; ++i) {
// virtual annotation to detect synthetic parameters in MethodWriter
av = mv.visitParameterAnnotation(i, "Ljava/lang/Synthetic;", false);
if (av != null) {
av.visitEnd();
}
}
for (; i < n + synthetics; ++i) {
int j = readUnsignedShort(v);
v += 2;
for (; j > 0; --j) {
av = mv.visitParameterAnnotation(i, readUTF8(v, buf), visible);
v = readAnnotationValues(v + 2, buf, true, av);
}
}
} |
86aba103-3a7b-4eef-8011-7488d4f75da3 | 7 | public static Object mlmpVehicleSpawn(int type, World world, double x, double y, double z, Entity thrower, Object currentEntity) throws Exception
{
Class mlmp = getClass("ModLoaderMp");
if (!isMLMPInstalled() || mlmp == null)
{
return currentEntity;
}
Object entry = mlmp.getDeclaredMethod("handleNetClientHandlerEntities", int.class).invoke(null, type);
if (entry == null)
{
return currentEntity;
}
Class entityClass = (Class)entry.getClass().getDeclaredField("entityClass").get(entry);
Object ret = (Entity)entityClass.getConstructor(World.class, Double.TYPE, Double.TYPE, Double.TYPE).newInstance(world, x, y, z);
if (entry.getClass().getDeclaredField("entityHasOwner").getBoolean(entry))
{
Field owner = entityClass.getField("owner");
if (!Entity.class.isAssignableFrom(owner.getType()))
{
throw new Exception(String.format("Entity\'s owner field must be of type Entity, but it is of type %s.", owner.getType()));
}
if (thrower == null)
{
System.out.println("Received spawn packet for entity with owner, but owner was not found.");
ModLoader.getLogger().fine("Received spawn packet for entity with owner, but owner was not found.");
}
else
{
if (!owner.getType().isAssignableFrom(thrower.getClass()))
{
throw new Exception(String.format("Tried to assign an entity of type %s to entity owner, which is of type %s.", thrower.getClass(), owner.getType()));
}
owner.set(ret, thrower);
}
}
return ret;
} |
fab11f24-3874-43c7-8494-e2f63e753ca6 | 3 | public static void enableEvent(Cuboid c, CuboidEvent event) {
if (c == null || event == null) return;
if (c.getEvents().contains(event)) return;
c.getEvents().add(event);
} |
5aa4060e-bfb3-4db7-9e9e-15a1fe9a444d | 6 | private void storeWrite() { try {
if (localstorefile==null) return;
PrintWriter writer=new PrintWriter(
new FileWriter(new File(localstorefile)) );
for (Enumeration e=localstore.keys(); e.hasMoreElements(); ) {
String k = (String)e.nextElement();
Object o = localstore.get(k);
if (o instanceof Integer) {
writer.println(k+"\tint\t"+o);
} else if (o instanceof Double) {
writer.println(k+"\tdouble\t"+o);
} else if (o instanceof String) {
writer.println(k+"\tString\t"+o);
}
}
writer.close();
} catch (IOException e) {
throw new JGameError("Error writing file '"+localstorefile+"'.",false);
} } |
dedfe408-9dfe-4fdb-9f28-cfadc9a9e2c8 | 1 | public boolean isGravityDebugStatus() {
if(frame == null) buildGUI();
return gravityDebugStatus.isSelected();
} |
da7f5ae4-755c-4dc7-beb2-eae0204df822 | 2 | public static ArrayList<Ticket> showAll() {
ArrayList<Ticket> tickets = new ArrayList<Ticket>();
Database db = dbconnect();
try {
db.prepare("SELECT * FROM ticket ORDER BY TID");
ResultSet rs = db.executeQuery();
while(rs.next()) {
tickets.add(TicketObject(rs));
}
db.close();
} catch (SQLException e) {
Error_Frame.Error(e.toString());
}
return tickets;
} |
6b220699-e769-4383-929a-3a0d40286793 | 4 | public boolean doneCheck(UQuest plugin, Player player){
try{
Quester quester = plugin.getQuestInteraction().getQuester(player);
//gatherObectives(plugin, player, quester);
int doneAmount = 0;
for(Objective objective : this.objectives){
if(objective.doneCheck(player, quester.getTracker(plugin, objective.getObjectiveName())))
doneAmount++;
}
if(doneAmount == this.objectives.size()){
return true;
}else{
player.sendMessage(ChatColor.RED + "You only have " + ChatColor.stripColor(Integer.toString(doneAmount)) + " objectives done!");
return false;
}
}catch(ArrayIndexOutOfBoundsException aiobe){
System.err.println("[Hawox's uQuest]:LoadedQuest:doneCheck:ArrayIndexOutOfBoundsException: Player didn't have a correct quest tracker.");
return false;
}
} |
398681a3-ae0e-4356-98d0-4b9cc42a9d6c | 1 | protected static Output getInstance() {
if (instance == null) {
new Output();
}
return instance;
} |
340dd8a2-1b8c-4591-a478-87b4be8dd13b | 4 | public String getClassType(int i) throws ClassFormatException {
if (i == 0)
return null;
if (tags[i] != CLASS)
throw new ClassFormatException("Tag mismatch");
String clName = getUTF8(indices1[i]);
if (clName.charAt(0) != '[') {
clName = ("L" + clName + ';').intern();
}
try {
TypeSignature.checkTypeSig(clName);
} catch (IllegalArgumentException ex) {
throw new ClassFormatException(ex.getMessage());
}
return clName;
} |
e8c6cdcf-226b-4d42-bb79-c37d0513625c | 8 | public Response changerEtatDuneAnomalie(String nomProjet,
String sujetAnomalie, Note note, UriInfo uri,String newEtat) throws Exception {
URI uriReponse;
Response reponse;
Projet projet;
Anomalie newAnomalie;
int index;
long idToRemove = -1;
projet = dao.getProjet(nomProjet);
if(projet != null){
if(projet.getAnomalies() != null){
for (index = 0; index<projet.getAnomalies().size(); index++) {
if(projet.getAnomalies().get(index).getSujet().equals(sujetAnomalie)){
newAnomalie = projet.getAnomalies().get(index);
idToRemove = newAnomalie.getId();
switch(newEtat){
case "AFFECTEE": newAnomalie.setEtatToAffectee();
break;
case "RESOLUE": newAnomalie.setEtatToResolue();
break;
case "FERMEE": newAnomalie.setEtatToFermee();
break;
default: throw new Exception("Invalid argument in projetJEE.ejb.gestionAnomalie.changerEtatDuneAnomalie");
}
newAnomalie.addNote(note);
projet.getAnomalies().set(index, newAnomalie);
break;
}
}
if(idToRemove!=-1){
dao.persisterProjet(projet);
dao.removeAnomalie(dao.getAnomalie(idToRemove));
uriReponse = uri.getBaseUriBuilder().path("projets").path("anomalies").path(""+projet.getAnomalies().get(index).getId()).build();
reponse = Response.created(uriReponse).build();
}else{
reponse = Response.status(Response.Status.BAD_REQUEST).entity("L'anomalie \""+sujetAnomalie+"\" n'est pas présente dans le projet \""+nomProjet+"\".").build();
}
}else{
reponse = Response.status(Response.Status.BAD_REQUEST).entity("Le projet \""+ nomProjet+"\" ne contient pas d'anomalies.").build();
}
}else{
reponse = Response.status(Response.Status.BAD_REQUEST).entity("Le projet \""+ nomProjet+"\" est inconnu.").build();
}
return reponse;
} |
f8100141-14a3-47e4-8099-5dbe6ecbd046 | 8 | @Override
public void actionPerformed(ActionEvent e) {
for(int i=0; i<10; i++){
if(levelItems[i]==e.getSource())
{
canvas.load(i);
break;
}
}
if(reset == e.getSource())
{
canvas.reset();
}
if(load == e.getSource())
{
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
canvas.load(file);
} else {
System.out.println("They canceled");
}
}
if(exit == e.getSource()){
System.exit(0);
}
/*Display the rules of the game*/
if(helpMenu == e.getSource())
{
JOptionPane.showMessageDialog(null, "Click on a piece to move it. Get the red piece to move to the 5th column and you have won.");
}
if(hint == e.getSource())
{
JOptionPane.showMessageDialog(null, canvas.getHint());
}
} |
1338262c-c87f-4348-9035-1b5aff283a5b | 0 | public static void main(String[] args) throws SocketException {
instance = new UDPChat();
} |
cd1a0410-20d9-436b-a43f-6f4f90972101 | 9 | @Override
public void dump(Map<String, Object> into) throws IOException {
super.dump(into);
{
StringBuilder request = new StringBuilder(requestHeaders);
request.append(EOL);
if (requestExcerpt != null) {
request.append(new String(requestExcerpt, requestEncoding));
}
into.put(REQUEST, request.toString());
}
{
HttpURLConnection http = (connection instanceof HttpURLConnection) ? (HttpURLConnection) connection
: null;
StringBuilder response = new StringBuilder();
String value;
for (int i = 0; (value = connection.getHeaderField(i)) != null; ++i) {
String name = connection.getHeaderFieldKey(i);
if (i == 0 && name != null && http != null) {
String firstLine = "HTTP " + getStatusCode();
String message = http.getResponseMessage();
if (message != null) {
firstLine += (" " + message);
}
response.append(firstLine).append(EOL);
}
if (name != null) {
response.append(name).append(": ");
name = name.toLowerCase();
}
response.append(value).append(EOL);
}
response.append(EOL);
if (body != null) {
response.append(new String(((ExcerptInputStream) body)
.getExcerpt(), getContentCharset()));
}
into.put(HttpMessage.RESPONSE, response.toString());
}
} |
Subsets and Splits