text stringlengths 14 410k | label int32 0 9 |
|---|---|
*/
public void abandonColony(Colony colony) {
if (!requireOurTurn()) return;
Player player = freeColClient.getMyPlayer();
// Sanity check
if (colony == null || !player.owns(colony)
|| colony.getUnitCount() > 0) {
throw new IllegalStateException("Abandon bogus colony");
}
// Proceed to abandon
Tile tile = colony.getTile();
if (askServer().abandonColony(colony)
&& tile.getSettlement() == null) {
player.invalidateCanSeeTiles();
gui.setActiveUnit(null);
gui.setSelectedTile(tile, false);
}
} | 6 |
public HashSet<String> loadProductNameWords(String productName,
HashSet<String> words) {
// HashSet<String> words = new HashSet<String>();
String[] wordArray = productName.split(" ");
for (String word : wordArray) {
if (isNumeric(word) || word.equals(" ")) {
continue;
}
words.add(word.trim());
}
return words;
} | 3 |
private List<ReducerEstimatedJvmCost> estimateReducersMemory(List<Reducer> eReducers, InitialJvmCapacity gcCap) {
int fReducerNum = finishedConf.getMapred_reduce_tasks();
if(fReducerNum == 0)
return null;
List<ReducerEstimatedJvmCost> reducersJvmCostList = new ArrayList<ReducerEstimatedJvmCost>();
ReducerMemoryEstimator memoryEstimator = new ReducerMemoryEstimator(finishedConf, newConf, gcCap);
ReducerEstimatedJvmCost jvmCost;
//reducer number doesn't change
if(fReducerNum == newConf.getMapred_reduce_tasks()) {
for(int i = 0; i < fReducerNum; i++) {
//use the corresponding finished reducer to estimate the new reducer
//if input data is changed, this model needs modification
//currently, this model assumes the total input data is as same as the finished one
jvmCost = memoryEstimator.esimateJvmCost(job.getReducerList().get(i), eReducers.get(i));
reducersJvmCostList.add(jvmCost);
}
}
//reducer number changes
else {
for(int i = 0; i < newConf.getMapred_reduce_tasks(); i++) {
//use all the finished reducers' infos to estimate the new reducer
jvmCost = memoryEstimator.esimateJvmCost(job.getReducerList(), eReducers.get(i));
reducersJvmCostList.add(jvmCost);
}
}
return reducersJvmCostList;
} | 4 |
public synchronized HijackCanvas getCanvas() {
if (canvas != null) {
return canvas;
}
if (loader == null || loader.getApplet() == null || !(loader.getApplet().getComponentAt(100, 100) instanceof HijackCanvas)) {
return null;
}
return (HijackCanvas) loader.getApplet().getComponentAt(100, 100);
} | 4 |
public <ObjectType> ObjectType bindAll( final ObjectType object ) {
Class cl = object.getClass();
for ( final Method method : cl.getMethods() ) {
Listener annotation = method.getAnnotation( Listener.class );
if ( annotation != null ) {
if ( method.getParameterTypes().length != 1 ) {
throw new ListenerTypeMismatch( method, eventClass );
}
Class<?> type = annotation.on();
if ( type.equals( Object.class )) {
type = method.getParameterTypes()[0];
}
if ( !eventClass.isAssignableFrom( type )) {
if ( annotation.strict() )
throw new ListenerTypeMismatch( method, eventClass );
else
continue;
}
//noinspection unchecked
getListeners().add( new ObjectListenerWrapper<Event>( (Class<Event>) type, new IListener<Event>() {
public void handle( Event event ) {
try {
method.invoke( object, event );
} catch ( Exception e ) {
throw new RuntimeException( "Exception in Event Handler", e );
}
}
}, object ));
}
}
return object;
} | 8 |
public Fibonacci union(Fibonacci H1, Fibonacci H2) {
Fibonacci H = new Fibonacci();
//tarkistetaan, ettei kummankaan keon minimi ole null
if ((H1 != null) && (H2 != null)) {
//tehdään alustavasti H1:n minimistä H:n minimi
H.min = H1.min;
if (H.min != null) {
if (H2.min != null) {
//lisätään H2 uuteen kekoon laittamalla sen alkiot oikeille paikoille
H.min.right.left = H2.min.left;
H2.min.left.right = H.min.right;
H.min.right = H2.min;
H2.min.left = H.min;
//tarkistetaan, onko H2 minimi pienempi kuin H1:n minimi
if (H2.min.value < H1.min.value) {
H.min = H2.min;
}
}
} else {
H.min = H2.min;
}
//kasvatetaan uuden keon kokoa
H.size = H1.size + H2.size;
}
return H;
} | 5 |
public boolean intersect(int[] start, int[] off) {
int len = this.start.length;
boolean isIntersect = true;
for (int i = 0; i < len; i++) {
if ((this.start[i] >= start[i] + off[i] || this.start[i]
+ this.chunkStep[i] <= start[i])) {
isIntersect = false;
}
}
return isIntersect;
} | 3 |
@Override
public Point getTarget(GameState state) {
float[][] candidates = new float[3][5];
Point target = null;
int i = 0;
for(TargetingStrategy strategy : strategies) {
target = strategy.getTarget(state);
if(target != null) {
candidates[target.x][target.y] += weights[i];
}
++i;
}
float greatest = 0f;
target = null;
for(int x = 0; x < 3; x++) {
for(int y = 0; y < 5; y++) {
if(candidates[x][y] > greatest) {
target = new Point(x,y);
greatest = candidates[x][y];
}
}
}
return target;
} | 5 |
private String statusSimple() {
int activeHosts = 0;
for (Host host : hosts.values())
if (host.isRunning())
activeHosts++;
int numServices = 0;
for (Map<String, Service> map : services.values())
numServices += map.size();
int forwardingConnections = 0;
for (Connection connection : connections)
if (connection.isForwarding())
forwardingConnections++;
return activeHosts + " active hosts, " + numServices + " services, " + forwardingConnections + " forwarding connections";
} | 5 |
private int[] sevenSeg(double[] signalFFT, double Fs){
double areaTotal = ArithmanticUtil.sum(signalFFT) / Fs;
double segmentSize = areaTotal / 7;
double[] area = new double[7];
int[] interval = new int[8];
interval[0] = 0;
for(int i = 1; i < interval.length; i++)
interval[i] = signalFFT.length;
double offset = segmentSize / 1000;
int limit = 150;
for(int k = 0; k < area.length - 1; k++){
int iteration = 0;
while(area[k] < segmentSize - offset || area[k] > segmentSize + offset){
if(iteration < limit){
iteration++;
if(area[k] < segmentSize - offset){
interval[k + 1] = (int)Math.floor((interval[k+2] - interval[k+1])/2 + interval[k+1]);
area[k] = ArithmanticUtil.sum(signalFFT, interval[k], interval[k+1]) / Fs;
}
else if(area[k] > segmentSize + offset){
interval[k+2] = interval[k+1];
interval[k+1] = (int) Math.floor(interval[k+1] - (interval[k+1] - interval[k])/2);
area[k] = ArithmanticUtil.sum(signalFFT, interval[k], interval[k+1]) / Fs;
}
}
else{
break;
}
}
}
interval[7] = signalFFT.length;
//area[7] = ArithmanticUtil.sum(signalFFT, interval[7], interval[8]) / Fs;
return interval;
} | 7 |
private void doUpdateJH(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String jhId = StringUtil.toString(request.getParameter("jhId"));
if(!StringUtil.isEmpty(jhId)) {
ObjectMapper mapper = new ObjectMapper();
Map result = new HashMap();
try {
LianXiWoMen oldLXWM = manager.findJHById(jhId);
LianXiWoMen newLXWM = fetchLXWMInfoFromRequest(request);
int flag = manager.updateJH(newLXWM);
if(flag > 0) {
logger.info("#########更新工作机会成功,新联系方式是:"+newLXWM+"\n"+"旧工作机会是:"+oldLXWM);
result.put("success",true);
}else{
logger.info("#########更新工作机会失败,新工作机会是:"+newLXWM+"\n"+"旧工作机会是:"+oldLXWM);
request.setAttribute("errorMsg","更新工作机会失败");
result.put("success",false);
}
} catch (SQLException e) {
result.put("success",false);
request.setAttribute("errorMsg","更新工作机会失败");
logger.error("更新工作机会失败", e);
}finally {
String out =mapper.writeValueAsString(result);
PrintWriter pw = response.getWriter();
pw.print(out);
}
}
} | 3 |
public final void doVote(final String player) {
// Check Player exists!
OfflinePlayer thePlayer = Bukkit.getOfflinePlayer(player);
if (!thePlayer.hasPlayedBefore()) {
log.info(String.format(plugin.getMessages().getString("player.never.played"), player));
return;
}
// Player in die Heutige Voteliste aufnehmen, verhindert die ausgabe von mehr als einer Zeile beim Broadcast
plugin.addVote(player);
VoteHistory vote = new VoteHistory();
vote.setMinecraftUser(player);
if (plugin.getPluginConfig().isFixEcon() || plugin.getPluginConfig().isOnlyEcon()) {
vote.setEconAmmount(plugin.getPluginConfig().getFixEconAmmount());
vote.setEcon(true);
}
if (!plugin.getPluginConfig().isOnlyEcon()) {
NextVoteRadomItem item = new NextVoteRadomItem(plugin);
if (item.isEcon()) {
vote.setEconAmmount(vote.getEconAmmount() + item.getEcoAmount());
vote.setEcon(true);
} else {
vote.setAmmount(item.getAmount());
vote.setDamage(item.getDamage());
vote.setItem(true);
vote.setLocalName(item.getLokalName());
vote.setName(item.getName());
vote.setMaterial(item.getMaterial());
}
}
vote.setTime(new Timestamp(System.currentTimeMillis()));
vote.setPaid(payVote(thePlayer, vote));
database.save(vote);
doMessage(thePlayer, vote);
log.info(String.format(plugin.getMessages().getString("player.voted"), player));
} | 5 |
public FieldName(final GObject gObj, ArrayList<String> fieldNames, String type, GridPane gp, int row, HistoryManager hm) {
gp.add(new Label(LabelGrabber.getLabel("field.name.text") + ":"), 0, row);
textField = new FieldNameTextField();
this.fieldNames = fieldNames;
this.historyManager = hm;
this.gObj = gObj;
// Grab the fieldname if already set (which is the case when loading from FXML).
if (gObj.getFieldName() != null) {
textField.setText(gObj.getFieldName());
fieldNames.add(gObj.getFieldName());
} else {
//Set default field name
type = type.substring(0, 1).toLowerCase() + type.substring(1);
int count = 1;
while (fieldNames.contains(type + count)) {
count++;
}
textField.setText(type + count);
gObj.setFieldName(type + count);
fieldNames.add(type + count);
}
gp.add(textField, 1, row);
//Upon losing focus, save to the GObject
textField.focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observableValue, Boolean aBoolean, Boolean aBoolean2) {
if (!aBoolean2) {
historyManager.addHistory(new HistoryItem() {
String old = gObj.getFieldName();
String nnew = textField.getText();
@Override
public void revert() {
gObj.setFieldName(old);
textField.setText(old);
}
@Override
public void restore() {
gObj.setFieldName(nnew);
textField.setText(nnew);
}
@Override
public String getAppearance() {
return old + " -> " + nnew;
}
});
gObj.setFieldName(textField.getText());
}
}
});
} | 4 |
@Test
public void test2() {
xmlReader.setContentHandler(new DefaultHandler() {
private String currentQName;
private int number;
private int requiredNumber = 2;
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {
currentQName = qName;
if ("name".equals(currentQName)) {
++number;
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (number == requiredNumber && "name".equals(currentQName)) {
System.out.println(new String(ch, start, length));
}
}
});
} | 3 |
public SystemXMLParser(String fileName) {
File schemaFile;
Schema schema;
Source xmlFile = new StreamSource(new File(fileName));
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schemaFile = new File("bin/schema.xsd");
try {
schema = schemaFactory.newSchema(schemaFile);
}
catch (SAXException e1) {
schema = null;
e1.printStackTrace();
}
Validator validator = schema.newValidator();
try {
validator.validate(xmlFile);
System.out.println(xmlFile.getSystemId() + " is valid");
System.out.println("Is Valid");
}
catch (SAXException e) {
System.out.println(xmlFile.getSystemId() + " is NOT valid");
System.out.println("Reason: " + e.getLocalizedMessage());
}
catch (IOException e) {
e.printStackTrace();
}
this.fileName = fileName;
parse(this.fileName);
for(int i = 0; i < collection.size(); i++){
System.out.println(collection.get(i).getName());
}
} | 4 |
public void setChangable(boolean b) {
changable = b;
if (b) {
questionBody.getHtmlPane().removeLinkMonitor();
if (!isChangable()) {
if (choices != null) {
for (AbstractButton x : choices)
x.addMouseListener(popupMouseListener);
}
}
}
else {
questionBody.getHtmlPane().addLinkMonitor();
if (isChangable()) {
if (choices != null) {
for (AbstractButton x : choices)
x.removeMouseListener(popupMouseListener);
}
}
}
} | 7 |
public static boolean isBlockSeparator(String s) {
if (s.startsWith("--") && s.endsWith("--")) {
return true;
}
if (s.startsWith("==") && s.endsWith("==")) {
return true;
}
if (s.startsWith("..") && s.endsWith("..") && s.equals("...") == false) {
return true;
}
if (s.startsWith("__") && s.endsWith("__")) {
return true;
}
return false;
} | 9 |
private Class classFor(final String name) {
if (name == null) throw new NullPointerException("missing required 'type' filter config parameter");
Class cl = null;
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
}
try {
return Class.forName(DEFAULT_PACKAGE + name + "Filter");
} catch (ClassNotFoundException e) {
}
if (cl == null) {
throw new Error("failed to load class for Filter type '" + name + "'");
}
return cl;
} | 4 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WithNotAnnotatedField that = (WithNotAnnotatedField) o;
if (firstName != null ? !firstName.equals(that.firstName) : that.firstName != null) return false;
return true;
} | 5 |
public static void main(String [] args) {
Primes primeGetter = new Primes();
int maxSummands = 0;
int j = 1;
// for every prime p ...
for (long p = primeGetter.getNth(j); p<=MAX_PRIME_VALUE; p = primeGetter.getNth(++j)) {
// ... start testing summations at each smaller primes p2 ...
int k = 1;
for (long p2 = primeGetter.getNth(k); p2<=p; p2 = primeGetter.getNth(++k)) {
long summation = p2;
int numberSummands = 1;
// ... add subsequent primes p3 until we hit or overshoot p
int l = k + 1;
for (long p3 = primeGetter.getNth(l); summation<=p; p3 = primeGetter.getNth(++l)) {
summation += p3;
numberSummands += 1;
if (summation == p) {
if (numberSummands > maxSummands) {
maxSummands = numberSummands;
// announce that we've beaten prior record
System.out.println("prime p: " + p + " is sum of: " + numberSummands + " consecutive smaller primes, biggest is " + p3);
}
}
}
}
}
} | 5 |
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
// Conditionally select and set the character encoding to be used
if (this.ignore || request.getCharacterEncoding() == null) {
String encod = selectEncoding();
if (encod != null) {
request.setCharacterEncoding(encod);
}
}
if (log.isDebugEnabled()) {
log.debug("CONTENT-TYPE(request):" + request.getContentType()); //$NON-NLS-1$
log.debug("CONTENT-TYPE(response):" + response.getContentType()); //$NON-NLS-1$
log.debug("CharacterEncoding:" + request.getCharacterEncoding()); //$NON-NLS-1$
log.debug("headers"); //$NON-NLS-1$
Enumeration enumeration1 = ((HttpServletRequest)request).getHeaderNames();
while (enumeration1.hasMoreElements()) {
String key = (String)enumeration1.nextElement();
log.debug(key + "=" + ((HttpServletRequest)request).getHeader(key)); //$NON-NLS-1$
}
log.debug("atributes"); //$NON-NLS-1$
Enumeration enumeration = request.getAttributeNames();
while (enumeration.hasMoreElements()) {
String key = (String)enumeration.nextElement();
log.debug(key + "=" + request.getAttribute(key)); //$NON-NLS-1$
}
log.debug("parameters"); //$NON-NLS-1$
Iterator it = request.getParameterMap().entrySet().iterator();
while (it.hasNext()) {
log.debug(it.next());
}
}
// Pass control on to the next filter
chain.doFilter(request, response);
} | 7 |
@Override
public void run() {
try {
prepare();
} catch (FileNotFoundException e) {
logger.fatal(e.getMessage());
return;
} catch (InterruptedException e) {
return;
}
String line;
int slipCounter = 0;
while (!Thread.currentThread().isInterrupted()) {
try {
line = logReader.readLine();
if (null == line) {
if (slipCounter >= maxSlipNumber) {
reopen();
slipCounter = 0;
continue;
}
slipCounter++;
Thread.sleep(updatePeriod);
} else {
slipCounter = 0;
if (recordsQueue.size() >= maxQueueSize)
recordsQueue.poll();
recordsQueue.put(line);
}
} catch (IOException e) {
logger.warn("Log reading some I/O error. Miss one line from log");
} catch (InterruptedException e) {
break;
}
}
try {
logReader.close();
} catch (IOException e1) {
logger.warn("Can't close log stream (file {}). It will no affect, but unpleasantly",
currentLogFile.getAbsolutePath());
}
} | 9 |
public void setVisible(boolean visible) {
if(window == null) {
initialize();
}
this.visible = visible;
} | 1 |
public LngLatAlt getCoordinates()
{
return coordinates;
} | 0 |
private void transformToRegularForm(String option) throws ConfigurationException, ConsoleException,
UnrecognizedCommandException, NullValueException {
if (!isTheoryModified) return;
Command transform = commands.getCommand(Transform.COMMAND_NAME);
String opt = "".equals(option.trim()) ? "" : transform.getOptionName(option);
if (null == opt) throw new UnrecognizedCommandException("option [" + option + "] not found");
if (opt.startsWith("regu")) return;
console.printf("theory is modified, perform regular form transformation? (Y/N) ");
String isTransform = scanner.next().trim();
if ("y".equalsIgnoreCase(isTransform) || "yes".equalsIgnoreCase(isTransform)) {
Object result = transform.execute("regu", theory, conclusions, null);
if (null != result) theory = (Theory) result;
isTheoryModified = false;
}
} | 7 |
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(VistaEditar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(VistaEditar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(VistaEditar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(VistaEditar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
VistaEditar dialog = new VistaEditar(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
} | 6 |
public List<Evidence> getEvidenceList(String fileName, String actionType, String teamType) {
List<Evidence> evidenceList = new ArrayList<Evidence>();
Element evidenceE;
Evidence evidence;
ClaimDao claimDao = new ClaimDao(fileName);
Claim claim = null;
List<Claim> claimAndSubclaimList = claimDao.getClaimAndSubclaimList(teamType);
for (Iterator i = root.elementIterator(actionType); i.hasNext();) {
evidenceE = (Element)i.next();
if (evidenceE.element("isDelete").getText().equals("false")) {
String id = evidenceE.element("id").getText()
, title = evidenceE.element("title").getText()
, description = evidenceE.element("description").getText()
, type = evidenceE.element("type").getText()
, timeAdded = evidenceE.element("timeAdded").getText()
, parentClaimId = evidenceE.element("parentClaim").getText()
, name = evidenceE.element("name").getText()
, debateId = evidenceE.element("debateId").getText()
, dialogState = evidenceE.elementText("dialogState");
for (int j = 0; j < claimAndSubclaimList.size(); j++) {
if (claimAndSubclaimList.get(j).getId().equals(parentClaimId)) {
claim = claimAndSubclaimList.get(j);
break;
}
}
evidence = new Evidence(id, title, description, type
, timeAdded, claim, name, debateId, dialogState);
evidenceList.add(evidence);
}
}
return evidenceList;
} | 4 |
private void setNameGameWorld(String name) {
nameGameWorld = name.substring(name.lastIndexOf(".") + 1, name.indexOf("Loc"));
} | 0 |
public int immuneCounter(Type primary, Type secondary) {
int counter = 0;
if (immuneTypes == null || immuneTypes.length ==0) {
return 0;
}
for (int i = 0; i < immuneTypes.length; i++) {
if (immuneTypes[i].equalsTo(primary.showType()) || immuneTypes[i].equalsTo(secondary.showType())) {
counter ++;
}
}
return counter;
} | 5 |
private void unfoldNonRecursiveTails() {
// a la mohri nederhof determinization:
// every time a nonrecursive tail is used, make a copy for the specific used position.
// this can be done before addReduceTransitions
Relation<Item, Item> edges = new Relation<Item, Item>();
for (Item i : allItems()) {
for (Transition t : i.derives) {
edges.add(i, t.target);
}
if (i.shift != null) {
edges.add(i, i.shift.target);
}
}
Relation<Item, Item> tc = new Relation<Item, Item>(Util.transitiveClosure2(edges.m));
Set<Transition> old = new ShareableHashSet<Transition>();
Set<Transition> neww = new ShareableHashSet<Transition>();
for (Item i : allItems()) {
if (tc.get(i).contains(i)) { // i is recursive
for (Transition t : i.derives) {
Item j = t.target;
if (!tc.get(j).contains(j)) { // j is not recusive
// unfold
Item u = unfold(j, i);
neww.add(addTransition(i, t.label, u));
old.add(t);
}
}
}
}
for (Transition t : old) {
t.source.derives.remove(t);
}
transitions.removeAll(old);
for (Transition t : neww) {
t.source.derives.add(t);
}
transitions.addAll(neww);
} | 9 |
protected int transform(JavaMethod javaMethod, List tokens, int i) {
if (!javaMethod.getName().equals("initializeClassAttributes")) {
return i;
}
javaMethod.methodBody.remove(i, i+5/*12*/);
if (((JavaToken)tokens.get(i)).value.equals("friends")) {
int end = javaMethod.methodBody.findClosingCallEnd(i);
javaMethod.methodBody.remove(i, end+1);
}
javaMethod.methodBody.remove(i, i+7);
int j = i;
tokens.add(j++, new JavaIdentifier("AboraSupport"));
tokens.add(j++, new JavaCallKeywordStart("findAboraClass"));
tokens.add(j++, new JavaIdentifier(javaMethod.javaClass.className));
tokens.add(j++, new JavaIdentifier("class"));
tokens.add(j++, new JavaCallEnd());
tokens.add(j++, new JavaCallKeywordStart("setAttributes"));
tokens.add(j++, new JavaKeyword("new"));
tokens.add(j++, new JavaCallStart("Set"));
tokens.add(j++, new JavaCallEnd());
while (j < tokens.size()) {
JavaToken token = (JavaToken)tokens.get(j);
if (token instanceof JavaIdentifier) {
tokens.remove(j);
tokens.add(j, new StringLiteral(token.value));
} else if (token instanceof JavaKeyword && token.value.equals(";")) {
tokens.remove(j);
j -= 1;
} else if (token.value.equals("yourself")) {
tokens.remove(j+1);
tokens.remove(j);
j -= 1;
} else if (token instanceof JavaParenthesisEnd) {
tokens.remove(j);
j -= 1;
} else if (token instanceof JavaArrayInitializerStart) {
//TODO shouldn't need to do this, as other transforms should set up string arrays properly...
tokens.add(j, new JavaKeyword("new"));
tokens.add(j+1, new JavaIdentifier("String[]"));
j += 2;
}
j += 1;
}
return i;
} | 9 |
private void updateButton(MouseEvent event)
{
int index = getUI().tabForCoordinate(CloseableTabbedPane.this, event.getX(), event.getY());
if (index != -1 && index != getSelectedIndex()) {
if (visibleIndex == index) {
return;
}
setButtonVisible(index, true);
if (visibleIndex != index && visibleIndex != -1 && visibleIndex != getSelectedIndex()) {
setButtonVisible(visibleIndex, false);
}
visibleIndex = index;
} else if (visibleIndex != -1 && visibleIndex != getSelectedIndex() && visibleIndex < getTabCount()) {
setButtonVisible(visibleIndex, false);
visibleIndex = -1;
}
} | 9 |
public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {} | 0 |
public void computeStabilities(String s) {
try {
BufferedReader bufferedreader = new BufferedReader(new FileReader(s));
for (int i = 0; i < 10000; i++) {
bufferedreader.readLine();
}
for (int j = 0; j < 0x3d0900; j++) {
String s1 = bufferedreader.readLine();
if (s1 == null) {
break;
}
try {
INSEvent insevent = new INSEvent();
LogItem logitem = new LogItem(s1);
insevent.fromLogItem(logitem);
mEventCache.add(insevent);
if (mCount == 0) {
mFirstEventTime = insevent.getTime();
}
else if (mCount == 1) {
mPeriod = insevent.getTime() - mFirstEventTime;
}
mCount++;
continue;
} catch (Exception exception1) {
System.err.println(exception1);
}
System.exit(0);
}
bufferedreader.close();
System.out.println(mEventCache.size());
computeStabilitiesHelperAccel();
computeStabilitiesHelperGyro();
} catch (Exception exception) {
exception.printStackTrace();
System.exit(1);
}
} | 7 |
private String loadRivers() {
if (details) System.out.println("Loading rivers.");
File imageFile = new File("output/"+Name+"/overviews/rivers_overview.png");
if (imageFile.exists()) {
try {
BufferedImage tempImage = ImageIO.read(imageFile);
if (tempImage.getWidth() == chunksX * MyzoGEN.DIMENSION_X && tempImage.getHeight() == chunksY * MyzoGEN.DIMENSION_Y) {
for (int i = 0; i < chunksX * MyzoGEN.DIMENSION_X; i++) {
for (int j = 0; j < chunksY * MyzoGEN.DIMENSION_Y; j++) {
Color pixel = new Color(tempImage.getRGB(i, j), true);
if (pixel.getBlue() == 255) {
MyzoGEN.getOutput().getTile(new Point(i, j)).tile = Tiles.WATER;
if (pixel.getAlpha() <= 254) {
MyzoGEN.getOutput().getTile(new Point(i, j)).tile = Tiles.WATER;
MyzoGEN.getOutput().getTile(new Point(i, j)).river = true;
MyzoGEN.getOutput().getTile(new Point(i, j)).riverID = 254 - pixel.getAlpha();
}
}
}
}
} else return "RiversGenerator critical error - the loaded temperature map does not match the specified dimensions. Loaded file is: "+tempImage.getWidth()+"x"+tempImage.getHeight()+
"while the specified dimensions are: "+(chunksX * MyzoGEN.DIMENSION_X)+"x"+(chunksY * MyzoGEN.DIMENSION_Y);
} catch (IOException e) {
e.printStackTrace();
return "RiversGenerator critical error - LOAD option is on but I can't load the file.";
}
} else return "RiversGenerator critical error - LOAD option is on but I can't find the rivers_overview.png file.";
return "No errors.";
} | 9 |
public String toString() {
String res = "[Polygon";
for(int i=0; i<corners.length && i<4; i++)
res += " " + corners[i].toString();
return res+"]\n";
} | 2 |
public int action(ArrayList<RObj> objs, int actionBy) {
Player plr = (Player) objs.get(0);
needIntersect = !needIntersect;
if (panel.isEnabled()) {
if (plr.getInv() == null) {
intersect = true;
fireThrough = true;
riftIntersect = true;
panel.setEnabled(false);
panel.setOpaque(false);
plr.setInv(this);
plr.setImgType(1);
}
} else {
JPanel p = new JPanel();
if (plr.getFacing() == 1)
p.setLocation(plr.getAX() - getAWidth(), plr.getAY() + plr.getAHeight() / 2);
else
p.setLocation(plr.getAX() + plr.getAWidth(), plr.getAY() + plr.getAHeight() / 2);
p.setSize(getAWidth(), getAHeight());
boolean good = true;
for (RObj o : objs)
if (Play.doIntersect(o.getPanel(), p) && !o.canIntersect())
good = false;
if (good) {
setAX((int) p.getLocation().getX());
setAY((int) p.getLocation().getY());
intersect = false;
fireThrough = false;
panel.setEnabled(true);
panel.setOpaque(true);
riftIntersect = false;
plr.setInv(null);
plr.setImgType(0);
}
}
plr.setFacing(plr.getFacing());
return 0;
} | 7 |
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
switch (key) {
case KeyEvent.VK_UP:
action.thrust = 0;
break;
case KeyEvent.VK_LEFT:
action.turn = 0;
break;
case KeyEvent.VK_RIGHT:
action.turn = 0;
break;
case KeyEvent.VK_SPACE:
action.shoot = false;
break;
case KeyEvent.VK_ALT:
keyList.remove((Integer) KeyEvent.VK_ALT);
break;
case KeyEvent.VK_ENTER:
keyList.remove((Integer) KeyEvent.VK_ENTER);
break;
}
} | 6 |
@Override
public boolean equals(Object other){
if(other == null){
return false;
} else if (this == other) {
return true;
} else if (!(other instanceof RecipeIngredient)) {
return false;
}
//Numbers in prefix and suffix might be sql doubles so we should remove
//their trailing zeros since they make no semantic difference.
String ownPrefix = adjustUnitsInString(prefix, 1);
String otherPrefix = adjustUnitsInString(((RecipeIngredient) other).getPrefix(), 1);
String ownSuffix = adjustUnitsInString(suffix, 1);
String otherSuffix = adjustUnitsInString(((RecipeIngredient) other).getSuffix(), 1);
return ownPrefix.equals(otherPrefix) &&
ownSuffix.equals((otherSuffix)) &&
ingredient.equals(((RecipeIngredient) other).getIngredient());
} | 5 |
public Iterable<Key> keys() {
Queue<Key> queue = new Queue<Key>();
for (Node x = first; x != null; x = x.next)
queue.enqueue(x.key);
return queue;
} | 1 |
@GET
@Path("events/{id}/participants")
@Produces({MediaType.APPLICATION_JSON })
public List<Participant> getEventParticipants(@PathParam("id")int idEvent){
System.out.println("Return the partcipants list of the event selected by the id");
return JpaTest.eventService.getParticipants(idEvent);
} | 0 |
public void testInverted() {
m_Filter = getFilter("1,2,3,4,5,6");
((TimeSeriesDelta)m_Filter).setInvertSelection(true);
Instances result = useFilter();
// Number of attributes shouldn't change
assertEquals(m_Instances.numAttributes(), result.numAttributes());
assertEquals(m_Instances.numInstances() - 1, result.numInstances());
// Check conversion looks OK
for (int i = 0; i < result.numInstances(); i++) {
Instance in = m_Instances.instance(i + 1);
Instance out = result.instance(i);
for (int j = 0; j < result.numAttributes(); j++) {
if ((j != 4) && (j != 5) && (j != 6)) {
if (in.isMissing(j)) {
assertTrue("Nonselected missing values should pass through",
out.isMissing(j));
} else if (result.attribute(j).isString()) {
assertEquals("Nonselected attributes shouldn't change. "
+ in + " --> " + out,
m_Instances.attribute(j).value((int)in.value(j)),
result.attribute(j).value((int)out.value(j)));
} else {
assertEquals("Nonselected attributes shouldn't change. "
+ in + " --> " + out,
in.value(j),
out.value(j), TOLERANCE);
}
}
}
}
} | 7 |
public void run(){
AudioInputStream stream = null;
for (int i = (int) (Math.random() * songs1.size()); i < songs1.size(); i++){
try {
// open the audio input stream
stream = AudioSystem.getAudioInputStream(songs1.get(i));
format = stream.getFormat();
// get the audio samples
samples = getSamples(stream);
}
catch (UnsupportedAudioFileException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
InputStream stream2 = new ByteArrayInputStream(getSamples());
play(stream2);
if (i == songs1.size() - 1 && !kill && playing) i = 0;
}
} | 6 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TAdjstkPK other = (TAdjstkPK) obj;
if (!Objects.equals(this.transNo, other.transNo)) {
return false;
}
if (!Objects.equals(this.itemCode, other.itemCode)) {
return false;
}
return true;
} | 4 |
@Override
public void conversion() {
switch (type) {
case RZ:
codageRZ();
break;
case NRZ:
codageNRZ();
break;
case NRZT:
codageNRZT();
break;
}
} | 3 |
public void setAction(TicketQueryAction value) {
this._action = value;
} | 0 |
public double rawAllResponsesVariance(){
if(!this.dataPreprocessed)this.preprocessData();
if(!this.variancesCalculated)this.meansAndVariances();
return this.rawAllResponsesVariance;
} | 2 |
public String getRecommendation() {
return recommendation;
} | 0 |
public float addWeight(int numberSum, int numberDirection) {
switch (numberDirection) {
case 1:
if (numberSum >= 4)
return 15;
else
return (float) 15 / (4 - 1) * numberSum - (float) 15 / (4 - 1);
case 2:
if (numberSum >= 7)
return 15;
else
return (float) 15 / (7 - 1) * numberSum - (float) 15 / (7 - 1);
case 3:
if (numberSum >= 12)
return 15;
else
return (float) 15 / (12 - 1) * numberSum - (float) 15
/ (12 - 1);
case 4:
if (numberSum >= 16)
return 15;
else
return (float) 15 / (16 - 1) * numberSum - (float) 15
/ (16 - 1);
default:
return 0;
}
} | 8 |
@Test
public void testCadastrarProduto(){
Produto p5 = new Produto(5,"Smartphone Samsung Galaxy Ace Preto, Desbloqueado Vivo, GSM, Android, C‚mera de 5MP, Tela Touchscreen 3.5\", 3G, Wi-Fi, Bluetooth e Cart„o de MemÛria 2GB",3, 499.00f);
try {
facade.cadastrarProduto(p5);
Assert.assertEquals(facade.listarProdutos().size(), 5);
Assert.assertTrue(facade.buscarProduto(5).getCodigo() == 5);
Assert.assertEquals(facade.buscarProduto(5).getDescricao(),"Smartphone Samsung Galaxy Ace Preto, Desbloqueado Vivo, GSM, Android, C‚mera de 5MP, Tela Touchscreen 3.5\", 3G, Wi-Fi, Bluetooth e Cart„o de MemÛria 2GB");
Assert.assertEquals(facade.buscarProduto(5).getQuantidade(), 3);
Assert.assertEquals(facade.buscarProduto(5).getValor(), 499.00f, 0.1);
Assert.assertTrue(facade.buscarProduto(5).equals(p5));
} catch (FacadeException e) {
Assert.fail(e.getMessage());
}
Produto p6 = new Produto(6,"Smartphone Samsung Galaxy Ace Preto, Desbloqueado Vivo, GSM, Android, C‚mera de 5MP, Tela Touchscreen 3.5\", 3G, Wi-Fi, Bluetooth e Cart„o de MemÛria 2GB",2, 499.00f);
try {
facade.cadastrarProduto(p6);
Assert.assertEquals(facade.listarProdutos().size(), 6);
Assert.assertTrue(facade.buscarProduto(6).getCodigo() == 6);
Assert.assertEquals(facade.buscarProduto(6).getDescricao(),"Smartphone Samsung Galaxy Ace Preto, Desbloqueado Vivo, GSM, Android, C‚mera de 5MP, Tela Touchscreen 3.5\", 3G, Wi-Fi, Bluetooth e Cart„o de MemÛria 2GB");
Assert.assertEquals(facade.buscarProduto(6).getQuantidade(), 2);
Assert.assertEquals(facade.buscarProduto(6).getValor(), 499.00f, 0.1);
Assert.assertTrue(facade.buscarProduto(6).equals(p6));
} catch (FacadeException e) {
Assert.fail(e.getMessage());
}
Produto p7 = new Produto(7,"Sof· de Canto Chicago - Chenille Preto - Gazin", 1, 799.90f);
try {
facade.cadastrarProduto(p7);
Assert.assertEquals(facade.listarProdutos().size(), 7);
Assert.assertTrue(facade.buscarProduto(7).getCodigo() == 7);
Assert.assertEquals(facade.buscarProduto(7).getDescricao(),"Sof· de Canto Chicago - Chenille Preto - Gazin");
Assert.assertEquals(facade.buscarProduto(7).getQuantidade(), 1);
Assert.assertEquals(facade.buscarProduto(7).getValor(), 799.90f, 0.1);
Assert.assertTrue(facade.buscarProduto(7).equals(p7));
} catch (FacadeException e) {
Assert.fail(e.getMessage());
}
} | 3 |
public AffichageUserGui() {
initComponents();
setSize(700, 500);
setMinimumSize(new Dimension(600, 0));
setMaximumSize(new Dimension(800, Integer.MAX_VALUE));
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
TableRowSorter<TableModel> sorter = new TableRowSorter<>(jTable1.getModel());
jScrollPane1.setBorder(null);
jTable1.setRowSorter(sorter);
jTable1.setFillsViewportHeight(true);
jTable1.setShowHorizontalLines(false);
Color JframeColor = new Color(63,70,73);
getContentPane().setBackground(JframeColor);
JTableHeader header = jTable1.getTableHeader();
Color bgcolor = new Color(45,47,49);
Color focolor = new Color(244,244,244);
header.setBackground(bgcolor);
header.setForeground(focolor);
header.setBorder(null);
//set text alignement
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setHorizontalAlignment(SwingConstants.CENTER);
TableColumn AlignementCol;
for(int i = 0; i < modeleUser.getColumnCount(); i++)
{
AlignementCol= jTable1.getColumnModel().getColumn(i);
AlignementCol.setCellRenderer(renderer);
}
//end set text alignement
//set blocked images
jTable1.getColumnModel().getColumn(12).setCellRenderer(new CustomCellRender_Blocked());
//set blocked images
//set header border:disabled
for(int i = 0; i < modeleUser.getColumnCount(); i++)
{
TableColumn column = jTable1.getColumnModel().getColumn(i);
column.setHeaderRenderer(new CustomCellRender());
}
//end set header border:disabled
Color HeaderColorBackground = new Color(34,168,108);
header.setBackground(HeaderColorBackground);
} | 2 |
@Override
public void addAllMapLast(Map<? extends K, ? extends Collection<? extends V>> map) {
for (Map.Entry<? extends K, ? extends Collection<? extends V>> en : map.entrySet()) {
addAllLast(en.getKey(), en.getValue());
}
} | 7 |
public void steppedOn(Level level, int xt, int yt, Entity entity) {
if (random.nextInt(60) != 0) return;
if (level.getData(xt, yt) < 5) return;
level.setTile(xt, yt, Tile.dirt, 0);
} | 2 |
public static Stella_Class getIdenticalClass(String classname, String stringifiedsource) {
{ Surrogate surrogate = Surrogate.lookupSurrogate(classname);
Stella_Object oldvalue = ((surrogate != null) ? surrogate.surrogateValue : ((Stella_Object)(null)));
if (oldvalue != null) {
if (Surrogate.subtypeOfClassP(Stella_Object.safePrimaryType(oldvalue))) {
{ Stella_Class oldvalue000 = ((Stella_Class)(oldvalue));
if ((oldvalue000.classStringifiedSource != null) &&
(Stella.stringEqlP(oldvalue000.classStringifiedSource, stringifiedsource) &&
(((Module)(surrogate.homeContext)) == ((Module)(Stella.$MODULE$.get()))))) {
return (oldvalue000);
}
}
}
else {
}
}
return (null);
}
} | 6 |
@Override
public String toString() {
final ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
PrintStream out;
try {
out = new PrintStream(bos, false, IOUtils.UTF_8);
} catch (UnsupportedEncodingException bogus) {
throw new RuntimeException(bogus);
}
out.println(" index FST:");
out.println(" " + indexNumBytes + " bytes");
out.println(" terms:");
out.println(" " + totalTermCount + " terms");
out.println(" " + totalTermBytes + " bytes" + (totalTermCount != 0 ? " (" + String.format(Locale.ROOT, "%.1f", ((double) totalTermBytes)/totalTermCount) + " bytes/term)" : ""));
out.println(" blocks:");
out.println(" " + totalBlockCount + " blocks");
out.println(" " + termsOnlyBlockCount + " terms-only blocks");
out.println(" " + subBlocksOnlyBlockCount + " sub-block-only blocks");
out.println(" " + mixedBlockCount + " mixed blocks");
out.println(" " + floorBlockCount + " floor blocks");
out.println(" " + (totalBlockCount-floorSubBlockCount) + " non-floor blocks");
out.println(" " + floorSubBlockCount + " floor sub-blocks");
out.println(" " + totalBlockSuffixBytes + " term suffix bytes" + (totalBlockCount != 0 ? " (" + String.format(Locale.ROOT, "%.1f", ((double) totalBlockSuffixBytes)/totalBlockCount) + " suffix-bytes/block)" : ""));
out.println(" " + totalBlockStatsBytes + " term stats bytes" + (totalBlockCount != 0 ? " (" + String.format(Locale.ROOT, "%.1f", ((double) totalBlockStatsBytes)/totalBlockCount) + " stats-bytes/block)" : ""));
out.println(" " + totalBlockOtherBytes + " other bytes" + (totalBlockCount != 0 ? " (" + String.format(Locale.ROOT, "%.1f", ((double) totalBlockOtherBytes)/totalBlockCount) + " other-bytes/block)" : ""));
if (totalBlockCount != 0) {
out.println(" by prefix length:");
int total = 0;
for(int prefix=0;prefix<blockCountByPrefixLen.length;prefix++) {
final int blockCount = blockCountByPrefixLen[prefix];
total += blockCount;
if (blockCount != 0) {
out.println(" " + String.format(Locale.ROOT, "%2d", prefix) + ": " + blockCount);
}
}
assert totalBlockCount == total;
}
try {
return bos.toString(IOUtils.UTF_8);
} catch (UnsupportedEncodingException bogus) {
throw new RuntimeException(bogus);
}
} | 9 |
@Override
public void update(double delta) {
if(linked.getRemoved()) {
getEntity().remove();
}
} | 1 |
public static SensitivityEnumeration fromString(String v) {
if (v != null) {
for (SensitivityEnumeration c : SensitivityEnumeration.values()) {
if (v.equalsIgnoreCase(c.toString())) {
return c;
}
}
}
throw new IllegalArgumentException(v);
} | 3 |
@Override
public ICacheable put(Object key, ICacheable value) {
if (key == null || value == null) {
throw new NullPointerException("key == null || value == null");
}
ICacheable previous = null;
synchronized (this) {
mPutCount++;
mCurrSize += safeSizeOf(key, value);
previous = mCacheMap.put(key, value);
if (previous != null) {
mCurrSize -= safeSizeOf(key, previous);
}
}
trimToSize(mMaxSize);
return previous;
} | 3 |
public void setResourceParameter(int resourceID, double cost)
{
Resource res = new Resource();
res.resourceId = resourceID;
res.costPerSec = cost;
res.resourceName = GridSim.getEntityName(resourceID);
// add into a list if moving to a new grid resource
resList_.add(res);
if (index_ == -1 && record_)
{
write("Allocates this Gridlet to " + res.resourceName +
" (ID #" + resourceID + ") with cost = $" + cost + "/sec");
}
else if (record_)
{
int id = resList_.get(index_).resourceId;
String name = resList_.get(index_).resourceName;
write("Moves Gridlet from " + name + " (ID #" + id + ") to " +
res.resourceName + " (ID #" + resourceID +
") with cost = $" + cost + "/sec");
}
index_++; // initially, index_ = -1
} | 3 |
public LSystemEnvironment(LSystemInputPane input) {
super(null);
this.input = input;
input.addLSystemInputListener(new LSystemInputListener() {
public void lSystemChanged(LSystemInputEvent event) {
setDirty();
}
});
} | 0 |
private void askForItemToUse() {
UseItemDialog dialog = new UseItemDialog("Choose item to use", 500, 500, objectTron.getActivePlayerInfo().getInventoryItems());
int answer = dialog.show();
if (answer == JOptionPane.OK_OPTION) {
int chosenItemIndex = dialog.getChosenItemIndex();
ElementInfo chosenItem = objectTron.getActivePlayerInfo().getInventoryItems().get(chosenItemIndex);
if (IdentityDisc.class.isAssignableFrom(chosenItem.getClass())) {
ChooseDirectionDialog dirDialog = new ChooseDirectionDialog("Choose the direction", 150, 175);
answer = dirDialog.show();
if (answer == JOptionPane.OK_OPTION) {
try {
objectTron.useItemAction(chosenItemIndex, dirDialog.getChosenDirection());
} catch (Exception e) {
e.printStackTrace();
showError(e.getClass().getSimpleName(), e.getMessage());
}
}
} else {
try {
objectTron.useItemAction(chosenItemIndex);
} catch (Exception e) {
e.printStackTrace();
showError(e.getClass().getSimpleName(), e.getMessage());
}
}
}
} | 5 |
@Override
public Object execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
Contexto oContexto = (Contexto) request.getAttribute("contexto");
oContexto.setVista("jsp/mensaje.jsp");
EntradaBean oEntradaBean = new EntradaBean();
EntradaParam oEntradaParam = new EntradaParam(request);
oEntradaBean = oEntradaParam.loadId(oEntradaBean);
try {
EntradaDao oEntradaDAO = new EntradaDao(oContexto.getEnumTipoConexion());
oEntradaDAO.remove(oEntradaBean);
} catch (Exception e) {
throw new ServletException("EntradaController: Remove Error: " + e.getMessage());
}
String strMensaje = "Se ha eliminado la información de la entrada con id=" + Integer.toString(oEntradaBean.getId()) + "<br />";
strMensaje += "<a href=\"Controller?class=entrada&method=list\">Ir al listado de entrada</a><br />";
String Mensaje = strMensaje;
return Mensaje;
} | 1 |
public synchronized void createTables() throws BoardInitException, SQLException {
ResultSet res;
String commonSql = null;
// Check if common stuff has already been created
tableChkStmt.setString(1, "index_counters");
res = tableChkStmt.executeQuery();
try {
if(!res.isBeforeFirst()) {
// Query to create tables common to all boards
try {
commonSql = Resources.toString(Resources.getResource(commonSqlRes), Charsets.UTF_8);
} catch(IOException e) {
throw new BoardInitException(e);
} catch(IllegalArgumentException e) {
throw new BoardInitException(e);
}
}
} finally {
res.close();
}
conn.commit();
// Check if the tables for this board have already been created too
// Bail out if yes
tableChkStmt.setString(1, this.table);
res = tableChkStmt.executeQuery();
try {
if(res.isBeforeFirst()) {
conn.commit();
return;
}
} finally {
res.close();
}
conn.commit();
// Query to create all tables for this board
String boardSql;
try {
boardSql = Resources.toString(Resources.getResource(boardSqlRes), Charsets.UTF_8);
boardSql = boardSql.replaceAll("%%BOARD%%", table);
boardSql = boardSql.replaceAll("%%CHARSET%%", charset);
} catch(IOException e) {
throw new BoardInitException(e);
} catch(IllegalArgumentException e) {
throw new BoardInitException(e);
}
// Query to create or replace triggers and procedures for this board
String triggersSql;
try {
triggersSql = Resources.toString(Resources.getResource(triggersSqlRes), Charsets.UTF_8);
triggersSql = triggersSql.replaceAll("%%BOARD%%", table);
triggersSql = triggersSql.replaceAll("%%CHARSET%%", charset);
} catch(IOException e) {
throw new BoardInitException(e);
} catch(IllegalArgumentException e) {
throw new BoardInitException(e);
}
Statement st = conn.createStatement();
try {
if(commonSql != null)
st.executeUpdate(commonSql);
st.executeUpdate(boardSql);
st.executeUpdate(triggersSql);
conn.commit();
} finally {
st.close();
}
} | 9 |
public Tile getBlockAt(int x, int y) {
if (!this.tiles.isEmpty()) {
for (int i = 0; i < this.tiles.size(); i++) {
if (this.tiles.get(i) != null) {
Tile tile = this.tiles.get(i);
if (tile.getX() / 48 == x && tile.getY() / 48 == y)
return tile;
}
}
}
return null;
} | 5 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ConstructorInfo other = (ConstructorInfo) obj;
if (beanClass == null) {
if (other.beanClass != null)
return false;
} else if (!beanClass.equals(other.beanClass))
return false;
if (constructors == null) {
if (other.constructors != null)
return false;
} else if (!constructors.equals(other.constructors))
return false;
return true;
} | 9 |
public void drawFields(Graphics2D g)
{
// WILL EVENTUALLY CHANGE THESE CONSTANT NUMBERS
for(int i = 0; i < this.getBoardSize(); i++)
{
if(i < 7)
this.fields.get(i).draw(g, field_size, Color.WHITE);
else if(i < 16)
this.fields.get(i).draw(g, field_size, Color.CYAN);
else if(i < 24)
this.fields.get(i).draw(g, field_size, Color.MAGENTA);
else if(i < 33)
this.fields.get(i).draw(g, field_size, Color.YELLOW);
else
this.fields.get(i).draw(g, field_size, Color.PINK);
}
} | 5 |
@Test
public void testParseArguments() {
Arguments args = new Arguments();
args.setArgument("var1",
"Teest1 test2 test3 blah blah blahtest3 blah blah "
+ "blahtest3 blah blah blahtest3 blah blah "
+ "blahtest3 blah blah blahtest3 blah blah "
+ "tblahtest3 blah blah blahtest3 blah blah blah",
false);
Argument arg2 = args.setOption("-b", "test2test3 blah blah blah", true);
args.setOption("-c,--continue", "test3test3 blah blah blahtest3"
+ " blah blah blahtest3 blah blah blah", false);
try {
String value = "ssss";
List<Argument> parsed = args.parseArguments(new String[] { "-b",
value });
assertEquals(1, parsed.size());
assertEquals(arg2, parsed.get(0));
assertEquals(value, parsed.get(0).getValue());
} catch (InvalidArgumentException e) {
fail(e.getMessage());
}
try {
args.parseArguments(new String[] { "-c", "ssss", "-b" });
fail("Should have failed.");
} catch (InvalidArgumentException e) {
// ok.
}
String message = args.getUsage("123456789012345678901234567890 1234567890", 30);
String[] lines = message.split("\n");
for (String l : lines) {
assertTrue(l.length() <= 30);
}
} | 3 |
private String getSelectedButtonName(ButtonGroup bg) {
String returnString = "";
boolean isFound = false;
Enumeration<AbstractButton> blockButtons = bg.getElements();
while(blockButtons.hasMoreElements() && !isFound) {
JToggleButton button = (JToggleButton) blockButtons.nextElement();
if(button.isSelected()) {
returnString = button.getName();
isFound = true;
}
}
return returnString;
} | 3 |
final void method3677(Canvas canvas) {
try {
aCanvas7575 = null;
anInt7621++;
aLong7636 = 0L;
if (canvas == null || canvas == aCanvas7626) {
aCanvas7575 = aCanvas7626;
aLong7636 = aLong7553;
} else if (aHashtable7577.containsKey(canvas)) {
Long var_long = (Long) aHashtable7577.get(canvas);
aLong7636 = var_long.longValue();
aCanvas7575 = canvas;
}
if (aCanvas7575 == null || aLong7636 == 0L)
throw new RuntimeException();
anOpenGL7664.setSurface(aLong7636);
method3745((byte) 92);
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
"qo.MF(" + (canvas != null
? "{...}"
: "null") + ')');
}
} | 7 |
public static void setDescriptor (
Device dev,
byte descriptorClass,
byte descriptorType,
byte id,
int index,
byte buf []
) throws IOException
{
if (index > 0xffff || buf.length > 0xffff)
throw new IllegalArgumentException ();
ControlMessage msg = new ControlMessage ();
msg.setRequestType ((byte)(msg.DIR_TO_DEVICE
| descriptorClass
| msg.RECIPIENT_DEVICE
));
msg.setRequest (msg.SET_DESCRIPTOR);
msg.setValue ((short) ((descriptorType << 8) | (0xff & id)));
msg.setIndex ((short) index);
msg.setBuffer (buf);
dev.control (msg);
} | 2 |
private void parseContributorList(String key) {
// Init
if (!contributors.containsKey(key))
{
contributors.put(key, new ArrayList<String>());
}
List<String> list = contributors.get(key);
if (config.has(key) && config.get(key).isJsonArray())
{
for(JsonElement el: config.get(key).getAsJsonArray()) {
list.add(el.getAsString());
}
}
} | 4 |
public String numberize(int number)
{
if (number >= 100)
return "" + number;
else if (number >= 10)
return "0" + number;
else
return "00" + number;
} | 2 |
@Override
public void render(GameContainer gc, StateBasedGame arg1, Graphics g)
throws SlickException {
backgroundImage.draw(0, 0);
for(Bird bird : birds) {
bird.render(gc, g);
}
for(Obstacle o : obstacles) {
o.render(gc, g);
}
controlledBird.render(gc, g);
HashMap<Integer, Boolean> enabled = birds.get(0).getEnabledBehaviors();
HashMap<Integer, IBehavior> available = birds.get(0).getAvailableBehaviors();
for(int i = 0; i < enabled.size(); i++) {
if(enabled.get(i)) {
g.setColor(Color.green);
} else {
g.setColor(Color.red);
}
g.drawString(available.get(i).getName(), 190 + (80 * i), 20);
g.drawString("Key: " + (i + 1), 190 + (80 * i), 35);
}
g.setColor(Color.black);
super.render(gc, arg1, g);
} | 4 |
@Override
public void startUp(final GameTime gameTime) {
// Call the start up methods of any children that previously existed on
// the logicalQueue
for (ILogical gameComponent : logicalQueue) {
gameComponent.startUp(gameTime);
}
// Also call the start up methods of any children that were queued to be
// added
startUpLogicalQueue(gameTime);
} | 1 |
public void paintComponent(Graphics g) {
super.paintComponent(g);
if ( (OSI == null) || OSI.getWidth() != getWidth() || OSI.getHeight() != getHeight() ) {
OSI = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
needsRedraw = true;
}
if (needsRedraw) {
Graphics OSG = OSI.getGraphics();
for (int r = 0; r < rows; r++)
for (int c = 0; c < columns; c++)
drawSquare(OSG,r,c,false);
OSG.dispose();
needsRedraw = false;
}
g.drawImage(OSI,0,0,null);
} | 6 |
Key[] resize(Key[] a, int n)
{
Key[] b = (Key[]) new Comparable[n];
System.arraycopy(a, 0, b, 0, (a.length < b.length) ? a.length
: b.length);
return b;
} | 1 |
private String Trans2Syn(String s)
{
Stack<Character> ts = new Stack<Character>();
for (int i = 0; i < s.length(); ++i)
{
if (Character.isDigit(s.charAt(i)))
{
if (ts.size() == 0 || !ts.peek().equals('i'))
{
ts.push('i');
}
} else
{
ts.push(s.charAt(i));
}
}
String tmp = "";
for (int i = 0; i < ts.size(); i++)
{
tmp += ts.elementAt(i);
}
return tmp;
} | 5 |
@EventHandler
public void handleBlockBreaks(BlockBreakEvent event) {
Player player = event.getPlayer();
User user = EdgeCoreAPI.userAPI().getUser(player.getName());
if (user != null) {
Cuboid cuboid = Cuboid.getCuboid(player.getLocation());
if (cuboid == null) {
if (!WorldManager.getInstance().isGlobalBlockInteractionAllowed() && !Level.canUse(user, Level.ARCHITECT)) {
player.sendMessage(lang.getColoredMessage(user.getLanguage(), "cuboid_nopermission"));
event.setCancelled(true);
}
} else {
if (Cuboid.getCuboid(event.getBlock().getLocation()) == null && !WorldManager.getInstance().isGlobalBlockInteractionAllowed() && !Level.canUse(user, Level.ARCHITECT)) {
player.sendMessage(lang.getColoredMessage(user.getLanguage(), "cuboid_nopermission"));
event.setCancelled(true);
}
if (!Flag.hasFlag(cuboid, Flag.BreakBlocks, player.getName())) {
player.sendMessage(lang.getColoredMessage(user.getLanguage(), "cuboid_nopermission"));
event.setCancelled(true);
}
}
}
} | 8 |
public static void decrypt(File inputFile, File outputFile) throws IOException {
BufferedImage img = ImageIO.read(inputFile);
int p1,p2;
/**
* Step 1: do the stuff
*/
p1 = img.getRGB(0, 0);
p2 = img.getRGB(1, 0);
int[] bitsPerChannel = new int[3];
getChannelEncoding(new byte[] { (byte)((p1 >> 16) & 0xff),
(byte)((p1 >> 8) & 0xff),
(byte)((p1) & 0xff) },
new byte[] { (byte)((p2 >> 16) & 0xff),
(byte)((p2 >> 8) & 0xff),
(byte)((p2) & 0xff) },
bitsPerChannel);
int next_image_pixel = 2;
int next_output_bit = 0;
int written_bytes = 0;
int size = -4;
FileOutputStream out = new FileOutputStream(outputFile);
ByteBuffer lengthBuffer = ByteBuffer.allocate(4);
byte current = 0;
while (written_bytes < size || size < 0) {
p1 = img.getRGB(next_image_pixel%img.getWidth(), next_image_pixel/img.getWidth());
next_image_pixel++;
byte[] pixel = new byte[] {
(byte)((p1 >> 16) & 0xff),
(byte)((p1 >> 8) & 0xff),
(byte)((p1) & 0xff),
};
for (int c=0; c<3; ++c) {
for (int b=0; b<bitsPerChannel[c]; ++b) {
if (written_bytes >= size && size >= 0) {
out.close();
return;
}
current |= (((pixel[c] >> b)&0x01) << next_output_bit);
if (next_output_bit >= 7) {
next_output_bit = 0;
if (size < 0) {
lengthBuffer.put(current);
size ++;
if (size == 0) {
lengthBuffer.rewind();
size = lengthBuffer.getInt();
System.out.println("found size: " + size);
}
} else {
out.write((int)current);
written_bytes ++;
}
current = 0x0;
} else {
next_output_bit ++;
}
}
}
}
out.close();
} | 9 |
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
try {
this.commandsManager.execute(command.getName(), args, sender, sender);
} catch (CommandPermissionsException e) {
sender.sendMessage(ChatColor.RED + "You don't have permission.");
} catch (MissingNestedCommandException e) {
sender.sendMessage(ChatColor.RED + e.getUsage());
} catch (CommandUsageException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
sender.sendMessage(ChatColor.RED + "Usage: " + e.getUsage());
} catch (WrappedCommandException e) {
sender.sendMessage(ChatColor.RED + "An unknown error has occurred. Please notify an administrator.");
e.printStackTrace();
} catch (UnhandledCommandException e) {
sender.sendMessage(ChatColor.RED + "Command could not be handled; invalid sender!");
} catch (CommandException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
}
return true;
} | 6 |
public static void main(String[] args)
{
Digraph G = null;
try
{
G = new Digraph(new In(args[0]));
System.out.println(args[0] + "\n" + G);
}
catch (Exception e)
{
System.out.println(e);
System.exit(1);
}
System.out.println("Vertex: Component");
StronglyConnectedComponents scc = new StronglyConnectedComponents(G);
for (int v = 0; v < G.V(); v++)
System.out.println(v + ": " + scc.id(v));
} | 2 |
protected boolean isFinished() {
return false;
} | 0 |
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}
Admin admin = (Admin) obj;
if (admin.getLogin() == login || (login.equals(admin.getLogin())) && admin.getPassword() == password || (password.equals(admin.getPassword()))) {
return true;
}
return false;
} | 7 |
@Test
public void depthest02vsdepthest21()
{
for(int i = 0; i < BIG_INT; i++)
{
int numPlayers = 2; //assume/require > 1, < 7
Player[] playerList = new Player[numPlayers];
ArrayList<Color> factionList = Faction.allFactions();
playerList[0] = new Player(chooseFaction(factionList), new DepthEstAI(0,2, new StandardEstimator()));
playerList[1] = new Player(chooseFaction(factionList), new DepthEstAI(2,1, new StandardEstimator()));
//P1 is 0,2
Color check1 = playerList[0].getFaction();
//P2 is 2,1
Color check2 = playerList[1].getFaction();
GameState state = new GameState(playerList, new Board(), gameDeck, gameBag, score);
Set<Player> winners = Game.run(state, new StandardSettings());
for(Player p : winners)
{
if(p.getFaction().equals(check1))
{
p1Wins++;
}
else if(p.getFaction().equals(check2))
{
p2Wins++;
}
}
}
System.out.println(p1Wins);
System.out.println(p2Wins);
assertTrue(p2Wins > p1Wins);
} | 4 |
public boolean hasPreviouslyJudged(Judge j, Pair pairToCheck,
List<Round> rounds) {
for (Round r : rounds) {
for (Pair currPair : r.getPairs()) {
if (currPair.getAffTeam() == pairToCheck.getAffTeam()
|| currPair.getAffTeam() == pairToCheck.getNegTeam()
|| currPair.getNegTeam() == pairToCheck.getAffTeam()
|| currPair.getNegTeam() == pairToCheck.getNegTeam()) {
if (currPair.getJudges().contains(j)) {
// the candidate judge has previously judged some team
// in the pair
return true;
}
}
}
}
return false;
} | 7 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Product other = (Product) obj;
if (!Objects.equals(this.name, other.name)) {
return false;
}
if (Double.doubleToLongBits(this.price) != Double.doubleToLongBits(other.price)) {
return false;
}
return true;
} | 4 |
public void setActive(boolean active){
if(this.active == false && active == true){
this.status = Status.JOINABLE;
}
if(this.active == true && active == false){
File fichier_language = new File(OneInTheChamber.instance.getDataFolder() + File.separator + "Language.yml");
FileConfiguration Language = YamlConfiguration.loadConfiguration(fichier_language);
String end = Language.getString("Language.Arena.End");
this.stop(end, Status.NOTJOINABLE);
}
this.active = active;
SignManager.updateSigns(this);
} | 4 |
@Override
public void update(Object obj) {
if(obj.equals("Revived") || obj.equals("Alive")){
recordRevive();
} else if(obj.equals("Dead")){
recordKill();
}
} | 3 |
@Override
public void run() {
File file = new File(tmpFileDestination);
if(file.exists()) {
File[] files = file.listFiles();
for(int i=0;i<files.length;i++)
files[i].delete();
MyLog.logINFO("tmpFile has been cleared...");
}
File filePic = new File(tmpPicDestination);
if(filePic.exists()){
File[] files = filePic.listFiles();
for(int i=0;i<files.length;i++)
files[i].delete();
MyLog.logINFO("tmpPicFile has been cleared...");
}
File fileConvertPic = new File(convertPicDestion);
if(fileConvertPic.exists()){
File[] files = fileConvertPic.listFiles();
for(int i=0;i<files.length;i++)
files[i].delete();
MyLog.logINFO("convertPicFile has been cleared...");
}
} | 6 |
public static BasicUser lookUp(String username, char[] password){
BasicUser ret = null;
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://174.102.54.43/communityhub", "commhubuser", "foobar");
String query = "SELECT password,role FROM user WHERE username='" + username + "';";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
rs.next();
String testPswd = new String(password);
String dbPswd = rs.getString("password");
String role = rs.getString("role");
ArrayList<Group> legal = new ArrayList<>();
query = "SELECT comm FROM commuser WHERE member='" + username + "';";
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
while(rs.next()){
legal.add(new Group(rs.getString("comm")));
}
if(dbPswd.equals(testPswd)){
switch(role){
case "admin":
ret = new HighPermUser(username, password, legal);
break;
case "moderator":
ret = new MidPermUser(username, password, legal);
break;
case "user":
ret = new LowPermUser(username, password, legal);
break;
}
}
conn.close();
} catch(Exception ex) {
System.out.print("ERROR:");
System.out.println(ex.getMessage());
System.out.println("Tried to login with:" + username);
Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
}
return ret;
} | 6 |
protected static FastVector merge(Sequence seq1, Sequence seq2, boolean oneElements, boolean mergeElements) {
FastVector mergeResult = new FastVector();
//merge 1-sequences
if (oneElements) {
Element element1 = (Element) seq1.getElements().firstElement();
Element element2 = (Element) seq2.getElements().firstElement();
Element element3 = null;
if (mergeElements) {
for (int i = 0; i < element1.getEvents().length; i++) {
if (element1.getEvents()[i] > -1) {
if (element2.getEvents()[i] > -1) {
break;
} else {
element3 = Element.merge(element1, element2);
}
}
}
}
FastVector newElements1 = new FastVector();
//generate <{x}{y}>
newElements1.addElement(element1);
newElements1.addElement(element2);
mergeResult.addElement(new Sequence(newElements1));
//generate <{x,y}>
if (element3 != null) {
FastVector newElements2 = new FastVector();
newElements2.addElement(element3);
mergeResult.addElement(new Sequence(newElements2));
}
return mergeResult;
//merge k-sequences, k > 1
} else {
Element lastElementSeq1 = (Element) seq1.getElements().lastElement();
Element lastElementSeq2 = (Element) seq2.getElements().lastElement();
Sequence resultSeq = new Sequence();
FastVector resultSeqElements = resultSeq.getElements();
//if last two events/items belong to the same element/itemset
if (lastElementSeq2.containsOverOneEvent()) {
for (int i = 0; i < (seq1.getElements().size()-1); i++) {
resultSeqElements.addElement(seq1.getElements().elementAt(i));
}
resultSeqElements.addElement(Element.merge(lastElementSeq1, lastElementSeq2));
mergeResult.addElement(resultSeq);
return mergeResult;
//if last two events/items belong to different elements/itemsets
} else {
for (int i = 0; i < (seq1.getElements().size()); i++) {
resultSeqElements.addElement(seq1.getElements().elementAt(i));
}
resultSeqElements.addElement(lastElementSeq2);
mergeResult.addElement(resultSeq);
return mergeResult;
}
}
} | 9 |
public ArrayList<ArrayList<String>> partition(String s) {
ArrayList<ArrayList<String>> rows = new ArrayList<ArrayList<String>>();
ArrayList<String> row = new ArrayList<String>();
int len = s.length();
if (len == 0 || len == 1){
row.add(s);
rows.add(row);
}
Set<String> dict = getPalindromes(s);
// String s2 = "$" + s;
// len = len+1;
// boolean[] possible = new boolean[len];
// possible[0] = true;
for (int i = 0; i < len; i++) {
for (int j = i; j >=0; j--) {
if (dict.contains(s.substring(j, i+1))){
}
}
rows.add(row);
}
return rows;
} | 5 |
private void constructAboutPopup()
{
aboutPane = new JEditorPane("text/html", ABOUT_CONTENTS);
aboutPane.addHyperlinkListener(new HyperlinkListener()
{
public void hyperlinkUpdate(HyperlinkEvent e)
{
if (EventType.ACTIVATED.equals(e.getEventType()))
{
try
{
if (Desktop.isDesktopSupported())
{
Desktop.getDesktop().browse(new URI(e.getDescription()));
}
}
catch( IOException e1 )
{
e1.printStackTrace();
}
catch( URISyntaxException e1 )
{
e1.printStackTrace();
}
}
}
});
aboutPane.setEditable(false);
} | 4 |
public void checkDragging(int c, int d) {
if(Greenfoot.mousePressed(this) && !isGrabbed){
// grab the object
isGrabbed = true;
wasGrabbed = true;
contGoneX = this.getX();
contGoneY = this.getY();
// the rest of this block will avoid this object being dragged UNDER other objects
World world = getWorld();
MouseInfo mi = Greenfoot.getMouseInfo();
world.removeObject(this);
world.addObject(this, mi.getX(), mi.getY());
setImage(new GreenfootImage("cont"+c+d+"drag.png"));
return;
}
// check for actual dragging of the object
if((Greenfoot.mouseDragged(this)) && isGrabbed){
// follow the mouse
MouseInfo mi = Greenfoot.getMouseInfo();
setLocation(mi.getX(), mi.getY());
return;
}
// check for mouse button release
if(Greenfoot.mouseDragEnded(this) && isGrabbed && wasGrabbed){
// release the object
setImage(new GreenfootImage("cont"+c+d+".png"));
isGrabbed = false;
wasGrabbed = true;
setLocation(contGoneX,contGoneY);
return;
}
} | 7 |
public Object makeDefaultValue(Class type)
{
if (type == int.class)
return new Integer(0);
else if (type == boolean.class)
return Boolean.FALSE;
else if (type == double.class)
return new Double(0);
else if (type == String.class)
return "";
else if (type == Color.class)
return Color.BLACK;
else if (type == Location.class)
return currentLocation;
else if (Grid.class.isAssignableFrom(type))
return currentGrid;
else
{
try
{
return type.newInstance();
}
catch (Exception ex)
{
return null;
}
}
} | 8 |
private String mobList(List<MOB> mobList, MOB oldMob, String oldValue)
{
final StringBuffer list=new StringBuffer("");
if(oldMob==null)
oldMob=RoomData.getMOBFromCatalog(oldValue);
for (final MOB M2 : mobList)
{
list.append("<OPTION VALUE=\""+RoomData.getMOBCode(mobList, M2)+"\" ");
if((oldMob!=null)&&(oldMob.sameAs(M2)))
list.append("SELECTED");
list.append(">");
list.append(M2.Name()+RoomData.getObjIDSuffix(M2));
}
list.append("<OPTION VALUE=\"\">------ CATALOGED -------");
final String[] names=CMLib.catalog().getCatalogMobNames();
for (final String name : names)
{
list.append("<OPTION VALUE=\"CATALOG-"+name+"\"");
if((oldMob!=null)
&&(CMLib.flags().isCataloged(oldMob))
&&(oldMob.Name().equalsIgnoreCase(name)))
list.append(" SELECTED");
list.append(">"+name);
}
return list.toString();
} | 8 |
@Override public boolean equals( Object oth ) {
if( !(oth instanceof TraceNode) ) return false;
TraceNode tn = (TraceNode)oth;
return
division == tn.division &&
equalsOrBothNull(material, tn.material) &&
splitPoint == tn.splitPoint &&
equalsOrBothNull(subNodeA, tn.subNodeA) &&
equalsOrBothNull(subNodeB, tn.subNodeB);
} | 5 |
public void WGSafeQuit(String sender) {
for(Game game : new HashSet<Game>(games.values())) {
if(saveGame(game)) {
sendMessage(sender, "Game " + game.id + " saved.");
}
else {
sendMessage(sender, MSG_SAVEERROR);
}
}
// Wait a second or 2, otherwise the bot will quit before the queue is processed
try {
Thread.sleep(2000);
} catch (Exception e2) {
// Do nothing.
}
disconnect();
System.out.println("Exiting, WGSAFEQUIT command issued.");
System.exit(0);
} | 3 |
private void calcNormalizedDirection(Point result,
int x1, int y1, int x2, int y2)
{
// Hajo: calculate normalized vector components
int dxn = (x1 == x2) ? 0 : (x1 < x2) ? 1 : -1;
int dyn = (y1 == y2) ? 0 : (y1 < y2) ? 1 : -1;
if(dxn != 0 && dyn != 0) {
// Hajo: diagonal cases ... we try each direction by random, but
// never both in one step, to get a walkable corridor.
if(rand.nextInt(1000) > 500) {
result.x = dxn;
result.y = 0;
} else {
result.x = 0;
result.y = dyn;
}
} else {
// Hajo: clean cases, length of (dx,dy) already 1
result.x = dxn;
result.y = dyn;
}
} | 7 |
public HashMap<String, String> constructHashMap(){
int num=255;
HashMap<String,String> binaryDecimal = new HashMap<String, String>();
binaryDecimal.put("00000000","0");
StringBuilder remainders ;
while(num!=0){
remainders = new StringBuilder();
int temp = num;
while(temp!=0){
remainders.append(temp%2);
temp=temp/2;
}
binaryDecimal.put(eightBitZeros.substring(0,8-remainders.length())+remainders.reverse().toString(), String.valueOf(num));
num--;
}
return binaryDecimal;
} | 2 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.