method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
4cf28e13-90f4-4c49-9217-0a3827d6183c | 1 | public void setDecimalformat(String format) {
dformat = (!format.startsWith("%")) ? ('%' + format) : format;
} |
f4543d50-bfde-45dc-be0c-43ea08d3a684 | 8 | /* */ public void damageCheck() {
/* 40 */ Random r = new Random();
/* 41 */ for (int i = 0; i < Core.units.size(); i++) {
/* 42 */ Unit u = (Unit)Core.units.get(i);
/* */
/* 44 */ if (!this.hitUnits.contains(u)) {
/* 45 */ if (u.collision.intersects(this.highDamage)) {
/* 46 */ u.setDamage(50 + r.nextInt(30));
/* 47 */ System.out.println("High");
/* 48 */ this.hitUnits.add(u);
/* 49 */ } else if (u.collision.intersects(this.lowDamage)) {
/* 50 */ u.setDamage(20 + r.nextInt(10));
/* 51 */ System.out.println("Low");
/* 52 */ this.hitUnits.add(u);
/* */ }
/* */ }
/* */ }
/* 56 */ for (int i = 0; i < Core.enemies.size(); i++) {
/* 57 */ Unit u = (Unit)Core.enemies.get(i);
/* */
/* 59 */ if (!this.hitUnits.contains(u))
/* 60 */ if (u.collision.intersects(this.highDamage)) {
/* 61 */ u.setDamage(90 + r.nextInt(45));
/* 62 */ System.out.println("High");
/* 63 */ this.hitUnits.add(u);
/* 64 */ } else if (u.collision.intersects(this.lowDamage)) {
/* 65 */ u.setDamage(50 + r.nextInt(20));
/* 66 */ System.out.println("Low");
/* 67 */ this.hitUnits.add(u);
/* */ }
/* */ }
/* */ } |
70a2ff46-e741-4a9c-b84b-df7ba3dd38df | 0 | public static void main(String[] args) {
int max = Integer.MAX_VALUE;
System.out.println("Overflow:");
System.out.println(max); // 2147483647
System.out.println(max + 1); // -2147483648
System.out.println(max + 2); // -2147483647
int min = Integer.MIN_VALUE;
System.out.println("Unceerflow:");
System.out.println(min); // -2147483648
System.out.println(max - 1); // 2147483647
System.out.println(max - 2); // 2147483646
} |
a49e5917-f88b-4877-bf20-c48c89597757 | 5 | private void drawNanopostImage() {
try {
File imgFile = np.getNanoPostFile(np.isFromOutbox());
if (!imgFile.exists()) {
panAttach.setVisible(false);
return;
}
BufferedImage image = ImageIO.read(imgFile);
if (image != null) {
if (image.getWidth() > 157 || image.getHeight() > 200) {
image = resize(image, 157, 200);
}
lblImg.setIcon(new ImageIcon(image));
lblImg.repaint();
}
} catch (IOException ex) {
Logger.getLogger(NanoPostPanel.class.getName()).log(Level.SEVERE, null, ex);
}
} |
3bdb6267-23e6-4591-856d-af191d38d93e | 8 | public static FelixString tryParse(ParserReader in) throws IOException {
in.mark(1); // Prepare to roll back if we don't see a quote character.
int quote = in.read();
boolean isQuote = quote == S || quote == D;
if(!isQuote) {
in.reset();
return null; // Not a string
}
StringBuffer buf = new StringBuffer(1000);
boolean triple = checkTriple(in, quote);
for(;;) {
int ch = in.read();
if(ch == -1) throw new EOFException("Reached EOF parsing string");
if(ch == quote && (!triple || checkTriple(in, quote))) {
return new FelixString(buf.toString(), quote, triple);
} else if(ch == ESCAPE) {
buf.append(mapSpecialChar(in.read()));
}
}
} |
77a03200-75a0-4e43-b234-8d94a3edae6b | 6 | private boolean checkTable() {
String sql = "";
try {
Statement state = con.createStatement();
sql = "DESC " + database + "." + table;
ResultSet rs = state.executeQuery(sql);
int size = 0;
while (rs.next()) {
String field = rs.getString("Field");
String type = rs.getString("Type");
if (!this.columns.containsKey(field)) {
System.err.println("Table column " + field + " is undefined in any patterns.");
return false;
}
else if (this.columns.get(field).toLowerCase().indexOf(type) == -1
&& type.indexOf(this.columns.get(field).toLowerCase()) == -1) {
System.err.println("Table column " + field + ":" + type +
" doesn't match defined patterns " + field + ":" + this.columns.get(field).toLowerCase() + ".");
return false;
}
size ++;
}
if (size != this.columns.size()) {
System.err.println("[Error] " + size + " columns defined in table, but " + this.columns.size() + " patterns defined.");
return false;
}
}
catch (Exception e) {
System.err.println(e.toString());
return false;
}
return true;
} |
0a1ae36b-8d4f-44aa-93d6-10a2e8e0099e | 2 | public List<Collidable> retrieve(List<Collidable> returnStuff,Collidable c) {
int index = getIndex(c);
if (index != -1 && nodes.get(0) != null) {
nodes.get(index).retrieve(returnStuff, c);
}
returnStuff.addAll(stuff);
return returnStuff;
} |
7cd1085e-a57c-43a1-9304-f34f15252490 | 0 | KeepAliveThread() {
lock = new ReentrantLock();
setName("KeepAliveThread");
setDaemon(true);
} |
067c91e0-4121-40f3-9d78-073a4d0bff7a | 9 | final public CommandControl isValid(List<String> lines) {
if (isCommandForbidden()) {
return CommandControl.NOT_OK;
}
final Matcher m1 = starting.matcher(lines.get(0).trim());
if (m1.matches() == false) {
return CommandControl.NOT_OK;
}
if (lines.size() == 1) {
return CommandControl.OK_PARTIAL;
}
int level = 1;
for (int i = 1; i < lines.size(); i++) {
final String s = lines.get(i).trim();
if (isLineConsistent(s, level) == false) {
return CommandControl.NOT_OK;
}
if (s.endsWith("{")) {
level++;
}
if (s.endsWith("}")) {
level--;
}
if (level < 0) {
return CommandControl.NOT_OK;
}
}
if (level != 0) {
return CommandControl.OK_PARTIAL;
}
actionIfCommandValid();
return CommandControl.OK;
} |
cdc440b6-39a6-489b-a739-6c0c118a46ca | 3 | public ListEnemy DeserializationListEnemy(String songTitle)
{
ListEnemy LE=null;
try {
FileInputStream fis = new FileInputStream(songTitle);
ObjectInputStream ois= new ObjectInputStream(fis);
try
{
LE = (ListEnemy) ois.readObject();
} finally
{
try
{
ois.close();
} finally
{
fis.close();
}
}
} catch(IOException ioe) {
ioe.printStackTrace();
} catch(ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
if(LE != null) {
System.out.println( "a ete deserialise");
return LE;
}
return null;
} |
b698e8ae-c726-49d8-b440-fbf1aa75d2af | 0 | @Override
public String getName() {
return this.name;
} |
ad927912-25d8-4475-bf22-40d304486804 | 6 | private void jaaPisteet(Siirto ensimmaisen, Siirto toisen, AI eka, AI toka) {
if (ensimmaisen == Siirto.YHTEISTYO && toisen == Siirto.YHTEISTYO) {
eka.lisaaPisteita(yhteistyonPalkinto);
toka.lisaaPisteita(yhteistyonPalkinto);
} else if (ensimmaisen == Siirto.YHTEISTYO && toisen == Siirto.PETOS) {
eka.lisaaPisteita(tyhmyrinRangaistus);
} else if (ensimmaisen == Siirto.PETOS && toisen == Siirto.YHTEISTYO) {
toka.lisaaPisteita(tyhmyrinRangaistus);
} else {
eka.lisaaPisteita(pettureidenKompromissi);
toka.lisaaPisteita(pettureidenKompromissi);
}
} |
aead7005-428a-4e00-a3e9-d97dab6d6005 | 5 | public StatFileWriter(Session var1, File var2) {
File var3 = new File(var2, "stats");
if (!var3.exists()) {
var3.mkdirs();
}
File[] var4 = var2.listFiles();
int var5 = var4.length;
for (int var6 = 0; var6 < var5; ++var6) {
File var7 = var4[var6];
if (var7.getName().startsWith("stats_") && var7.getName().endsWith(".dat")) {
File var8 = new File(var3, var7.getName());
if (!var8.exists()) {
System.out.println("Relocating " + var7.getName());
var7.renameTo(var8);
}
}
}
this.statsSyncher = new StatsSyncher(var1, this, var3);
} |
347b4a19-d474-4b0b-8439-b4df13408391 | 0 | @RequestMapping(method = RequestMethod.DELETE, value = "{id}")
public void deleteTask(@PathVariable("id") Integer id) {
tasksService.deleteById(id);
} |
dff7dced-bd09-4961-871a-bdcffdc1cfe4 | 2 | public void visitInnerClass(final String aname, final String outerName, final String innerName, final int attr_access) {
if ((name != null) && name.equals(aname)) {
this.access = attr_access;
}
super.visitInnerClass(aname, outerName, innerName, attr_access);
} |
9486f8fc-0192-4425-b33a-dc2bb966b2e6 | 5 | public int hashCode() {
int result;
result = (street != null ? street.hashCode() : 0);
result = 29 * result + (city != null ? city.hashCode() : 0);
result = 29 * result + (country != null ? country.hashCode() : 0);
result = 29 * result + (state != null ? state.hashCode() : 0);
result = 29 * result + (zip != null ? zip.hashCode() : 0);
return result;
} |
7cd422ae-786f-4740-aa74-676b15e02433 | 3 | public static String toHtml(String text, String url) throws Exception {
ParserConverter oParserConverter = new ParserConverter();
try {
if (text != null) {
if (!text.equals("")) {
text = oParserConverter.tag(text, "======", "h6");
text = oParserConverter.tag(text, "=====", "h5");
text = oParserConverter.tag(text, "====", "h4");
text = oParserConverter.tag(text, "===", "h3");
text = oParserConverter.tag(text, "==", "h2");
text = oParserConverter.tag(text, "=", "h1");
text = oParserConverter.tag(text, "\\*\\*", "b");
text = oParserConverter.tag(text, "\\$\\$", "i");
text = oParserConverter.a(text, url);
text = oParserConverter.p(text);
}
}
} catch (Exception e) {
throw new ServletException("TextParser Error: " + e.getMessage());
}
return text;
} |
6b60ec75-4210-4e7b-a7e6-97f490e73be7 | 2 | @Override
protected void loadDatabase() throws DataLoadFailedException {
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException ex) {
throw new DataLoadFailedException(ex);
}
try {
connection = DriverManager.getConnection("jdbc:sqlite:" + path);
} catch (SQLException ex) {
throw new DataLoadFailedException(ex);
}
} |
6deaa9f6-4562-4d89-b71e-d46ce31fc7ef | 6 | public void start(BundleContext context) throws Exception {
m_context = context;
// We synchronize while registering the service listener and
// performing our initial dictionary service lookup since we
// don't want to receive service events when looking up the
// dictionary service, if one exists.
synchronized (this) {
// Listen for events pertaining to dictionary services.
m_context.addServiceListener(this, "(&(objectClass=" + DictionaryService.class.getName() + ")" + "(Language=*))");
// Query for any service references matching any language.
ServiceReference[] refs = m_context.getServiceReferences(DictionaryService.class.getName(), "(Language=*)");
// If we found any dictionary services, then just get
// a reference to the first one so we can use it.
if (refs != null) {
m_ref = refs[0];
m_dictionary = (DictionaryService) m_context.getService(m_ref);
}
}
try {
System.out.println("Enter a blank line to exit.");
String word = "";
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Loop endlessly.
while (true) {
// Ask the user to enter a word.
System.out.print("Enter word: ");
word = in.readLine();
// If the user entered a blank line, then
// exit the loop.
if (word.length() == 0) {
break;
}
// If there is no dictionary, then say so.
else if (m_dictionary == null) {
System.out.println("No dictionary available.");
}
// Otherwise print whether the word is correct or not.
else if (m_dictionary.checkWord(word)) {
System.out.println("Correct.");
} else {
System.out.println("Incorrect.");
}
}
} catch (Exception ex) {
}
} |
5ef4477e-92c8-41cf-a478-b1adedbce090 | 8 | public static void copyFile(String fileFrom, String fileTo) {
File srcFile = new File(fileFrom);
if (!srcFile.exists()) {
return;
}
File destFile = new File(fileTo);
if (destFile.exists()) {
destFile.delete();
}
try {
destFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(fileFrom);
out = new FileOutputStream(fileTo);
byte[] bt = new byte[5 * 1024];
int count;
while ((count = in.read(bt)) > 0) {
out.write(bt, 0, count);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
} |
7b0936de-579e-44d5-9fa4-caba5f19a5b6 | 0 | public Address getAddressCompany() {
return addressCompany;
} |
ac12b39b-93e5-41c7-839e-5deff2e092f8 | 4 | public boolean equalsExpr(final Expr other) {
return (other != null) && (other instanceof ShiftExpr)
&& (((ShiftExpr) other).dir == dir)
&& ((ShiftExpr) other).expr.equalsExpr(expr)
&& ((ShiftExpr) other).bits.equalsExpr(bits);
} |
fa930ae9-48a8-4794-954d-1487c83c0174 | 1 | public static DataTag getPlayerData(){
Object obj = read("player/player");
if(obj == null)
return null;
JSONObject data = (JSONObject) obj;
return new DataTag(data);
} |
ea0754ca-c748-460e-9d1b-65c39feb8e24 | 7 | @AroundInvoke
public Object invoke(InvocationContext context) throws Exception {
EntityTransaction trx = manager.getTransaction();
boolean criador = false;
try {
if (!trx.isActive()) {
// truque para fazer rollback no que já passou
// (senão, um futuro commit confirmaria até mesmo operações sem transação)
trx.begin();
trx.rollback();
// agora sim inicia a transação
trx.begin();
criador = true;
}
return context.proceed();
} catch (Exception e) {
if (trx != null && criador) {
trx.rollback();
}
throw e;
} finally {
if (trx != null && trx.isActive() && criador) {
trx.commit();
}
}
} |
4ebe3499-831b-46f3-8cf1-f8f829433fbd | 0 | public void setRap_num(int rap_num) {
this.rap_num = rap_num;
} |
d1d9695e-6d93-4fd2-940e-eca8540aa33d | 8 | private void recurseClick(int x, int y) {
Square square = board.getSquare(x, y);
if (square.isRevealed() || square.isFlagged() || square.isQuestioned()) return;
//first click square
square.setClicked();
listener.squareRevealed(x, y, square.numMines());
unclickedNonmines--;
//then check if it has any adjacent mines. If it doesn't, recurse.
if (square.numMines() == 0 && square.isRevealed()) {
for (int i = x - 1; i <= x + 1; i++) {
for (int j = y - 1; j <= y + 1; j++) {
if (!board.positionExists(i, j)) continue;
recurseClick(i, j);
}
}
}
} |
ce543d01-a2e8-4206-8a8c-f9310e7f0d50 | 5 | public void merge(int low, int mid, int high){
//copy the entire array in the Auxilary array
for(int i=low;i<=high;i++){
arrAux[i] = arrInput[i];
}
int i = low;
int j = mid+1;
int k = low;
while(i<=mid && j<=high){
if(arrAux[i]<=arrAux[j]){
arrInput[k]=arrAux[i];
i++;
}
else{
arrInput[k]=arrAux[j];
j++;
}
k++;
}
while(i<=mid){
arrInput[k]=arrAux[i];
i++;
k++;
}
} |
20a61ca6-3876-4051-9ac9-c3e3f2acbef8 | 0 | public StringBuilder getText() {
return text;
} |
201f5b93-20a9-4201-a799-7652e56c7a54 | 8 | @Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
p.doYourThing(gc,gameplayEnvironment);
gameplayEnvironment.doYourThing(gc);
if((System.currentTimeMillis() - lastKITick) > 300){
for(objekt a : gameplayEnvironment.getEnvironment()){
lastKITick = System.currentTimeMillis();
if(a instanceof mob && !(a instanceof player)){
mob m = (mob)a;
double t = Math.random();
if(t > 0.5 || m.getEnvironmentCollisionList(gameplayEnvironment).contains(co.COLLISION_LEFT)){
m.removeDir(co.DIR_LEFT);
m.setDir(co.DIR_RIGHT);
}
else if(t <= 0.5f || m.getEnvironmentCollisionList(gameplayEnvironment).contains(co.COLLISION_RIGHT)){
m.removeDir(co.DIR_RIGHT);
m.setDir(co.DIR_LEFT);
}
}
}
}
} |
2a99a652-2bb8-4eb2-8228-752536a7d20a | 0 | public static void main(String[] args) {
// wap to find square root of number
ky = new Scanner(System.in);
System.out.println("enter the number");
double k=ky.nextDouble();
System.out.println("the square root is" +Math.sqrt(k));
} |
e440ce8d-ab35-4f71-a627-f40166bb5da4 | 9 | public void testMergeWithDifferentPartitions() throws Exception {
d=createChannel(a);
d.setName("D");
rd=new MyReceiver("D", d);
d.setReceiver(rd);
modifyConfigs(d);
d.connect("OverlappingMergeTest");
// Inject view {A,C,B} into A, B and C:
View new_view=View.create(a.getAddress(), 4, a.getAddress(), c.getAddress(), b.getAddress());
System.out.println("\n ==== Injecting view " + new_view + " into A, B and C ====");
injectView(new_view,false,a,b,c);
assert Util.isCoordinator(a);
assert !Util.isCoordinator(b);
assert !Util.isCoordinator(c);
View view_d=View.create(b.getAddress(), 4, b.getAddress(), a.getAddress(), c.getAddress(), d.getAddress());
System.out.println("\n ==== Injecting view " + view_d + " into D ====\n");
injectView(view_d, false, d);
assert !Util.isCoordinator(d);
for(JChannel ch: Arrays.asList(a,b,c,d))
System.out.println(ch.getName() + ": " + ch.getView());
// start merging
Event merge_evt=createMergeEvent(a,b,c,d);
System.out.println("\n==== Injecting a merge event into members ====");
for(JChannel ch: new JChannel[]{a,b,c,d}) {
GMS gms=ch.getProtocolStack().findProtocol(GMS.class);
gms.setLevel("trace");
}
injectMergeEvent(merge_evt,a,b,c,d);
for(int i=0; i < 20; i++) {
if(a.getView().size() == 4 && b.getView().size() == 4 && c.getView().size() == 4 && d.getView().size() == 4)
break;
Util.sleep(2000);
injectMergeEvent(createMergeEvent(a,b,c,d), a,b,c,d);
}
for(JChannel ch: Arrays.asList(a,b,c,d))
System.out.println(ch.getName() + ": " + ch.getView() + " (coord=" + isCoord(ch) + ")");
for(JChannel ch: Arrays.asList(a,b,c,d)) {
assert ch.getView().size() == 4 : ch.getName() + ": view is " + ch.getView();
GMS gms=ch.getProtocolStack().findProtocol(GMS.class);
gms.setLevel("warn");
}
System.out.println("\n");
} |
d497ec57-16de-4caa-a525-253eec7e1e28 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Group other = (Group) obj;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
} |
78d1081c-de82-4819-be5f-85590aeff452 | 3 | private static void closeStatement(Statement stmt) {
if( stmt != null ) {
try {
if( !stmt.isClosed() ) {
stmt.close();
}
} catch (SQLException e) {
logger.error("Error closing the statement.", e);
}
}
} |
4d628fad-7e36-4f68-8bf0-8a3983a24015 | 7 | @Override
public int getCurrentBall()
{
assert !isGameOver();
int currentBall = 10;
for (int i = 0; i < rollCount; i++)
{
int pinsKnockedDown = pinsKnockedDownArray[i];
if (getCurrentFrame() == 10)
{
currentBall += 3.33;
}
else
{
if (pinsKnockedDown == 0)
{
currentBall += 5;
}
if (pinsKnockedDown != 10 && pinsKnockedDown != 0)
{
currentBall += 5;
}
else if (pinsKnockedDown == 10)
{
currentBall += 10;
}
}
}
if (currentBall % 2 == 0)
{
return 1;
}
return 2;
} |
0fa8f2e0-8a13-4131-b9e9-0b7e63298a38 | 6 | @Override
public int match(String[] argsToTest) {
// args must contain one of the required pairs
int errorCount = 0;
for (String[] requiredElem : required) {
boolean found = false;
for (String testArg : argsToTest) {
if (isCommandArg(testArg)) {
if (matches(testArg, requiredElem)) {
found = true;
}
}
}
if (!found) {
addMismatch(requiredElem);
errorCount++;
}
}
if (errorCount == 0) {
return Constants.OK;
}
return Constants.ERROR;
} |
875ffc16-63f3-42da-ba05-00ee7c6171c9 | 7 | public int findKth(int[] nums1, int[] nums2, int k) {
int p1 = 0;
int p2 = 0;
System.out.println("p1: " + p1 + "p2: " + p2 + "k: " + k);
while (p1 < nums1.length && p2 < nums2.length) {
if (nums1[p1] > nums2[p2]) {
if (k == 1) {
return nums2[p2];
}
p2++;
} else {
if (k == 1) {
return nums1[p1];
}
p1++;
}
k--;
}
if (p1 < nums1.length) {
return nums1[p1 + k - 1];
}
if (p2 < nums2.length) {
return nums2[p2 + k - 1];
}
return 0;
} |
f30c142e-1ea2-467c-9639-099a81fcb494 | 1 | public void ajErrorOutputNode() {
setMisalignment(this.getPotential() * (1 - this.getPotential()) * (this.getAnswer() - this.getPotential()));
//Adjustment of synaptic weights on the output layer
double lErr = this.getMisalignment();
for (int t = 0; t < this.getIncomingLinksNumber(); t++) {
double oldWeight = this.getIncomingLink(t).getWeight();
double out = this.getIncomingLink(t).getIn_node().getPotential();
double newWeight = oldWeight + NeatClass.p_training_coefficient * lErr * out;
this.getIncomingLink(t).setWeight(newWeight);
}
} |
426eb895-31de-488f-af3b-30861d5295be | 6 | 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(FlowView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex)
{
java.util.logging.Logger.getLogger(FlowView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(FlowView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(FlowView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new FlowView().setVisible(true);
}
});
} |
a42569cf-a5cb-4fac-a411-22da365f5d31 | 2 | private void updateGrid(ClientUI client) {
Iterator<Integer> iter = client.net.getTerritoriesLayout().keySet().iterator();
TerritoriesLayout territories = client.net.getTerritoriesLayout();
while (iter.hasNext()) {
Integer key = iter.next();
Button button = client.buttonsMap.get(territories.get(key).getId());
PlayerColor owner = territories.get(key).getOwner();
int unitNumber = territories.get(key).getUnitNumber();
int id = territories.get(key).getId();
button.setText(mapButtonMessage(id, owner, unitNumber));
if (client.net.getColor() != owner)
button.setEnabled(false);
else
button.setEnabled(true);
}
} |
59b4f921-8ef2-411c-8304-235e9310cc8a | 5 | public void mouseEntered(MouseEvent arg0) {
setBorder(bigBord);
double coutAttaque = Partie.getInstance().coutAttaque(territoire);
List<Element> elements = territoire.getElements();
String txt = "";
String occupantName;
Peuple occupant = this.territoire.getOccupant();
int nbUnite = this.territoire.getNbUnite();
if (occupant != null) {
occupantName = occupant.getNom() + " (" + occupant.getJoueur().getNom() + ")";
}
else if (nbUnite > 0) {
occupantName = "Thésard";
}
else {
occupantName = "Aucun";
}
txt += "Occupant : " + occupantName + "\n\n";
txt += "Nombre d'unité...... " + nbUnite + "\n";
if (Double.isInfinite(coutAttaque)) {
txt += "Coût de l'attaque... Imprenable !\n\n";
}
else {
txt += "Coût de l'attaque... " + Math.round(coutAttaque) + " unité(s)\n\n";
}
txt += "Eléments contenus :\n";
if (elements.isEmpty()) {
txt += "\tAucun.";
}
else {
Iterator<Element> it = elements.iterator();
while (it.hasNext()) {
txt += "\t" + it.next().getNom() + "\n";
}
}
Game.getInstance().showInfo(txt);
} |
a8bd79d3-d1d5-43ef-8394-1bc54317924a | 7 | @Override
public void connect(T t1, T t2, String s, int weight){
if (!nodes.containsKey(t1) || !nodes.containsKey(t2)){
throw new NoSuchElementException("Node finns ej vid connect");
}
if (nodes.get(t1) == nodes.get(t2)){
//this shouldn't happen as you can't select the same circle twice (as it will be deselected on the second click), but just in case
throw new IllegalArgumentException("Origin and destination is the same object");
}
boolean exists = false;
List<Edge<T>> fromList = nodes.get(t1);
List<Edge<T>> toList = nodes.get(t2);
for (Edge<T> e : fromList){
if(e.getName().equalsIgnoreCase(s) && e.getDest() == t2) {
exists = true;
}
}
if (!exists){
Edge<T> e1 = new Edge<T>(t2, s, weight);
Edge<T> e2 = new Edge<T>(t1, s, weight);
fromList.add(e1);
toList.add(e2);
}
else{
throw new IllegalArgumentException("Finns redan en båge med detta namn");
}
} |
193c6e88-1ace-4413-b7a5-8c253f1f8f30 | 6 | public 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(CustomerAccount_DeleteAccount.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CustomerAccount_DeleteAccount.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CustomerAccount_DeleteAccount.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CustomerAccount_DeleteAccount.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 CustomerAccount_DeleteAccount(db, currentUser).setVisible(true);
}
});
} |
fbef8cca-1bd8-416c-b330-9ce0f5bd0943 | 3 | public void addMessage(String user, String message) throws ChatRoomInvalidStateException {
try {
ChatRoomMessage msg = dbConnector.addMessage(user, chatRoomName, message);
ChatRoomMessage stub = (ChatRoomMessage) UnicastRemoteObject.exportObject(msg, 0);
for(ChatRoomMessageListener l : listners) {
try {
l.processNewMessage(stub);
} catch(RemoteException e) {
e.printStackTrace();
}
}
} catch (SQLException | RemoteException e) {
throw new ChatRoomInvalidStateException();
}
} |
68222310-b46b-4c11-875b-6d08ec654e23 | 9 | @Override
public HashMap<String, Float> getWeightsForQuery(HashMap<String, Integer> query) {
try {
HashMap<String, Float> weights = new HashMap<String, Float>();
float total = 0.0f;
for (int n : query.values()){
total += n;
}
if (total == 0)
total = 1.0f;
for (String stem : query.keySet()) {
float wtq;
switch (MODEL){
case 1:
wtq = 1.0f;
break;
case 2:
wtq = query.get(stem) / total;
break;
case 3:
case 4:
wtq = index.getIdfsForStem(stem);
break;
case 5:
wtq = (float)Math.log10(query.get(stem)/total) * index.getIdfsForStem(stem);
break;
default:
wtq = 1.0f;
}
weights.put(stem, wtq);
}
return weights;
} catch (Exception e) {
e.printStackTrace();
return null;
}
} |
82ce2cfe-7b77-4380-a75f-d7489f4f6841 | 5 | private void changeSelection(Item.Pocket newPocket)
{
if (state == State.BUY)
{
pocket = newPocket;
currentDisplay.clear();
for (Item aFullInventory : fullInventory) {
if (aFullInventory.pocket == newPocket)
currentDisplay.add(aFullInventory);
}
}
else
{
pocket = newPocket;
currentDisplay.clear();
for (int i = 0; i < Inventory.fullInventory.size(); i++)
{
if (Inventory.fullInventory.get(i).pocket == newPocket)
{
currentDisplay.add(Inventory.fullInventory.get(i));
}
}
}
} |
8a1f0246-e72e-4888-b687-099560c336e1 | 5 | public Wave23(){
super();
MobBuilder m = super.mobBuilder;
for(int i = 0; i < 615; i++){
if(i % 5 == 0)
add(m.buildMob(MobID.ODDISH));
else if(i % 4 == 0)
add(m.buildMob(MobID.BELLSPROUT));
else if(i % 3 == 0)
add(m.buildMob(MobID.MEOWTH));
else if(i % 2 == 0)
add(m.buildMob(MobID.MANKEY));
else
add(m.buildMob(MobID.VULPIX));
}
} |
288c5807-e47f-4e44-aa5c-9394549741b3 | 3 | public EulerCamera(KeyboardBuffer kb, Vector3f position, Vector3f rotation) {
super(kb);
this.position = position;
this.rotation = rotation;
// Enable Depth clamping if supported
if (GLContext.getCapabilities().GL_ARB_depth_clamp) {
GL11.glEnable(ARBDepthClamp.GL_DEPTH_CLAMP);
}
//Instance the Mouse object if it does not already exist
//TODO: Move this to the InputManager
try {
if(!Mouse.isCreated()) Mouse.create();
} catch (LWJGLException e) {
e.printStackTrace();
}
//Register the input keys
this.registerKBInputs(new int[] {
Keyboard.KEY_W,
Keyboard.KEY_A,
Keyboard.KEY_S,
Keyboard.KEY_D,
Keyboard.KEY_SPACE,
Keyboard.KEY_LSHIFT,
Keyboard.KEY_ESCAPE
});
} |
521aa659-d8cc-499a-8e64-9e56f03cf944 | 5 | public static boolean LoadNatives() {
String OS = System.getProperty("os.name").toLowerCase();
String os_res = "";
if (isWindows(OS)) {
os_res = "windows";
} else if (isMac(OS)) {
os_res = "macosx";
} else if (isUnix(OS)) {
os_res = "linux";
} else if (isSolaris(OS)) {
os_res = "solaris";
}
if (os_res != "") System.setProperty("org.lwjgl.librarypath", new File("res" + System.getProperty("file.separator") + os_res).getAbsolutePath());
return os_res != "";
} |
78fa0e0f-64aa-4eaf-aa12-e96a115cabcf | 6 | public Class<?> getCollectionOrArrayType() {
if (propertyDescriptor.getReadMethod().getReturnType().isArray()) {
return propertyDescriptor.getReadMethod().getReturnType()
.getComponentType();
}
if (!Collection.class.isAssignableFrom(getPropertyType())) {
throw new UnsupportedOperationException(
propertyDescriptor.getName() + " of "
+ getClass().getSimpleName()
+ " is not a Collection property");
}
Type type = propertyDescriptor.getReadMethod().getGenericReturnType();
Type[] typeArgs = getGenericTypeArguments(type);
if (typeArgs != null && typeArgs.length > 0) {
return (Class<?>) typeArgs[0];
} else {
throw new UnsupportedOperationException(
propertyDescriptor.getName() + " of "
+ getClass().getSimpleName()
+ " is not a parametrized Collection property");
}
} |
e23b91d5-6e99-4e8b-afe9-8ccd0efe8286 | 6 | public void map(LongWritable key, Text values, Context context) throws IOException, InterruptedException {
Configuration conf = context.getConfiguration();
long numofSeqs = Long.valueOf(conf.get("numofSeqs"));
Double Support = Double.valueOf(conf.get("Support"));
//only one reducer as is the final wrap
// newkey.set("one reducer");
String item = null;
String value = null;
Map<String, String> listresults = new HashMap<String, String>();
String[] splits = values.toString().split("\n");
for (String val : splits){
if (val.split("\t").length ==3) {
item = val.split("\t")[1];
value = val.split("\t")[2];
}
else if(val.split("\t").length ==2){
item = val.split("\t")[0];
value = val.split("\t")[1];
}
if (listresults.get(item) != null){
long oldvalue = Long.valueOf(listresults.get(item));
String newvalue = String.valueOf(oldvalue + Long.valueOf(value));
listresults.put(item,newvalue);
}
else{
listresults.put(item,value);
}
}
for (String i : listresults.keySet()){
// if (Long.valueOf(listresults.get(i)) >= numofSeqs*Support) {
if (!i.contentEquals("size")) {
result.set(listresults.get(i));
newkey.set(i);
context.write(newkey, result);
// }
}
}
} |
2d476585-a60f-40e3-aa5c-c83539550694 | 7 | public void calculateEntitesCount(DatasetLoader datasetHandler) throws Exception{
Hashtable<String, Document> documentsHash = datasetHandler.loadDocuments();
int numberOfUniqueWords = 0;
int numberOfEdges = 0;
long startTime = System.currentTimeMillis();
Enumeration ids = documentsHash.keys();
ArrayList<String> documentIDs = datasetHandler.getDocumentsIDS();
for (int i = 0; i < documentIDs.size(); i++) {
Document doc = documentsHash.get(documentIDs.get(i));
System.out.println("Processing Document " + doc.getId() + "From class " + doc.getOrginalCluster() );
ArrayList<Sentence> sentencesList = doc.getSentences();
sentencesCount += sentencesList.size();
for (int sentenceIndex = 0; sentenceIndex < sentencesList.size(); sentenceIndex++) {
Sentence currentSentence = sentencesList.get(sentenceIndex);
ArrayList<Word> currentSentenceWords = currentSentence.getWords();
Word previousWord = null;
Word currentWord = null;
for (int wordIndex = 0; wordIndex < currentSentenceWords.size(); wordIndex++) {
currentWord = currentSentenceWords.get(wordIndex);
if (wordsCount.containsKey(currentWord.getContent())){
wordsCount.put(currentWord.getContent(), wordsCount.get(currentWord.getContent())+1);
}else{
numberOfUniqueWords++;
wordsCount.put(currentWord.getContent(),1);
}
if((previousWord != null) && (currentWord != null)){
String edgeID = previousWord.getContent()+"_"+currentWord.getContent();
if(edgesCount.containsKey(edgeID)){
edgesCount.put(edgeID, edgesCount.get(edgeID)+1);
}else{
numberOfEdges++;
edgesCount.put(edgeID, 1);
}
}
previousWord = currentWord;
}//end looping for words
}//end looping for sentences
}//end looping for documents
System.out.println("********************************");
System.out.println("Number of sentences = " + this.sentencesCount);
System.out.println("Number of words = "+ numberOfUniqueWords);
System.out.println("Number of edges = " + numberOfEdges);
System.out.println("*********************************");
} |
1469ca98-49f7-4941-a66a-8a7fff8db3d3 | 9 | @Override
public String toString() {
return "Remarks {"
+ (extReferences != null ? " extReferences [" + extReferences + "]" : "")
+ (cls != null ? " cls [" + cls + "]" : "")
+ (idx != null ? " idx [" + idx + "]" : "")
+ (recommendedValue != null ? " recommendedValue [" + recommendedValue + "]" : "")
+ (quality != null ? " quality [" + quality + "]" : "")
+ (legacyReleasability != null ? " legacyReleasability [" + legacyReleasability + "]" : "")
+ (value != null ? " value [" + value + "]" : "")
+ (remarks != null ? " remarks [" + remarks + "]" : "")
+ (availability != null ? " availability [" + availability + "]" : "")
+ "}";
} |
dd5f0689-66eb-4d31-97d1-0fa5fa7d0e69 | 3 | @Override
public void withdraw(String accountId, double amount) throws InvalidParamException, OverdraftException {
MethodResponse response = this.stub.sendMethodRequest("withdraw",
new Class[]{String.class, double.class},
new Object[]{accountId, amount});
Throwable t = response.getThrowable();
if (t != null) {
if (InvalidParamException.check(t)) {
throw new InvalidParamException(t.getMessage());
} else if (OverdraftException.check(t)) {
throw new OverdraftException(t.getMessage());
} else {
throw new RuntimeException("Remote Exception", t);
}
}
} |
1b2d004a-be61-4fd5-9cb4-0deae68099b5 | 6 | public static void startupCppTranslate() {
{ Object old$Module$000 = Stella.$MODULE$.get();
Object old$Context$000 = Stella.$CONTEXT$.get();
try {
Native.setSpecial(Stella.$MODULE$, Stella.$STELLA_MODULE$);
Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get())));
if (Stella.currentStartupTimePhaseP(2)) {
_StartupCppTranslate.helpStartupCppTranslate1();
_StartupCppTranslate.helpStartupCppTranslate2();
}
if (Stella.currentStartupTimePhaseP(4)) {
_StartupCppTranslate.helpStartupCppTranslate3();
}
if (Stella.currentStartupTimePhaseP(6)) {
Stella.finalizeClasses();
}
if (Stella.currentStartupTimePhaseP(7)) {
_StartupCppTranslate.helpStartupCppTranslate4();
_StartupCppTranslate.helpStartupCppTranslate5();
Stella.defineFunctionObject("CPP-TRANSLATE-ACTUAL-PARAMETERS", "(DEFUN (CPP-TRANSLATE-ACTUAL-PARAMETERS CONS) ((TREE CONS)))", Native.find_java_method("edu.isi.stella.Cons", "cppTranslateActualParameters", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("CPP-TRANSLATE-VARIABLE-LENGTH-ACTUALS", "(DEFUN (CPP-TRANSLATE-VARIABLE-LENGTH-ACTUALS CONS) ((ACTUALS CONS) (METHOD METHOD-SLOT)))", Native.find_java_method("edu.isi.stella.Cons", "cppTranslateVariableLengthActuals", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons"), Native.find_java_class("edu.isi.stella.MethodSlot")}), null);
Stella.defineFunctionObject("CPP-TRANSLATE-CALL-METHOD-SETTER", "(DEFUN (CPP-TRANSLATE-CALL-METHOD-SETTER CONS) ((TREE CONS)))", Native.find_java_method("edu.isi.stella.Cons", "cppTranslateCallMethodSetter", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("CPP-CREATE-OVERLOADED-FUNCTION-NAME", "(DEFUN (CPP-CREATE-OVERLOADED-FUNCTION-NAME SYMBOL) ((FUNCTIONNAME SYMBOL) (CLASSTYPE TYPE)))", Native.find_java_method("edu.isi.stella.Symbol", "cppCreateOverloadedFunctionName", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Surrogate")}), null);
Stella.defineFunctionObject("CPP-TRANSLATE-METHOD-CALL", "(DEFUN (CPP-TRANSLATE-METHOD-CALL CONS) ((TREE CONS) (REFERENCED? BOOLEAN)))", Native.find_java_method("edu.isi.stella.Cons", "cppTranslateMethodCall", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons"), java.lang.Boolean.TYPE}), null);
Stella.defineFunctionObject("CPP-TRANSLATE-NORMAL-METHOD-CALL", "(DEFUN (CPP-TRANSLATE-NORMAL-METHOD-CALL CONS) ((METHODNAME SYMBOL) (OWNER TYPE) (ARGUMENTS CONS) (REFERENCED? BOOLEAN)))", Native.find_java_method("edu.isi.stella.Symbol", "cppTranslateNormalMethodCall", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Surrogate"), Native.find_java_class("edu.isi.stella.Cons"), java.lang.Boolean.TYPE}), null);
Stella.defineFunctionObject("CPP-TRANSLATE-DEFINED?-METHOD-CALL", "(DEFUN (CPP-TRANSLATE-DEFINED?-METHOD-CALL CONS) ((ARGUMENTTYPE TYPE) (ARGUMENT OBJECT) (NULL? BOOLEAN)))", Native.find_java_method("edu.isi.stella.Surrogate", "cppTranslateDefinedPMethodCall", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Surrogate"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE}), null);
Stella.defineFunctionObject("CPP-TRANSLATE-NTH-METHOD-CALL", "(DEFUN (CPP-TRANSLATE-NTH-METHOD-CALL CONS) ((OPERATOR SYMBOL) (OWNER TYPE) (ARGUMENTS CONS)))", Native.find_java_method("edu.isi.stella.Symbol", "cppTranslateNthMethodCall", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Surrogate"), Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("CPP-TRANSLATE-AREF-METHOD-CALL", "(DEFUN (CPP-TRANSLATE-AREF-METHOD-CALL CONS) ((OPERATOR SYMBOL) (OWNER TYPE) (ARGUMENTS CONS)))", Native.find_java_method("edu.isi.stella.Symbol", "cppTranslateArefMethodCall", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Surrogate"), Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("CPP-TRANSLATE-CODE-SIGNATURE", "(DEFUN (CPP-TRANSLATE-CODE-SIGNATURE CONS) ((SIGNATURE CONS)))", Native.find_java_method("edu.isi.stella.Cons", "cppTranslateCodeSignature", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("CPP-TRANSLATE-METHOD-CODE-SIGNATURE", "(DEFUN (CPP-TRANSLATE-METHOD-CODE-SIGNATURE CONS) ((SIGNATURE CONS)))", Native.find_java_method("edu.isi.stella.Cons", "cppTranslateMethodCodeSignature", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("CPP-TRANSLATE-CALL-FUNCTION-CODE", "(DEFUN (CPP-TRANSLATE-CALL-FUNCTION-CODE CONS) ((TREE CONS)))", Native.find_java_method("edu.isi.stella.Cons", "cppTranslateCallFunctionCode", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("CPP-TRANSLATE-CALL-METHOD-CODE", "(DEFUN (CPP-TRANSLATE-CALL-METHOD-CODE CONS) ((TREE CONS)))", Native.find_java_method("edu.isi.stella.Cons", "cppTranslateCallMethodCode", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("GET-LAST-N-ELEMENTS", "(DEFUN (GET-LAST-N-ELEMENTS CONS) ((LIST CONS) (N INTEGER)))", Native.find_java_method("edu.isi.stella.Cons", "getLastNElements", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons"), java.lang.Integer.TYPE}), null);
Stella.defineFunctionObject("CPP-YIELD-UNUSED-DUMMY-ARGS", "(DEFUN (CPP-YIELD-UNUSED-DUMMY-ARGS CONS) ((METHOD METHOD-SLOT) (ARGS CONS)))", Native.find_java_method("edu.isi.stella.MethodSlot", "cppYieldUnusedDummyArgs", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.MethodSlot"), Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("CPP-TRANSLATE-FUNCTION-CALL", "(DEFUN (CPP-TRANSLATE-FUNCTION-CALL CONS) ((TREE CONS) (METHOD METHOD-SLOT)))", Native.find_java_method("edu.isi.stella.Cons", "cppTranslateFunctionCall", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons"), Native.find_java_class("edu.isi.stella.MethodSlot")}), null);
Stella.defineFunctionObject("CPP-TRANSLATE-OPERATOR-TREE", "(DEFUN (CPP-TRANSLATE-OPERATOR-TREE CONS) ((TREE CONS)))", Native.find_java_method("edu.isi.stella.Cons", "cppTranslateOperatorTree", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("CPP-TRANSLATE-OPERATOR-CALL", "(DEFUN (CPP-TRANSLATE-OPERATOR-CALL CONS) ((OPERATORNAMES CONS) (ARGUMENTS CONS) (ARITY INTEGER)))", Native.find_java_method("edu.isi.stella.Cons", "cppTranslateOperatorCall", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons"), Native.find_java_class("edu.isi.stella.Cons"), java.lang.Integer.TYPE}), null);
Stella.defineFunctionObject("CPP-TRANSLATE-HARDCODED-SYMBOL-REFERENCE", "(DEFUN (CPP-TRANSLATE-HARDCODED-SYMBOL-REFERENCE CONS) ((OPERATOR SYMBOL) (OFFSET INTEGER)))", Native.find_java_method("edu.isi.stella.Symbol", "cppTranslateHardcodedSymbolReference", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Symbol"), java.lang.Integer.TYPE}), null);
Stella.defineFunctionObject("STARTUP-CPP-TRANSLATE", "(DEFUN STARTUP-CPP-TRANSLATE () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella._StartupCppTranslate", "startupCppTranslate", new java.lang.Class [] {}), null);
{ MethodSlot function = Symbol.lookupFunction(Stella.SYM_STELLA_STARTUP_CPP_TRANSLATE);
KeyValueList.setDynamicSlotValue(function.dynamicSlots, Stella.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("_StartupCppTranslate"), Stella.NULL_STRING_WRAPPER);
}
}
if (Stella.currentStartupTimePhaseP(8)) {
Stella.finalizeSlots();
Stella.cleanupUnfinalizedClasses();
}
if (Stella.currentStartupTimePhaseP(9)) {
Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("/STELLA")))));
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *CPP-TRUE-STRING-WRAPPER* STRING-WRAPPER (WRAP-LITERAL \"TRUE\") :PUBLIC? FALSE :DOCUMENTATION \"Wrapped TRUE string, used to reduce consing.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *CPP-FALSE-STRING-WRAPPER* STRING-WRAPPER (WRAP-LITERAL \"FALSE\") :PUBLIC? FALSE :DOCUMENTATION \"Wrapped FALSE string, used to reduce consing.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *DUMMYDECLARATIONS* CONS NULL :DOCUMENTATION \"Temporary List of declarations for unused return parameters\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *CURRENTDUMMYINDEX* INTEGER NULL-INTEGER :DOCUMENTATION \"Current index of dummy parameter for unused return value\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *OPERATOR-TABLE* KEY-VALUE-LIST (DICTIONARY @KEY-VALUE-LIST (QUOTE ++) (CONS (WRAP-LITERAL \"++\") NIL) (QUOTE --) (CONS (WRAP-LITERAL \"--\") NIL) (QUOTE +) (CONS (WRAP-LITERAL \"+\") NIL) (QUOTE -) (CONS (WRAP-LITERAL \"-\") NIL) (QUOTE *) (CONS (WRAP-LITERAL \"*\") NIL) (QUOTE /) (CONS (WRAP-LITERAL \"/\") NIL) (QUOTE EQ?) (CONS (WRAP-LITERAL \"==\") NIL) (QUOTE !=) (CONS (WRAP-LITERAL \"!=\") NIL) (QUOTE >) (CONS (WRAP-LITERAL \">\") NIL) (QUOTE >=) (CONS (WRAP-LITERAL \">=\") NIL) (QUOTE =>) (CONS (WRAP-LITERAL \">=\") NIL) (QUOTE <) (CONS (WRAP-LITERAL \"<\") NIL) (QUOTE =<) (CONS (WRAP-LITERAL \"<=\") NIL) (QUOTE <=) (CONS (WRAP-LITERAL \"<=\") NIL) (QUOTE AND) (CONS (WRAP-LITERAL \"&&\") NIL) (QUOTE OR) (CONS (WRAP-LITERAL \"||\") NIL) (QUOTE NOT) (CONS (WRAP-LITERAL \"!\") NIL) (QUOTE CHOOSE) (CONS (WRAP-LITERAL \"?\") (CONS (WRAP-LITERAL \":\") NIL))) :DOCUMENTATION \"Mapping from STELLA operators to C++ operators\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *CPP-RESERVED-WORD-TABLE* (STRING-HASH-TABLE OF STRING STRING-WRAPPER) (CPP-CREATE-RESERVED-WORD-TABLE))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *CPP-CURRENT-UNIT-MODULE* MODULE NULL :DOCUMENTATION \"Home module of the currently translated unit. Needed for\nproper name translation for units whose home module is different than the\nfile module (occurs in some PowerLoom files - I thought we had outlawed that).\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *CPP-CHARACTER-SUBSTITUTION-TABLE* STRING (CPP-CREATE-CHARACTER-SUBSTITUTION-TABLE))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *CPP-NAME-QUALIFICATION-MODE* KEYWORD :CLEVER)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *CPP-NAMESPACE-SEPARATOR* STRING \"::\")");
}
} finally {
Stella.$CONTEXT$.set(old$Context$000);
Stella.$MODULE$.set(old$Module$000);
}
}
} |
ad3a9add-c3fd-421b-91af-f4c752ad1883 | 6 | public void leesQuizzenVanBestand(OpdrachtCatalogus opdrachtCatalogus, QuizCatalogus quizCatalogus){
File file = new File("bestanden/quizzen");
//
try{
Scanner scanner = new Scanner(file);
while (scanner.hasNext()){
List<Opdracht> opdrachten = new ArrayList<Opdracht>();
String lijn = scanner.nextLine();
String [] velden = lijn.split(",");
int id = Integer.parseInt(velden[0]);
int aantalDeelnames=Integer.parseInt(velden[1]);
String leerjaarNaam=velden[2];
Klas leerjaar= Klas.valueOf(leerjaarNaam);
String onderwerp=velden[5];
String quizStatusNaam = velden[6];
QuizStatus quizStatus= QuizStatus.valueOf(quizStatusNaam);
String leraarNaam=velden[3]+velden[4];
Leraar leraar = Leraar.valueOf(leraarNaam);
List<Integer>ids = new ArrayList<Integer>();
for(int i=7; i< velden.length;i++){
ids.add(Integer.parseInt(velden[i]));
}
for(int i = 0; i< ids.size(); i++){
opdrachten.add(this.getBepaaldeOpdrachten(ids.get(i), opdrachtCatalogus));
}
Quiz quiz = new Quiz(id,aantalDeelnames, leerjaar, leraar, onderwerp, quizStatus, opdrachten);
quizCatalogus.getQuizzen().add(quiz);
}
if (scanner!=null){
scanner.close();
}
}
catch(FileNotFoundException ex){
System.out.println("bestand niet gevonden");
}
catch(Exception ex){
System.out.println(ex.getMessage());
}
} |
918709ea-db5d-4573-a6c5-0a005648fc53 | 3 | public Produto getProduto(String nomeOUcodigo) {
for (Produto p : produtos) {
if (p.getNome().equalsIgnoreCase(nomeOUcodigo) || p.getCodigo().equalsIgnoreCase(nomeOUcodigo)) {
return p;
}
}
return null;
} |
73765737-f844-4d2f-9c11-15155f38992f | 4 | public static void rename(Automaton a) {
State[] s = a.getStates();
int maxId = s.length - 1;
Set untaken = new HashSet(), reassign = new HashSet(Arrays.asList(s));
for (int i = 0; i <= maxId; i++)
untaken.add(new Integer(i));
for (int i = 0; i < s.length; i++)
if (untaken.remove(new Integer(s[i].getID())))
reassign.remove(s[i]);
// Now untaken has the untaken IDs, and reassign has the
// states that need reassigning.
s = (State[]) reassign.toArray(new State[0]);
Iterator it = untaken.iterator();
for (int i = 0; i < s.length; i++) {
s[i].setID(((Integer) it.next()).intValue());
}
} |
e2227fa3-5d9e-4d66-a03f-e7fe58dd1004 | 2 | public static Collection<User> getUsers()
{
List<User> users = new LinkedList<User>();
try
{
String sql = "SELECT user_id,name from user_table";
PreparedStatement ps = Connect.getConnection().getPreparedStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next())
users.add(new User(rs.getInt(1), rs.getString(2)));
}
catch (SQLException e)
{
e.printStackTrace();
}
return users;
} |
5039aee0-f6fd-47b2-b4ad-6ef9afc7eddc | 6 | @Override
public void createFromXML(NodeList attributes) {
for(int i = 0; i < attributes.getLength(); i++) {
Node node = attributes.item(i);
if(node.getNodeType() == Node.ELEMENT_NODE) {
Node value = node.getFirstChild();
if(node.getNodeName().equalsIgnoreCase("ActorType")) {
actorType = value.getNodeValue();
}
else if(node.getNodeName().equalsIgnoreCase("ActorName")) {
actorName = value.getNodeValue();
}
else if(node.getNodeName().equalsIgnoreCase("Allegiance")) {
allegiance = value.getNodeValue();
}
else if(node.getNodeName().equalsIgnoreCase("ExpValue")) {
expValue = Integer.parseInt(value.getNodeValue());
}
}
}
} |
7c9eb481-91f9-4d6e-9e4f-51dad598bc5b | 1 | public static void rowStringValues(String row[], int[] idx, String[] vals) {
for (int i = 0; i < vals.length; i++) {
vals[i] = row[idx[i]];
}
} |
6e89c81b-729c-49ca-8671-061df8c6f897 | 8 | public static boolean literalEqlP(Stella_Object x, Stella_Object y) {
if (((x != null) &&
Stella_Object.isaP(x, Stella.SGT_STELLA_BOOLEAN_WRAPPER)) ||
((y != null) &&
Stella_Object.isaP(y, Stella.SGT_STELLA_BOOLEAN_WRAPPER))) {
return (((((BooleanWrapper)(x)) == null) &&
(!BooleanWrapper.coerceWrappedBooleanToBoolean(((BooleanWrapper)(y))))) ||
(((((BooleanWrapper)(y)) == null) &&
(!BooleanWrapper.coerceWrappedBooleanToBoolean(((BooleanWrapper)(x))))) ||
Stella_Object.eqlP(x, y)));
}
return (Stella_Object.eqlP(x, y));
} |
f6294592-2fc9-468d-8ba6-a5b3e0037923 | 0 | public void setName(String value) {
this.name = value;
} |
c3d49e29-e40e-45a6-b7da-9411f9172f58 | 4 | public void run() {
long lastTime = System.nanoTime();
double nsPerTick = 1000000000.0 / 60.0;
double time = 0;
long lastSecond = System.currentTimeMillis();
this.requestFocus();
while(running){
long now = System.nanoTime();
time += (now - lastTime) / nsPerTick;
lastTime = now;
boolean render = true;
while(time >= 1){
tick();
time -= 1;
render = true;
}
if(render)render();
if(System.currentTimeMillis() - lastSecond > 1000){
lastSecond += 1000;
System.out.println("FPS - " +renders +", TICKS - " + ticks);
ticks = renders = 0;
}
}
} |
08de6030-0a1f-4650-ac86-5facb248f182 | 2 | public String printParkInfo() {
String txt="";
if(ParkManage.getInstance().getParkList().size() == 0) {
txt="目前没有创建任何停车场,请先创建停车场!";
return txt;
}
int emptyNum = 0;
int totalNum = 0;
txt= txt + "-----------------------------------------"+ "\n";
for(int i = 0; i < ParkManage.getInstance().getParkList().size(); i ++) {
Park park = ParkManage.getInstance().getParkList().get(i);
txt= txt + "停车场编号:" + park.getCode() + "\n";
txt= txt + "停车场编号:" + park.getParkName() + "\n";
txt= txt + " 车位数:" + park.getTotalNum() + "\n";
txt= txt + " 空位数:" + park.getEmptyNum() + "\n";
emptyNum += park.getEmptyNum();
totalNum += park.getTotalNum();
}
txt= txt +"-----------------------------------------"+"\n";
txt= txt + "共计车位数:" + totalNum +"\n" ;
txt= txt + "共计空位数:" + emptyNum +"\n" ;
return txt;
} |
a198c3d3-e3ad-460f-80a4-a4f3dba363ae | 4 | public CtConstructor[] getDeclaredConstructors() {
CtMember.Cache memCache = getMembers();
CtMember cons = memCache.consHead();
CtMember consTail = memCache.lastCons();
int n = 0;
CtMember mem = cons;
while (mem != consTail) {
mem = mem.next();
CtConstructor cc = (CtConstructor)mem;
if (cc.isConstructor())
n++;
}
CtConstructor[] result = new CtConstructor[n];
int i = 0;
mem = cons;
while (mem != consTail) {
mem = mem.next();
CtConstructor cc = (CtConstructor)mem;
if (cc.isConstructor())
result[i++] = cc;
}
return result;
} |
3f031b3f-195f-4966-b47b-2be6089ebb94 | 3 | public static void clearBodies(){
Array<Body> bodies = new Array<Body>();
Objects.world.getBodies(bodies);
for(int i = 0; i < bodies.size; i++){
if(bodies.get(i) != null ){
if(bodies.get(i).getUserData() != null){
Objects.world.destroyBody(bodies.get(i));
}
}
}
} |
2e8e2a89-9715-4fe3-ab36-e375bc2ad8f7 | 3 | private long getTime() {
switch (type) {
case WALL_TIME:
return getWallTime();
case CPU_TIME:
return getCpuTime();
case USER_TIME:
return getUserTime();
default:
break;
}
return getCpuTime();
} |
07bd9763-c68d-4be2-b44d-d13d66c57d97 | 3 | private void jBtnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnDeleteActionPerformed
// TODO add your handling code here:
try {
String sql = "DELETE FROM productos_has_pedidos WHERE pedidos_idpedidos = ? AND productos_idproductos = ? ";
String sql1 = "SELECT descuento FROM pedidos WHERE idpedidos = ? ";
String sql2 = "UPDATE pedidos SET precio_total = ? WHERE idpedidos = ? ";
String sql3 = "UPDATE productos SET cantidad = cantidad + ? WHERE idproductos = ?";
Connection conn = Conexion.GetConnection();
PreparedStatement ps = conn.prepareStatement(sql);
PreparedStatement ps1 = conn.prepareStatement(sql1);
PreparedStatement ps2 = conn.prepareStatement(sql2);
PreparedStatement ps3 = conn.prepareStatement(sql3);
//Borra producto del pedido
ps.setString(1, (String) tmPed.getValueAt(jTablePedidos.getSelectedRow(), 0));
ps.setString(2, (String) jTablePedHas.getValueAt(jTablePedHas.getSelectedRow(), 0));
ps.execute();
//Regres la cantidad a la tabla productos
ps3.setString(1, (String) jTablePedHas.getValueAt(jTablePedHas.getSelectedRow(), 3));
ps3.setString(2, (String) jTablePedHas.getValueAt(jTablePedHas.getSelectedRow(), 0));
ps3.execute();
cargarPedHas();
//Calcula el precio actual
Double precio = 0.0, desc, total;
int rows = jTablePedHas.getRowCount();
for (int j = 0; j < rows; j++) {
precio += (Double.parseDouble((String) jTablePedHas.getValueAt(j, 4)));
}
//Obtiene el descuento del pedido
ps1.setString(1, tmPed.getValueAt(jTablePedidos.getSelectedRow(), 0).toString());
Pedidos = ps1.executeQuery();
Pedidos.next();
desc = Pedidos.getDouble(1);
if (desc == 0.0) {
total = precio;
} else {
total = (1 - (desc / 100) * precio);
}
System.out.println(total);
ps2.setDouble(1, total);
ps2.setString(2, getSelectedPedido());
ps2.executeUpdate();
clearPedidos();
cargarPedidos();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}//GEN-LAST:event_jBtnDeleteActionPerformed |
148ada43-5e8c-447f-8724-f331f09a7fb6 | 2 | private void createGameSelector(java.util.List<GameToSelect> gamesToSelect) {
JPanel container = new JPanel(new FlowLayout());
final JComboBox<GameToSelect> combo = new JComboBox<GameToSelect>();
combo.setSize(100, 20);
for(GameToSelect gameToSelect : gamesToSelect)
combo.addItem(gameToSelect);
container.add(combo);
JButton playButton = new JButton("Play");
playButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GameToSelect selected = (GameToSelect) combo.getSelectedItem();
//Appel WS service_game
try {
String xml_data = WebRequester.sendDataRetrivingRequest(urlToGetData, userId, selected.gameId);
(LoginWindow.this).setVisible(false);
new MainControler(xml_data);
} catch (UnsupportedEncodingException e1) {
statutLabel.setText("Error on game retrieving");
LoginWindow.this.repaint();
e1.printStackTrace();
}
}
});
container.add(playButton);
panel.add(container);
this.setSize(300, 200);
panel.repaint();
} |
4a5f8f2c-80d5-4b06-950a-80d951cbfc75 | 2 | public boolean crearConexion(String db) {
boolean encontrado = false;
if (db.equals(ControladorServidor.BD_PERSONAL)) {
factory = new ConnectionFactory(
ControladorServidor.ARCHIVO_POSTGRESQL);
System.out.println("DEBUG: Creada connectionFactory con Postgres!");
encontrado = true;
} else if (db.equals(ControladorServidor.BD_FACTURACION)) {
factory = new ConnectionFactory(
ControladorServidor.ARCHIVO_FIREBIRD);
System.out.println("DEBUG: Creada connectionFactory con Firebird!");
encontrado = true;
}
return encontrado;
} |
5d49fb68-f5df-4001-bdaf-e7743dc62b96 | 0 | @Override
public String toString() {
return "[Object of " + getClass().getName() + "]";
} |
e9332cef-47b6-4a8b-bcc8-dc56d75fe9b8 | 9 | @Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
System.out.println("Move up");
break;
case KeyEvent.VK_DOWN:
currentSprite = characterDown;
if (robot.isJumped() == false) {
robot.setDucked(true);
robot.setSpeedX(0);
}
break;
case KeyEvent.VK_LEFT:
robot.moveLeft();
robot.setMovingLeft(true);
break;
case KeyEvent.VK_RIGHT:
robot.moveRight();
robot.setMovingRight(true);
break;
case KeyEvent.VK_SPACE:
robot.jump();
break;
case KeyEvent.VK_CONTROL:
if (robot.isDucked() == false && robot.isJumped() == false)
robot.shoot();
break;
}
} |
69344007-1267-4a4f-88c7-c1576b4a7696 | 8 | public boolean IsSimilarTo(Cluster other, double overlapDegree) {
assert(other != null);
// ------------------------------------------------
// Find the common documents. If there are only a few documents,
// a linear search is used; otherwise the search uses a hash table.
int common = 0;
if((documents_.size() <= 3) &&
(other.documents_.size() <= 3)) {
// Few documents case, do a linear search.
for(int i = 0; i < documents_.size(); i++) {
Document doc = documents_.get(i);
if(other.documents_.contains(doc)) {
common++;
}
}
}
else {
// Many documents case, use a hash table.
Hashtable<Document, Document> hash = new Hashtable<Document, Document>();
int count = documents_.size();
for(int i = 0; i < count; i++) {
Document doc = documents_.get(i);
hash.put(doc, doc);
}
// Check which of the documents from the other clusters
// are found in the hash table.
count = other.documents_.size();
for(int i = 0; i < count; i++) {
if(hash.containsKey(other.documents_.get(i))) {
common++;
}
}
}
return ((double)common / (double)documents_.size()) > overlapDegree &&
((double)common / (double)other.documents_.size()) > overlapDegree;
} |
65ae4c1c-d8a5-4f5d-9707-16de80a0227c | 5 | public static void main(String args[]) {
Game g = new Othello();
Timer t = new Timer(g);
Timer t2 = new Timer(null);
t.setHours(t.m_hour_test);
if (t.getHours() == t.m_hour_test) {
System.out.println("Hour Set Success " + t.getHours());
}
t.setMinutes(t.m_minute_test);
if (t.getHours() == t.m_minute_test) {
System.out.println("Hour Set Success " + t.getHours());
}
t.setSeconds(t.m_second_test);
if (t.getHours() == t.m_second_test) {
System.out.println("Hour Set Success " + t.getHours());
}
if (t.setRunning() == true) {
System.out.println("Set Running Success");
}
t.secondInterval();
if (t.getSeconds() == (t.m_second_test + 1)) {
System.out.println("Added Second Successfully");
}
t.run();
System.out.println(t.toString());
} |
ea2f826a-3b9e-433d-bc20-27a1f171f088 | 6 | public void setBlockBoundsBasedOnState(IBlockAccess par1IBlockAccess, int par2, int par3, int par4)
{
int var5 = par1IBlockAccess.getBlockMetadata(par2, par3, par4);
switch (getDirectionMeta(var5))
{
case 0:
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.25F, 1.0F);
break;
case 1:
this.setBlockBounds(0.0F, 0.75F, 0.0F, 1.0F, 1.0F, 1.0F);
break;
case 2:
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.25F);
break;
case 3:
this.setBlockBounds(0.0F, 0.0F, 0.75F, 1.0F, 1.0F, 1.0F);
break;
case 4:
this.setBlockBounds(0.0F, 0.0F, 0.0F, 0.25F, 1.0F, 1.0F);
break;
case 5:
this.setBlockBounds(0.75F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
}
} |
63cd711a-b6a8-4d22-a5bf-d689531bf775 | 1 | @Override
public JSONObject main(Map<String, String> params, Session session)
throws Exception {
JSONObject rtn = new JSONObject();
long day = Long.parseLong(params.get("timestamp"));
day = DateUtil.getStartOfDay(day);
rtn.put("rtnCode", this.getRtnCode(200));
List<Appointment> aAppt = Appointment.findByDay(session.getActiveUserId(), day);
JSONArray apptJa = new JSONArray();
for(Appointment iAppt:aAppt) {
apptJa.put(iAppt.toJson(session.getActiveUserId()));
}
rtn.put("aAppointment", apptJa);
return rtn;
} |
299d4250-fa50-4e66-9584-514a55f43f3d | 2 | public boolean isInCorrectFormForConversion(Automaton automaton) {
if (hasSingleFinalState(automaton)
&& hasTransitionsInCorrectForm(automaton)) {
return true;
}
return false;
} |
d6096668-f700-4438-b5ee-230bbaaaa69a | 4 | public void FillRectW(int X, int Y, int H, int W, byte with)
{
for (int i1 = Math.max(X,0); i1 < Math.min(X+W,w); i1 ++)
{
for (int i2 = Math.max(Y,0); i2 < Math.min(Y+H,h); i2 ++)
{
if (cellData[i1][i2]!=CRYSTAL&&cellData[i1][i2]!=ETHER)
cellData[i1][i2]=with;
}
}
} |
63053cb9-2a00-4c60-ae27-a68e59508b0d | 9 | private void file_search(String nickname, String query) throws IOException {
/* (Re)build list of files in directory */
File directory = new File(folder);
if (!directory.isDirectory()) {
gui.update("[Client] ERROR: Not a directory.");
return;
}
if (directory.listFiles().length == 0 || !open) {
return;
}
/* Search for file(s) matching query */
LinkedList<String> results = new LinkedList<String>();
File[] files = directory.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].toString().replaceAll(folder + "/", "").toLowerCase()
.contains(query.toLowerCase())) {
if (files[i].toString()
.charAt(files[i].toString().length() - 1) != '~' && files[i].isFile())
results.add(files[i].toString()
.replaceAll(folder + "/", ""));
}
}
if (results.isEmpty()) return;
/* Tell server to expect file list */
outToServer.writeInt(8);
/* Tell server who the file list is for */
outToServer.writeUTF(nickname);
/* Tell server how long the list is. */
outToServer.writeInt(results.size());
/* Send results */
for (String s : results) {
outToServer.writeUTF(s);
}
} |
f0e0a80b-2185-44d3-bd31-cdf1c33aeb6c | 5 | public byte[] read(int begin, int length) throws IOException {
if (!isAvaiable(begin, length)) {
throw new EOFException("Data not available " + "begin: " + begin + " length: " + length);
}
int filePieceIndex = findFilePieceIndex(begin);
FilePieceMapper filePiece = files.get(filePieceIndex);
byte[] block = new byte[length];
int readBytes = 0;
while (readBytes < length) {
RandomAccessFile raf = filePiece.getFile();
Long seek = filePiece.getFileOffset() + ((begin + readBytes) - filePiece.getPieceOffset());
raf.seek(seek);
int byteToRead = length - readBytes;
Long byteAvaiableInThisFile = raf.length() - seek;
Long byteAvaiableToRead = byteToRead < byteAvaiableInThisFile ? byteToRead : byteAvaiableInThisFile;
raf.readFully(block, readBytes, byteAvaiableToRead.intValue());
readBytes += byteAvaiableToRead.intValue();
if (byteAvaiableToRead.equals(byteAvaiableInThisFile) && readBytes < length) {
filePiece = files.get(++filePieceIndex);
}
}
return block;
} |
ed92c013-284a-498c-b77d-65e3c287a431 | 3 | private Token tokenFromXml(int status, String content) {
Token token = new Token();
try {
Error error = errorFromXml(status, content);
if(error != null) {
token.setError(error);
return token;
}
JAXBContext context = JAXBContext.newInstance(Hash.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
StringReader xml = new StringReader(content);
Hash hash = (Hash)unmarshaller.unmarshal(new StreamSource(xml));
token = new Token(status, content);
token.setValid(token.isOk() && hash.getToken().equals(VALID_TOKEN_MESSAGE));
}
catch(JAXBException e) {
e.printStackTrace();
}
return token;
} |
5c55e9ab-f1bb-4741-b066-c1d4d0d5f71a | 6 | public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html;charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("<!DOCTYPE html>\n");
out.write("<html>\n");
out.write(" <head>\n");
out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
out.write(" <title>JSP Page</title>\n");
out.write(" </head>\n");
out.write(" <body>\n");
out.write(" <a href=\"");
if (_jspx_meth_c_url_0(_jspx_page_context))
return;
out.write("\">Store</a>|<a href=\"ShowBookList.view\">Store</a>|<a href=\"addBook.jsp\">Store</a>\n");
out.write(" </body>\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
} |
94072c43-0990-4a5d-8649-d90abb3b378b | 2 | public void initConnection()
{
//---Get Connection----
try
{
//JNDI Lookups for connection to database through JDBC
Context ic = new InitialContext();
datasource = (DataSource) ic.lookup("java:comp/env/" + DATA_SOURCE_NAME);
connection = datasource.getConnection();
}
catch (NamingException ne)
{
System.out.println("Naming Exception in DatabaseConnector.java");
ne.printStackTrace();
}
catch (SQLException e)
{
System.out.println("SQL Exception in DatabaseConnector.java");
e.printStackTrace();
}
} |
ced64617-efbd-4ff7-8238-48a0d2b31844 | 9 | private void applyHighlighting(String content, int line) throws BadLocationException {
int startOffset = rootElement.getElement(line).getStartOffset();
int endOffset = rootElement.getElement(line).getEndOffset() - 1;
int lineLength = endOffset - startOffset;
int contentLength = content.length();
if (endOffset >= contentLength)
endOffset = contentLength - 1;
// check for multi line comments
// (always set the comment attribute for the entire line)
if (endingMultiLineComment(content, startOffset, endOffset)
|| isMultiLineComment()
|| startingMultiLineComment(content, startOffset, endOffset)) {
if (attributes.containsKey("comment"))
doc.setCharacterAttributes(startOffset, endOffset - startOffset + 1, attributes.get("comment"), true);
return;
}
// set default attributes for the line
if (attributes.containsKey("default"))
doc.setCharacterAttributes(startOffset, lineLength, attributes.get("default"), true);
// check for single line comment
int index = content.indexOf(';', startOffset);
if ((index > -1) && (index < endOffset)) {
if (attributes.containsKey("comment"))
doc.setCharacterAttributes(index, endOffset - index + 1, attributes.get("comment"), true);
endOffset = index - 1;
}
// check for tokens
checkForTokens(content, startOffset, endOffset);
} |
3637ab5b-a9a7-4bff-a7b4-a7c753f7e14e | 7 | synchronized void startLogging() {
if (fLoggingEnabled)
return;
//
// If the first log file doesn't exist or its content length is 0,
// then don't shit files. [V1.85]
//
if (!fFiles[0].exists() || readContent(0).length() == 0)
fFiles[0].delete();
else {
//
// Shift files
//
fFiles[fNoOfLogFiles-1].delete();
for (int i = fNoOfLogFiles - 2; i >= 0; i --)
fFiles[i].renameTo(fFiles[i+1]);
}
//
// Now create a FileWriter where
//
try {
fFileWriter = new FileWriter(fFiles[0]);
} catch (FileNotFoundException e) {
//
// If the file name contains illegal characters, this exception will happen
//
return;
} catch (IOException e) {
System.out.println(e.toString());
}
String timeStampHeader = fDateFormat.format(new Date()) + "\n";
try {
fFileWriter.write(timeStampHeader, 0, timeStampHeader.length());
fFileWriter.flush();
} catch (IOException e) {
System.out.println(e.toString());
}
fLoggingEnabled = true;
} |
93aeae8d-f23f-4616-947c-ebb599df5e78 | 0 | public Wrapping(int x) {
i = x;
} |
ac670d1a-4508-457c-853f-99cf1443396a | 8 | public double Cldj(int iy, int im, int id) throws palError {
long iyL, imL;
/* Month lengths in days */
final int mtab[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
TRACE("Cldj");
/* Validate year */
if (iy < -4699) {
Status = 1;
throw new palError(Status, "Cldj: Bad Year");
}
/* Validate month */
if ((im < 1) || (im > 12)) {
Status = 2;
throw new palError(Status, "Cldj: Bad Month");
}
/* Allow for leap year */
mtab[1] = (((iy % 4) == 0) && (((iy % 100) != 0) || ((iy % 400) == 0))) ? 29 : 28;
/* Validate day */
if (id < 1 || id > mtab[im - 1]) {
Status = 3;
throw new palError(Status, "Cldj: Bad Day");
}
/* Lengthen year and month numbers to avoid overflow */
iyL = iy;
imL = im;
ENDTRACE("Cldj");
/* Perform the conversion */
return ((1461L * (iyL - (12L - imL) / 10L + 4712L)) / 4L + (306L * ((imL + 9L) % 12L) + 5L) / 10L
- (3L * ((iyL - (12L - imL) / 10L + 4900L) / 100L)) / 4L + id - 2399904L);
} |
3ff99dce-104f-4708-8fa6-04d353c92220 | 2 | public SimpleFind(String args[]) {
// Get input from the console
String startingPath = ConsoleTools.getNonEmptyInput("Enter starting path: ");
String query = ConsoleTools.getNonEmptyInput("Enter string to find: ");
String[] fileExtensions = ConsoleTools.getSeriesOfInputs("Enter file extension to match: ");
while (fileExtensions.length <= 0) {
fileExtensions = ConsoleTools.getSeriesOfInputs("Enter file extension to match: ");
}
System.out.println("");
// Setup the Crawler
DirectoryCrawler crawler = new DirectoryCrawler();
crawler.setFileHandler(new SimpleFindFileContentsHandler(query,FileTools.LINE_ENDING_WIN));
crawler.setFileFilter(new FileExtensionFilter(fileExtensions));
crawler.setVerbose(false);
// Do the Crawl
System.out.println("STARTING...");
int status = crawler.crawl(startingPath);
if (status == DirectoryCrawler.SUCCESS) {
int totalMatches = ((SimpleFindFileContentsHandler) crawler.getFileHandler()).getTotalNumberOfMatches();
System.out.println("Total Matches Found: " + totalMatches);
}
System.out.println("DONE");
// java -classpath com.organic.maynard.jar com.organic.maynard.SimpleFind
} |
77b3d181-bf14-4dc1-930d-eebc93fe80d5 | 2 | public static void stop(String s) {
if (clips.get(s) == null)
return;
if (clips.get(s).isRunning())
clips.get(s).stop();
} |
25b4b9d6-c313-4007-8f85-41a7dacd6f3a | 2 | public Boolean teamIDExists(String userTeam, String userMatch){
try {
cs = con.prepareCall("{call GET_TEAMID(?,?)}");
cs.setString(1, userTeam);
cs.setString(2, userMatch);
if(!cs.executeQuery().next()){
return false;
}
} catch (SQLException e) {
e.printStackTrace();
}
return true;
} |
e38a5664-9827-47ed-8a2f-8de562930689 | 8 | private void assignStudentToCourse(Scanner sn) {
sn = new Scanner(new InputStreamReader(System.in));
Student newStudent = new Student();
System.out.print("Student first name: ");
String firstName = sn.next();
System.out.print("Student last name: ");
String lastName = sn.next();
System.out.print("Student id: ");
String id = sn.next();
newStudent.setFirstName(firstName);
newStudent.setLastName(lastName);
newStudent.setID(id);
System.out.print("Assign to course (yes/y or no/n): ");
String addNew = sn.next();
while (addNew.equals("y") || addNew.equals("yes"))
{
System.out.print("Assign to course (name): ");
String courseName = sn.next();
// System.out.print("Assign to session: ");
Course course = null;
for (Course c : prototypeCourses) {
if (c.getName().equals(courseName)) {
course = c;
break;
}
}
course.getStudents().add(newStudent);
newStudent.getCourses().add(course);
ArrayList<Session> currentCourseSessions = course.getSessions();
for (Session s : currentCourseSessions) {
System.out.print("Input attendance for session" + s.getSessionName() + "(T/F/MV): ");
String att = sn.next();
AttendanceEnum attEnum = null;
switch (att.toUpperCase()) {
case "T":
attEnum = AttendanceEnum.PRESENT;
break;
case "F":
attEnum = AttendanceEnum.ABSENT;
break;
case "MV":
attEnum = AttendanceEnum.MV;
}
s.getStudentAttendance().put(newStudent, attEnum);
}
System.out.print("Assign to course (yes/y or no/n): ");
addNew = sn.next();
}
prototypeStudents.add(newStudent);
} |
8746c28a-ddae-4aae-92e2-0c935eac2d90 | 5 | void setGreen(States newState, int duration) {
if (currentState == NONE) {
if(!constructionRoad.isEmpty()) {
Iterator<Pair<States,Car>> iter = constructionRoad.values().iterator();
iter.hasNext();
if(newState == iter.next().getKey()) {
currentState = newState;
nextState = newState;
waitUntil = currentTime;
askAgain = currentTime+duration;
} else {
nextState = newState;
waitUntil = currentTime+tB;
askAgain = waitUntil+duration;
}
} else {
currentState = newState;
nextState = newState;
waitUntil = currentTime;
askAgain = currentTime+duration;
}
} else if (newState == NONE ){
currentState = newState;
nextState = currentState;
waitUntil = currentTime+intervalBetweenCars;
askAgain = waitUntil+duration;
} else if (currentState != newState) {
currentState = NONE;
nextState = newState;
waitUntil = currentTime+tB;
askAgain = waitUntil+duration;
} else {
waitUntil = currentTime;
askAgain = currentTime+duration;
}
} |
9f090866-a61c-4942-80ae-116460dc4242 | 7 | public Creature(int t) {
super(true, 0);
type = t;
if(type == 1){
ManaCost = 2;
attack = 1;
toughness = 1;
Name = "Pig";
Description ="This is a Pig, it has 1 attack and 1 toughness. It has the ability 'Floop to disable Corn'.";
} else if(type == 2){
ManaCost = 2;
attack = 1;
toughness = 1;
Name = "Goat";
Description ="This is a Goat, it has 1 attack and 1 toughness. It has the ability 'Floop to disable Mountains'.";
} else if(type == 3){
ManaCost = 2;
attack = 1;
toughness = 1;
Name = "Cow";
Description ="This is a Cow, it has 1 attack and 1 toughness.";
} else if(type == 4){
ManaCost = 3;
attack = 2;
toughness = 3;
Name = "Husker Knight";
Description ="This is a Husker Knight, it has 2 attack and 3 toughness.";
} else if(type == 5){
ManaCost = 3;
attack = 3;
toughness = 2;
Name = "Archer Dan";
Description ="This is an Archer Dan, it has 3 attack and 2 toughness. It has the ability 'Can attack from Caves, but at a cost" +
" of -1/0'.";
} else if(type == 6){
ManaCost = 4;
attack = 1;
toughness = 1;
Name = "Ancient Scholar";
Description ="This is an Ancient Scholar, it has (base) 1 attack and 4 toughness. It has the ability 'Floop, with 3 Mana and" +
" a Library to gain +1/0 permanently'";
} else if(type == 7){
ManaCost = 5;
attack = 1;
toughness = 1;
Name = "Dragon";
Description ="This is a Dragon, it has 4 attack and 4 toughness. It has the ability 'Is not blocked by Castles'";
}
super.setManaCost(ManaCost);
} |
216e0c9e-76a3-420e-971b-974f4fd750b2 | 7 | @EventHandler(priority = EventPriority.MONITOR)
public void onSignBreak(BlockBreakEvent event) {
Material block = event.getBlock().getType();
Player player = event.getPlayer();
if ((block.equals(Material.SIGN_POST)) || (block.equals(Material.WALL_SIGN))) {
Sign sign = (Sign) event.getBlock().getState();
String[] line = sign.getLines();
String name = ChatColor.DARK_BLUE + "[Shop]";
if (line[0].equalsIgnoreCase(name)){
if (player.hasPermission("MyTownEcon.cmd.shop.remove")) {
String shopName = line[1];
String[] shops = Shops.getShopList();
String shop = null;
for (int i = 0; i < shops.length; i++) {
if (shops[i].equalsIgnoreCase(shopName)) {
shop = shops[i];
}
}
if (shop != null) {
Shops.setSignLocation(shop, "null");
player.sendMessage(ChatColor.GREEN + line[1] + " Removed!");
}
} else {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "You Dont Not Have Permission to Break Shop Sign!");
}
}
}
} |
14158687-2154-4856-aa3c-fb8da29aee86 | 2 | private int readZoomHeaders(SeekableStream fis, long fileOffset, int zoomLevels, boolean isLowToHigh) {
int level = 0;
BBZoomLevelHeader zoomLevelHeader;
if(zoomLevels < 1)
return 0;
// create zoom headers and data containers
zoomLevelHeaders = new ArrayList<BBZoomLevelHeader>();
// get zoom header information for each zoom levelsRead
for(int index = 0; index < zoomLevels; ++index) {
level = index + 1;
// read zoom level header - read error is returned as Runtime Exception
zoomLevelHeader = new BBZoomLevelHeader(fis, fileOffset, level, isLowToHigh);
zoomLevelHeaders.add(zoomLevelHeader);
fileOffset += BBZoomLevelHeader.ZOOM_LEVEL_HEADER_SIZE;
}
return level;
} |
f52c3bf1-440b-4cf1-ba13-809fb7f6d3b0 | 2 | @Override
public boolean isSoundbankSupported(Soundbank soundbank) {
for (Synthesizer s : theSynths)
if (!s.isSoundbankSupported(soundbank))
return false;
return true;
} |
9a04704b-24dc-4d7d-b5ea-dd73be1d7617 | 8 | public int getSearchCount(String colName, String search) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
StringBuilder sb = new StringBuilder();
sb.append("select count(*) from member where ");
sb.append(colName);
sb.append(" like '%");
sb.append(search);
sb.append("%'");
int cnt = 0;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sb.toString());
rs = pstmt.executeQuery();
if (rs.next()) {
cnt = rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return cnt;
} |
4f9d6437-7812-4b36-956d-fb0b2b7dc6c7 | 3 | private static List<TimeSerie> getNeighboursWithinRange(int index) {
List<TimeSerie> neighbours = new ArrayList<TimeSerie>();
for (int i = 0; i < distanceMatrix.length; i++) {
if (i != index) {
double distance = distanceMatrix[index][i];
if (distance < eps) {
neighbours.add(timeSeries.get(i));
}
}
}
return neighbours;
} |
e23f45b1-bb62-49fc-bf8d-6aee0310f4a4 | 1 | @Override
public void endConnecting() {
if( itemShown ){
parent.removeItem( line );
}
itemShown = false;
} |
9e0068fd-b9b9-45c2-8c84-586674d9c59b | 0 | public Object clone() {
return new Animation(frames, totalDuration);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.