method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
68f92de9-a133-4856-82ad-28e8d128dc0d | 3 | public static void renderSVG(Card card, Graphics2D g) {
try {
SVGDiagram diagram;
if (card == null) {
diagram = universe.getDiagram(ImageManager.class.getResource(urlBase + "blank.svg").toURI());
} else {
diagram = universe.getDiagram(ImageManager.class.getResource(urlBase + card.getSuit().name().toLowerCase() + "/" + card.getRank().ordinal() + ".svg").toURI());
}
diagram.setIgnoringClipHeuristic(true);
diagram.render(g);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (SVGException e) {
e.printStackTrace();
}
} |
f2524fb6-8025-4507-92a0-e6b7f6f030b3 | 7 | private KDNode construct(List<E> c,int depth) throws VariedDimensionException {
int length = c.size();
// edge cases
if (length == 0) {
return null;
}
if (length == 1) {
if (c.get(0).getDimension() != dimension) {
throw new VariedDimensionException("ERROR: Input list contained objects with non-matching dimensions to this tree. Tree has been cleared.");
} else {
return new KDNode(c.get(0),depth);
}
}
// sorting & median calculation - insures balanced tree
Collections.sort(c,new DimComparator<E>(depth));
int medianIndex = length/2;
E median = c.get(medianIndex);
KDNode midNode = new KDNode(median,depth);
//check for mismatched dimension
if (median.getDimension() != dimension) {
throw new VariedDimensionException("ERROR: Input list contained objects with non-matching dimensions to this tree. Tree has been cleared.");
}
// construct subtrees recursively
// sorting/sublist interaction can cause weird side effects, so sublists are copied into new lists, then those are sorted
List<E> leftList = new ArrayList<E>(medianIndex);
Iterator<E> leftIter = c.subList(0, medianIndex).iterator();
while (leftIter.hasNext()) {
leftList.add(leftIter.next());
}
midNode.left = construct(leftList,depth+1);
if (medianIndex + 1 <= length) {
List<E> rightList = new ArrayList<E>(length - 1 - medianIndex);
Iterator<E> rightIter = c.subList(medianIndex+1, length).iterator();
while (rightIter.hasNext()) {
rightList.add(rightIter.next());
}
midNode.right = construct(rightList,depth+1);
} // else null
return midNode;
} |
4c565b23-d850-4a76-8ed3-26132d1c24a8 | 8 | public String getNoDiskVMTemplate(String id)
{
String template = "";
try {
ApplianceDescriptor a = idApp.get(id);
String vmNetwork = "";
Collection<OVFVirtualNetwork> ns = a.getAssociatedVirtualNetworks();
for (OVFVirtualNetwork v : ns)
{
if (v != null)
{
if (this.version.startsWith("2.2"))
vmNetwork += "NIC = [NETWORK=\"" + v.getName() + "\"]\n";
else if (this.version.startsWith("3.4"))
vmNetwork += "NIC = [NETWORK=\"" + v.getName() + "\",\nNETWORK_UNAME=\"" + adminname + "\"]\n";
}
}
String vmName = a.getID();
String vmCPUpct = "1";
String vmVCPU = "";
String vmMEM = "";
Collection<OVFVirtualSystem> vss = a.getVirtualSystems();
OVFVirtualSystem vs = vss.iterator().next();
Collection<OVFVirtualHardware> vhs = vs.getRequiredHardware();
for (OVFVirtualHardware vh : vhs)
{
if (vh.getResourceType() == 3)
vmVCPU = String.valueOf(((OVFVirtualHwCpu) vh).getVirtualQuantity());
else if (vh.getResourceType() == 4)
vmMEM = String.valueOf(((OVFVirtualHwMemory) vh).getVirtualQuantity());
}
template = COMMON_VM_TEMPLATE.replaceAll("vmNAME", vmName).replaceAll("vmCPUpct", vmCPUpct).replaceAll("vmVCPU", vmVCPU)
.replaceAll("vmMEM", vmMEM).replaceAll("vmNETWORKS", vmNetwork);
} catch (Exception e) {
System.err.println("Parsing of the OVF failed at NoDiskVMTemplate");
}
return template;
} |
ff9cff7f-8f0e-455f-8706-828312c69b9a | 3 | public FordFulkerson(FlowNetwork G, int s, int t) {
value = 0.0;
while (hasAugmentingPath(G, s, t)) {
double bottle = Double.POSITIVE_INFINITY;
// compute bottleneck capacity
for (int v = t; v != s; v = edgeTo[v].other(v))
bottle = Math.min(bottle, edgeTo[v].residualCapacityTo(v));
// augment flow
for (int v = t; v != s; v = edgeTo[v].other(v))
edgeTo[v].addResidualFlowTo(v, bottle);
value += bottle;
}
} |
9e4c7a8b-1f6a-4943-91c9-d23c88e74c7c | 1 | public BigDecimal getValue1(int row, int clums, int sheetat) {
BigDecimal value = new BigDecimal(0);
String s = null;
try {
XSSFSheet xSheet = xWorkbook.getSheetAt(sheetat);
XSSFRow xRow = xSheet.getRow(row - 1);
XSSFCell xCell = xRow.getCell(clums - 1);
xCell.setCellType(Cell.CELL_TYPE_STRING);
s = xCell.getStringCellValue();
value = new BigDecimal(s).setScale(2, BigDecimal.ROUND_HALF_UP);
} catch (Exception e) {
value = new BigDecimal(0);
}
return value;
} |
2d8c566c-dd45-46e2-9100-da4fcce303b5 | 6 | private static void loadAnimations() {
File f = new File(Preferences.ANIMATION_PATH);
String[] folders = f.list();
String[] files;
if (folders != null) {
for (String s : folders) {
f = new File(Preferences.ANIMATION_PATH + "/" + s);
files = f.list();
if (files != null) {
ArrayList<BufferedImage> images = new ArrayList<BufferedImage>();
for (String ss : files) {
try {
BufferedImage readImage = ImageIO.read(new File(Preferences.ANIMATION_PATH + "/" + s + "/" + ss));
if (readImage != null) {
images.add(readImage);
}
} catch (IOException e) {
e.printStackTrace();
}
}
animations.put(s, new AnimationHolder(images));
}
}
}
} |
5e1f3810-89db-43bb-a2e5-9c3ce18c9edf | 3 | void start() {
while (true) {
int random = generateRandomNumber();
prevayler.execute(new NumberStorageTransaction(random));
int randomNumbersSize = numbers.numbersSize();
System.out.println("Random numbers generated: " + randomNumbersSize
+ ". Last number generated: " + random + " Previous number: " + numbers.returnLastNumber());
if (randomNumbersSize > 100) {
System.out.println("current - 100 number: " + numbers.getNumbers().get(numbers.numbersSize() - 100));
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
} |
bbb12450-2f87-4ccd-a2cc-13a4b1e9b24a | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Contact other = (Contact) obj;
if (firstname == null) {
if (other.firstname != null)
return false;
} else if (!firstname.equals(other.firstname))
return false;
if (lastname == null) {
if (other.lastname != null)
return false;
} else if (!lastname.equals(other.lastname))
return false;
return true;
} |
46310535-4f73-4380-80ae-437a65eee96c | 9 | public int pobierzZListyPozycjiStatkiPrzezID(int aktTrafionyId, Plansza plansza) {
Integer[][] x;
Integer[][] y;
int wynik = 0;
int k = 0;
int posX;
int posY;
plansza.otoczenieListaStrzalow.clear();
while (k < plansza.pozycjeStatki.size()) {
x = plansza.pozycjeStatki.get(k);
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < x[i].length - 2; j++) {
wynik = x[i][2];
if (wynik == aktTrafionyId) {
otoczenieStrzal = new Integer[1][2];
otoczenieStrzal[0][0] = x[i][0];
aktualnaPozycja[0][0] = x[i][0];
otoczenieStrzal[0][1] = x[i][1];
aktualnaPozycja[0][1] = x[i][1];
plansza.otoczenieListaStrzalow.add(otoczenieStrzal); // czyli tworzy obiket trafiony
break;
}
}
k++;
}
}
// Sprawdzenie, czy v lub h prze porownaniem elementow listy
String value = null;
if (plansza.otoczenieListaStrzalow.size() > 1) {
x = plansza.otoczenieListaStrzalow.get(0);
y = plansza.otoczenieListaStrzalow.get(1);
} else {
x = plansza.otoczenieListaStrzalow.get(0);
y = plansza.otoczenieListaStrzalow.get(0);
}
plansza.h = x[0][0] - 1;
plansza.dlugoscH = 2;
plansza.dlugoscV = 2;
if (x[0][0] == y[0][0]) {
value = "h";
if (plansza.precyzjaListaStrzalow.size() > 0) {
plansza.precyzjaListaStrzalow.clear();
}
rUzupNewListaStrzalowH(plansza, x[0][0] - 1, x[0][1] - 1, value);
} else if (x[0][1] == y[0][1]) {
value = "v";
if (plansza.precyzjaListaStrzalow.size() > 0) {
plansza.precyzjaListaStrzalow.clear();
}
rUzupNewListaStrzalowV(plansza, x[0][0] - 1, x[0][1] - 1, value);
}
return wynik;
} |
5ac5e848-af7d-4625-b868-005003c73cba | 4 | protected void render() {
final float FADE_TIME = 0.25f ;
super.render() ;
final Texture realTex = texture ;
final float realAlpha = absAlpha ;
texture = highlit ;
if (amPressed() || amDragged() || amClicked()) {
absAlpha *= pressLit ;
super.render() ;
}
if (amHovered()) {
absAlpha *= hoverLit ;
absAlpha *= Visit.clamp(myHUD.timeHovered() / FADE_TIME, 0, 1) ;
super.render() ;
}
absAlpha = realAlpha ;
texture = realTex ;
} |
ac9a7e32-f8ca-40d1-8574-247a1ba1dbbc | 6 | @Override
public boolean deleteCustomer(Customer customer) {
if (doc == null)
return false;
Element currRoot = doc.getRootElement();
Element parrentCusto = currRoot.getChild("customers");
List<Element> listCusto = parrentCusto.getChildren();
if (customer.getLoanList() != null)
for (Loan item : customer.getLoanList()) {
if (!deleteLoan(item)) {
return false;
}
}
for (Element currCusto : listCusto) {
int custoID = Integer.parseInt(currCusto.getChild("customerID")
.getText());
if (customer.getCustomerID() == custoID) {
parrentCusto.removeContent(currCusto);
return true;
}
}
return false;
} |
b158f902-dc7c-40ab-b232-d7bfda06b2d1 | 7 | public static void testValidity(Object o) throws JSONException {
if (o != null) {
if (o instanceof Double) {
if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
throw new JSONException("JSON does not allow non-finite numbers.");
}
} else if (o instanceof Float) {
if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
throw new JSONException("JSON does not allow non-finite numbers.");
}
}
}
} |
3369dc6a-5795-4e11-9086-a272f8db6e86 | 5 | @Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() >= 2) {
if (e.getButton() == MouseEvent.BUTTON3) {
callSmoothZoom(e.getX(), e.getY(), 1);
return;
} else if (e.getButton() == MouseEvent.BUTTON1) {
callSmoothZoom(e.getX(), e.getY(), -1);
return;
}
}
if (e.getButton() == MouseEvent.BUTTON3) {
Edge edge = drawMapComponent.findClosestRoad(e.getX(), e.getY());
navigationBar.setToNode(setNode(edge, e));
drawMapComponent.setTo(e.getX(), e.getY());
navigationBar.getTo().setText(edge.getRoadName());
} else if (e.getButton() == MouseEvent.BUTTON1) {
Edge edge = drawMapComponent.findClosestRoad(e.getX(), e.getY());
navigationBar.setFromNode(setNode(edge, e));
navigationBar.getFrom().setText(edge.getRoadName());
drawMapComponent.setFrom(e.getX(), e.getY());
repaint();
}
} |
e83ff41c-5bae-48c3-aaf2-bf447381ef34 | 9 | public int nextNode()
{
if(m_foundLast)
return DTM.NULL;
int next;
org.apache.xpath.VariableStack vars;
int savedStart;
if (-1 != m_stackFrame)
{
vars = m_execContext.getVarStack();
// These three statements need to be combined into one operation.
savedStart = vars.getStackFrame();
vars.setStackFrame(m_stackFrame);
}
else
{
// Yuck. Just to shut up the compiler!
vars = null;
savedStart = 0;
}
try
{
if(DEBUG)
System.out.println("m_pattern"+m_pattern.toString());
do
{
next = getNextNode();
if (DTM.NULL != next)
{
if(DTMIterator.FILTER_ACCEPT == acceptNode(next, m_execContext))
break;
else
continue;
}
else
break;
}
while (next != DTM.NULL);
if (DTM.NULL != next)
{
if(DEBUG)
{
System.out.println("next: "+next);
System.out.println("name: "+m_cdtm.getNodeName(next));
}
incrementCurrentPos();
return next;
}
else
{
m_foundLast = true;
return DTM.NULL;
}
}
finally
{
if (-1 != m_stackFrame)
{
// These two statements need to be combined into one operation.
vars.setStackFrame(savedStart);
}
}
} |
a1f7f614-f07e-4809-8cac-4aad0f581de0 | 5 | private void parseDocument() {
//get a factory
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
//get a new instance of parser
SAXParser sp = spf.newSAXParser();
//parse the file and also register this class for call backs
try {
sp.parse(xmlfile, this);
} catch(FileNotFoundException fnf) {
System.out.println("\nFile not found.");
}
}catch(SAXParseException spe) {
System.out.println("\nParse Exception (Invalid file).");
}catch(SAXException se) {
se.printStackTrace();
}catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch(IOException ie) {
System.out.println("\nInvalid file.");
}
} |
68179439-cf69-494c-9c43-4c57e4fb8ecd | 9 | public void deleteEntry() {
if (isOnline) {
getListOfEvents(false);
System.out.println("Which entry do you want to delete? Input the number.");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String numberOfLine = null;
try {
numberOfLine = br.readLine();
} catch (IOException e) {
System.out.println("IO error!");
System.exit(1);
}
int numLine = Integer.parseInt(numberOfLine);
File file = new File("Calendar.txt");
try {
br = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String lineToRemove = null;
try {
while ((numLine--) != 0) {
lineToRemove = br.readLine();
}
System.out.println(lineToRemove);
br.close();
String currentLine = null;
ArrayList<String> lines = new ArrayList<String>();
br = new BufferedReader(new FileReader(file));
while ((currentLine = br.readLine()) != null) {
if (currentLine.equals(lineToRemove))continue;
lines.add(currentLine);
}
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Calendar.txt", true)));
for (int i = 0; i < lines.size(); i++) {
out.println(lines.get(i));
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
for (String s:activeNodes) {
deleteOverRPC(s, lineToRemove);
}
} else {
System.out.println("Node is offline! Operation is not allowed");
}
} |
16120d95-7bbc-451b-bffb-c5ab151875de | 2 | public void removerAdmin(String nick){
try{
if(getAdmin().getPassword().equals(Login.getPasswordOculta())){
admins.remove(buscarAdmin(nick));
System.out.println("Se ha borrado exitosamente.");
}
}catch(Exception err){
System.out.println("No se ha encontrado.");
}
} |
77aba09d-5cc2-4f5c-a352-27df6bd2c551 | 9 | public void drop(DropTargetDropEvent e) {
UIManager.put("OptionPane.background", Color.WHITE);
UIManager.put("Panel.background", Color.WHITE);
Transferable tr = e.getTransferable();
DataFlavor[] flavors = tr.getTransferDataFlavors();
File file;
for (int i = 0; i < flavors.length; i++) {
if (flavors[i].isFlavorJavaFileListType()) {
e.acceptDrop(DnDConstants.ACTION_COPY);
List<?> list = null;
try {
list = (List<?>) tr.getTransferData(flavors[i]);
for (int j = 0; j < list.size(); j++) {
file = new File(list.get(j).toString());
if (file.isDirectory()) {
currentLibrary = file.getCanonicalPath();
} else if (currentLibrary.isEmpty()) {
JOptionPane.showMessageDialog(null, "Please choose a directory for your library.");
} else {
model.addRow(file);
model.fireTableDataChanged();
}
}
// GUI.LibrarySave();
e.dropComplete(true);
return;
} catch (UnsupportedFlavorException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
e.rejectDrop();
} |
197a5476-46f4-446b-9ca0-6576bb8b7521 | 7 | private void jMenu1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu1MouseClicked
// TODO add your handling code here:
boolean cambios = true;
String contenidoEditor = Editor.getText();
String contenidoArchivo = "";
if(nombreArchivo != null){
try{
FileReader archivo = new FileReader(nombreArchivo);
BufferedReader buffer = new BufferedReader(archivo);
buff = new char[1000];
String contenido = "";
try{
int leidos = buffer.read(buff);
for(int i = 0; i < leidos; i++){
contenido += buff[i];
}
contenidoArchivo = contenido;
}catch(java.io.IOException e){
JOptionPane.showMessageDialog(rootPane, "No se pudo leer el archivo");
}
}catch(java.io.FileNotFoundException e){
JOptionPane.showMessageDialog(rootPane, "No se pudo abrir el archivo");
}
}
if(contenidoArchivo.equals(contenidoEditor)) cambios = false;
if( (nombreArchivo == null) || cambios){
JOptionPane.showMessageDialog(rootPane,"Primero debe guardar el archivo");
}else{
// Inicia el proceso de compilacion
Sintactico analizadorSintactico = new Sintactico(nombreArchivo,titulo);
analizadorSintactico.establecerSalidaErrores(jTextArea2);
analizadorSintactico.limipiarSalidaErrores();
analizadorSintactico.iniciarAnalisis();
}
}//GEN-LAST:event_jMenu1MouseClicked |
9a93312e-e9e8-45cb-945d-c92008b745b2 | 2 | private boolean const_decl_id() {
if( is(TK.ID) ) {
boolean ret;
if (ret = symtab.add_entry(tok.string, tok.lineNumber, TK.CONST)) {
gcprint("int ");
gcprintid(tok.string);
}
scan();
return ret;
}
else {
parse_error("expected id in const declaration, got " + tok);
return false; // meaningless since parse_error doesn't return
}
} |
06012e2a-f226-4008-b85c-ad4e7c2de1c4 | 6 | @Override
public void mouseClicked(final MouseEvent e) {
if (e.getSource() instanceof CellPanel && type != 42 && color != 42) {
for (int y = 0; y < Board.Y; y++) {
for (int x = 0; x < Board.X; x++) {
if (((CellPanel) e.getSource()).getCell() == game.getBoard().getCell(x, y)) {
client.doHumanMove(x, y, type, color);
type = 42;
color = 42;
}
}
}
}
} |
25db5ef3-5eb2-4d91-8cfa-b355da9eec0a | 5 | @Override
protected void addActualItem(Class<? extends Item> genericItem) {
super.addActualItem(genericItem);
Item item = null;
try {
item = genericItem.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
for (Class<? extends Item> genericIngredient : item.getCraftingIngredients().keySet()) {
this.addActualItem(genericIngredient);
}
} |
738a77d4-223b-4882-8ed5-729b1a4a301f | 5 | @Override
public void shoot(Spieler gegner) {
boolean invalidInput = true;
String input = null;
ausgabe.printSeparator();
System.out.println("Geben sie das Ziel an: x,y");
// Einleseschleife
while (invalidInput) {
try {
input = eingabe.getUserInput();
} catch (Exception e) {
e.printStackTrace();
}
Koordinate zielKoordinate = eingabe.string2Koord(input);
if (!gegner.getSpielfeld().validKoordinaten(zielKoordinate)) {
ausgabe.printFalscheEingabe();
continue;
}
invalidInput = false;
invalidInput = !gegner.getSpielfeld().shoot(zielKoordinate);
if (invalidInput) {
ausgabe.printFalscheEingabe();
} else
isGameOver();
} // invalidInput
if (!Client.getClient().getIsLocal())
client.sendPlayerInput(input);
} |
e3b43bdf-413d-4fa9-be78-40e546e7e480 | 1 | public Object get(int index) throws JSONException {
Object object = this.opt(index);
if (object == null) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
return object;
} |
39b4db33-daeb-4892-a190-a6cc15c88bf6 | 5 | public UmlDiagramData readXml( XElement xdiagram, UmlDiagramConverter converter ){
UmlDiagramData diagram = new UmlDiagramData();
diagram.setNextUnqiueId( xdiagram.getElement( "next-unique-id" ).getInt() );
XElement xitems = xdiagram.getElement( "items" );
for( XElement xdata : xitems ) {
switch( xdata.getName() ){
case "connection":
diagram.addData( readConnection( xdata, converter ) );
break;
case "connectionLabel":
diagram.addData( readConnectionLabel( xdata, converter ) );
break;
case "comment":
diagram.addData( readComment( xdata, converter ) );
break;
case "type":
diagram.addData( readType( xdata, converter ) );
break;
}
}
return diagram;
} |
d98862aa-794f-4e59-9964-41e5b86ac58b | 3 | public String toString() {
Enumeration<?> enm;
StringBuffer result;
result = new StringBuffer();
enm = elements();
while (enm.hasMoreElements()) {
result.append(enm.nextElement().toString());
if (enm.hasMoreElements())
result.append(",");
}
return result.toString();
} |
fb183012-fa10-409f-8a63-605230307cd2 | 8 | private int handleT(String value,
DoubleMetaphoneResult result,
int index) {
if (contains(value, index, 4, "TION")) {
result.append('X');
index += 3;
} else if (contains(value, index, 3, "TIA", "TCH")) {
result.append('X');
index += 3;
} else if (contains(value, index, 2, "TH") || contains(value, index,
3, "TTH")) {
if (contains(value, index + 2, 2, "OM", "AM") ||
//-- special case "thomas", "thames" or germanic --//
contains(value, 0, 4, "VAN ", "VON ") ||
contains(value, 0, 3, "SCH")) {
result.append('T');
} else {
result.append('0', 'T');
}
index += 2;
} else {
result.append('T');
index = contains(value, index + 1, 1, "T", "D") ? index + 2 : index + 1;
}
return index;
} |
fa01f94c-2e97-4d6b-b906-b9c6dc26212f | 1 | public void queueOver(int r, int c)
{
if (p2u != null) {
core.GroupOfUnits unit = p2u.get(r, c);
updateStats(unit);
}
} |
a1aedcca-dac1-457c-9f58-1aa5a362439f | 1 | public String optimizeAt(String in, int level){
for(int i=0;i<level;i++)
in = this.optimize(in);
//in = this.optimizeOneTime(in);
return in;
} |
45b1c812-a63d-429e-bbe8-12da57b49763 | 6 | public void run() {
long timer = System.currentTimeMillis();
long lastTime = System.nanoTime();
double delta = 0;
final double NS = 1000000000. / 60.;
requestFocus();
Sound.MUSIC_MENU.play(true);
while(running){
updated = false;
long now = System.nanoTime();
delta += (now - lastTime) / NS;
lastTime = now;
while (delta >= 1) {
update();
updates++;
delta--;
updated = true;
}
if(updated){
render();
frames++;
}
if (System.currentTimeMillis() - timer > 1000) {
timer += 1000;
if(level != null) level.timer();
fps = frames;
ups = updates;
frames = 0;
updates = 0;
seconds ++;
if(seconds > 100000) seconds = 0;
}
}
} |
6e5248fd-1e59-475f-96c6-8ca57a9490f6 | 9 | public static void quick_srt(int array[], int low, int n) {
int lo = low;
int hi = n;
if (lo >= n) {
return;
}
int mid = array[(lo + hi) / 2];
while (lo < hi) {
while (lo < hi && array[lo] < mid) {
lo++;
}
while (lo < hi && array[hi] > mid) {
hi--;
}
if (lo < hi) {
int T = array[lo];
array[lo] = array[hi];
array[hi] = T;
}
}
if (hi < lo) {
int T = hi;
hi = lo;
lo = T;
}
quick_srt(array, low, lo);
quick_srt(array, lo == low ? lo + 1 : lo, n);
} |
0ebf4c49-f722-4f8c-9145-b467ae2252cb | 0 | public boolean shouldProceed() {
return this.shouldProceed;
} |
15146a85-656d-415e-a5d6-3a604c2acd78 | 8 | public void run() {
//This method keeps listening the socket
Message message;
Task task = null;
long time = -1;
while(menager.hasMessage()){
try {
System.out.print("message comming\n");
message = (Message) input.readObject();
if(message != null){
if(message instanceof ServerStatusMessage){
//TODO server status manipulation
}else{
if(message instanceof SuccessMessage){
SuccessMessage m = ((SuccessMessage)message);
task = m.getTask();
time = m.getElapsedTime();
}
if(message instanceof FailMessage){
FailMessage m = ((FailMessage)message);
task = m.getTask();
time = m.getElapsedTime();
}
menager.removeProcessingTask(task);
log.add(new LogEntry(task, message.getSender(), time));
}
status = SERVER_STATUS.Avaible;
}
Thread.sleep(Constants.LISTEN_INTERVAL);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
status = SERVER_STATUS.Dead;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} |
d54b48ff-0e3b-4722-9c3f-8097f610acc0 | 0 | public Footer() {
initComponents();
} |
f4b8809f-85dd-47ab-9fc1-d493d1a61500 | 3 | public JSONArray toJSONArray(JSONArray names) throws JSONException {
if (names == null || names.length() == 0) {
return null;
}
JSONArray ja = new JSONArray();
for (int i = 0; i < names.length(); i += 1) {
ja.put(this.opt(names.getString(i)));
}
return ja;
} |
c4d38bc2-0a52-4330-ae6a-146ee30566bc | 3 | public void append(String str)
{
int newsize = this.size + str.length();
// If there's insufficient capacity, make a new array
if (newsize >= this.contents.length)
{
char[] oldcontents = this.contents;
this.contents = new char[computeNeededCapacity(newsize)];
for (int i = 0; i < this.size; i++)
this.contents[i] = oldcontents[i];
} // if
// Copy the characters.
for (int i = this.size; i < newsize; i++)
this.contents[i] = str.charAt(i - this.size);
// Update the size
this.size = newsize;
} // append(String) |
19cb474c-38e4-49bf-b04a-0d0551aa8ef2 | 3 | public HungarianAlgorithm(double[][] costMatrix) {
this.dim = Math.max(costMatrix.length, costMatrix[0].length);
this.rows = costMatrix.length;
this.cols = costMatrix[0].length;
this.costMatrix = new double[this.dim][this.dim];
for (int w = 0; w < this.dim; w++) {
if (w < costMatrix.length) {
if (costMatrix[w].length != this.cols) {
throw new IllegalArgumentException("Irregular cost matrix");
}
this.costMatrix[w] = Arrays.copyOf(costMatrix[w], this.dim);
} else {
this.costMatrix[w] = new double[this.dim];
}
}
labelByWorker = new double[this.dim];
labelByJob = new double[this.dim];
minSlackWorkerByJob = new int[this.dim];
minSlackValueByJob = new double[this.dim];
committedWorkers = new boolean[this.dim];
parentWorkerByCommittedJob = new int[this.dim];
matchJobByWorker = new int[this.dim];
Arrays.fill(matchJobByWorker, -1);
matchWorkerByJob = new int[this.dim];
Arrays.fill(matchWorkerByJob, -1);
} |
d40a3f9c-9128-40a9-a037-9f08d26fccf1 | 9 | public Function computeFirstDerivative() {
if (mFunctionTerms == null) {
throw new IllegalStateException(
"mFunctionTerms is null - Did you forget to override computeFirstDerivative()?");
}
int termSize = mFunctionTerms.size();
Function deriv = new Function(new ArrayList<FunctionComponent>());
List<Function> temp = new ArrayList<Function>();
temp.add((Function) mFunctionTerms.get(0));
for (int x = 1; x + 1 < termSize; x += 2) {
if (mFunctionTerms.get(x) instanceof Sign) {
Function f = (Function) mFunctionTerms.get(x + 1);
switch ((Sign) mFunctionTerms.get(x)) {
case PLUS:
case MIN:
if (temp.size() > 1) {
deriv.addComponent(productRule(temp));
} else {
deriv.addComponent(temp.get(0).computeFirstDerivative());
}
deriv.addComponent(mFunctionTerms.get(x));
temp = new ArrayList<Function>();
temp.add(f);
break;
case MULT:
temp.add(f);
break;
case DIV:
temp.add(new Power(f, new Const(-1)));
break;
}
}
}
if (temp.size() > 1) {
deriv.addComponent(productRule(temp));
} else {
deriv.addComponent(temp.get(0).computeFirstDerivative());
}
return deriv;
} |
2e74fcd4-d070-4ff2-9bd3-5f2e13e0d772 | 9 | private void processFiles(Connection dbConnection) {
logger.info("Polling for files that need processing...");
try {
PreparedStatement s = dbConnection.prepareStatement("SELECT * FROM files WHERE ready_for_processing=1 AND process_state=0 AND ready_for_delete=0 AND (session_id IS NOT NULL OR in_use=1) AND (heartbeat IS NULL OR heartbeat<?)"+getFileTypeIdsWhereString("file_type_id")+" ORDER BY updated_at DESC");
int i = 1;
s.setTimestamp(i++, heartbeatManager.getProcessingFilesTimestamp());
for (FileType a : FileType.values()) {
s.setInt(i++, a.getObj().getId());
}
ResultSet r = s.executeQuery();
while(r.next()) {
logger.info("Looking at file with id "+r.getInt("id")+".");
// create File obj
File file = DbHelper.buildFileFromResult(r);
Integer numJobsOnLeastLoadedServer = getNumJobsOnLeastLoadedServer(dbConnection);
if (numJobsOnLeastLoadedServer != null && numJobsOnLeastLoadedServer < filesInProgress.size()) {
logger.info("File with id "+file.getId()+" will not be picked up on this server as there is another server which is currently processing fewer files, and therefore that should pick this up.");
continue;
}
else if (filesInProgress.size() >= config.getInt("general.noThreads")) {
logger.info("File with id "+file.getId()+" will not be picked up at the moment as there are no free threads available.");
continue;
}
Object heartbeatManagerFileLockObj = new Object();
try {
if (!heartbeatManager.registerFile(file, false)) {
logger.info("File with id "+file.getId()+" will not be processed because it's heartbeat was updated somewhere else.");
continue;
}
DbHelper.updateStatus(dbConnection, file.getId(), "Added to process queue.", null);
// now set the server_id field so that other servers can determine that this server is working on this file.
PreparedStatement s2 = dbConnection.prepareStatement("UPDATE files SET server_id=? WHERE id=?");
s2.setInt(1, config.getInt("server.id"));
s2.setInt(2, file.getId());
s2.executeUpdate();
filesInProgress.add(file);
}
catch(Exception e) {
// an exception occurred so unregister the file and then rethrow the exception.
heartbeatManager.unRegisterFile(file);
filesInProgress.remove(file);
throw(e);
}
// first delete anything that might have been left behind if a previous attempt failed abruptly
if (!removeChildFilesAndRecords(dbConnection, file, false)) {
logger.warn("Failed to delete some files that were left behind from when file with id "+r.getInt("id")+" was processed previously. Not starting job.");
heartbeatManager.unRegisterFile(file);
filesInProgress.remove(file);
}
else {
// change the lock to an object that the job can have control over
heartbeatManager.switchLockObj(file, Thread.currentThread(), heartbeatManagerFileLockObj);
Job job = new Job(taskCompletionHandler, file, heartbeatManagerFileLockObj);
threadPool.execute(job);
logger.info("Created and scheduled process job for file with id "+r.getInt("id")+".");
}
}
s.close();
} catch (SQLException e) {
logger.error("SQLException when trying to query databases for files that need processing.");
e.printStackTrace();
}
logger.info("Finished polling for files that need processing.");
} |
6a405cc5-0986-4724-836c-a465ed3f77a1 | 5 | public static double pearsonsCorrelatrion(double[] obs, double[] sim, double missingValue) {
sameArrayLen(obs, sim);
double syy = 0.0, sxy = 0.0, sxx = 0.0, ay = 0.0, ax = 0.0;
int n = 0;
for (int j = 0; j < obs.length; j++) {
if (obs[j] > missingValue) {
ax += obs[j];
ay += sim[j];
n++;
}
}
if (n == 0) {
throw new RuntimeException("Pearson's Correlation cannot be calculated due to no observed values");
}
ax = ax / ((double) n);
ay = ay / ((double) n);
for (int j = 0; j < obs.length; j++) {
if (obs[j] > missingValue) {
double xt = obs[j] - ax;
double yt = sim[j] - ay;
sxx += xt * xt;
syy += yt * yt;
sxy += xt * yt;
}
}
return sxy / Math.sqrt(sxx * syy);
} |
fb66302e-1711-4fae-8300-619be3769037 | 1 | protected void createTeleport() {
if (isTeleport) {
teleport.resetDuration();
}
isTeleport = true;
teleport.setLocations(ball);
} |
b131b86f-1ee3-488a-a96e-98aa6c99f0f4 | 5 | public ShopEvent createEvent(Node n, int value) {
String name = "";
String res = "";
Node attr = n.getFirstChild();
while(attr != null) {
if(attr.getNodeType() == Node.ELEMENT_NODE) {
if(attr.getNodeName().equalsIgnoreCase("Name")) {
name = attr.getFirstChild().getNodeValue();
}
else if(attr.getNodeName().equalsIgnoreCase("Resource")) {
res = attr.getFirstChild().getNodeValue();
}
}
attr = attr.getNextSibling();
}
if(name.equalsIgnoreCase("Buy Actor")) {
return new BuyActorEvent(value, res);
}
return null;
} |
8446583f-4c3a-46cb-8d7e-8659b8012165 | 8 | void FormalParameters(ProcedureBuilder pb) throws Exception {
if (Current_Token != Token.TOK_OPAREN) {
throw new Exception("Opening Parenthesis expected");
}
GetNext();
ArrayList lst_types = new ArrayList();
while (Current_Token == Token.TOK_VAR_BOOL
|| Current_Token == Token.TOK_VAR_NUMBER
|| Current_Token == Token.TOK_VAR_STRING) {
SymbolInfo inf = new SymbolInfo();
inf.Type = (Current_Token == Token.TOK_VAR_BOOL)
? TypeInfo.TYPE_BOOL : (Current_Token == Token.TOK_VAR_NUMBER)
? TypeInfo.TYPE_NUMERIC : TypeInfo.TYPE_STRING;
GetNext();
if (Current_Token != Token.TOK_UNQUOTED_STRING) {
throw new Exception("Variable Name expected");
}
inf.SymbolName = this.last_str;
lst_types.add(inf.Type);
pb.AddFormals(inf);
pb.AddLocal(inf);
GetNext();
if (Current_Token != Token.TOK_COMMA) {
break;
}
GetNext();
}
prog.AddFunctionProtoType(pb.getProcedureName(), pb.getTypeInfo(), lst_types);
return;
} |
bef4ddd3-1bbb-4891-83c7-603597eb5466 | 3 | @SuppressWarnings({ "deprecation", "unused" })
public static void setBar(Location origin, int length, int height) {
//origin.getBlock().setTypeIdAndData(35, (byte) 5, true);
Location loc10 = new Location(Bukkit.getWorld("COC"), origin.getX()+10, origin.getY(), origin.getZ());
int currentlength = 0;
while(currentlength <= length) {
currentlength = currentlength + 1;
Location temloc = new Location(Bukkit.getWorld("COC"), origin.getX()-currentlength, origin.getY()+10, origin.getZ());
temloc.getBlock().setTypeIdAndData(35, (byte) 5, true);
//for each length we want to add onto the lengthtest (int)
// i have an idea wait could we just increment it by ++
}
int currentheight = 0;
currentlength = 0;
while(currentheight <= height) {
currentheight = currentheight + 1;
while(currentlength <= length) {
currentlength = currentlength + 1;
Location temloc = new Location(Bukkit.getWorld("COC"), origin.getX()-currentlength, origin.getY()+10+currentheight, origin.getZ());
temloc.getBlock().setTypeIdAndData(35, (byte) 5, true);
}
}
} |
09b6d6e3-1911-4f39-9738-dbf95d751995 | 5 | @Override
protected void startMaster(StartMaster startMaster) {
try {
super.startMaster(startMaster);
StartMasterVcf startMasterVcf = (StartMasterVcf) startMaster;
vcfFileIterator = new VcfFileIterator(startMasterVcf.vcfFileName);
vcfFileIterator.setParseNow(parseNow);
// Show header
if (showHeader) {
// Read header
vcfFileIterator.readHeader();
// Add lines header?
if (addHeader != null) {
// Add header lines
for (String add : addHeader)
vcfFileIterator.getVcfHeader().addLine(add);
}
// Show header
String headerStr = vcfFileIterator.getVcfHeader().toString();
if (!headerStr.isEmpty()) System.out.println(headerStr);
}
} catch (Throwable t) {
t.printStackTrace();
shutdown();
}
} |
7530349b-bff0-4f7b-aaa9-207a9e763157 | 7 | @Override
public boolean equals(Object o) {
if (!(o instanceof ImageInfo)) {
return false;
}
ImageInfo ii = (ImageInfo) o;
if (width != ii.width || height != ii.height) {
return false;
} else if (clip != null && ii.clip != null) {
return clip.equals(ii.clip);
} else if (clip == null && ii.clip == null) {
return true;
} else {
return false;
}
} |
ec4a4fd5-860e-4754-95c6-48cc171c2c84 | 8 | public boolean save(String key, InputStream in) {
if (in == null) return false;
OutputStream out = null;
File file = null;
try {
file = DiskUtils.getCacheFileForName(mAppContext, key);
file.getParentFile().mkdirs();
out = new FileOutputStream(file);
// Copying in to out
byte[] buffer = new byte[BUFFER_SIZE];
int c;
while ((c = in.read(buffer)) != -1) {
out.write(buffer, 0, c);
}
} catch (Throwable e) {
if(file != null) file.delete();
return false;
} finally {
if (in != null) try {
in.close();
} catch (IOException e) {
}
if (out != null) try {
out.close();
} catch (IOException e) {
}
}
DiskUtils.keepCacheDirWithinSize(mAppContext, mMaxInternalDiskUsage, mMaxExternalDiskUsage);
return file.exists(); // may be cleaned while keepDirWithinSize
} |
b02b733a-4f9f-431c-84c9-207a9ded90a7 | 5 | public static int floatToShortBits( float fval )
{
int fbits = Float.floatToIntBits( fval );
int sign = fbits >>> 16 & 0x8000; // sign only
int val = ( fbits & 0x7fffffff ) + 0x1000; // rounded value
if( val >= 0x47800000 ) // might be or become NaN/Inf
{ // avoid Inf due to rounding
if( ( fbits & 0x7fffffff ) >= 0x47800000 )
{ // is or must become NaN/Inf
if( val < 0x7f800000 ) // was value but too large
return sign | 0x7c00; // make it +/-Inf
return sign | 0x7c00 | // remains +/-Inf or NaN
( fbits & 0x007fffff ) >>> 13; // keep NaN (and Inf) bits
}
return sign | 0x7bff; // unrounded not quite Inf
}
if( val >= 0x38800000 ) // remains normalized value
return sign | val - 0x38000000 >>> 13; // exp - 127 + 15
if( val < 0x33000000 ) // too small for subnormal
return sign; // becomes +/-0
val = ( fbits & 0x7fffffff ) >>> 23; // tmp exp for subnormal calc
return sign | ( ( fbits & 0x7fffff | 0x800000 ) // add subnormal bit
+ ( 0x800000 >>> val - 102 ) // round depending on cut off
>>> 126 - val ); // div by 2^(1-(exp-127+15)) and >> 13 | exp=0
} |
73b54539-dc5f-4f5c-804c-9dbedad8c528 | 4 | public void visitTryCatchBlock(final Label start, final Label end,
final Label handler, final String type) {
checkStartCode();
checkEndCode();
checkLabel(start, false, "start label");
checkLabel(end, false, "end label");
checkLabel(handler, false, "handler label");
checkNonDebugLabel(start);
checkNonDebugLabel(end);
checkNonDebugLabel(handler);
if (labels.get(start) != null || labels.get(end) != null
|| labels.get(handler) != null) {
throw new IllegalStateException(
"Try catch blocks must be visited before their labels");
}
if (type != null) {
checkInternalName(type, "type");
}
mv.visitTryCatchBlock(start, end, handler, type);
} |
f9fcbd39-c704-429f-8ef9-0325e0991f98 | 5 | private boolean isInRect(){
if(mouse == null) return false;
int x = mouse.x;
int y = mouse.y;
if(x > getxPos() && x < (getxPos() + width)){
if(y > yPos && y < (yPos + height)){
return true;
}
}
return false;
} |
a7f4980d-0090-4e5a-b5cf-890807ad43a1 | 2 | public void setPassengerCarsCnt(int passengerCarsCnt) throws OutOfRangeException {
if (( passengerCarsCnt < 0 )&&( passengerCarsCnt > MAX_PASSENGERCARS_CNT )) {
logger.error("incorrect passengerCarsCnt argument: " + passengerCarsCnt);
throw new OutOfRangeException();
}
this.passengerCarsCnt = passengerCarsCnt;
} |
7c546c7b-9f6a-4311-addc-4233a8711b62 | 8 | public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> resArr = new ArrayList<ArrayList<Integer>>();
if (root == null)
return resArr;
ArrayList<TreeNode> tmp = new ArrayList<TreeNode>();
ArrayList<TreeNode> pre = new ArrayList<TreeNode>();
ArrayList<Integer> valArr = new ArrayList<Integer>();
pre.add(root);
boolean flag = true;
while (pre.size() > 0) {
for (int i = pre.size() - 1; i >= 0; i--) { // 逆序
TreeNode tmpNode = pre.get(i);
valArr.add(tmpNode.val);
if (flag) { // 区分添加顺序
if (tmpNode.left != null)
tmp.add(tmpNode.left);
if (tmpNode.right != null)
tmp.add(tmpNode.right);
} else {
if (tmpNode.right != null)
tmp.add(tmpNode.right);
if (tmpNode.left != null)
tmp.add(tmpNode.left);
}
}
resArr.add((ArrayList<Integer>) valArr.clone());
valArr.clear();
pre = (ArrayList<TreeNode>) tmp.clone();
tmp.clear();
flag = !flag;
}
return resArr;
} |
1143b048-bf4e-47ae-a0ef-b504a0b6f92f | 9 | public static PDFDecrypter createDecryptor
(PDFObject encryptDict, PDFObject documentId, PDFPassword password)
throws
IOException,
EncryptionUnsupportedByPlatformException,
EncryptionUnsupportedByProductException,
PDFAuthenticationFailureException {
// none of the classes beyond us want to see a null PDFPassword
password = PDFPassword.nonNullPassword(password);
if (encryptDict == null) {
// No encryption specified
return IdentityDecrypter.getInstance();
} else {
PDFObject filter = encryptDict.getDictRef("Filter");
// this means that we'll fail if, for example, public key
// encryption is employed
if (filter != null && "Standard".equals(filter.getStringValue())) {
final PDFObject vObj = encryptDict.getDictRef("V");
int v = vObj != null ? vObj.getIntValue() : 0;
if (v == 1 || v == 2) {
final PDFObject lengthObj =
encryptDict.getDictRef("Length");
final Integer length =
lengthObj != null ? lengthObj.getIntValue() : null;
return createStandardDecrypter(
encryptDict, documentId, password, length, false,
StandardDecrypter.EncryptionAlgorithm.RC4);
} else if (v == 4) {
return createCryptFilterDecrypter(
encryptDict, documentId, password, v);
} else {
throw new EncryptionUnsupportedByPlatformException(
"Unsupported encryption version: " + v);
}
} else if (filter == null) {
throw new PDFParseException(
"No Filter specified in Encrypt dictionary");
} else {
throw new EncryptionUnsupportedByPlatformException(
"Unsupported encryption Filter: " + filter +
"; only Standard is supported.");
}
}
} |
b5d77bd2-37f2-4b4f-87f8-1866341d5762 | 4 | public void run()
{
while(threadSocket != null && !socket.isClosed())
{
try{
Message message = (Message) reader.readObject();
message.setIp(socket.getInetAddress().getHostAddress());
message.setPort(socket.getPort());
threadSocket.receiveMessage(message);
}
catch(IOException e)
{
ClientHelper.log(LogType.ERROR, "Fehler beim Empfangen einer Nachricht (IOException)");
close();
}
catch(ClassNotFoundException e)
{
ClientHelper.log(LogType.ERROR, "Empfangene Nachricht hat nicht den Typ Message");
}
}
ClientHelper.log(LogType.ERROR, "Verbindung zu " + socket.getInetAddress().getHostAddress() + ":" + socket.getPort() + " unterbrochen");
close();
} |
a21aa494-1025-45d6-aea2-d1793b701f12 | 8 | public static void LoadSettings()
{
File f = new File ("ue.ini");
if (!f.exists())
{
CreateDefaultSettings();
}
else
{
try
{
FileReader in = new FileReader("ue.ini");
BufferedReader br = new BufferedReader(in);
String currentLine = "";
while( (currentLine = br.readLine()) != null)
{
if (currentLine.indexOf(";") == 0)
{
continue;
}
if (currentLine.contains("="))
{
String[] parts = currentLine.split("=");
String setting = parts[0].trim().toLowerCase();
String value = parts[1].trim();
if (setting.equals("linelength"))
{
try
{
lineLength = Integer.parseInt(value);
}
catch(NumberFormatException nfe)
{
}
}
//TODO: add other settings
}
}
br.close();
in.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
} |
210041f9-d627-4e3c-804f-ffea127adfca | 3 | public static String localXpath (Node node) throws DOMException {
String localname = node.getLocalName();
if (null == localname) {
throw new DOMException(DOMException.NOT_FOUND_ERR, "DOM Node doesn't have a local name!");
}
else {
int position = 1;
Node current = node;
Node previous = current.getPreviousSibling();
while (null != previous) {
if (localname.equals(previous.getLocalName()))
// need to check on this because sibling nodes are not guaranteed
// to be all of the same kind.
{
position++;
}
current = previous;
previous = current.getPreviousSibling();
}
return localname + "[" + position + "]";
}
} |
ae49d8dc-598b-4157-85d8-678ec9e60f5f | 7 | public String decrypt (String input) {
if(input.matches(".*\\d.*")) throw new IllegalArgumentException();
String formatted = input.toUpperCase().replaceAll("[^A-Z]", "");
if(formatted.length() == 0) throw new IllegalArgumentException();
char[] characters = formatted.toCharArray();
char[][] Table5x5 = _makeTable5x5(this.cipherKey.replaceAll("[^A-Z]", ""));
int[] combined = new int[characters.length * 2];
int combinedIdx = 0;
for(int i = 0; i < characters.length; i++) {
for(int row = 0; row < 5; row++) {
for(int column = 0; column < 5; column++) {
if(Table5x5[row][column] == characters[i]) {
combined[combinedIdx] = row;
combined[combinedIdx + 1] = column;
combinedIdx += 2;
}
}
}
}
char[] value = new char[characters.length];
for(int i = 0; i < characters.length; i++) {
value[i] = Table5x5[combined[i]][combined[i + characters.length]];
}
return new String(value);
} |
f3cde5c1-3e6f-4bab-9f84-66b9e94005b6 | 2 | public void setPasswordButtonBorderthickness(int[] border) {
if ((border == null) || (border.length != 4)) {
this.buttonPW_Borderthickness = UIBorderthicknessInits.PW_BTN.getBorderthickness();
} else {
this.buttonPW_Borderthickness = border;
}
somethingChanged();
} |
5a216c55-0725-47ce-99c2-1ce8c81d98ca | 7 | @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String action = request.getParameter("act");
String login = request.getParameter("login");
String pass = request.getParameter("pass");
try {
RequestContext context = new RequestContext(request);
if(action == null) {
if(context.isLogged()) {
response.sendRedirect("home.jsp");
} else {
response.sendRedirect("login.jsp");
}
} else {
if(action.equals("logout")) {
logout(request, response);
return;
}
if(!context.isLogged()) {
if(action.equals("login")) {
authenticate(login, pass, response);
}
if(action.equals("register")) {
String lang = context.getLanguage();
register(login, pass, lang, response);
}
} else {
response.sendRedirect("home.jsp");
}
}
} catch(SQLException e) {
log.error("SQLException caught in Authentication servlet.", e);
response.sendRedirect("error.jsp?err=dberr");
}
} |
10491d18-7bb1-4f94-9249-581d374a9d8a | 8 | public TexturePortalFX()
{
super(Block.portal.blockIndexInTexture);
Random var1 = new Random(100L);
for (int var2 = 0; var2 < 32; ++var2)
{
for (int var3 = 0; var3 < 16; ++var3)
{
for (int var4 = 0; var4 < 16; ++var4)
{
float var5 = 0.0F;
int var6;
for (var6 = 0; var6 < 2; ++var6)
{
float var7 = (float)(var6 * 16) * 0.5F;
float var8 = (float)(var6 * 16) * 0.5F;
float var9 = ((float)var3 - var7) / 16.0F * 2.0F;
float var10 = ((float)var4 - var8) / 16.0F * 2.0F;
if (var9 < -1.0F)
{
var9 += 2.0F;
}
if (var9 >= 1.0F)
{
var9 -= 2.0F;
}
if (var10 < -1.0F)
{
var10 += 2.0F;
}
if (var10 >= 1.0F)
{
var10 -= 2.0F;
}
float var11 = var9 * var9 + var10 * var10;
float var12 = (float)Math.atan2((double)var10, (double)var9) + ((float)var2 / 32.0F * (float)Math.PI * 2.0F - var11 * 10.0F + (float)(var6 * 2)) * (float)(var6 * 2 - 1);
var12 = (MathHelper.sin(var12) + 1.0F) / 2.0F;
var12 /= var11 + 1.0F;
var5 += var12 * 0.5F;
}
var5 += var1.nextFloat() * 0.1F;
var6 = (int)(var5 * 100.0F + 155.0F);
int var13 = (int)(var5 * var5 * 200.0F + 55.0F);
int var14 = (int)(var5 * var5 * var5 * var5 * 255.0F);
int var15 = (int)(var5 * 100.0F + 155.0F);
int var16 = var4 * 16 + var3;
this.portalTextureData[var2][var16 * 4 + 0] = (byte)var13;
this.portalTextureData[var2][var16 * 4 + 1] = (byte)var14;
this.portalTextureData[var2][var16 * 4 + 2] = (byte)var6;
this.portalTextureData[var2][var16 * 4 + 3] = (byte)var15;
}
}
}
} |
ba607b2a-02e2-4495-b8e6-fb0b51135838 | 5 | private void findParent_knn(double[] target, KDNode node, int d) {
// If the node would be inserted in the branch "below"
if(target[d] < node.values[d]){
if (++d == dimensionCount) {
d = 0;
}
if(node.below == null){
tryToSave(node, target);
return;
}
tryToSave(node.below, target);
findParent_knn(target, node.below, d);
}
// If the node would be inserted in the branch "above".
if(++d == dimensionCount) {
d = 0;
}
if(node.above == null){
tryToSave(node, target);
return;
}
tryToSave(node.above, target);
findParent_knn(target, node.above, d);
} |
fcd57e20-6fe3-44f9-912d-af43ecfb869b | 7 | public static void checkRank(Player player) {
int kills = player.getKillCount();
for (int i = 0; i < ranks.length; i++) {
PkRank rank = ranks[i];
if (rank == null)
break;
if (rank.username.equalsIgnoreCase(player.getUsername())) {
ranks[i] = new PkRank(player);
sort();
return;
}
}
for (int i = 0; i < ranks.length; i++) {
PkRank rank = ranks[i];
if (rank == null) {
ranks[i] = new PkRank(player);
sort();
return;
}
}
for (int i = 0; i < ranks.length; i++) {
if (ranks[i].kills < kills) {
ranks[i] = new PkRank(player);
sort();
return;
}
}
} |
02ae603c-4f30-43da-82a0-4a0fa850b55a | 4 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
GenericDTO other = (GenericDTO) obj;
if (codigo != other.codigo)
return false;
return true;
} |
0ffbef7f-330e-467c-a5e0-8ed477c2612a | 2 | public String Decrypt(String ctext)
{
BigInteger c = new BigInteger(ctext, 16);
BigInteger m = this.DoPrivate(c);
if (m.equals(Zero))
{
return null;
}
byte[] bytes = this.pkcs1unpad2(m, this.GetBlockSize());
if (bytes == null)
{
return null;
}
return new String(bytes);
} |
0c2d2b30-2278-4505-8def-65d10a59e1f8 | 6 | public void tabDragging(TabButton draggingTab){
if(getMousePosition() == null){
return;
}
int w = getMousePosition().x;
draggingTab.setLocation(w-draggingTab.dragXOffset, draggingTab.getLocation().y);
dropHighlightInfo.visible = true;
dropHighlightInfo.x = (getMousePosition().x/TOTAL_BUTTON_WIDTH) * TOTAL_BUTTON_WIDTH + 4;
checkDropLocationValid();
boolean mouseOnTop = getMousePosition().y < getHeight()/2;
if(mouseOnTop){
dropHighlightInfo.orientation = 0;
if(draggingTab.data.orientation != 0){
draggingTab.setOrientation(0);
bottomPanel.remove(draggingTab);
topPanel.add(draggingTab);
}
}
else{
dropHighlightInfo.orientation = 1;
if(draggingTab.data.orientation != 1){
draggingTab.setOrientation(1);
topPanel.remove(draggingTab);
bottomPanel.add(draggingTab);
}
}
if(draggingTab.data.orientation == 0){
topPanel.setComponentZOrder(draggingTab, 0);
}
else if(draggingTab.data.orientation == 1){
bottomPanel.setComponentZOrder(draggingTab, 0);
}
topPanel.repaint();
bottomPanel.repaint();
} |
e3739e34-3e5c-4f8c-a476-6ce11a8d00e5 | 1 | public void setSave(final Expr expr, final boolean flag) {
if (SSAPRE.DEBUG) {
System.out.println(" setting save for " + expr + " to "
+ flag);
}
saves.put(expr, new Boolean(flag));
} |
a9622b74-d382-4783-9173-13415f2db3bd | 4 | @EventHandler(priority = EventPriority.NORMAL)
public void onPlayerKick(final PlayerKickEvent event) {
if (event.isCancelled() || event.getLeaveMessage() == null) {
return;
}
for (final IRCChannel c : Variables.channels) {
if (!c.getBlockedEvents().contains("game_kick")) {
IRC.sendMessageToChannel(
c.getChannel(),
ColorUtils.formatGametoIRC(event.getPlayer()
.getDisplayName()
+ " has been kicked."));
}
}
} |
17d2cf59-ccb9-4571-b40a-a52f505a607a | 9 | public void writeTo(DataOutput dout) throws IOException {
// Write out the size (number of entries) of the constant pool.
int size = getSize() + 1; // add one because constant 0 is reserved
if (size >= 65535) {
throw new RuntimeException
("Constant pool entry count cannot exceed 65535: " + size);
}
dout.writeShort(size);
if (mIndexedConstants == null || !mPreserveOrder) {
mIndexedConstants = new Vector(size);
mIndexedConstants.setSize(size);
int index = 1; // one-based constant pool index
// First write constants of higher priority -- String, Integer,
// Float.
// This is a slight optimization. It means that Opcode.LDC will
// more likely be used (one-byte index) than Opcode.LDC_W (two-byte
// index).
Iterator it = mConstants.keySet().iterator();
while (it.hasNext()) {
ConstantInfo constant = (ConstantInfo)it.next();
if (constant.hasPriority()) {
constant.mIndex = index;
mIndexedConstants.set(index, constant);
index += constant.getEntryCount();
}
}
// Now write all non-priority constants.
it = mConstants.keySet().iterator();
while (it.hasNext()) {
ConstantInfo constant = (ConstantInfo)it.next();
if (!constant.hasPriority()) {
constant.mIndex = index;
mIndexedConstants.set(index, constant);
index += constant.getEntryCount();
}
}
}
// Now actually write out the constants since the indexes have been
// resolved.
for (int i=1; i<size; i++) {
Object obj = mIndexedConstants.get(i);
if (obj != null) {
((ConstantInfo)obj).writeTo(dout);
}
}
} |
cc82b58e-db75-4958-8b8f-c12a4512952b | 8 | void handleFocus(int type) {
switch (type) {
case SWT.FocusIn: {
if (hasFocus)
return;
if (getEditable())
text.selectAll();
hasFocus = true;
Shell shell = getShell();
shell.removeListener(SWT.Deactivate, listener);
shell.addListener(SWT.Deactivate, listener);
Display display = getDisplay();
display.removeFilter(SWT.FocusIn, filter);
display.addFilter(SWT.FocusIn, filter);
Event e = new Event();
notifyListeners(SWT.FocusIn, e);
break;
}
case SWT.FocusOut: {
if (!hasFocus)
return;
Control focusControl = getDisplay().getFocusControl();
if (focusControl == arrow || focusControl == list
|| focusControl == text)
return;
hasFocus = false;
Shell shell = getShell();
shell.removeListener(SWT.Deactivate, listener);
Display display = getDisplay();
display.removeFilter(SWT.FocusIn, filter);
Event e = new Event();
notifyListeners(SWT.FocusOut, e);
break;
}
}
} |
b7085ff0-cef9-498e-afd9-e1bf84e01932 | 3 | public HttpRequest(String path, InputStream inputStream, OutputStream outputStream, int postIndex, Map<String, List<String>> headers) {
this.inputStream = inputStream;
this.outputStream = outputStream;
this.postIndex = postIndex;
this.headers = headers;
try {
this.url = new URL(path);
this.path = url.getPath();
} catch (MalformedURLException e) {
try {
path = URLDecoder.decode(path, Charset.defaultCharset().name());
} catch (UnsupportedEncodingException e1) {
throw new RuntimeException(e1);
}
int index = path.indexOf("?");
if (index > 0)
path = path.substring(0, index);
this.path = path.replaceAll("//","/");
}
} |
d4373067-a8c2-4056-8020-72a05d74cd9c | 4 | public Transaction oldesttransactionLockOnVar(int index) {
List<Transaction> transactionsLockOnVar = new ArrayList<Transaction>();
for (Transaction t: locks.keySet()) {
ArrayList<Lock> lockListT = locks.get(t);
for (Lock lock: lockListT) {
if(lock.getIndex()==index) {
transactionsLockOnVar.add(t);
}
}
}
Collections.sort(transactionsLockOnVar, new Comparator<Transaction>() {
public int compare(Transaction t0, Transaction t1) {
return t0.getStartTime() > t1.getStartTime() ? 1 : -1;
}
});
return transactionsLockOnVar.get(0);
} |
475e73dc-0a5c-478f-b6dc-d3d2849f2aa4 | 8 | public ControllerNode(int _ControllerId, Config config, String jobConf) throws IOException, ParseException {
controllerId = _ControllerId;
primary = config.getController(_ControllerId).isPrimary();
JsonParser parser = new JsonParser(jobConf);
workerNum = safeLongToInt(parser.parseWorkerNum());
dataPath = parser.parseDataPath();
tokenList = parser.parseTokens();
//log(tokenList.toString());
controllerList = new ArrayList<>();
for( int i = 0; i < config.getNcontrollers(); i++){
Config.ControllerConfig cc = config.getController(i);
ControllerConf conf = new ControllerConf(cc.getIpAddr(),cc.getPort(),cc.isPrimary());
controllerList.add(conf);
}
workerList = new ArrayList<>();
workerDataMapping = new ArrayList<>();
for( int i = 0; i < config.getNworkers(); i++){
Config.WorkerConfig cc = config.getWorker(i);
WorkerConf conf = new WorkerConf(cc.getIpAddr(),cc.getPort(),cc.getNThreads());
workerList.add(conf);
}
dataMapping = new ArrayList<>();
File file = new File(dataPath);
fileSize = file.length();
Long start = 0l;
Long length = fileSize / workerNum;
for (int i = 0; i < workerNum; i++) {
if(i==(workerNum-1)){
length=fileSize-start;
}
DataSegment ds = new DataSegment(start, length);
dataMapping.add(ds);
start += length;
}
tokenTable = new TokenTable(tokenList.size(),workerNum);
this.controllerDataMapping = new ArrayList<>();
for ( int i = 0; i < controllerList.size(); i++){
ControllerConf cc = controllerList.get(i);
try{
ControllerInterface controllerRMI = ControllerClient.connectToController(cc.getUrl());
ControllerDataTuple tuple = new ControllerDataTuple(controllerRMI, cc.isPrimary(), false);
controllerDataMapping.add(tuple);
} catch (MalformedURLException e){
throw new RemoteException("Malformed controller URL: " + cc.getUrl());
}
}
for( int i = 0; i < workerList.size(); i++){
WorkerConf wc = workerList.get(i);
try{
WorkerInterface workerRMI = WorkerClient.connectToWorker(wc.getUrl());
WorkerDataTuple tuple = new WorkerDataTuple(workerRMI, i, false, false);
workerDataMapping.add(tuple);
} catch (MalformedURLException e) {
throw new RemoteException("Malformed worker URL: " + wc.getUrl());
}
}
} |
214e8f7d-d7c9-4311-8fe5-03d4ef029f22 | 2 | public boolean remove(int codigo) {
boolean status = false;
Connection con = null;
PreparedStatement pstm = null;
try {
con = ConnectionFactory.getConnection();
pstm = con.prepareStatement(REMOVE);
pstm.setInt(1, codigo);
pstm.execute();
status = true;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erro ao excluir Funcionario: " + e.getMessage());
} finally {
try {
ConnectionFactory.closeConnection(con, pstm);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erro ao fechar conexão: " + e.getMessage());
}
}
return status;
} |
93c65791-27b1-417d-8069-8ccb7b676964 | 3 | public Transition getOutgoingTransition (State toState) throws NoSuchTransitionException {
Transition trans = null;
for(Transition t:outgoingTransitions) {
if (t.getToState() == toState) {
trans = t;
break;
}
}
if(trans == null)
throw new NoSuchTransitionException();
else
return trans;
} |
a6901bed-2967-4a7c-a269-ca8d7dc8c7de | 8 | public Particle getParticle(PhysicsEvent event){
try {
if(particleID==5000) return event.beamParticle();
if(particleID==5001) return event.targetParticle();
if(particleType.compareTo("-")==0){
Particle fromEvent = event.getParticleByCharge(-1,particleSkip);
return new Particle(this.overrideParticleID,
this.particleSign*fromEvent.px(),
this.particleSign*fromEvent.py(),
this.particleSign*fromEvent.pz(),
fromEvent.vertex().x(),
fromEvent.vertex().y(),
fromEvent.vertex().z()
);
}
if(particleType.compareTo("+")==0){
Particle fromEvent = event.getParticleByCharge(1,particleSkip);
return new Particle(this.overrideParticleID,
this.particleSign*fromEvent.px(),
this.particleSign*fromEvent.py(),
this.particleSign*fromEvent.pz(),
fromEvent.vertex().x(),
fromEvent.vertex().y(),
fromEvent.vertex().z()
);
}
if(particleType.compareTo("n")==0){
Particle fromEvent = event.getParticleByCharge(0,particleSkip);
return new Particle(this.overrideParticleID,
this.particleSign*fromEvent.px(),
this.particleSign*fromEvent.py(),
this.particleSign*fromEvent.pz(),
fromEvent.vertex().x(),
fromEvent.vertex().y(),
fromEvent.vertex().z()
);
}
if(event.countByPid(particleID)<particleSkip) return null;
Particle fromEvent = event.getParticleByPid(particleID, particleSkip);
if(this.overridePid==false){
return new Particle(particleID,
this.particleSign*fromEvent.px(),
this.particleSign*fromEvent.py(),
this.particleSign*fromEvent.pz(),
fromEvent.vertex().x(),
fromEvent.vertex().y(),
fromEvent.vertex().z()
);
}
return new Particle(this.overrideParticleID,
this.particleSign*fromEvent.px(),
this.particleSign*fromEvent.py(),
this.particleSign*fromEvent.pz(),
fromEvent.vertex().x(),
fromEvent.vertex().y(),
fromEvent.vertex().z()
);
} catch (Exception e){
}
return null;
} |
16fb6e9b-2184-4efd-95e7-c652cdfefb6d | 4 | public void readFile() throws IOException {
try{
FileInputStream fstream = new FileInputStream("dataIn.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int memi = -1;
int strLineMemory = 59;
while ((strLine = br.readLine()) != null) {
t.data[strLineMemory++][1] = String.valueOf(strLine);
memi++;
size++;
while((strLine = br.readLine()) != null && !strLine.startsWith("*")){
String[] arr = strLine.split(" ");
String command = arr[0];
String operand = arr[1];
toMemory(command, operand, memarray[memi]);
memarray[memi] = memarray[memi] + 2;
System.out.printf("%s %s ", command, operand);
}
}
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
MOSMain mos = new MOSMain();
mos.planner();
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.setSize(830, 800);
t.setVisible(true);
t.setTitle("Printer");
sortTime();
} |
8ed5fdd3-5eee-4fd0-a3b2-bea52913d3da | 7 | public boolean doReadPackage() {
boolean result = true;
try {
mBis.reset();
int len = 0;
int totalLen = 0;
while ((len = mSocketChannel.read(mBuffer)) > 0) {
totalLen += len;
}
if (totalLen > 0) {
mBuffer.flip(); // important
mBuffer.get(mData, 0, totalLen);
ObjectInputStream in = new ObjectInputStream(mBis);
if (getListener() != null)
getListener().onRecvPackage(mSessionId, (NetSystem.Package)in.readObject());
mBuffer.clear();
} else if (len < 0) {
result = false;
if (getListener() != null)
getListener().onDisconnected(mSessionId);
}
} catch (Exception e) {
System.out.print(e.toString() + "\n");
result = false;
if (getListener() != null)
getListener().onDisconnected(mSessionId);
}
return result;
} |
c7be955a-5c42-4aae-860b-5facf5673414 | 5 | public static void write(Matrix matrix, String path) throws MatrixIndexOutOfBoundsException {
int rows = matrix.getRowsCount();
int cols = matrix.getColsCount();
BufferedWriter buffer = null;
long startTime = System.currentTimeMillis();
try {
buffer = new BufferedWriter(new FileWriter(path));
buffer.write(rows + " " + cols + "\r\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
buffer.write(matrix.getValue(i, j) + " ");
}
buffer.write("\r\n");
}
} catch (IOException e) {
System.out.println("It is not possible to make record in the specified file.");
} catch (MatrixIndexOutOfBoundsException ex) {
System.out.println("Error: " + ex);
}
try {
buffer.flush();
buffer.close();
} catch (IOException e) {
System.out.println("Error of input-output.");
}
//run time
long endTime = System.currentTimeMillis();
long time = endTime - startTime;
System.out.println("Recording of the file lasted " + time + " ms.");
} |
c81f0ec8-3f2f-46ae-97cc-2db4427f3147 | 6 | public void init( StorageTable directories, WorkBookHandle wbh ) throws StorageNotFoundException
{
Storage child = directories.getChild( "_SX_DB_CUR" );
if( wbh != null )
{
caches = new HashMap();
book = wbh.getWorkBook();
}
while( child != null )
{
if( wbh != null )
{
caches.put( Integer.valueOf( child.getName() ), child );
}
ArrayList<BiffRec> curRecs = new ArrayList();
BlockByteReader bytes = child.getBlockReader();
int len = bytes.getLength();
for( int i = 0; i <= (len - 4); )
{
byte[] headerbytes = bytes.getHeaderBytes( i );
short opcode = ByteTools.readShort( headerbytes[0], headerbytes[1] );
int reclen = ByteTools.readShort( headerbytes[2], headerbytes[3] );
BiffRec rec = XLSRecordFactory.getBiffRecord( opcode );
// init the mighty rec
rec.setWorkBook( book );
rec.setByteReader( bytes );
rec.setLength( (short) reclen );
rec.setOffset( i );
rec.init();
/*
// KSC: TESTING
try {
System.out.println(rec.getClass().getName().substring(rec.getClass().getName().lastIndexOf(".")+1) + ": " + Arrays.toString(((PivotCacheRecord)rec).getRecord()));
} catch (ClassCastException e) {
System.out.println(rec.getClass().getName().substring(rec.getClass().getName().lastIndexOf(".")+1) + ": " + Arrays.toString(ByteTools.shortToLEBytes(rec.getOpcode())) + Arrays.toString(ByteTools.shortToLEBytes((short)rec.getData().length)) + Arrays.toString(rec.getData()));
}
*/
if( wbh != null )
{
curRecs.add( rec );
}
i += reclen + 4;
}
if( wbh != null )
{
pivotCacheRecs.put( Integer.valueOf( child.getName() ), curRecs );
}
child = directories.getNext( child.getName() );
}
// KSC: TESTING
// Logger.logInfo("PivotCache.end init");
} |
c700d5ef-53f4-4a23-9f5b-08ae55406584 | 3 | public static int getMouseButtonCode(MouseEvent e) {
switch (e.getButton()) {
case MouseEvent.BUTTON1:
return MOUSE_BUTTON_1;
case MouseEvent.BUTTON2:
return MOUSE_BUTTON_2;
case MouseEvent.BUTTON3:
return MOUSE_BUTTON_3;
default:
return -1;
}
} |
ebf49d66-b205-46c4-9af3-2c78dcf83596 | 2 | private boolean jj_3R_76() {
Token xsp;
xsp = jj_scanpos;
if (jj_3_17()) {
jj_scanpos = xsp;
if (jj_3_18()) return true;
}
return false;
} |
6b7f6036-e80f-4c2b-9d44-1ee3f9605b7f | 5 | public String getStringLine(int n,int largeur) {
String toRet = "";
if(n>getHauteur()-1) {
for(int i = 0; i < (largeur-1)/2 ; i++) {
toRet+=" ";
}
toRet+="|";
for(int i = 0; i < (largeur-1)/2 ; i++) {
toRet+=" ";
}
}
else {
for(int i = 0; i < (largeur-(2*this.tour.get(n).getTaille()-1))/2 ; i++) {
toRet+=" ";
}
toRet+=this.tour.get(n).getStringDisque();
for(int i = 0; i < (largeur-(2*this.tour.get(n).getTaille()-1))/2 ; i++) {
toRet+=" ";
}
}
return toRet;
} |
3eeefdad-91aa-4556-884e-49cc2ed52d28 | 8 | public static java.util.List doit(String[] args) {
try {
// Check to see whether there is a provider that can do TripleDES
// encryption. If not, explicitly install the SunJCE provider.
try {
Cipher c = Cipher.getInstance("DESede");
} catch (Exception e) {
// An exception here probably means the JCE provider hasn't
// been permanently installed on this system by listing it
// in the $JAVA_HOME/jre/lib/security/java.security file.
// Therefore, we have to install the JCE provider explicitly.
System.err.println("Installing SunJCE provider.");
Provider sunjce = new com.sun.crypto.provider.SunJCE();
Security.addProvider(sunjce);
}
// This is where we'll read the key from or write it to
File keyfile = new File(args[1]);
// Now check the first arg to see what we're going to do
if (args[0].equals("-g")) { // Generate a key
System.out.print("Generating key. This may take some time...");
System.out.flush();
SecretKey key = generateKey();
writeKey(key, keyfile);
System.out.println("done.");
System.out.println("Secret key written to " + args[1]
+ ". Protect that file carefully!");
} else if (args[0].equals("-estd")) { // Encrypt stdin to stdout
SecretKey key = readKey(keyfile);
encrypt(key, System.in, System.out);
} else if (args[0].equals("-dstd")) { // Decrypt stdin to stdout
SecretKey key = readKey(keyfile);
decrypt(key, System.in, System.out);
}else if (args[0].equals("-e")) { // Encrypt filein to fileout
SecretKey key = readKey(keyfile);
File fin = new File(args[2]);
File fout = new File(args[3]);
FileOutputStream out = new FileOutputStream(fout);
DataInputStream in = new DataInputStream(new FileInputStream(fin));
encrypt(key, in, out);
} else if (args[0].equals("-d")) { // Decrypt filein to fileout
SecretKey key = readKey(keyfile);
File fin = new File(args[2]);
File fout = new File(args[3]);
FileOutputStream out = new FileOutputStream(fout);
DataInputStream in = new DataInputStream(new FileInputStream(fin));
decrypt(key, in, out);
}
else if (args[0].equals("-dl")) { // Decrypt filein to list
SecretKey key = readKey(keyfile);
ReadFromFileURL fr=new ReadFromFileURL("file:"+args[2]);
DataInputStream in = new DataInputStream(fr.is);
String ts=decryptintostring(key, in);
java.util.List tlist=fr.read(ts);
return tlist;
}
} catch (Exception e) {
System.err.println(e);
System.err.println("Usage: java " + sdi3DES.class.getName()
+ " -d|-dl|-dstd|-e|-estd|-g <keyfile> filein fileout");
}
return null;
} |
0041b9f0-3861-4dea-9ce8-157e304e07d1 | 7 | public void render(GameContainer container, Graphics g) {
g.setFont(container.getDefaultFont());
float val = 1.00f - (isActive() ? (Board.mouseButtons.isDown(0) ? 0.20f : 0.10f) : 0.00f);
int offset = (isActive() ? (Board.mouseButtons.isDown(0) ? 1 : 0) : 0);
g.drawImage(buttonImage, getX() + 1, getY() + 1, new Color(val, val, val));
if(!(Board.mouseButtons.isDown(0)) && isActive() || !isActive())
g.drawImage(buttonImage, getX(), getY(), new Color(val, val, val));
g.setColor(Color.black);
g.drawString(text, (3 + offset) + getX() + (getWidth() / 2) - (container.getDefaultFont().getWidth(text) / 2), (3 + offset) + getY() + (getHeight() / 2) - (container.getDefaultFont().getHeight(text) / 2));
g.setColor(Color.white);
g.drawString(text, (1 + offset) + getX() + (getWidth() / 2) - (container.getDefaultFont().getWidth(text) / 2), (1 + offset) + getY() + (getHeight() / 2) - (container.getDefaultFont().getHeight(text) / 2));
} |
c5fa75b9-6be3-447f-8e09-4d3ac981d7d0 | 1 | public static byte[] toByte(String hexString) {
int len = hexString.length()/2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
return result;
} |
69c13159-75cb-48b3-8fb0-f2451f0279b7 | 5 | public String guiPressed(String button)
{
guiPressed = button;
if(inBattle)
{
if(button.equals("hitFace") || button.equals("hitSholder"))
{
return Battle(button);
}
if(button.startsWith("inv") && !(inventory.getItem(getInt(button) - 1) == null))
{
return Battle(button);
}
}
return "";
} |
a2b983d3-9cb5-41fb-996f-94b573d722bb | 0 | @Override
public String toString() {
return "Section "+id+" of "+parent.toString();
} |
e06c1536-f4b4-40a5-af54-584e97ce409c | 2 | public static Inventory decodeString(String encoded) {
YamlConfiguration configuration = new YamlConfiguration();
try {
configuration.loadFromString(Base64Coder.decodeString(encoded));
Inventory i = Bukkit.createInventory(null, configuration.getInt("Size"), StringUtil.limitCharacters(configuration.getString("Title"), 32));
ConfigurationSection contents = configuration.getConfigurationSection("Contents");
for (String index : contents.getKeys(false)) {
i.setItem(Integer.parseInt(index), contents.getItemStack(index));
}
return i;
} catch (InvalidConfigurationException e) {
return null;
}
} |
c0dcdadc-854d-4c34-a8f1-080ee59512a3 | 4 | public void keyReleased(KeyEvent e)
{
int key = e.getKeyCode();
if (key == KeyEvent.VK_A)
{
dx = 0;
}
if (key == KeyEvent.VK_D)
{
dx = 0;
}
if (key == KeyEvent.VK_W)
{
dy = 0;
}
if (key == KeyEvent.VK_S)
{
dy = 0;
}
} |
4b0ac27e-ee7e-4390-a610-7fa24094e85b | 5 | final Class299 method3706(Class299 class299, Class299 class299_24_,
float f, Class299 class299_25_) {
try {
anInt9873++;
if (f < 0.5F)
return class299;
return class299_24_;
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929
(runtimeexception,
("bga.SD(" + (class299 != null ? "{...}" : "null") + ','
+ (class299_24_ != null ? "{...}" : "null") + ',' + f
+ ',' + (class299_25_ != null ? "{...}" : "null")
+ ')'));
}
} |
706716f3-a049-4716-a812-3c414bf85941 | 8 | public static void kFoldValidation(double data[][],int k,ProbabilityOptions options)
{
int interval = data.length / k;
double[][] results = new double[k][4];
ArrayList<ArrayList<double[]>> partitionedData = new ArrayList<ArrayList<double[]>>();
Classifier cl;
double fScore = 0;
for(int i = 0; i<k; i++)
partitionedData.add(new ArrayList<double[]>());
//partition the data into k array lists
//by adding the ith element in data to the i%kth array list
for(int i = 0; i < data.length; i++)
partitionedData.get(i%k).add(data[i]);
// perform validations
for(int i = 0; i<k; i++)
{
System.out.println("VALIDATION TEST NUMBER: " + (i+1));
cl = new Classifier(options);
//load training data into classifier
for(int j = 0; j<k; j++)
{
if(i!=j)
for(double[] d : partitionedData.get(j))
cl.addData(d);
}
results[i] = validate(cl,partitionedData.get(i));
}
//Print out results
double meanAccuracy = 0;
double meanFScore = 0;
double standardError=0;
System.out.println("aggregate results:\n Accuracy precision recall f-1 score");
for(int i = 0; i < k; i++)
{
System.out.printf("%3d %10f %10f %10f %10f\n",i,results[i][0],results[i][1],results[i][2],results[i][3]);
meanAccuracy += results[i][0];
meanFScore+=results[i][3];
}
meanAccuracy /= (double)k;
meanFScore /= (double)k;
//calculate standard deviation of accuracy:
for(int i = 0; i < k; i++)
{
standardError += (results[i][0] - meanAccuracy)*(results[i][0] - meanAccuracy);
}
standardError = Math.sqrt(standardError/(double)k);
//calculate standard error
standardError = standardError / Math.sqrt(k);
System.out.println("Mean Accuracy : " + meanAccuracy);
System.out.println("Standard Error: " + standardError);
System.out.println("Mean F1 Score : " + meanFScore);
return;
} |
950322de-a624-4e5b-8b06-b0c01c2efec3 | 4 | public static void main(String[] args){
if (args.length != 1){
throw new RuntimeException("invalid number of arguments. Must receive one argument specifying working directory!!!");
}
workingDir = args[0].replace("\\", "/");
if (workingDir.charAt(workingDir.length() - 1) != '/')
workingDir += '/';
new File(workingDir).mkdirs();
siteUID = loadSiteUID();
AirNowParser parser = new AirNowParser(workingDir);
System.out.println("Attempting to upload location data");
try{
FileInputStream fis = new FileInputStream (workingDir + "sites.dat");
AirNowData siteData = parser.parseSiteInfo(fis);
fis.close();
if (uploadLocationData(siteData))
System.out.println("Successfuly uploaded site locations!");
else
System.out.println("Failed to upload site locations!");
}
catch (Exception e){
System.out.println("Failed to upload site locations!");
}
System.exit(0);
} |
dfecf9e5-27c3-44ab-8092-c2026213f30f | 8 | public void sendMessage(String channel, String message, boolean sanityCheck) {
if(espanol && !message.startsWith("Activated on ")) {
message = Translator.getInstance().translate(message, Language.ENGLISH, Language.SPANISH);
espanol = false;
}
if(isTeamSpeak) {
if(channel.equals("#pringers")) {
for(String s : message.split(" ")) {
if(s.matches("^(https?)://.*$")) {
message = message.replace(s, "[URL]" + s + "[/URL]");
}
}
message = message
.replace(Colors.BOLD, "[b]")
.replace(Colors.UNDERLINE, "[u]")
.replace(Colors.REVERSE, "")
.replace(Colors.PURPLE, "[color=#9C009C]")
.replace(Colors.RED, "[color=#FF0000]")
.replace(Colors.GREEN, "[color=#009300]")
.replace(Colors.BLUE, "[color=#00007F]")
.replace(Colors.YELLOW, "[color=#FFFF00]")
.replace(Colors.BLACK, "[color=#000000]")
.replace(Colors.CYAN, "[color=#009393]")
.replace(Colors.WHITE, "[color=#FFFFFF]")
.replace(Colors.NORMAL, "[color=#000000]");
tspw.println("PRIVMSG " + message.replace(" ", "\\s"));
}
} else if(isTest) {
System.out.println("To: " + channel + ", Message: " + message);
} else {
sendMessage(channel, message);
if(sanityCheck) {
logMessage(botname, channel, message);
} else {
onMessage(botname, channel, botname, botname, message);
}
}
} |
9d7f39d8-3336-4df7-ada4-90087d7d958e | 7 | public String deltalogin(){
System.out.println("111 Userbean ");
String returnValue="login"; //default
if((username != null )&& ( pw!= null) && (newpw!=null) ){
System.out.println("116 Userbean ");
String strSQL;
DBResults rs=null;
strSQL= "call loginCheck('"+ username + "','" + pw + "')";
rs = DBUtils.selectSQL(strSQL);
// select firstname, lastname, username, perms, user_id from users where username = uname AND pw = passwd
if((rs!= null ) &&( rs.getRowSize() > 0) && (rs.getElement(1, 1) != null)){
this.loggedin=true;
this.firstname = rs.getElement(1, 1);
this.lastname = rs.getElement(1, 2);
this.username = rs.getElement(1, 3);
this.userperms = Integer.parseInt(rs.getElement(1, 4));
this.user_id = Integer.parseInt(rs.getElement(1, 5));
// 1 5 15
System.out.println("132 Userbean ");
if(this.userperms==15){
returnValue = "admin";
} else {
returnValue = "viewschedule48";
}
strSQL= "call updatePassword("+ this.user_id + ",'" + this.newpw + "');";
System.out.println("140 Userbean: SQL" + strSQL);
DBUtils.executeSQL(strSQL);
System.out.println("142 Userbean ");
}// name/pw found
else {loginresult=0; returnValue="login";}
} // if incoming username and pw are not blank
System.out.println("147 Userbean returnValue= " +returnValue);
return returnValue;
} // method |
267ca259-9df0-43a1-a7fa-89cc06218fa6 | 4 | public static Suit getSuit(String suit) {
switch(suit.toLowerCase()) {
case ("s"): return Spades;
case ("h"): return Hearts;
case ("d"): return Diamonds;
case ("c"): return Clubs;
default: throw new RuntimeException("what suit is this?!");
}
} |
e57ac95e-a2ab-4540-97f0-6cb04f01e05f | 2 | public boolean matchesSub(Identifier ident, String name) {
for (int i = 0; i < matchers.length; i++) {
if (matchers[i].matchesSub(ident, name) == isOr)
return isOr;
}
return !isOr;
} |
61ebf518-dd77-4a4a-bf5c-cd5c8e08b465 | 7 | @Override
protected boolean isValidNonDropMove(GameState state, int x, int y) {
/* Checks if the target tile is 2 tiles in front
* and one to the side.
* Then verifies if the target tile is still in the board,
* and whether the target tile could be moved into.
* */
return (((y == this.y+2*this.allegiance)
&& (x == this.x-1 || x == this.x+1))
&& !(y < 0 || y > 8)
&& !(x < 0 || x > 8)
&& (state.getPieceAt(x, y).getAllegiance() != this.allegiance));
} |
4ddef974-1417-44d5-aba3-ce48326a9f8a | 9 | * @param bestMUM the best MUM at the start. may be a transposition
* @throws Exception
*/
void mergeSpecial( Graph g, MUM bestMUM ) throws Exception
{
TreeMap<SpecialArc,Graph> specials =
new TreeMap<SpecialArc,Graph>(new SpecialComparator());
while ( bestMUM != null )
{
if ( bestMUM.verify() )
{
bestMUM.merge();
SimpleQueue<SpecialArc> leftSpecials =
bestMUM.getLeftSpecialArcs();
SimpleQueue<SpecialArc> rightSpecials =
bestMUM.getRightSpecialArcs();
while ( leftSpecials != null && !leftSpecials.isEmpty() )
installSpecial( specials, leftSpecials.poll(),
bestMUM.getLeftSubgraph(), true );
while ( rightSpecials != null && !rightSpecials.isEmpty() )
installSpecial( specials, rightSpecials.poll(),
bestMUM.getRightSubgraph(), false );
}
else // try again
{
bestMUM = recomputeMUM( bestMUM );
if ( bestMUM != null )
specials.put( bestMUM.getArc(), bestMUM.getGraph() );
}
// POP topmost entry, if possible
bestMUM = null;
if ( specials.size() > 0 )
{
SpecialArc key = specials.firstKey();
if ( key != null )
{
g = specials.remove( key );
bestMUM = key.getBest();
}
}
}
} |
80a4e6e7-5e4c-4be3-8240-079d44a8d0bb | 8 | public synchronized void startElement(String uri, String localName,
String qName, Attributes attrList)
throws SAXException
{
ElementImpl elem;
int i;
String tagName = getName(qName, localName);
if ( tagName == null )
throw new SAXException( "HTM004 Argument 'tagName' is null." );
// If this is the root element, this is the time to create a new document,
// because only know we know the document element name and namespace URI.
if ( _document == null )
{
// No need to create the element explicitly.
_document = new HTMLDocumentImpl();
elem = (ElementImpl) _document.getDocumentElement();
_current = elem;
if ( _current == null )
throw new SAXException( "HTM005 State error: Document.getDocumentElement returns null." );
// Insert nodes (comment and PI) that appear before the root element.
if ( _preRootNodes != null )
{
for ( i = _preRootNodes.size() ; i-- > 0 ; )
_document.insertBefore( (Node) _preRootNodes.elementAt( i ), elem );
_preRootNodes = null;
}
}
else
{
// This is a state error, indicates that document has been parsed in full,
// or that there are two root elements.
if ( _current == null )
throw new SAXException( "HTM006 State error: startElement called after end of document element." );
elem = (ElementImpl) _document.createElement( tagName );
_current.appendChild( elem );
_current = elem;
}
// Add the attributes (specified and not-specified) to this element.
if ( attrList != null )
{
for ( i = 0 ; i < attrList.getLength() ; ++ i ) {
elem.setAttribute(getName(attrList.getQName(i), attrList.getLocalName(i)), attrList.getValue( i ) );
}
}
} |
e969caec-68d1-497b-9445-167c48c52db7 | 3 | public ListNode reverseKGroup(ListNode head, int k) {
if(k <= 1) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode p = dummy;
ListNode f = dummy;
int i = 0;
while(f.next != null){
f = f.next;
if(++i % k ==0){
ListNode tmp = f.next;
f.next = null;
ListNode h = p.next;
ListNode r = reverse(h);
p.next = r;
h.next = tmp;
f = h;
p = h;
}
}
return dummy.next;
} |
Subsets and Splits