text stringlengths 14 410k | label int32 0 9 |
|---|---|
private final void setBufferStrategy() {
try {
createBufferStrategy(2);
Thread.sleep(1000);
} catch (Exception e) {
logger.error(e, "Couldn't set buffer strategy");
Runtime.getRuntime().exit(0xDEADBEEF);
}
bufferStrategy = getBufferStrategy();
} | 1 |
protected String getExtension(String path) {
String extension = "";
int i = path.lastIndexOf('.');
if (i > 0) {
extension = path.substring(i+1);
}
return extension;
} | 1 |
@Override
public void caseAParaComando(AParaComando node)
{
inAParaComando(node);
if(node.getVar() != null)
{
node.getVar().apply(this);
}
if(node.getADe() != null)
{
node.getADe().apply(this);
}
if(node.getAAte() != null)
{
node.getAAte().apply(this);
}
{
List<PComando> copy = new ArrayList<PComando>(node.getComando());
for(PComando e : copy)
{
e.apply(this);
}
}
outAParaComando(node);
} | 4 |
public Node<T> getSuccessor(Node<T> node) {
if (node.getRight() != null) {
node = node.getRight();
while (node.getLeft() != null)
node = node.getLeft();
return node;
}
Node<T> temp = node.getParent();
while (temp != null && node == temp.getRight()) {
node = temp;
temp = temp.getParent();
}
return temp;
} | 4 |
private int writeXrefSubSection(int beginIndex) throws IOException {
int beginObjNum = entries.get(beginIndex).getReference().getObjectNumber();
// Determine how many entries in this sub-section
int nextContiguous = beginObjNum + 1;
for(int i = beginIndex+1; i < entries.size(); i++) {
if (entries.get(i).getReference().getObjectNumber() == nextContiguous)
nextContiguous++;
else
break;
}
int subSectionLength = nextContiguous - beginObjNum;
// Output sub-section header
writeInteger(beginObjNum);
output.write(SPACE);
writeInteger(subSectionLength);
output.write(NEWLINE);
for(int i = beginIndex; i < (beginIndex+subSectionLength); i++) {
Entry entry = entries.get(i);
if (entry.isDeleted()) {
// 10-digit-integer:nextFreeObjectNumber SPACE 5-digit-integer:generationNumber SPACE 'f' CRLF
writeZeroPaddedLong(entry.getNextDeletedObjectNumber(), 10);
output.write(' ');
writeZeroPaddedLong(entry.getReference().getGenerationNumber()+1, 5);
output.write(' ');
output.write('f');
output.write('\r');
output.write('\n');
}
else {
// 10-digit-integer:byteOffset SPACE 5-digit-integer:generationNumber SPACE 'n' CRLF
writeZeroPaddedLong(entry.getPosition(), 10);
output.write(' ');
writeZeroPaddedLong(entry.getReference().getGenerationNumber(), 5);
output.write(' ');
output.write('n');
output.write('\r');
output.write('\n');
}
}
return subSectionLength;
} | 4 |
public void saveAs() {
try {
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Windows BMP file", "bmp");
FileNameExtensionFilter filter2 = new FileNameExtensionFilter(
"JPEG file", "jpg", "jpeg");
FileNameExtensionFilter filter3 = new FileNameExtensionFilter(
"PNG", "png");
JFileChooser chooser = new JFileChooser();
chooser.addChoosableFileFilter(filter);
chooser.addChoosableFileFilter(filter2);
chooser.addChoosableFileFilter(filter3);
if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
if (!file.getName().contains(".")) {
if (chooser.getFileFilter() == filter3) {
file = new File(file.getParent(), file.getName()
+ ".png");
ImageIO.write(image, "PNG", file);
} else if (chooser.getFileFilter() == filter2) {
file = new File(file.getParent(), file.getName()
+ ".jpg");
ImageIO.write(image, "JPEG", file);
} else if (chooser.getFileFilter() == filter) {
file = new File(file.getParent(), file.getName()
+ ".bmp");
ImageIO.write(image, "BMP", file);
} else {
file = new File(file.getParent(), file.getName()
+ ".png");
ImageIO.write(image, "PNG", file);
}
}
GUI.setTitle(file.getName()
+ "-GrapficEditor " + Constants.ver + " \"" + Constants.verName + "\" " + lang);
}
} catch (IOException e) {
e.printStackTrace();
}
} | 6 |
public static void main(String[] args) {
try { test1(); }
catch (ArithmeticException e) { e.printStackTrace(); }
StdOut.println("--------------------------------");
try { test2(); }
catch (ArithmeticException e) { e.printStackTrace(); }
StdOut.println("--------------------------------");
try { test3(); }
catch (ArithmeticException e) { e.printStackTrace(); }
StdOut.println("--------------------------------");
try { test4(); }
catch (ArithmeticException e) { e.printStackTrace(); }
StdOut.println("--------------------------------");
int M = Integer.parseInt(args[0]);
int N = Integer.parseInt(args[1]);
double[] c = new double[N];
double[] b = new double[M];
double[][] A = new double[M][N];
for (int j = 0; j < N; j++)
c[j] = StdRandom.uniform(1000);
for (int i = 0; i < M; i++)
b[i] = StdRandom.uniform(1000);
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
A[i][j] = StdRandom.uniform(100);
Simplex lp = new Simplex(A, b, c);
StdOut.println(lp.value());
} | 8 |
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
boolean isPalindrome = false;
int counter = 0;
int middle = input.length()/2;
for (int i=0; i<middle; i++){
int m = input.length();
if (input.charAt(i) == input.charAt(m-1 -i)){
counter++;
}
}
if(counter == middle) {
isPalindrome = true;
System.out.println(isPalindrome);
}
} | 3 |
public String getURLName() {
return "n!\"" + name.replace(" ", "+") + (set != null ? "\"%20e:" + set : "\"");
} | 1 |
public long getS() {
return initTemps[0];
} | 0 |
public Deck(){
super();
// Populate our deck
Card.CARD_SUIT[] arrSuits = Card.CARD_SUIT.values();
Card.FACE_VALUE[] arrFaces = Card.FACE_VALUE.values();
for(Card.CARD_SUIT s : arrSuits) {
for(Card.FACE_VALUE f : arrFaces) {
this.addCard(new Card(s, f));
}
}
} | 2 |
@SuppressWarnings({"unchecked"})
private void heapifyMax(int index) {
int left = getLeft(index);
int right = getRight(index);
int greatest;
if (left < size && comparator.compare((T) queue[left], (T) queue[index]) > 0) {
greatest = left;
} else {
greatest = index;
}
if (right < size && comparator.compare((T) queue[right], (T) queue[greatest]) > 0) {
greatest = right;
}
if (greatest != index) {
swap(index, greatest);
heapifyMax(greatest);
}
} | 5 |
public boolean insertarProceso(Proceso p) {
int prioridad = p.getPrioridadDinamica();
boolean agrego = false;
if (this.listas[prioridad].indexOf(p) == -1) {
if (prioridad < this.menorPrioridadNoVacia) {
this.menorPrioridadNoVacia = prioridad;
}
agrego = this.listas[prioridad].add(p);
if (agrego) {
this.numProcesos++;
}
}
return agrego;
} | 3 |
private static int initOriginal(final Display display, Composite inComposite) {
final Composite originalCompsite = new Composite(inComposite, SWT.BORDER);
int heightHint = 0;
try {
original = new Image(display, Resource.class.getResourceAsStream(IMAGE_PATH));
if (original.getImageData().depth != 8 && original.getImageData().depth != 24)
throw new RuntimeException("Only support 8 bit images. The current image's depth is "
+ original.getImageData().depth);
} catch (Exception e1) {
throw new RuntimeException(e1);
}
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.grabExcessHorizontalSpace = true;
heightHint = original.getImageData().height + 20;
gridData.heightHint = heightHint;
originalCompsite.setLayoutData(gridData);
originalHisto = ImageUtils.analyzeHistogram(original.getImageData());
originalCompsite.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent event) {
ImageUtils.paintImage(event.gc, original, originalHisto);
}
});
return heightHint;
} | 3 |
public void dump() {
int i = 0;
while (i<hp) {
int len = heap[i];
System.out.print("Object at address " + (i - size)
+ ", length=" + len
+ ", data=[");
for (int j=1; j<=len; j++) {
System.out.print(Integer.toString(heap[i+j]));
if (j<len) {
System.out.print(", ");
}
}
System.out.println("]");
i += (len + 1);
}
System.out.println("Heap allocation pointer: " + hp);
} | 3 |
@Override
public synchronized void execute() throws IOException, RoutingException
{
try
{
/* Set the local node as already asked */
nodes.put(this.localNode.getNode(), ASKED);
/**
* We add all nodes here instead of the K-Closest because there may be the case that the K-Closest are offline
* - The operation takes care of looking at the K-Closest.
*/
List<Node> allNodes = this.localNode.getRoutingTable().getAllNodes();
this.addNodes(allNodes);
/* Also add the initial set of nodes to the routeLengthChecker */
this.routeLengthChecker.addInitialNodes(allNodes);
/**
* If we haven't found the requested amount of content as yet,
* keey trying until config.operationTimeout() time has expired
*/
int totalTimeWaited = 0;
int timeInterval = 10; // We re-check every n milliseconds
while (totalTimeWaited < this.config.operationTimeout())
{
if (!this.askNodesorFinish() && !isContentFound)
{
wait(timeInterval);
totalTimeWaited += timeInterval;
}
else
{
break;
}
}
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
} | 4 |
private int[] parsePrefix() {
assert (peek() != null) : "parsePrefix() can't start at EOF";
int[] toReturn = {0, 0, 0};
// First, parse a digit, if we begin with one
Boolean quitNow = parseFirstDigit(toReturn);
if (quitNow == Boolean.TRUE){
return toReturn;
}
// Parse whatever's left
switch(peek().type){
case NTY:
parseNty(toReturn);
break;
case TEEN:
toReturn[TENS_DIG] = 1;
toReturn[ONES_DIG] = consume().value;
break;
case DIGIT:
assert(toReturn[HUNDREDS_DIG] != 0) : "We should've parsed this above";
toReturn[ONES_DIG] = consume().value;
break;
default:
if (toReturn[HUNDREDS_DIG] == 0){
em.error("Unexpected token: \"%s\"", peek());
return null;
}
break;
}
return toReturn;
} | 5 |
private void connectToNotchers()
{
//define and instantiate a worker thread to create the file
//----------------------------------------------------------------------
//class SwingWorker
//
workerThread = new SwingWorker<Void, String>() {
@Override
public Void doInBackground() {
notcherHandler.connect();
createNotcherControllersTrigger = true;
return(null);
}//end of doInBackground
@Override
public void done() {
//clear in progress message here if one is being displayed
try {
//use get(); function here to retrieve results if necessary
//note that Void type here and above would be replaced with
//the type of variable to be returned
Void v = get();
} catch (InterruptedException ignore) {}
catch (java.util.concurrent.ExecutionException e) {
String why;
if (e.getCause() != null) {
why = e.getCause().getMessage();
} else {
why = e.getMessage();
}
System.err.println("Error creating file: " + why);
}//catch
}//end of done
@Override
protected void process(java.util.List <String> pairs) {
//this method is not used by this application as it is limited
//the publish method cannot be easily called outside the class, so
//messages are displayed using a ThreadSafeLogger object and status
//components are updated using a GUIUpdater object
}//end of process
};//end of class SwingWorker
//----------------------------------------------------------------------
workerThread.execute();
}//end of Controller::connectToNotchers | 3 |
public void update() {
int xa = 0, ya = 0;
if(anim < 7500) anim++;
else anim = 0;
if (input.up) ya--;
if (input.down) ya++;
if (input.left) xa--;
if (input.right) xa++;
if (xa != 0 || ya != 0){
move(xa, ya);
walking = true;
} else walking = false;
} | 7 |
private void goToMarket() {
switch(mSSN % 4) {
case 0:
mItemsDesired.put(EnumItemType.PIZZA, sBaseWanted);
break;
case 1:
mItemsDesired.put(EnumItemType.STEAK, sBaseWanted);
break;
case 2:
mItemsDesired.put(EnumItemType.CHICKEN, sBaseWanted);
break;
case 3:
mItemsDesired.put(EnumItemType.SALAD, sBaseWanted);
break;
}
//activate marketcustomer role
for (Role iRole : mRoles.keySet()){
if (iRole instanceof MarketCustomer){
mRoles.put(iRole, true); //set active
iRole.setPerson(this);
}
}
Location location;
if(mSSN%2 == 0) {
location = ContactList.getDoorLocation(ContactList.cMARKET1_LOCATION);
} else {
location = ContactList.getDoorLocation(ContactList.cMARKET2_LOCATION);
}
mCommuterRole.mActive = true;
mCommuterRole.setLocation(location);
mCommutingTo = EnumCommuteTo.MARKET;
mCommuterRole.mState = PersonState.walking;
} | 7 |
public long getSalary() {
return salary;
} | 0 |
@EventHandler
public void EnderDragonFastDigging(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getEnderDragonConfig().getDouble("EnderDragon.FastDigging.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getEnderDragonConfig().getBoolean("EnderDragon.FastDigging.Enabled", true) && damager instanceof EnderDragon && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, plugin.getEnderDragonConfig().getInt("EnderDragon.FastDigging.Time"), plugin.getEnderDragonConfig().getInt("EnderDragon.FastDigging.Power")));
}
} | 6 |
public void mapToKey(GameAction gameAction, int keyCode) {
keyActions[keyCode] = gameAction;
} | 0 |
public void setLayout(int layoutType){
switch (layoutType) {
case LookManager.GREEN_LAYOUT:
Dimension size = (getSize().height == 0 ? getPreferredSize() : getSize());
setIcon(new ImageIcon(imgLdr.scaleBufferedImage(imgLdr.loadBufferedImage(GUIImageLoader.GREEN_BUTTON_ACTIVE), size)));
setRolloverIcon(new ImageIcon(imgLdr.scaleBufferedImage(imgLdr.loadBufferedImage(GUIImageLoader.GREEN_BUTTON_HOVER), size)));
setPressedIcon(new ImageIcon(imgLdr.scaleBufferedImage(imgLdr.loadBufferedImage(GUIImageLoader.GREEN_BUTTON_PRESSED), size)));
setDisabledIcon(new ImageIcon(imgLdr.scaleBufferedImage(imgLdr.loadBufferedImage(GUIImageLoader.GREEN_BUTTON_INACTIVE), size)));
break;
default:
break;
}
setHorizontalTextPosition(JButton.CENTER);
setVerticalTextPosition(JButton.CENTER);
} | 2 |
public void dragSelectCard(CardView clickCardView , int distance) {
int startindex = cardViews.indexOf(clickCardView);
int endIndex = 0;
if (distance < 0) {
distance -= cardGap / 2;
}
int count = distance/cardGap;
boolean isModeZero = (distance % cardGap == 0);
if(count > 0) {
endIndex = startindex + count;
} else if(count < 0){
endIndex = startindex ;
startindex = startindex + count;
} else {
if (!isModeZero) {
if (Math.abs(distance % cardGap) < cardGap / 2) {
startindex = -1;
}
}
endIndex = startindex;
}
CardView cardView;
boolean isSelect;
for(int i = 0 ; i < cardViews.size() ; i ++ ) {
cardView = cardViews.get(i);
isSelect = cardViewsSelectState.get(i);
if(i >= startindex && i <= endIndex)
isSelect = !isSelect;
selectCard(cardView , isSelect);
}
} | 8 |
public void updateBundles(byte[] data) {
bundles.clear();
int dIndex = 0;
while (dIndex < data.length) {
int startIndex = dIndex+2;
byte bundleID = data[dIndex+1];
int endIndex = (int)data[dIndex] + dIndex;
long value = 0;
for (int i = startIndex; i <= endIndex; i++)
value = (value << 8) + (data[i] & 0xff);
bundles.add("Bundle " + (char)bundleID + ": " + String.valueOf(value));
dIndex = endIndex + 1;
}
} | 2 |
public boolean ewify() throws IOException, FileNotFoundException{
FileReader input = new FileReader(this.source);
BufferedReader bufRead = new BufferedReader(input);
String myLine = null;
ArrayList<EweRule> arrayRules=new ArrayList<EweRule>();
int currentRule=0;
boolean flagThen=false;
boolean flagWhen=false;
User user=new User("my user");
Service service = new Service("Drools");
user.setService(service);
while ( (myLine = bufRead.readLine()) != null)
{
if(myLine.startsWith("rule")){
String title = myLine.split("\"")[1];
EweRule myRule=new EweRule(title);
myRule.setUser(user);
arrayRules.add(myRule);
}
if(flagWhen){
//ewe only supports one event
flagWhen=false;
EweRule copyRule=arrayRules.get(currentRule);
Event myEvent=new Event(myLine);
copyRule.getUser().getService().setEvent(myEvent);
arrayRules.set(currentRule, copyRule);
}
if(myLine.contains("when")){
flagWhen=true;
}
if(flagThen&&myLine.contains("end")){
flagThen=false;
rdfy(arrayRules.get(currentRule));
currentRule++;
}
if (flagThen){
//flagThen=false;
EweRule copyRule=arrayRules.get(currentRule);
Action myAction=new Action(myLine);
copyRule.getUser().getService().setAction(myAction);
arrayRules.set(currentRule, copyRule);
}
if(myLine.contains("then")){
flagWhen=false;
flagThen=true;
}
}
return true;
} | 8 |
static void graph1(Metrics metrics, Main main){
Metrics.Graph graph = metrics.createGraph("action");
String ac = main.getConfig().getString("action");
if (ac.equalsIgnoreCase("warn")) {
graph.addPlotter(new SimplePlotter("Warn"));
} else if(ac.equalsIgnoreCase("kick")){
graph.addPlotter(new SimplePlotter("Kick"));
}else if(ac.equalsIgnoreCase("ban")){
graph.addPlotter(new SimplePlotter("Ban"));
}else if(ac.equalsIgnoreCase("custom")){
graph.addPlotter(new SimplePlotter("Custom"));
}else{
graph.addPlotter(new SimplePlotter("Other"));
}
main.debug("graph1 sent");
} | 4 |
public static void noSpace(String string) throws JSONException {
int i, length = string.length();
if (length == 0) {
throw new JSONException("Empty string.");
}
for (i = 0; i < length; i += 1) {
if (Character.isWhitespace(string.charAt(i))) {
throw new JSONException("'" + string +
"' contains a space character.");
}
}
} | 3 |
private void jRadioButtonXMLtoJSONActionPerformed(
final java.awt.event.ActionEvent evt) {
switch (etat) {
case INIT_JSON_XML:
etat = Etat.INIT_XML_JSON;
break;
case INIT_XML_JSON:
etat = Etat.INIT_XML_JSON;
break;
case OUTPUT_JSON_XML:
throw new RuntimeException("Bouton Convertir : "
+ "action interdite car "
+ "Etat OUTPUT_JSON_XML");
case OUTPUT_XML_JSON:
throw new RuntimeException("Bouton Convertir : "
+ "action interdite car "
+ "Etat OUTPUT_XML_JSON");
case OUTPUT_XML_JSON_VIA_DOM:
throw new RuntimeException("Bouton Convertir : "
+ "action interdite car "
+ "Etat OUTPUT_XML_JSON_VIA_DOM");
case VIEW_JSON_XML:
throw new RuntimeException("Bouton Convertir : "
+ "action interdite car"
+ "Etat VIEW_JSON_XML");
case VIEW_XML_JSON:
throw new RuntimeException("Bouton Convertir : "
+ "action interdite car "
+ "Etat VIEW_XML_JSON");
default:
break;
}
gestionEtat(etat);
} | 7 |
public static void main( String[] args ) {
JFrame frame = new JFrame( "Graph" );
frame.setBounds( 20, 20, 800, 600 );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
Graph graph = new Graph();
for( GraphItem item : createTestItems() ){
graph.addItem( item );
}
ConnectionableCapabilityHandler connectability = new ConnectionableCapabilityHandler();
connectability.setOpenEnded( new OpenEndedLineConnectionStrategy() );
connectability.setFactory( factory() );
GraphPanel panel = new GraphPanel();
panel.setGraph( graph );
panel.setCapability( CapabilityName.CONNECTABLE, connectability );
frame.add( panel );
frame.setVisible( true );
} | 1 |
public void printATMs()
{
Set<Integer> keys = supportedATMs.keySet();
System.out.println("Bank " + bankID + " ATMs:");
for(Integer key: keys)
{
System.out.println(supportedATMs.get(key));
}
} | 1 |
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(ShortcutConfig.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ShortcutConfig.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ShortcutConfig.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ShortcutConfig.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
ShortcutConfig dialog = new ShortcutConfig(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 synchronized void transfer(int from, int to, double amount) throws InterruptedException
{
while (accounts[from] < amount)
wait();
System.out.print(Thread.currentThread());
accounts[from] -= amount;
System.out.printf(" %10.2f from %d to %d", amount, from, to);
accounts[to] += amount;
System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
notifyAll();
} | 1 |
@Override
protected void finalize() throws Throwable {
try {
close();
} catch (final IOException ex) {
LOGGER.warn("Problem trying to auto close file handles...", ex);
} finally {
super.finalize();
}
} | 1 |
public List<Integer> findSubstring2(String S, String[] L) {
List<Integer> res = new ArrayList<Integer>();
if(S == null || S.length() == 0 || L == null || L.length == 0) return res;
int L2 = S.length();
int l = L[0].length();
int L1 = L.length * l;
for(int i = 0; i <= L2 - L1; ++i) {
String sub = S.substring(i, i + L1);
List<String> T = new ArrayList<String>(L.length);
for(int j = 0; j < L.length; ++j){
String meta = sub.substring(j * l, (j + 1) * l);
T.add(meta);
}
for (String s : L){
if (!T.remove(s)) break;
}
if (T.isEmpty()) res.add(i);
}
return res;
} | 9 |
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
try{
//Se extraen todas las caciones
leer_archivo cancionesActualizadas=new leer_archivo(100);
String [] lista_p=cancionesActualizadas.leer_archivo1("Lista_canciones.txt");
// Se tiene que actulizar el txt de todas las canciones
File TXTactualizado = new File("Lista_canciones.txt");
TXTactualizado.createNewFile();
FileWriter TXTactualizadoEscritura = new FileWriter(TXTactualizado);
BufferedWriter TXTactualizadoEscribir = new BufferedWriter(TXTactualizadoEscritura);
//Se realiza con control para asegurarse de no escribir el nombre de la cancion que se elimino
int i=0;
boolean espacio=false;
while(lista_p[i]!=null){
if(Lista_meta[1].equals(lista_p[i])||lista_p[i].equals("") ){
}
else{
espacio=true;
TXTactualizadoEscribir.write(lista_p[i]);
}
if(espacio){
TXTactualizadoEscribir.newLine();
}
espacio=false;
i++;
}
TXTactualizadoEscribir.close();
File eliminarTXT=new File(Lista_meta[1]+".txt");
eliminarTXT.delete();
JOptionPane.showMessageDialog(frame,"La cancion ha sido eliminada exitosamente");
dispose();
InterfazPrincipal ob = new InterfazPrincipal();
ob.setVisible(true);
}
catch(Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_jButton3ActionPerformed | 5 |
int snake( int x, int y, FragList fl )
{
while ( x<fl.fragments.size()&&y<fragments.size() )
{
if ( fragments.get(y).equals(fl.fragments.get(x)) )
{
x++;
y++;
}
else
break;
}
return x;
} | 3 |
public int calculateRewardPoints() {
int points = 0;
for (int i = 0; i < purchases; i++) {
points = points + 100;
}
return points;
} | 1 |
public void putByte(byte newByte) {
byte[] ar = new byte[1];
ar[0] = newByte;
msg = new String(ar);
if (newByte == '<') {
// new Message Start detected
// reset Msg String and add Start-delimiter
//outmsg = msg;
receivingMessage = true;
} else if (newByte == '>' && receivingMessage == true) {
// End of Message
// Put Message in Receive-Buffer
//outmsg = outmsg.concat(msg);
try {
inQueue.put(outmsg);
testMethod(outmsg);
} catch (InterruptedException e) {
// TODO handle Exception
}
msg = "";
outmsg = "";
receivingMessage = false;
} else if (receivingMessage == true) {
// Add Byte to receive Message String
outmsg = outmsg.concat(msg);
} else {
// Dont process Data
}
} | 5 |
@Test
public void sizeIsCorrect()
{
boolean test = true;
for (int i = 0; i < 10000; i++)
{
queue.clear();
Random rand = new Random();
int r = rand.nextInt(1000);
for (int j = 0; j < r; j++) queue.enqueue("allo");
int b = (r <= 0) ? 0 : rand.nextInt(r);
for (int j = 0; j < b; j++) queue.dequeue();
if (queue.size() != r - b) test = false;
}
assertTrue(test);
} | 5 |
public StartMenu(GameStateManager gsm) {
this.gsm = gsm;
try {
bg = new Background("/Background/Background.png", 1, false, 0);
bg.setVector(-0.1, 0);
titleColor = new Color(128, 0, 0);
titleFont = new Font("Maximilien", Font.PLAIN, 28);
maximilien = new Font("Maximilien", Font.PLAIN, 15);
} catch (final Exception e) {
e.printStackTrace();
}
} | 1 |
public synchronized static void addTheaterSeats(TheaterSeats theSeats){
if(!seats.contains(theSeats)){
if(seats.size() < cacheLimit)
seats.add(theSeats);
else{
for(int i=0;i<(cacheLimit/10);i++)
seats.removeFirst(); //Removes the oldest seat in the list
seats.add(theSeats);
}
}
else{
seats.remove(theSeats);
seats.add(theSeats);
}
} | 3 |
public static String doubleToString(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
return "null";
}
// Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d);
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
} | 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(TelaRelatorio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TelaRelatorio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TelaRelatorio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TelaRelatorio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
TelaRelatorio dialog = new TelaRelatorio(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 JSONArray names() {
JSONArray ja = new JSONArray();
Iterator keys = this.keys();
while (keys.hasNext()) {
ja.put(keys.next());
}
return ja.length() == 0 ? null : ja;
} | 2 |
public void updateDamageListener(String resource, int damageToAdd) {
GameActor actor = actors.get(resource);
if(actor == null) {
createPrototype(resource);
actor = actors.get(resource);
}
WeaponsComponent wc = (WeaponsComponent)actor.getComponent("WeaponsComponent");
wc.setDamage(wc.getDamage() + damageToAdd);
} | 1 |
public ConvexMultivariateRealFunction[] getResourcesConvexConditions(double alpha)
{
resourcesConvex = null; // нужный костыль
if(resourcesConvex == null)
{
double talpha = getT(alpha);
int mainSize = db.tools.size();
int rowSize = db.resources.size();
ConvexMultivariateRealFunction[] conditions = new ConvexMultivariateRealFunction[rowSize];
for(Resource currentResource : db.resources)
{
int i = db.resourceIndexById.get(currentResource.getId());
double[][] p = new double[mainSize][mainSize];
double[] q = new double[mainSize];
double[] nrftsm = getNrftsm()[i];
double[] nrftsD = getNrftsd()[i];
double resourceNumber = getResourceNumber()[i];
double resourceNumberDeviation = getResourceNumberDeviation()[i];
//0.5*XPX + QX + R <= 0
//Fill p-matrix
for (int j = 0; j < mainSize; ++j)
{
for (int k = 0; k < mainSize; ++k)
{
p[j][k] = -nrftsm[j]*nrftsm[k];//-2*nrftsm[j]*nrftsm[k];
if(k == j)
p[j][j] += Math.pow(talpha*nrftsD[j], 2);
p[j][k] *= 2;
}
}
//Fill q-array
for (int j = 0; j < mainSize; ++j)
q[j] = 2*resourceNumber*nrftsm[j];
//r-value
double r =
Math.pow(talpha*resourceNumberDeviation,2)
- Math.pow(resourceNumber, 2);
conditions[i]
= new QuadraticMultivariateRealFunction(p, q, r);
}
resourcesConvex = conditions;
}
return resourcesConvex;
} | 6 |
void updateHash(byte[] input, int pos, int end) {
// WINDOW_MASK
int hPos = pos & 0x7FFF;
int val = this.val;
val = ((val << 5) ^ (pos + 2 < end ? input[pos + 2] & 0xFF : 0)) & 0x7FFF;
hashVal[hPos] = val;
int tmp = head[val];
prev[hPos] = (tmp != -1 && hashVal[tmp] == val) ? tmp : hPos;
head[val] = hPos;
tmp = same[(pos - 1) & 0x7FFF];
if (tmp < 1) {
tmp = 1;
}
tmp += pos;
byte b = input[pos];
while (tmp < end && b == input[tmp]) {
tmp++;
}
tmp -= pos;
tmp--;
same[hPos] = tmp;
tmp = ((tmp - 3) & 0xFF) ^ val;
hashVal2[hPos] = tmp;
int h = head2[tmp];
prev2[hPos] = h != -1 && hashVal2[h] == tmp ? h : hPos;
head2[tmp] = hPos;
this.val = val;
} | 8 |
public static void listPortals( BSPlayer p ) {
for ( ServerInfo s : portals.keySet() ) {
String message = "";
message += ChatColor.GOLD + s.getName() + ": " + ChatColor.RESET;
ArrayList<Portal> list = portals.get( s );
for ( Portal portal : list ) {
message += portal.getName() + ", ";
}
p.sendMessage( message );
}
} | 2 |
public Point2D[] points() {
return (Point2D[]) verticesToPoints.values().toArray(new Point2D[0]);
} | 0 |
private void fileUpload(final DataPacket<AFile> dp, Object[] args){
/*
* Get some information out of data packet
*/
AFile recvAfile = dp.getContent();
byte[] filecontent = recvAfile.getFile();
Log fileLog = dp.getLog();
byte[] logToByte = recvAfile.getEditInfo().getBytes();
PublicKey clientPK = CryptoKit.getPublicKey(fileLog.getidentity());
/*
* verify success
*/
if(clientPK != null && CryptoKit.verifyWithRSA(TransformKit.byteMerger(filecontent, logToByte),
recvAfile.getSignature(),
clientPK)) {
System.out.println("file recv, verify success");
String fileName = recvAfile.getName();
File createFile = new File(filePath + fileName);
File createLog = new File(filePath + fileName + ".log");
try {
/*
* create real file
*/
createFile.createNewFile();
/*
* create .log file
*/
createLog.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
/*
* write .log file
*/
/*
* xxx.log format is like getEditInfo() | signature()
*/
String logContent = recvAfile.getEditInfo() + "|" + TransformKit.bytes2HexString(recvAfile.getSignature());
FileKit.write(logContent.getBytes(), createLog);
/*
* write real file
*/
FileKit.write(filecontent, createFile);
} catch (IOException e) {
e.printStackTrace();
}
/*
* check file's name are in the file list or not;
* if not, then add it
* if it is in, then do nothing
*/
if(!fileList.contains(createFile)){
fileListLock.lock();
try{
fileList.add(createFile);
}
finally{
fileListLock.unlock();
}
}
/*
* add this operation into operation Log
*/
XMLHelper xhelper = new XMLHelper(operationLogPath, operationLogRoot);
try {
xhelper.addlog(dp.getLog());
} catch (Exception e) {
e.printStackTrace();
}
broadcastMessage(recvAfile.getp2pMessages(), args, dp.getSenderIP());
}
/*
* is verify is failed,then send a failed datapacket back
*/
else{
System.out.println(fileLog.getidentity() + "(" + dp.getSenderIP() + ") tries to upload a file, "
+ "but signature is not valid.");
final DataPacket<String> returndp = new DataPacket<String>(myIP, String.class, OperationType.fileOpFail);
returndp.setContent("[Error from server] Signature verification failed");
final String clientIP = dp.getSenderIP();
(new Thread() {
public void run() {
try {
IHost senderStub = getStub(clientIP);
if (senderStub != null)
senderStub.transferData(returndp);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
} | 8 |
private Integer findNext(String date, TreeSet<Integer> dates) {
int givenDate = Integer.parseInt(date.split("/")[0] + date.split("/")[1]);
for (Integer integer : dates) {
if (integer == givenDate || integer > givenDate)
return integer;
}
return 0;
} | 3 |
private void generateOpenAndClosedLists() {
/*load intial starting cell into the open list*/
for (int i = 0; i < localMap.size(); i++) {
if (localMap.get(i).locX == sX && localMap.get(i).locY == sY) {
openList.add(generateNewCell(localMap.get(i), new Cell(localMap.get(i), sX, sY, 0, 0)));
break;
}
}
/*loop unit finished*/
for (;;) {
if (graphics) {
graphic.updateGraphics();
}
/*find the lowest score*/
int lowestFScore = Integer.MAX_VALUE;
for (int i = 0; i < openList.size(); i++) {
if (openList.get(i).fScore < lowestFScore) {
lowestFScore = openList.get(i).fScore;
openList.addLast(openList.get(i));
openList.remove(i);
}
}
/*remove lowest score from the open list and add to closed list*/
closedList.addLast(openList.removeLast());
/*if this is has a h score of zero then we are at our destination*/
if (closedList.getLast().hScore == 0) {
break;
}
/*add 4 adjacent squares to open list if applicable*/
addAdjacentCells(closedList.getLast());
}
} | 8 |
private int countEmptyNeighbor(char colorPiece) {
int cnt = 0;
int[] nIndex = new int[TOTALPOS];
for (int t = 0; t < TOTALPOS; t++) {
nIndex[t] = TOTALPOS;
}
for (int i = 0; i < position.length; i++) {
MorrisIntersection pos = position[i];
if (pos.getLetter() == colorPiece) {
List<MorrisIntersection> neighbors = pos.getNeighbor();
for (Iterator<MorrisIntersection> iter = neighbors.iterator(); iter.hasNext(); ) {
MorrisIntersection ngh = iter.next();
if (ngh.isEmpty()) {
int emptyIndex = ngh.getIndex();
boolean added = false;
for (int j = 0; j < TOTALPOS; j++) {
if (emptyIndex == nIndex[j]) {
//this empty is added
added = true;
break;
}
}
if (!added) {
//add this empty to the array, and cnt + 1
nIndex[cnt] = emptyIndex;
cnt++;
}
}
}
}
}
return cnt;
} | 8 |
private void recalcLevel() {
hasGainedLevels = levelOfTower.recalculateLevel();
if (hasGainedLevels != 0) {
for ( GameAction action : getGameActions()) {
if (action.getAttackData() != null) { // getAttackData() returns null if the gameAction does not have an attack.
action.getAttackData().recalculateLevelMultiplier(hasGainedLevels);
}
}
}
} | 3 |
@Override
public Response list() throws IOException
{
if(username.equals(""))
{
return new MessageResponse("Please log in first.");
}
else
{
synchronized(serverIdentifier)
{
if(serverIdentifier.isEmpty())
{
return new MessageResponse("No files available");
}
else
{
Set<String> files = new HashSet<String>();
for(FileServerInfo i: serverIdentifier.values())
{
if(i.isOnline())
{
Socket socket = new Socket(i.getAddress(), i.getPort());
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.flush();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ListRequest listRequest = new ListRequest(hMac.createHash("!list"));
oos.writeObject(listRequest);
oos.flush();
try
{
Response response = (Response) ois.readObject();
if(response instanceof ListResponse)
{
ListResponse listResponse = (ListResponse)response;
if(!hMac.verifyHash(listResponse.gethMac(), listResponse.toString()))
{
System.out.println("This message has been tampered with: " + listResponse.toString());
}
oos.close();
ois.close();
socket.close();
files.addAll(listResponse.getFileNames());
}
if(response instanceof MessageResponse)
{
if(((MessageResponse)response).getMessage().equals("!again"))
{
return list();
}
}
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
return new ListResponse("", files);
}
}
}
} | 9 |
private void spawnBox(int size, int xStart, int yStart){
size = size + 2;
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
if (i == 0 || i == size - 1 || j == 0 || j == size - 1){
Boot.getWorldObj().getTileAtCoords(xStart + i, yStart + j).setTileID(TileID.ASPHALT);
}
}
}
} | 6 |
@Override
public List<V_Ficha_Trab_Num_C> Buscar_Ficha_Trabajador(String iddep, String dni, String nom, String ape_p, String ape_m) {
this.conn = FactoryConnectionDB.open(FactoryConnectionDB.ORACLE);
String sql = "select d.*,RHFU_VIG_CON (d.id_trabajador) as VI_CONTRATO from (select * from RHVD_TRABAJADOR) d, RHVD_USUARIO u where u.id_usuario= d.id_usuario_creacion ";
nom = nom.toUpperCase();
ape_p = ape_p.toUpperCase();
ape_m = ape_m.toUpperCase();
sql += (!"".equals(dni)) ? " and trim(d.NU_DOC)='" + dni.trim() + "'" : "";
sql += (!"".equals(nom)) ? " and upper(d.NO_TRABAJADOR)like '%" + nom.trim() + "%'" : "";
sql += (!"".equals(ape_p)) ? " and upper(d.AP_PATERNO)like '%" + ape_p.trim() + "%'" : "";
sql += (!"".equals(ape_m)) ? " and upper(d.AP_MATERNO)like '%" + ape_m.trim() + "%'" : "";
sql += " order by d.ID_TRABAJADOR desc";
List<V_Ficha_Trab_Num_C> list = new ArrayList<V_Ficha_Trab_Num_C>();
try {
ResultSet rs = this.conn.query(sql);
while (rs.next()) {
V_Ficha_Trab_Num_C v = new V_Ficha_Trab_Num_C();
v.setNo_s_educativa(rs.getString("no_s_educativa"));
v.setAp_nombres_madre(rs.getString("ap_nombres_madre"));
v.setAp_nombres_padre(rs.getString("ap_nombres_padre"));
v.setEs_trabaja_upeu_c(rs.getString("es_trabaja_upeu_c"));
v.setAp_nombres_c(rs.getString("ap_nombres_c"));
v.setFe_nac_c(rs.getString("fe_nac_c"));
v.setId_tipo_doc_c(rs.getString("id_tipo_doc_c"));
v.setNu_doc_c(rs.getString("nu_doc_c"));
v.setLi_inscripcion_vig_essalud_c(rs.getString("li_inscripcion_vig_essalud_c"));
v.setId_conyugue(rs.getString("id_conyugue"));
v.setNo_carrera(rs.getString("no_carrera"));
v.setNo_universidad(rs.getString("no_universidad"));
v.setAr_foto(rs.getString("ar_foto"));
v.setDe_foto(rs.getString("de_foto"));
v.setId_foto(rs.getString("id_foto"));
v.setNo_ar_foto(rs.getString("no_ar_foto"));
v.setTa_ar_foto(rs.getString("ta_ar_foto"));
v.setId_trabajador(rs.getString("id_trabajador"));
v.setAp_paterno(rs.getString("ap_paterno"));
v.setAp_materno(rs.getString("ap_materno"));
v.setNo_trabajador(rs.getString("no_trabajador"));
v.setTi_doc(rs.getString("ti_doc"));
v.setNu_doc(rs.getString("nu_doc"));
v.setEs_civil(rs.getString("es_civil"));
v.setFe_nac(rs.getString("fe_nac"));
v.setNo_nacionalidad(rs.getString("no_nacionalidad"));
v.setNo_departamento(rs.getString("no_departamento"));
v.setNo_provincia(rs.getString("no_provincia"));
v.setNo_distrito(rs.getString("no_distrito"));
v.setTe_trabajador(rs.getString("te_trabajador"));
v.setCl_tra(rs.getString("cl_tra"));
v.setDi_correo_personal(rs.getString("di_correo_personal"));
v.setDi_correo_inst(rs.getString("di_correo_inst"));
v.setCo_sistema_pensionario(rs.getString("co_sistema_pensionario"));
v.setId_situacion_educativa(rs.getString("id_situacion_educativa"));
v.setLi_reg_inst_educativa(rs.getString("li_reg_inst_educativa"));
v.setEs_inst_educ_peru(rs.getString("es_inst_educ_peru"));
v.setCm_otros_estudios(rs.getString("cm_otros_estudios"));
v.setEs_sexo(rs.getString("es_sexo"));
v.setLi_grupo_sanguineo(rs.getString("li_grupo_sanguineo"));
v.setDe_referencia(rs.getString("de_referencia"));
v.setLi_religion(rs.getString("li_religion"));
v.setNo_iglesia(rs.getString("no_iglesia"));
v.setDe_cargo(rs.getString("de_cargo"));
v.setLi_autoridad(rs.getString("li_autoridad"));
v.setNo_ap_autoridad(rs.getString("no_ap_autoridad"));
v.setCl_autoridad(rs.getString("cl_autoridad"));
v.setId_no_afp(rs.getString("id_no_afp"));
v.setEs_afiliado_essalud(rs.getString("es_afiliado_essalud"));
v.setLi_tipo_trabajador(rs.getString("li_tipo_trabajador"));
v.setCa_tipo_hora_pago_refeerencial(rs.getString("ca_tipo_hora_pago_refeerencial"));
v.setEs_factor_rh(rs.getString("es_factor_rh"));
v.setLi_di_dom_a_d1(rs.getString("li_di_dom_a_d1"));
v.setDi_dom_a_d2(rs.getString("di_dom_a_d2"));
v.setLi_di_dom_a_d3(rs.getString("li_di_dom_a_d3"));
v.setDi_dom_a_d4(rs.getString("di_dom_a_d4"));
v.setLi_di_dom_a_d5(rs.getString("li_di_dom_a_d5"));
v.setDi_dom_a_d6(rs.getString("di_dom_a_d6"));
v.setDi_dom_a_ref(rs.getString("di_dom_a_ref"));
v.setDi_dom_a_distrito(rs.getString("di_dom_a_distrito"));
v.setLi_di_dom_leg_d1(rs.getString("li_di_dom_leg_d1"));
v.setDi_dom_leg_d2(rs.getString("di_dom_leg_d2"));
v.setLi_di_dom_leg_d3(rs.getString("li_di_dom_leg_d3"));
v.setDi_dom_leg_d4(rs.getString("di_dom_leg_d4"));
v.setLi_di_dom_leg_d5(rs.getString("li_di_dom_leg_d5"));
v.setDi_dom_leg_d6(rs.getString("di_dom_leg_d6"));
v.setDi_dom_leg_distrito(rs.getString("di_dom_leg_distrito"));
v.setCa_ing_qta_cat_empresa(rs.getString("ca_ing_qta_cat_empresa"));
v.setCa_ing_qta_cat_ruc(rs.getString("ca_ing_qta_cat_ruc"));
v.setCa_ing_qta_cat_otras_empresas(rs.getString("ca_ing_qta_cat_otras_empresas"));
v.setCm_observaciones(rs.getString("cm_observaciones"));
v.setUs_creacion(rs.getString("us_creacion"));
v.setFe_creacion(rs.getString("fe_creacion"));
v.setUs_modif(rs.getString("us_modif"));
v.setFe_modif(rs.getString("fe_modif"));
v.setIp_usuario(rs.getString("ip_usuario"));
v.setId_usuario_creacion(rs.getString("id_usuario_creacion"));
v.setId_universidad_carrera(rs.getString("id_universidad_carrera"));
v.setId_nacionalidad(rs.getString("id_nacionalidad"));
v.setDistrito_nac(rs.getString("distrito_nac"));
v.setVi_contrato(rs.getString("vi_contrato"));
//v.setEs_proceso(rs.getInt("es_proceso"));
list.add(v);
}
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
} catch (Exception e) {
throw new RuntimeException("ERROR :" + e.getMessage());
} finally {
try {
this.conn.close();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
return list;
} | 8 |
public static String doubleToString(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
return "null";
}
// Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d);
if (string.indexOf('.') > 0 && string.indexOf('e') < 0
&& string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
} | 7 |
public char[] readFile(String filename)
{
char[] content = null;
File file = new File(filename); //for ex foo.txt
FileReader reader = null;
try {
reader = new FileReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
//content = new String(chars);
content=chars;
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader !=null){try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
}
return content;
} | 3 |
@Override
public void windowClosing(WindowEvent e) {
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
this.setVisible(false);
this.dispose();
}
} | 1 |
private Map<String, String> getProperties() {
Map<String, String> properties = new HashMap<String, String>();
String line;
try {
while ((line = bundle.readLine()) != null) {
boolean isComment = line.trim().length() < 1 && line.trim().startsWith("#");
if (!isComment) {
String[] entry = line.split("=");
if (entry.length == 2) {
properties.put(entry[0], entry[1]);
}
}
}
return properties;
} catch (IOException e) {
throw new ConfigNotPossibleException("Fisierul de configurare nu poate fi citit", e);
}
} | 5 |
public static ByteArrayInputStream readStreamToMemory(InputStream inputStream) throws IOException {
if (inputStream instanceof ByteArrayInputStream) {
inputStream.reset();
return (ByteArrayInputStream) inputStream;
}
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024 * 80);
IOUtils.copy(inputStream, outputStream);
return new ByteArrayInputStream(outputStream.toByteArray());
}
finally {
IOUtils.closeQuietly(inputStream);
}
} | 1 |
public boolean canEncode(Serializable structure) {
return false; // Serialization is deprecated as a saving method.
} | 0 |
public static void processCollision(RigidBody rigidBody1, Vector3d point1,
RigidBody rigidBody2, Vector3d point2, Vector3d relativeVelocity,
Vector3d normal, Matrix3d k, double restitution, double timeStep) {
Vector3d impulse = new Vector3d();
// Coefficient of friction
double friction = Math.max(rigidBody1.getFriction(),
rigidBody2.getFriction());
// Inverse of K
Matrix3d kInverse = new Matrix3d(k);
kInverse.invert();
// Static friction impulse calculation
Vector3d deltaURel = new Vector3d(normal);
deltaURel.scale(-restitution * relativeVelocity.dot(normal));
deltaURel.scaleAdd(-1, relativeVelocity, deltaURel);
Vector3d row0 = new Vector3d();
Vector3d row1 = new Vector3d();
Vector3d row2 = new Vector3d();
kInverse.getRow(0, row0);
kInverse.getRow(1, row1);
kInverse.getRow(2, row2);
impulse.set(row0.dot(deltaURel), row1.dot(deltaURel),
row2.dot(deltaURel));
Vector3d impulseTangential = new Vector3d(normal);
impulseTangential.scaleAdd(-impulse.dot(normal), impulse);
if (impulseTangential.length() <= friction * impulse.dot(normal)) {
// Static friction<
if (rigidBody2.dynamicsType == RigidBody.DYNAMIC) {
rigidBody2.applyImpulse(impulse, point2, timeStep);
}
if (rigidBody1.dynamicsType == RigidBody.DYNAMIC) {
impulse.scale(-1);
rigidBody1.applyImpulse(impulse, point1, timeStep);
}
} else {
// Kinetic friction
// Re-using impulseTangential
impulseTangential.set(normal);
impulseTangential.scaleAdd(-relativeVelocity.dot(normal),
relativeVelocity);
impulseTangential.normalize();
Vector3d frictionSubtractedNormal = new Vector3d(impulseTangential);
frictionSubtractedNormal.scale(-friction);
frictionSubtractedNormal.add(normal);
Vector3d col0 = new Vector3d();
Vector3d col1 = new Vector3d();
Vector3d col2 = new Vector3d();
k.getColumn(0, col0);
k.getColumn(1, col1);
k.getColumn(2, col2);
double impulseNormal = -(restitution + 1)
* relativeVelocity.dot(normal)
/ new Vector3d(normal.dot(col0), normal.dot(col1),
normal.dot(col2)).dot(frictionSubtractedNormal);
impulse.set(impulseTangential);
impulse.scale(-friction * impulseNormal);
impulse.scaleAdd(impulseNormal, normal, impulse);
if (rigidBody2.dynamicsType == RigidBody.DYNAMIC) {
rigidBody2.applyImpulse(impulse, point2, timeStep);
}
if (rigidBody1.dynamicsType == RigidBody.DYNAMIC) {
impulse.scale(-1);
rigidBody1.applyImpulse(impulse, point1, timeStep);
}
}
} | 5 |
public static void main(String[] args) {
System.out.println("hello Hyun Kyu");
} | 0 |
int writeJavaAnnotations(List<Attribute.Compound> attrs) {
if (attrs.isEmpty()) return 0;
ListBuffer<Attribute.Compound> visibles = new ListBuffer<Attribute.Compound>();
ListBuffer<Attribute.Compound> invisibles = new ListBuffer<Attribute.Compound>();
for (Attribute.Compound a : attrs) {
switch (types.getRetention(a)) {
case SOURCE: break;
case CLASS: invisibles.append(a); break;
case RUNTIME: visibles.append(a); break;
default: ;// /* fail soft */ throw new AssertionError(vis);
}
}
int attrCount = 0;
if (visibles.length() != 0) {
int attrIndex = writeAttr(names.RuntimeVisibleAnnotations);
databuf.appendChar(visibles.length());
for (Attribute.Compound a : visibles)
writeCompoundAttribute(a);
endAttr(attrIndex);
attrCount++;
}
if (invisibles.length() != 0) {
int attrIndex = writeAttr(names.RuntimeInvisibleAnnotations);
databuf.appendChar(invisibles.length());
for (Attribute.Compound a : invisibles)
writeCompoundAttribute(a);
endAttr(attrIndex);
attrCount++;
}
return attrCount;
} | 9 |
public void setDAO(String daoLine) {
if (daoLine.equals("Mock")) {
dao = new MockDAO();
}
else if (daoLine.equals("MySQL")) {
dao = new MySQLDAO();
}
} | 2 |
@Override
public void actionPerformed(ActionEvent event) {
/* Redo listenner */
if (event.getSource().equals(redo)) {
points = drawPanel.getPoints();
for (Point point : pointstoAddorRemove) {
points.add(point);
}
drawPanel.setPoints(points);
drawPanel.paintComponent(drawPanel.getNextGraphics());
}
/* Undo listenner */
if (event.getSource().equals(undo)) {
points = drawPanel.getPoints();
if (!(drawPanel.getPointsToRemoveorAdd().size() == 0))
pointstoAddorRemove = drawPanel.getPointsToRemoveorAdd();
for (Point removeThisPoint : pointstoAddorRemove) {
for (int i = 0; i < points.size(); i++) {
if (points.get(i).equals(removeThisPoint)) {
points.remove(i);
}
}
}
drawPanel.setPointsToRemove();
drawPanel.setPoints(points);
drawPanel.paintComponent(drawPanel.getPrevGraphics());
}
} | 7 |
public void insertIntoGraph(mxICell cell)
{
mxICell parent = cell.getParent();
mxICell source = cell.getTerminal(true);
mxICell target = cell.getTerminal(false);
// Fixes possible inconsistencies during insert into graph
cell.setTerminal(null, false);
cell.setTerminal(null, true);
cell.setParent(null);
if (parent != null)
{
parent.insert(cell);
}
if (source != null)
{
source.insertEdge(cell, true);
}
if (target != null)
{
target.insertEdge(cell, false);
}
} | 3 |
@Override
public int getPixel(int x, int y)
{
int bx = x / 8;
int by = y / 8;
int offs = bx + by * (width / 8) - tileOffset;
if (offs < 0)
return 0;
offs *= 64;
offs += x % 8 + 8 * (y % 8);
if (offs < 0)
return 0;
if (offs >= data.length)
return 0;
return data[offs] & 0xFF;
} | 3 |
public InputStream getInputStream() throws java.io.IOException{
if (inputStream==null) {
setInputStream(socket.getInputStream());
}
return inputStream;
} | 1 |
@Override
public void logicUpdate(GameTime gameTime) {
// Decrease the timer by the current game time in milliseconds
countDownTimer.decreaseTimer(gameTime.getElapsedTimeMilli());
// If our timer is now over, time to call our timeOver method. The class
// that instantiates this will have to provide that method for
// themselves.
if (countDownTimer.isFinished()) {
timeOver();
}
if (countDownTimer.hasChanged && showTimer) {
// Update the text as required
drawnText.setText(countDownTimer.getAsString());
// Note, at this point we DO NOT update the spatial.width when the
// text as changed. The reason for this is, if it is aligned
// relatively right to the viewport.. Then it will move slightly to
// the left and right as the size of digits change, which would look
// odd
}
} | 3 |
public String cypher(String input) throws UnsupportedEncodingException {
try {
MessageDigest md = MessageDigest.getInstance("MD5"); //MD5 is the only allowed algorithm.
String intermediate = new String(md.digest(input.getBytes("UTF-8"))); // don't do UTF-16
String output = new String();
//iterate through output; convert non-printables to printable
CharacterIterator it = new StringCharacterIterator(intermediate);
for(char ch = it.first(); ch != CharacterIterator.DONE; ch = it.next()) {
if(ch >= 0x7F) { // if new char above 0d127, move to 0d0-127 range
ch = (char) (ch - 0x7F);
}
if(ch < 0x30) { // if new char < 0d32, move to above 0d32
ch = (char) (ch + 0x30);
}
if(ch < 0x7F) { // skip weird stuff like unicode above 0d255
output = output.concat(String.valueOf(ch));
}
}
//System.out.println("New Output: " + output);
return output;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("No MD5 implementation.");
}
} | 5 |
private static String formatMessage(String msg, String p, boolean b) {
String message = (b ? (PARAGRAPH + "9[SkyDregg] ") : "") + PARAGRAPH + p;
Pattern pattern = Pattern.compile("(?<NUMBER>[ ][0-9]+)|(?<WHITESPACE>[ \f\t\r\n])|(?<WORD>[^ ]+)");
Matcher matcher = pattern.matcher(msg);
while (matcher.find()) {
if (matcher.group("WHITESPACE") != null) {
message += matcher.group("WHITESPACE");
} else if (matcher.group("NUMBER") != null) {
message += PARAGRAPH + "c" + matcher.group("NUMBER") + PARAGRAPH + p;
} else if (matcher.group("WORD") != null) {
String word = matcher.group("WORD");
if (Bukkit.getPlayer(word) != null && Bukkit.getPlayer(word).getName().equals(word)) {
message += Bukkit.getPlayer(word).getPlayerListName();
} else {
message += word;
}
}
}
return message;
} | 7 |
@EventHandler
public void ZombieRegeneration(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getZombieConfig().getDouble("Zombie.Regeneration.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getZombieConfig().getBoolean("Zombie.Regeneration.Enabled", true) && damager instanceof Zombie && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, plugin.getZombieConfig().getInt("Zombie.Regeneration.Time"), plugin.getZombieConfig().getInt("Zombie.Regeneration.Power")));
}
} | 6 |
private void encrypt(String pass) {
try {
byte[] utf8 = pass.getBytes("UTF8");
byte[] enc = this.encrypter.doFinal(utf8);
this.setEncryptedPass(Base64.encode(enc));
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
}
} | 3 |
@Test
public void tiedostonMuokkaaminenToimii() {
kasittelija.setFile(tiedosto);
kasittelija.tallennaTiedostoon("testi1\ttesti2\ttesti3\ttesti4\ttesti5");
String a = "";
ArrayList<String[]> lista = new ArrayList<>();
lista.add(new String[]{"testi1", "testi2", "testi3", "testi4", "muokattuTesti5"});
try {
kasittelija.muokkaaTiedostonTiettyjaRiveja(lista);
Scanner lukija = new Scanner(tiedosto);
a += lukija.nextLine();
} catch (Exception e){
a += "Tiedostoa ei löydy";
}
assertEquals("testi1\ttesti2\ttesti3\ttesti4\tmuokattuTesti5", a);
} | 1 |
public void train(){
int sinceBelowMin = 0;
Player[] players = new Player[]{
new PlayerComputer(this),
new PlayerComputer(new ModelRandom())
};
while (sinceBelowMin < 50)
{
Game g = Game.create(players, 5, 1, false);
g.play(new Random().nextInt(players.length));
sinceBelowMin = rl.gamesSinceBelowMin();
}
} | 1 |
public static void write() { //writes the file back out if it's been modified
if(file == null) {
JOptionPane.showMessageDialog(null,
"Read-only file was imported. Can not write.",
"Read-Only file", JOptionPane.INFORMATION_MESSAGE);
return;
}
try {
fWriter = new PrintWriter(file, "UTF-8");
writeOut(head); //recursive write method
fWriter.close();
}
catch(FileNotFoundException e) {
JOptionPane.showMessageDialog(null,
"File not found.\nCan not write.", "Error",
JOptionPane.ERROR_MESSAGE);
}
catch(UnsupportedEncodingException e) {
JOptionPane
.showMessageDialog(
null,
"Unsupported Encoding charset \"UTF-8\"\nCan not write.",
"Error", JOptionPane.ERROR_MESSAGE);
}
} | 3 |
public static ListNode partition(ListNode head, int x) {
ListNode f = null;
ListNode s = null;
ListNode p = null, q = null;
ListNode h = head;
ListNode e = h;
while (null != h) {
if (h.val < x) {
if (null == f) f = h;
if (null == p) p = h;
else {
p.next = h;
p = p.next;
}
} else {
if (null == s) s = h;
if (null == q) q = h;
else {
q.next = h;
q = q.next;
}
}
e = h;
h = h.next;
e.next = null;
}
if (null != p) p.next = s;
return null == f ? s : f;
} | 8 |
@SuppressWarnings("rawtypes")
public final static Pedidos jsonToPedidos(String json) throws ParseException {
Pedidos ped= new Pedidos();
JSONParser parser = new JSONParser();
ContainerFactory containerFactory = new ContainerFactory() {
public List<String> creatArrayContainer() {
return new LinkedList<String>();
}
public Map<String, String> createObjectContainer() {
return new LinkedHashMap<String, String>();
}
};
Map map = (Map) parser.parse(json, containerFactory);
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
if (entry.getKey().equals("id_pedido"))
ped.setIdpedido(Long.parseLong(entry.getValue().toString()));
else if (entry.getKey().equals("namefarm")) {
ped.setNameFarm(entry.getValue().toString());
System.out.println(entry.getValue().toString());
} else if (entry.getKey().equals("cantidad"))
ped.setcantidad(entry.getValue().toString());
else if (entry.getKey().equals("id_farmprod"))
ped.setIdfarmprod(Long.parseLong(entry.getValue().toString()));
else if (entry.getKey().equals("precio"))
ped.setprecio(entry.getValue().toString());
else if (entry.getKey().equals("nameuser"))
ped.setNameUser(entry.getValue().toString());
else if (entry.getKey().equals("fecha"))
ped.setfecha(entry.getValue().toString());
else if (entry.getKey().equals("estado"))
ped.setestado(entry.getValue().toString());
}
return ped;
} | 9 |
@Override
public List<Produto> searchProducts(String category, String price) {
try {
String query = "";
if (!category.equals("")) {
query = "where categoria like '%" + category + "%'";
}
if (!price.equals("") && price.equals("max")) {
query += "order by preco desc";
}
Connection connection = UtilDAO.getConn();
List<Produto> productList = new ArrayList<Produto>();
String sql = "Select * from produto " + query;
PreparedStatement stmt = connection.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Produto product = new Produto();
product.setName(rs.getString("nome"));
product.setPrice(rs.getDouble("preco"));
product.setDescription(rs.getString("descricao"));
product.setImage(rs.getString("imagem"));
productList.add(product);
}
return productList;
} catch (Exception e) {
return null;
}
} | 5 |
public static boolean isRequired(Parameter parameter)
{
boolean angleBrackets;
Requirement requirement = parameter.getProperty(Properties.REQUIREMENT);
requirement = requirement == null ? DEFAULT : requirement;
switch (requirement)
{
case REQUIRED:
angleBrackets = true;
break;
case OPTIONAL:
angleBrackets = false;
break;
case DEFAULT:
default:
angleBrackets = parameter.getParameterType() != ParameterType.NAMED;
}
return angleBrackets;
} | 4 |
public BoxSelectionCapability( DefaultBox<?> box ) {
this.box = box;
} | 1 |
public void actionPerformed(ActionEvent e) {
if (e.getSource() == mntmExportar) {
do_mntmExportar_actionPerformed(e);
}
if (e.getSource() == mntmSair) {
do_mntmSair_actionPerformed(e);
}
if (e.getSource() == btnCalcularSubrede) {
do_btnCalcularSubrede_actionPerformed(e);
}
if (e.getSource() == btnVerificarConn) {
try {
do_btnVerificarConn_actionPerformed(e);
} catch (IOException e1) {
e1.printStackTrace();
}
}
} | 5 |
public void testEquipBravesNotEnoughReqGoods() {
Game game = ServerTestHelper.startServerGame(getTestMap());
AIMain aiMain = ServerTestHelper.getServer().getAIMain();
FreeColTestCase.IndianSettlementBuilder builder
= new FreeColTestCase.IndianSettlementBuilder(game);
IndianSettlement camp = builder.initialBravesInCamp(3).build();
NativeAIPlayer player = (NativeAIPlayer) aiMain.getAIPlayer(camp.getOwner());
game.setCurrentPlayer(camp.getOwner());
int bravesToEquip = camp.getUnitCount() - 1;
int horsesReqPerUnit = indianHorsesEqType.getAmountRequiredOf(horsesType);
int musketsReqPerUnit = indianMusketsEqType.getAmountRequiredOf(musketsType);
int totalHorsesAvail = bravesToEquip * horsesReqPerUnit
+ horsesType.getBreedingNumber();
int totalMusketsAvail = bravesToEquip * musketsReqPerUnit;
// Verify initial conditions
assertEquals("No horses should exist in camp", 0,
camp.getGoodsCount(horsesType));
assertEquals("No muskets should exist in camp", 0,
camp.getGoodsCount(musketsType));
for (Unit unit : camp.getUnitList()) {
if (unit.isMounted()) {
fail("Indian should not have mounted braves");
}
if (unit.isArmed()) {
fail("Indian should not have armed braves");
}
}
// Setup
camp.addGoods(horsesType, totalHorsesAvail);
camp.addGoods(musketsType, totalMusketsAvail);
assertEquals("Wrong initial number of horses in Indian camp",
totalHorsesAvail, camp.getGoodsCount(horsesType));
assertEquals("Wrong initial number of muskets in Indian camp",
totalMusketsAvail, camp.getGoodsCount(musketsType));
// Exercise SUT
player.equipBraves(camp);
// Verify results
int mounted = 0;
int armed = 0;
for (Unit unit : camp.getUnitList()) {
if (unit.isMounted()) mounted++;
if (unit.isArmed()) armed++;
}
assertEquals("Wrong number of units armed", bravesToEquip, armed);
assertEquals("Wrong number of units mounted", bravesToEquip, mounted);
assertEquals("Wrong final number of muskets in Indian camp",
0, camp.getGoodsCount(musketsType));
assertEquals("Wrong final number of horses in Indian camp",
horsesType.getBreedingNumber(), camp.getGoodsCount(horsesType));
} | 6 |
@Override
protected Rectangle[] createHandles()
{
p = createPoints(state);
Rectangle[] h = new Rectangle[4];
mxPoint p0 = state.getAbsolutePoint(0);
mxPoint pe = state.getAbsolutePoint(state.getAbsolutePointCount() - 1);
h[0] = createHandle(p0.getPoint());
h[2] = createHandle(pe.getPoint());
// Creates the middle green edge handle
mxGeometry geometry = graphComponent.getGraph().getModel().getGeometry(
state.getCell());
List<mxPoint> points = geometry.getPoints();
Point pt = null;
if (points == null || points.isEmpty())
{
pt = new Point((int) (Math.round(p0.getX()) + Math
.round((pe.getX() - p0.getX()) / 2)), (int) (Math.round(p0
.getY()) + Math.round((pe.getY() - p0.getY()) / 2)));
}
else
{
mxGraphView view = graphComponent.getGraph().getView();
pt = view.transformControlPoint(state, points.get(0))
.getPoint();
}
// Create the green middle handle
h[1] = createHandle(pt);
// Creates the yellow label handle
h[3] = createHandle(state.getAbsoluteOffset().getPoint(),
mxConstants.LABEL_HANDLE_SIZE);
// Makes handle slightly bigger if the yellow label handle
// exists and intersects this green handle
if (isHandleVisible(3) && h[1].intersects(h[3]))
{
h[1] = createHandle(pt, mxConstants.HANDLE_SIZE + 3);
}
return h;
} | 4 |
public void clearCircle(int cx, int cy, int radius) {
int ci = getI(cx);
int cj = getJ(cy);
int iradius = getI(radius);
for (int i = ci - iradius; i < ci + iradius; i++) {
for (int j = cj - iradius; j < cj + iradius; j++) {
if (i < 0 || j < 0 || i >= voxels.length
|| j >= voxels[0].length)
continue;
double di = i - ci;
double dj = j - cj;
double idist = Math.sqrt(di * di + dj * dj);
if (idist < iradius) {
voxels[i][j] = 0;
double x = getX(i);
double y = getY(j);
for (ResourceClump clump : clumps) {
double dx = clump.cx - x;
double dy = clump.cy - y;
if (dx * dx + dy * dy <= clump.radius * clump.radius) {
clump.num_voxels--;
}
}
}
}
}
} | 9 |
public void addMessage(CheckResultMessage message) {
if (message == null || message.getMessage().trim().isEmpty()) {
return;
}
if (message.getType() == CheckResultMessage.SYSTEM) {
addSystemMessage(message.getMessage());
} else if (message.getType() == CheckResultMessage.CHECK_OK) {
this.addOkMessage(message.getMessage());
} else if (message.getType() == CheckResultMessage.CHECK_ERROR) {
StatData.errorNumber++;
this.addErrorMessage(message.getMessage());
} else if (message.getType() == CheckResultMessage.CHECK_WARN) {
this.addWarnMessage(message.getMessage());
}
} | 6 |
public RandomListNode copyRandomList(RandomListNode head) {
if(head == null )
return head;
//copy and linked.
RandomListNode prev;
RandomListNode head2;
for(prev = head;prev != null;prev = prev.next.next){
//copy a node
RandomListNode t = new RandomListNode(prev.label);
t.next = prev.next;
//linked after prev;
prev.next = t;
}
prev = head;
while(prev != null && prev.next != null){
RandomListNode t = prev.next;
if(prev.random != null)
t.random = prev.random.next;
else
t.random = null;
prev = t.next;
}
// for(prev = head;prev!= null;prev = prev.next){
// System.out.print(prev.label+" ");
// }
// System.out.println();
//chaifen linkedlist;
prev = head;
head2 = prev.next;
while(prev != null && prev.next != null){
RandomListNode t = prev.next;
prev.next = t.next;
prev = prev.next;
if(t.next != null)
t.next = t.next.next;
}
return head2;
} | 8 |
private static String getPortImageFile(PortType portType)
{
switch (portType)
{
case WOOD:
return "images/ports/port_wood.png";
case BRICK:
return "images/ports/port_brick.png";
case SHEEP:
return "images/ports/port_sheep.png";
case WHEAT:
return "images/ports/port_wheat.png";
case ORE:
return "images/ports/port_ore.png";
case THREE:
return "images/ports/port_three.png";
default:
assert false;
return null;
}
} | 6 |
private void creatTPoly(){
double xO = (this.getWidth()/2. - (10.5*l)/2.);
double yO = (this.getHeight()/2. - (7*l*Math.sqrt(3))/2.);
int k = 4,alignD =1;
int num=0;
for(int i=0;i<7;i++){
if(i>3){alignD=i -3;}
else{alignD=0;}
for(int j=0;j<k;j++){
int xA=(int)((j * 3./2. * l )+ l + alignD * 3./2. * l + xO);
int yA=(int)(3 * (l * Math.sqrt(3)) / 2. + (l * Math.sqrt(3)) / 2. - j * (l * Math.sqrt(3)) / 2. + i * ( l * Math.sqrt(3)) - alignD * ( l * Math.sqrt(3)) /2. + yO );
if(testTortue[num]==1){
tPoint[num]=new Point(xA, yA);
}
else if(testTortue[num]==2){
tPoint[num]=new Point(xA, yA);
}
else if(testTortue[num]==3){
tPoint[num]=new Point(xA, yA);
}
else{
tPoint[num]=new Point(xA, yA);
}
num++;
}
if(i<3){k++;}
else {k--;}
}
for(int i=0;i<37;i++){
if(tPoint[i]!=null){
int x=tPoint[i].x;
int y=tPoint[i].y;
Polygon poly =new Polygon(new int[]{-l+x,-l/2+x,l/2+x,l+x,l/2+x,x-l/2}, new int[]{y+0,y+(int) (l* Math.sqrt(3)/2),y+(int) (l* Math.sqrt(3)/2),y+0,y-(int) (l* Math.sqrt(3)/2),y-(int) (l* Math.sqrt(3)/2)}, 6);
tPoly[i]=poly;
}
else{
tPoly[i]=null;
}
}
} | 9 |
public boolean validateStr(String s) {
char[] tempCharArray = s.toCharArray();
boolean check = false;
if (s.equals("")) {
// if the user does not input anything: return false
return false;
} else {
// for loop cycles through each position of the char array to check
// if there are any characters
// returns false if any special character appears
for (int i = 0; i < tempCharArray.length; i++) {
if (tempCharArray[i] == ',' || tempCharArray[i] == '%'
|| tempCharArray[i] == '<' || tempCharArray[i] == '>') {
// shows the user an error message informing them not to
// input special characters (especially not the ones listed
// in the message)
JOptionPane
.showMessageDialog(
new JFrame(),
"<html>Special characters are not allowed<p>This includes: < ,> ,% , (and no commas)</html>",
"Special Character Error",
JOptionPane.ERROR_MESSAGE);
return false;
}
// if checks if there user just held down the space bar
else if (tempCharArray[i] == ' ' && check == false) {
check = false;
}
// if the character is valid: check becomes true
else {
check = true;
}
}// end of for loop
// if check is true: true is returned; string is valid
if (check) {
return true;
}
// if check is false: false is returned; string is invalid
else {
return false;
}
}
} | 9 |
@SuppressWarnings("unchecked")
public TypeComboBox(JFrame frame, EnterTyped fn) {
setEditable(true);
setModel(new MyFilterComboBoxModel(ComboElemPersistence.getComboData()));
setPreferredSize(new java.awt.Dimension(100, 21));
getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(java.awt.event.KeyEvent evt) {
// 为下拉菜单添加过滤功能
char c = evt.getKeyChar();
Debugger.debug(() -> {
System.out.println("char: " + (int) c);
});
if (65535 == c) {
return;
}
if (KeyEvent.VK_ENTER == c && null != fn) {
fn.enter((String) getSelectedItem());
return;
}
if (!CharUtils.isEnglishLetter(c) && KeyEvent.VK_BACK_SPACE != c) {
MessageBox.showConfirmBox(frame, "Error", "只能输入英文字母", () -> {
getEditor().setItem(null);
});
return;
}
String perfix = (String) getEditor().getItem();
Debugger.debug(() -> {
System.out.println("perfix: " + perfix);
});
IFilterComboBoxModel<String> model = (IFilterComboBoxModel<String>) getModel();
hidePopup();
model.filter(perfix);
showPopup();
getEditor().setItem(perfix);
Component editor = getEditor().getEditorComponent();
if (editor instanceof JTextComponent) {
JTextComponent jtc = (JTextComponent) editor;
jtc.setSelectionStart(jtc.getText().length());
}
}
});
// getEditor().getEditorComponent().addFocusListener(new FocusAdapter() {
// @Override
// public void focusGained(FocusEvent e) {
// Debugger.debug(() -> {
// System.out.println("focus on " + e.getSource().getClass().getName());
// });
// }
// });
} | 6 |
public void dump(String prefix) {
System.out.println(toString(prefix));
if (children != null) {
for (int i = 0; i < children.length; ++i) {
SimpleNode n = (SimpleNode)children[i];
if (n != null) {
n.dump(prefix + " ");
}
}
}
} | 3 |
@Override
public Long countAll() throws Exception {
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
//Query q = session.getNamedQuery("count.all");
Query q = session.getNamedQuery(getNamedQueryToCountAll());
Long count = (Long) q.uniqueResult();
session.getTransaction().commit();
return count;
} catch (HibernateException e) {
throw new Exception(e.getCause().getMessage());
} finally {
releaseSession(session);
}
} | 1 |
public BaiduPhotoSpider(String startSite, String dirPath, Cobweb cobweb, int maxDepth) throws Exception {
super(startSite, dirPath, cobweb, maxDepth);
} | 0 |
public JSONObject increment(String key) throws JSONException {
Object value = this.opt(key);
if (value == null) {
this.put(key, 1);
} else if (value instanceof Integer) {
this.put(key, (Integer) value + 1);
} else if (value instanceof Long) {
this.put(key, (Long) value + 1);
} else if (value instanceof Double) {
this.put(key, (Double) value + 1);
} else if (value instanceof Float) {
this.put(key, (Float) value + 1);
} else {
throw new JSONException("Unable to increment [" + quote(key) + "].");
}
return this;
} | 5 |
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.