method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
e944e7c3-a8fc-4c36-b213-9e282ede772d | 9 | public String fractionToDecimal(int numerator, int denominator) {
StringBuffer ans = new StringBuffer();
Map<Long, Integer> map = new HashMap<>();
String sign;
if ((numerator == 0) || (numerator >= 0 && denominator > 0) || (numerator < 0 && denominator < 0)) {
sign = "";
} else {
sign = "-";
}
ans.append(sign);
long lnumerator = Math.abs((long) numerator);
long ldenominator = Math.abs((long) denominator);
ans.append(lnumerator / ldenominator);
long r = lnumerator % ldenominator;
if (r > 0) {
ans.append(".");
} else {
return ans.toString();
}
while (!map.containsKey(r) && r > 0) {
map.put(r, ans.length());
ans.append(10 * r / ldenominator);
r = (10 * r % ldenominator);
}
if (r > 0) {
long len = map.get(r);
ans.insert((int) len, "(");
ans.append(")");
}
return ans.toString();
} |
703624d2-6613-4e1f-ae85-33434fd4de00 | 8 | public void run() {
boolean eof = false;
byte[] buffer = new byte[65536];
int timeout = 0;
while(!eof && !super.killed()) {
int read=0;
try {
read = in.read(buffer);
} catch (SocketTimeoutException ste) {
if(!super.killed()) {
timeout++;
if(timeout > 225) {
ptc.printLogMessage("Connection timed out");
return;
}
continue;
}
} catch (IOException e) {
ptc.printLogMessage("Unable to read from socket");
return;
}
timeout = 0;
if(read == -1) {
ptc.printLogMessage("Connection reached end");
eof = true;
} else {
try {
out.write(buffer, 0, read);
} catch (IOException e) {
ptc.printLogMessage("Error writing to socket");
return;
}
}
}
ptc.interrupt();
} |
02c40fc2-73f6-426d-a50f-8fcf45078a89 | 5 | private void initializeLauncherMenuBar(JFrame launcherMainFrame, JFrame launcherLogWindow)
{
this.launcherMainFrame = launcherMainFrame;
this.launcherLogWindow = launcherLogWindow;
//int acceleratorMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
// File menu
if (!System.getProperty("os.name").startsWith("Mac"))
{
fileMenu.add(exitMenuItem);
add(fileMenu);
}
// Edit menu
// The edit menu was only implemented for Mac OS X in the wxPython
// Launcher, because on Mac OS X, in wxPython you don't get the
// right-click menu in a text area (e.g. log window), so you need
// an Edit menu to be able to copy or select all.
if (System.getProperty("os.name").startsWith("Mac"))
{
editMenu.add(cutMenuItem);
editMenu.add(copyMenuItem);
editMenu.add(pasteMenuItem);
editMenu.add(selectAllMenuItem);
editMenu.add(selectNoneMenuItem);
add(editMenu);
}
launcherMainFrameMenuItem.setText(launcherMainFrame.getTitle());
windowMenu.add(launcherMainFrameMenuItem);
if (launcherLogWindow!=null)
{
logWindowHasBeenAddedToWindowsMenu = true;
launcherLogWindowMenuItem.setText(launcherLogWindow.getTitle());
windowMenu.add(launcherLogWindowMenuItem);
}
add(windowMenu);
helpMenu.add(aboutMenuItem);
add(helpMenu);
// File menu event handlers
exitMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
// FIXME: Should do a clean up here.
System.exit(0);
}
});
// Edit menu event handlers
cutMenuItem.setAccelerator(KeyStroke.getKeyStroke("meta pressed X"));
copyMenuItem.setAccelerator(KeyStroke.getKeyStroke("meta pressed C"));
pasteMenuItem.setAccelerator(KeyStroke.getKeyStroke("meta pressed V"));
selectAllMenuItem.setAccelerator(KeyStroke.getKeyStroke("meta pressed A"));
selectNoneMenuItem.setAccelerator(KeyStroke.getKeyStroke("shift meta pressed A"));
if (System.getProperty("os.name").startsWith("Mac"))
{
cutMenuItem.addActionListener(new DefaultEditorKit.CutAction());
copyMenuItem.addActionListener(new DefaultEditorKit.CopyAction());
pasteMenuItem.addActionListener(new DefaultEditorKit.PasteAction());
class SelectAllAction extends TextAction
{
public SelectAllAction()
{
super("Select All");
}
public void actionPerformed(ActionEvent e)
{
JTextComponent component = getFocusedComponent();
component.selectAll();
}
}
selectAllMenuItem.addActionListener(new SelectAllAction());
class SelectNoneAction extends TextAction
{
public SelectNoneAction()
{
super("Select None");
}
public void actionPerformed(ActionEvent e)
{
JTextComponent component = getFocusedComponent();
component.setCaretPosition(0);
}
}
selectNoneMenuItem.addActionListener(new SelectNoneAction());
}
// Window menu event handlers
launcherMainFrameMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
launcherMenuBar.launcherMainFrame.setVisible(true);
launcherMenuBar.launcherMainFrame.setExtendedState(JFrame.NORMAL);
launcherMenuBar.launcherMainFrame.toFront();
launcherMenuBar.launcherMainFrame.requestFocus();
//launcherMainFrameMenuItem.setState(true);
//launcherLogWindowMenuItem.setState(false);
}
});
if (launcherLogWindow!=null)
{
launcherLogWindowMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
launcherMenuBar.launcherLogWindow.setVisible(true);
launcherMenuBar.launcherLogWindow.setExtendedState(JFrame.NORMAL);
launcherMenuBar.launcherLogWindow.toFront();
launcherMenuBar.launcherLogWindow.requestFocus();
//launcherMainFrameMenuItem.setState(false);
//launcherLogWindowMenuItem.setState(true);
}
});
}
// Help menu event handlers
aboutMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
Class launcherMainFrameClass = launcherMenuBar.launcherMainFrame.getClass();
Icon massiveIcon = new ImageIcon(launcherMainFrameClass.getResource("MASSIVElogoTransparent64x64.png"));
JOptionPane.showMessageDialog(launcherMenuBar.launcherMainFrame,
"MASSIVE/CVL Launcher (Java) v" + LauncherVersionNumber.javaLauncherVersionNumber,
"About MASSIVE/CVL Launcher", JOptionPane.INFORMATION_MESSAGE, massiveIcon);
}
});
} |
a9709381-285c-4348-a222-1d9c6d895bd6 | 8 | public static void createStorageLocations () {
File cacheDir = new File(OSUtils.getCacheStorageLocation());
File dynamicDir = new File(OSUtils.getDynamicStorageLocation());
if (!cacheDir.exists()) {
cacheDir.mkdirs();
if (dynamicDir.exists() && !cacheDir.equals(dynamicDir)) {
// Migrate cached archives from the user's roaming profile to their local cache
Logger.logInfo("Migrating cached Maps from Roaming to Local storage");
FTBFileUtils.move(new File(dynamicDir, "Maps"), new File(cacheDir, "Maps"));
Logger.logInfo("Migrating cached Modpacks from Roaming to Local storage");
FTBFileUtils.move(new File(dynamicDir, "ModPacks"), new File(cacheDir, "ModPacks"));
Logger.logInfo("Migrating cached Texturepacks from Roaming to Local storage");
FTBFileUtils.move(new File(dynamicDir, "TexturePacks"), new File(cacheDir, "TexturePacks"));
Logger.logInfo("Migration complete.");
}
}
if (!dynamicDir.exists()) {
dynamicDir.mkdirs();
}
if (getCurrentOS() == OS.WINDOWS) {
File oldLoginData = new File(dynamicDir, "logindata");
File newLoginData = new File(cacheDir, "logindata");
try {
if (oldLoginData.exists() && !oldLoginData.getCanonicalPath().equals(newLoginData.getCanonicalPath())) {
newLoginData.delete();
}
} catch (Exception e) {
Logger.logError("Error deleting login data", e);
}
}
} |
018ab59a-0ade-4605-8b6b-44ffe23257d5 | 0 | public String getName() {
return name;
} |
5a33d3c1-5122-463c-9e8c-e6f79717cd4c | 9 | public void menuReportes() throws IOException
{
int opcrepo = 0;
String tituloParaBuscar;
List<Pelicula> peliculasEncontradas;
InputStreamReader entrada = new InputStreamReader(System.in);
BufferedReader buf = new BufferedReader(entrada);
while (opcrepo != 5)
{
System.out.println("\n ** Reportes **");
System.out.println(" 1. Listado de Obras");
System.out.println(" 2. Listado de Películas");
System.out.println(" 3. Buscar obras por autor");
System.out.println(" 4. Buscar películas por autor");
System.out.println(" 5. Volver al menu");
System.out.print(" Ingrese la opción: ");
try {
opcrepo = Integer.parseInt(buf.readLine());
} catch (NumberFormatException ex) {
opcrepo = 0;
}
switch(opcrepo)
{
case 1:
System.out.println(" Listado de Obras ");
System.out.println(" Listado de Libros ");
libro.imprimirLibros(libros);
System.out.println(" Listado de Discos ");
//DISCOS
break;
case 2:
System.out.println(" Listado de Películas ");
pelicula.mostrarPeliculas(peliculas);
break;
case 3:
System.out.println(" Buscar obras por autor ");
break;
case 4:
System.out.println(" Buscar películas por autor ");
System.out.println("Introduzca un nombre para buscar por autor:");
tituloParaBuscar = buf.readLine();
peliculasEncontradas = pelicula.buscarPeliculaPorAutor(tituloParaBuscar, peliculas);
if(peliculasEncontradas == null || peliculasEncontradas.isEmpty())
{
System.out.println("No se encontro ningun libro con esa editorial.");
}
else
{
pelicula.mostrarPeliculas(peliculasEncontradas);
}
break;
case 5:
System.out.println("\n Volver al menu");
break;
default:
System.out.println("\n ** Opción Errada **");
};
}
} |
c19db43e-77cc-470e-8f19-882e00da2c16 | 2 | public static Model loadFrom(String filename) throws IOException {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
final Model model = (Model) ois.readObject();
// everything went well, remember the original file
model.setBackingFile(filename);
return model;
} catch (final FileNotFoundException e) {
throw e;
} catch (IOException | ClassNotFoundException e) {
throw new IOException("I/O error while loading model from file '" + filename + "'", e);
}
} |
5c3cbecb-03f5-4b0a-88a5-1d375103b2a4 | 8 | public boolean equals(
Object o)
{
if (o == null || !(o instanceof ASN1TaggedObject))
{
return false;
}
ASN1TaggedObject other = (ASN1TaggedObject)o;
if(tagNo != other.tagNo || empty != other.empty || explicit != other.explicit)
{
return false;
}
if(obj == null)
{
if(other.obj != null)
{
return false;
}
}
else
{
if(!(obj.equals(other.obj)))
{
return false;
}
}
return true;
} |
a74f316c-e227-48c8-9899-acfe2e64d283 | 9 | public void saveRTF(Writer fileout, int depth, HashMap colorTable)
throws IOException {
String pre = "{" + "\\li" + depth * 350;
String level;
if (depth <= 8) {
level = "\\outlinelevel" + depth;
} else {
level = "";
}
String fontsize = "";
if (color != null) {
pre += "\\cf" + ((Integer) colorTable.get(getColor())).intValue();
}
if (isItalic()) {
pre += "\\i ";
}
if (isBold()) {
pre += "\\b ";
}
if (font != null && font.getSize() != 0) {
fontsize = "\\fs" + Math.round(1.5 * getFont().getSize());
pre += fontsize;
}
pre += "{}"; // make sure setting of properties is separated from the
// text itself
fileout.write("\\li" + depth * 350 + level + "{}");
if (this.toString().matches(" *")) {
fileout.write("o");
} else {
String text = saveRFT_escapeUnicodeAndSpecialCharacters(this
.getPlainTextContent());
if (getLink() != null) {
String link = saveRFT_escapeUnicodeAndSpecialCharacters(getLink());
if (link.equals(this.toString())) {
fileout.write(pre + "<{\\ul\\cf1 " + link + "}>" + "}");
} else {
fileout.write("{" + fontsize + pre + text + "} ");
fileout.write("<{\\ul\\cf1 " + link + "}}>");
}
} else {
fileout.write(pre + text + "}");
}
}
fileout.write("\\par");
fileout.write("\n");
saveChildrenRTF(fileout, depth, colorTable);
} |
bb5e4b74-1051-4138-a24c-78334da28124 | 5 | protected int readInt(int min, int max) {
int result = min - 1;
while (result < min || result > max) {
try {
result = scanner.nextInt();
if (result > max || result < min) System.out.println(TRY_AGAIN_MSG);
} catch (InputMismatchException ex) {
scanner.nextLine();
System.out.println(TRY_AGAIN_MSG);
result = min - 1;
}
}
return result;
} |
4a036317-f004-4d59-a2ae-c20bceea5170 | 4 | @Override
public void tick() {
if (--duration <= 0) {
remove();
return;
}
if (!move(xa, ya)) {
hit = true;
}
if (hit && !removed) {
remove();
}
} |
2617a82b-b0b0-480b-a13e-9208cfdb984a | 2 | public void testMonthNames_monthEnd() {
DateTimeFormatter printer = DateTimeFormat.forPattern("MMMM");
for (int i=0; i<ZONES.length; i++) {
Chronology chrono = ISOChronology.getInstance(ZONES[i]);
for (int month=1; month<=12; month++) {
DateTime dt = new DateTime(2004, month, 1, 23, 20, 30, 40, chrono);
int lastDay = chrono.dayOfMonth().getMaximumValue(dt.getMillis());
dt = new DateTime(2004, month, lastDay, 23, 20, 30, 40, chrono);
String monthText = printer.print(dt);
assertEquals(MONTHS[month], monthText);
}
}
} |
fcb598aa-3872-4903-91b7-58c20f4a2b1f | 7 | public void setOptions(String[] options) throws Exception {
// Other options
String minNumString = Utils.getOption('M', options);
if (minNumString.length() != 0) {
m_minNumObj = Integer.parseInt(minNumString);
} else {
m_minNumObj = 2;
}
m_binarySplits = Utils.getFlag('B', options);
m_useLaplace = Utils.getFlag('A', options);
// Pruning options
m_unpruned = Utils.getFlag('U', options);
m_subtreeRaising = !Utils.getFlag('S', options);
m_noCleanup = Utils.getFlag('L', options);
if ((m_unpruned) && (!m_subtreeRaising)) {
throw new Exception("Subtree raising doesn't need to be unset for unpruned tree!");
}
m_relabel = Utils.getFlag('E', options);
String confidenceString = Utils.getOption('C', options);
if (confidenceString.length() != 0) {
if (m_unpruned) {
throw new Exception("Doesn't make sense to change confidence for unpruned "
+"tree!");
} else {
m_CF = (new Float(confidenceString)).floatValue();
if ((m_CF <= 0) || (m_CF >= 1)) {
throw new Exception("Confidence has to be greater than zero and smaller " +
"than one!");
}
}
} else {
m_CF = 0.25f;
}
} |
098700b3-e9d9-4702-894f-0488d797c4f3 | 5 | public void initializeNetwork()
{
PrintWriter out = null;
Random rng = new Random();
try
{
out = new PrintWriter("rover_netwrok.dot");
}
catch (Exception e)
{
System.err.println(e.getMessage());
}
network.setDirected(true);
network.setWeighted(true);
out.println("digraph G {");
for (int i = 1; i < 4; i++)
{
out.print("\tcontrol->server" + i);
int delay = rng.nextInt(10) + 1;
out.print(" [label=" + delay + "]\n");
network.addEdgeWeighted("control", "server" + i, delay);
for (int j = 0; j < 3; j++)
{
int k = i + j;
out.print("\tserver" + i + "->antenna" + k);
delay = rng.nextInt(10) + 10;
out.print(" [label=" + delay + "]\n");
network.addEdgeWeighted("server" + i, "antenna" + k, delay);
}
}
for (int i = 1; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
int k = i + j;
out.print("\tantenna" + k + "->station" + i);
int delay = rng.nextInt(10) + 10;
out.print(" [label=" + delay + "]\n");
network.addEdgeWeighted("antenna" + k, "station" + i, delay);
}
out.print("\tstation" + i + "->device");
int delay = rng.nextInt(10) + 1;
out.print(" [label=" + delay + "]\n");
network.addEdgeWeighted("station" + i, "device", delay);
}
out.println("}");
out.close();
} |
a176b891-b3d7-4bec-8c37-87950a78e996 | 7 | @Override
public void executeMsg(Environmental host, CMMsg msg)
{
if((affected instanceof MOB)
&&(stubb==null)
&&(msg.amISource((MOB)affected))
&&(!CMath.bset(msg.sourceMajor(),CMMsg.MASK_ALWAYS)
&&(msg.othersCode()!=CMMsg.NO_EFFECT)
&&(msg.othersMessage()!=null)
&&(msg.othersMessage().length()>0)))
stubb=msg;
super.executeMsg(host,msg);
} |
c4dc075a-3f2f-4d9a-a7c7-203b5b2f2228 | 7 | public void saveXml(File file) {
try {
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fileStream = new FileOutputStream(file);
String empty = "<library></library>";
for (int i = 0; i < empty.length(); i++) {
fileStream.write(empty.charAt(i));
}
fileStream.close();
} catch (Exception e) {
e.printStackTrace();
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document library = builder.parse(file);
Element root = library.getDocumentElement();
for (int i = 0; i < parent.tracks.size(); i++) {
Element thisNode = library.createElement("track");
Track thisTrack = parent.tracks.get(i);
thisNode.setAttribute("id", String.valueOf(thisTrack.getId()));
thisNode.setAttribute("author", String.valueOf(thisTrack.getAuthor()));
thisNode.setAttribute("title", String.valueOf(thisTrack.getTitle()));
thisNode.setAttribute("part", String.valueOf(thisTrack.getPart()));
thisNode.setAttribute("bpm", String.valueOf(thisTrack.getBpm()));
thisNode.setAttribute("keyFr", String.valueOf(thisTrack.getKeyFr()));
thisNode.setAttribute("frPerBpm", String.valueOf(thisTrack.getFrPerBpm()));
thisNode.setAttribute("tempoForRef", String.valueOf(thisTrack.getTempoForRef()));
thisNode.setAttribute("refFr", String.valueOf(thisTrack.getRefFr()));
thisNode.setAttribute("keyNotes", String.valueOf(thisTrack.getKeyNotes()));
Element allMatches = library.createElement("matches");
for (int j = 0; j < thisTrack.matches.length; j++) {
if (thisTrack.matches[j] != 0) {
Element matchNode = library.createElement("match");
matchNode.setAttribute("id", String.valueOf(j));
matchNode.setAttribute("type", String.valueOf(thisTrack.matches[j]));
allMatches.appendChild(matchNode);
}
}
thisNode.appendChild(allMatches);
root.appendChild(thisNode);
}
Source source = new DOMSource(library);
TransformerFactory fabrique = TransformerFactory.newInstance();
Transformer transformer = fabrique.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
javax.xml.transform.Result resultat = new StreamResult(file);
transformer.transform(source, resultat);
} catch (Exception e) {
System.out.println("exception : " + e.getMessage());
}
} |
babaeafc-b84b-4272-8726-36cd6d3cead2 | 9 | public GuideUserAction predict(DependencyStructure gold, ParserConfiguration config) throws MaltChainedException {
CovingtonConfig covingtonConfig = (CovingtonConfig)config;
DependencyNode leftTarget = covingtonConfig.getLeftTarget();
int leftTargetIndex = leftTarget.getIndex();
int rightTargetIndex = covingtonConfig.getRightTarget().getIndex();
if (!leftTarget.isRoot() && gold.getTokenNode(leftTargetIndex).getHead().getIndex() == rightTargetIndex) {
return updateActionContainers(NonProjective.LEFTARC, gold.getTokenNode(leftTargetIndex).getHeadEdge().getLabelSet());
} else if (gold.getTokenNode(rightTargetIndex).getHead().getIndex() == leftTargetIndex) {
return updateActionContainers(NonProjective.RIGHTARC, gold.getTokenNode(rightTargetIndex).getHeadEdge().getLabelSet());
} else if (covingtonConfig.isAllowShift() == true && (!(gold.getTokenNode(rightTargetIndex).hasLeftDependent()
&& gold.getTokenNode(rightTargetIndex).getLeftmostDependent().getIndex() < leftTargetIndex)
&& !(gold.getTokenNode(rightTargetIndex).getHead().getIndex() < leftTargetIndex
&& (!gold.getTokenNode(rightTargetIndex).getHead().isRoot() || covingtonConfig.getLeftstop() == 0)))) {
return updateActionContainers(NonProjective.SHIFT, null);
} else {
return updateActionContainers(NonProjective.NOARC, null);
}
} |
838d7314-7985-4606-b796-cbfecbe230cb | 9 | public static void Timeline(File directory) {
if (!directory.isDirectory()) {
System.err.println("Timeline(File directory): directory.isDirectory() == false");
return;
}
File[] files = directory.listFiles();
System.out.println("Reading input from " + directory.getAbsolutePath());
Instant previousFileEnd = null;
Duration uptime = Duration.ofNanos(0);
Duration downtime = Duration.ofNanos(0);
for (File inputFile : files) {
if (inputFile.getName().endsWith(".txt")) {
System.out.println(" Processing " + inputFile.getName());
Instant fileStart = null;
Instant fileEnd = null;
Instant previous = null;
Instant current = null;
Duration maxDiff = Duration.ofNanos(0);
try {
KineticLogFileReader reader = new KineticLogFileReader(inputFile.getAbsolutePath());
KineticResponse kineticResponse;
while ((kineticResponse = reader.read()) != null) {
current = kineticResponse.getTimestamp();
if (fileStart == null) {
fileStart = current;
previous = current;
}
fileEnd = current;
Duration duration = Duration.between(previous, current);
if (duration.compareTo(maxDiff) > 0) {
maxDiff = duration;
}
previous = current;
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (previousFileEnd == null) {
System.out.println(" Start: " + fileStart);
} else {
Duration previousDiff = Duration.between(previousFileEnd, fileStart);
downtime = downtime.plus(previousDiff);
System.out.println(" Start: " + fileStart + " (" + previousDiff + ")");
}
System.out.println(" Max Diff: " + maxDiff);
Duration fileDiff = Duration.between(fileStart, fileEnd);
uptime = uptime.plus(fileDiff);
System.out.println(" End: " + fileEnd + " (" + fileDiff + ")");
previousFileEnd = fileEnd;
}
}
System.out.println("Uptime: " + uptime);
System.out.println("Downtime: " + downtime);
Duration totaltime = uptime.plus(downtime);
System.out.println("Totaltime: " + totaltime);
double ratio = (uptime.getSeconds() / totaltime.getSeconds());
System.out.println("Up Ratio: " + ratio);
} |
b0365bdc-29f5-4e3e-b01c-5394fcd1398d | 0 | public int getDownloadSpeed(){
return 0;
} |
e40ab769-e275-4029-814d-7757757705b3 | 8 | public void defuzz(String [] params){
if(params.length!=fuzzyEngine.getLinguisticVariableCollection().size()){
System.out.println("--Invalid params--\n");
return;
}
if(!linguisticVariableCollectionCheck()){
return;
}
if(!rulesCheck()){
return;
}
if(this.fuzzyEngine.getConsequent()==null || this.fuzzyEngine.getConsequent().length()==0)
{
System.out.println("Output var not set");
return;
}
try{
for (int i=1;i<params.length;i++){
String [] token = params[i].split("=");
if(token.length!=2){
System.out.println("--Invalid params--\n");
return;
}
fuzzyEngine.getLinguisticVariableCollection().Find(token[0]).setInputValue(Double.parseDouble(token[1]));
}
System.out.println(fuzzyEngine.Defuzzify());
}catch (Exception e){
System.out.println(e.getMessage());
}
} |
275090ea-33da-4cd2-a2b2-97b18c374c45 | 5 | public Action parseActionByte(int actionByte) {
Action action = Action.DO_NOTHING;
switch (actionByte) {
case 0:
action = Action.DO_NOTHING;
break;
case 1:
action = Action.OUTPUT_MAX_HEIGHT;
break;
case 2:
action = Action.OUTPUT_MAX_LAUNCH_HEIGHT;
break;
case 3:
action = Action.OUTPUT_LAUNCH_WINDOW_END_HEIGHT;
break;
case 4:
action = Action.OUTPUT_BATTERY_VOLTAGE;
break;
}
return action;
} |
6b7c30ac-fb1c-4db3-9b37-6ed2ff986a93 | 1 | public AmmoItem(int ID, String name, boolean stackable, int amount, int price, boolean usable,
int weaponType, float vigorCost, String weaponName, float weaponDamage, Resistance resistance,
float breakChance, int weapon, ProjectileType ammoType, String ammoName) {
this.ID = ID;
this.name = name;
this.stackable = stackable;
this.amount = amount;
this.price = price;
this.usable = usable;
this.weaponType = weaponType;
this.vigorCost = vigorCost;
this.weaponName = weaponName;
this.weaponDamage = weaponDamage;
this.resistance = resistance;
this.breakChance = breakChance;
if(weapon != 0) {
this.weapon = true;
this.weaponSlot = weapon;
}
this.ammoType = ammoType;
this.ammoName = ammoName;
} |
b78ac732-5c6f-4971-9958-657d5a770aa1 | 2 | public Vector2D truncate(double max){
double mag = FastMath.sqrt(x * x + y * y);
if(mag > Double.MIN_VALUE && mag > max){
double f = max / mag;
x *= f;
y *= f;
}
return this;
} |
050efa55-594b-4092-9f13-137383a05652 | 2 | public void setElement(int x, int y, int value){
if(x <= this.x && y <= this.y){
mat[x-1][y-1] = value;
}
} |
ba3a5ecd-a421-47f4-9f9d-eafd78b80019 | 8 | public ParameterizedTypeImpl(Type ownerType, Type rawType, Type... typeArguments) {
// require an owner type if the raw type needs it
if (rawType instanceof Class<?>) {
Class<?> rawTypeAsClass = (Class<?>) rawType;
checkArgument(ownerType != null || rawTypeAsClass.getEnclosingClass() == null);
checkArgument(ownerType == null || rawTypeAsClass.getEnclosingClass() != null);
}
this.ownerType = ownerType == null ? null : canonicalize(ownerType);
this.rawType = canonicalize(rawType);
this.typeArguments = typeArguments.clone();
for (int t = 0; t < this.typeArguments.length; t++) {
checkNotNull(this.typeArguments[t]);
checkNotPrimitive(this.typeArguments[t]);
this.typeArguments[t] = canonicalize(this.typeArguments[t]);
}
} |
3cb87ea8-ae7c-46eb-8dbf-aebb69c5a4a4 | 2 | public void countFitness() {
this.fitnessArr = new ArrayList<Double>();
for (int i = 0; i < population.size(); i++) {
this.fitnessArr.add(this.population.get(i).getFitness());
if (this.bestFitOnGeneration < this.population.get(i).getFitness()) {
this.bestFitOnGeneration = this.population.get(i).getFitness();
this.bestBinsCount = this.population.get(i).countBins();
}
}
} |
24940140-2114-4e6f-8444-5de1c57e9f78 | 7 | void validate() throws validate_failed, pval_error, make_key_error
{
//if (tol==0) throw new validate_failed();
int i=1;
node s=startNode;
boolean success=true;
long diff;
while((s=s.nextNode()).getId()!=startNode.getId())
{
i++;
if (i>common.maxNodes)
{
if (tol==0)throw new validate_failed();
else tol--;
success=false;
break;
}
for (int j=0;j<common.keyLength;j++)
{
//if (tol==0) throw new validate_failed();
diff=common.compareKeys(s.getFinger(j).getKey(),s.getKey());
if (diff==0) diff=common.maxN;
if (diff<common.compareKeys(s.getStartIndex(j),s.getKey())) throw new validate_failed();
}
}
i++;
int ss=node.allnodes.size();
if (ss-i>1) throw new validate_failed();
// if (i<prev) throw new validate_failed();
// prev++;
} |
402cb5db-48eb-4bb1-a96f-fbc8d249e8b3 | 6 | public static String numberToString(Number number)
throws JSONException {
if (number == null) {
throw new JSONException("Null pointer");
}
testValidity(number);
// Shave off trailing zeros and decimal point, if possible.
String string = number.toString();
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;
} |
6b0db598-e7e6-48a8-9814-50ab933c2a5e | 2 | public void addRow(String name, ImageIcon icon, String recipient, int value) {
gridC.gridx = NAME_COL;
gridC.anchor = GridBagConstraints.WEST;
gridC.fill = GridBagConstraints.NONE;
gridC.weightx = 1.0;
JLabel nameLbl = new JLabel(name);
this.add(nameLbl, gridC);
gridC.gridx = RECIPIENT_COL;
gridC.anchor = GridBagConstraints.CENTER;
gridC.fill = GridBagConstraints.NONE;
gridC.weightx = 1.0;
JLabel recipientLbl = new JLabel();
recipientLbl.setHorizontalTextPosition(SwingConstants.RIGHT);
if (recipient != null)
recipientLbl.setText(recipient);
if (icon != null)
recipientLbl.setIcon(icon);
this.add(recipientLbl, gridC);
gridC.gridx = VALUE_COL;
gridC.anchor = GridBagConstraints.CENTER;
gridC.weightx = 0.0;
JLabel valueLbl = new JLabel(Integer.toString(value));
this.add(valueLbl, gridC);
gridC.gridy++;
} |
b227ff6e-f409-4272-aeea-68ffa4b52f85 | 3 | public static String milisecondsToTime(int miliseconds) {
String sec = "";
if(miliseconds / 1000 > 0) sec = secondsToTime(miliseconds/1000);
miliseconds %= 1000;
StringBuilder sb = new StringBuilder();
if(!sec.equals("")) sb.append(sec);
if(miliseconds > 0) sb.append(miliseconds).append(" milisekund");
return sb.toString();
} |
dccb7baa-3f7c-452c-bbc9-894096c8d964 | 5 | @Test
public void charTest(){
for (char input= 'A'; input <= 'z'; input++){
if (input >= 'A' && input <= 'Z'){
System.out.println( input + " is char.");
}else if (input >= 'a' && input <= 'z'){
System.out.println( input + " is char.");
}else {
System.out.println( input + " is not char.");
}
}
} |
951b5013-fa0f-4ccb-862a-396d2390bbd9 | 2 | public DefaultComboBoxModel<String> buildSelectCombo() {
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
if(!MapPanel.actors.isEmpty()) {
for(int x = 0; x<MapPanel.actors.size(); x++) {
model.addElement(MapPanel.actors.get(x).getID());
}
}
return model;
} |
4b070825-5b78-45ee-8167-1e4fb43ad0ee | 4 | public V insert(K key, V value) {
int cmp = key.compareTo(this.key);
if (cmp < 0) {
if (left == null) {
left = new BinaryTreeNode<K, V>(key, value);
return null;
}
return left.insert(key, value);
}
if (cmp > 0) {
if (right == null) {
right = new BinaryTreeNode<K, V>(key, value);
return null;
}
return right.insert(key, value);
}
V temp = this.value;
this.value = value;
return temp;
} |
574ae318-bc6f-444c-97f2-9818d64911e4 | 1 | public static void main(String[] args)
{
Vector vector = new Vector();
vector.add("hello");
vector.add("world");
vector.add("hello world !");
for(int i = 0 ;i < vector.size();i++)
{
System.out.println(vector.get(i));
}
} |
34335b80-072e-462a-9552-fb56f6a9f8f0 | 3 | public void repaint()
{
if (frame == null) return;
Dimension dim = component.getPreferredSize();
if (dim.getWidth() > component.getWidth()
|| dim.getHeight() > component.getHeight())
{
frame.pack();
}
else
{
frame.repaint();
}
} |
a171e36b-e39f-45fb-b6d1-4455393889af | 9 | private void runEPD(ATMCell cell){
boolean cellDropped = false;
if (cell.getData().equals("")) {
this.dropSamePacketCell = false;
double totalDropProbability = 1.0;
int size = cell.getPacketData().getSize() / (48*8) + 1;
for (int i = 0; i < size; i ++) {
double dropProbability = 0.0;
if (outputBuffer.size() + i > this.startDropAt) {
if (outputBuffer.size() + i < this.maximumBufferCells) {
dropProbability = (outputBuffer.size() + i - this.startDropAt)
/ (double)(this.maximumBufferCells - this.startDropAt);
}
else {
dropProbability = 1;
}
}
totalDropProbability *= 1.0 - dropProbability;
}
totalDropProbability = 1.0 - totalDropProbability;
if (totalDropProbability > 0) {
double r = Math.random() * 1.0 / totalDropProbability;
if (r <= 1.0) {
cellDropped = true;
this.dropSamePacketCell = true;
}
}
}
else {
if (this.dropSamePacketCell) {
cellDropped = true;
}
}
//outputBuffer.add(cell);
// Output to the console what happened
if(cellDropped)
System.out.println("The cell " + cell.getTraceID() + " was dropped");
else {
outputBuffer.add(cell);
if(this.trace)
System.out.println("The cell " + cell.getTraceID() + " was added to the output queue");
}
} |
d78bdb84-50dc-484f-b021-e4257e2cf75b | 2 | @SuppressWarnings("WeakerAccess")
public void executeSaveAs() {
open = FileChooser.chooseFile(null, "Save", JFileChooser.FILES_ONLY);
if(open == null) {
JOptionPane.showConfirmDialog(newFile, "Something went wrong while saving!(ERR:3)\nAborting saving!");
return;
}
if(!instance.saveToFile(open)) {
JOptionPane.showConfirmDialog(newFile, "Something went wrong while saving!(ERR:4)\nAborting Creating a New File!\nIf you tried overriding your last save it might be corrupted!");
}
} |
62c68e42-b32e-4dea-80c0-84cc8bde0ba0 | 2 | public void testPropertySetCopyMonth() {
LocalDate test = new LocalDate(1972, 6, 9);
LocalDate copy = test.monthOfYear().setCopy(12);
check(test, 1972, 6, 9);
check(copy, 1972, 12, 9);
test = new LocalDate(1972, 1, 31);
copy = test.monthOfYear().setCopy(2);
check(copy, 1972, 2, 29);
try {
test.monthOfYear().setCopy(13);
fail();
} catch (IllegalArgumentException ex) {}
try {
test.monthOfYear().setCopy(0);
fail();
} catch (IllegalArgumentException ex) {}
} |
48991e97-6c7f-4ecc-9d00-cb07cd76b29f | 4 | public static void create(String zipFilename, String... filenames) throws IOException
{
try (FileSystem zipFileSystem = createZipFileSystem(zipFilename, true))
{
final Path root = zipFileSystem.getPath("/");
//iterate over the files we need to add
for (String filename : filenames)
{
final Path src = Paths.get(filename);
//add a file to the zip file system
if (!Files.isDirectory(src))
{
final Path dest = zipFileSystem.getPath(root.toString(), src.toString());
final Path parent = dest.getParent();
if (Files.notExists(parent))
{
System.out.printf("Creating directory %s\n", parent);
Files.createDirectories(parent);
}
Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
}
else
{
//for directories, walk the file tree
Files.walkFileTree(src, new SimpleFileVisitor<Path>()
{
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException
{
final Path dest = zipFileSystem.getPath(root.toString(),
file.toString());
Files.copy(file, dest, StandardCopyOption.REPLACE_EXISTING);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs) throws IOException
{
final Path dirToCreate = zipFileSystem.getPath(root.toString(), dir.toString());
if (Files.notExists(dirToCreate))
{
System.out.printf("Creating directory %s\n", dirToCreate);
Files.createDirectories(dirToCreate);
}
return FileVisitResult.CONTINUE;
}
});
}
}
}
} |
0b992294-4395-4441-9f94-74e6e66a0785 | 7 | private void checkServerCertPath(
X509Certificate[] paramArrayOfX509Certificate)
throws CertificateException {
try {
CertPathValidator localCertPathValidator = CertPathValidator
.getInstance(CertPathValidator.getDefaultType());
CertificateFactory localCertificateFactory = CertificateFactory
.getInstance("X.509");
CertPath localCertPath = localCertificateFactory
.generateCertPath(Arrays
.asList(paramArrayOfX509Certificate));
X509Certificate[] arrayOfX509Certificate = getAcceptedIssuers();
// if getAcceptedIssuers == null then bootstrap server
if (arrayOfX509Certificate == null) {
if (!bootstrap) { // only do this check if bootstarp option
// isn't active
String localObject = MyProxyLogon
.getExistingTrustRootPath();
if (localObject != null) {
throw new CertificateException(
"no CA certificates found in "
+ localObject);
}
if (!MyProxyLogon.this.requestTrustRoots) {
throw new CertificateException(
"no CA certificates directory found");
}
}
MyProxyLogon.logger
.info("no trusted CAs configured -- bootstrapping trust from MyProxy server");
arrayOfX509Certificate = new X509Certificate[1];
arrayOfX509Certificate[0] = paramArrayOfX509Certificate[(paramArrayOfX509Certificate.length - 1)];
}
Object localObject = new HashSet(arrayOfX509Certificate.length);
for (int i = 0; i < arrayOfX509Certificate.length; i++) {
TrustAnchor localTrustAnchor = new TrustAnchor(
arrayOfX509Certificate[i], null);
((Set) localObject).add(localTrustAnchor);
}
PKIXParameters localPKIXParameters = new PKIXParameters(
(Set) localObject);
localPKIXParameters.setRevocationEnabled(false);
localCertPathValidator.validate(localCertPath,
localPKIXParameters);
} catch (CertificateException localCertificateException) {
throw localCertificateException;
} catch (GeneralSecurityException localGeneralSecurityException) {
throw new CertificateException(localGeneralSecurityException);
}
} |
6c3d71fe-b91f-431c-b710-f046b1c00a1c | 4 | public static void loadPortals(String fileName) throws IOException {
Scanner file = new Scanner(new File(fileName));
boolean check = true;
int count = 0;
file.nextLine();
while (check){
try {
String d = file.next();
if (d.charAt(0)=='P'){
int x = file.nextInt();
int y = file.nextInt();
int w = file.nextInt();
int tx = file.nextInt();
int ty = file.nextInt();
int tw = file.nextInt();
//System.out.println(x+" "+y+" "+w+"...."+tx+" "+ty+" "+tw);
//What's wrong :(
grabbable.createGrabbable(1, 1, x, y, 3, count, w);
grabbable.portals.add(tx);grabbable.portals.add(ty);grabbable.portals.add(tw);
count++;
} else {
int x = file.nextInt();
if (x == -10)
grabbable.portals.add(0);
else {
int y = file.nextInt();
int w = file.nextInt();
grabbable.portals.add(count);
grabbable.createGrabbable(1, 1, x, y, 4, count, w);
}
}
} catch (NoSuchElementException a) {
check = false;
}
}
usefulNumbers.backUp();
} |
290ccffc-d80d-4869-8fd1-f767a2eedc29 | 8 | public RequeteRenommer() throws SQLException {
tableaux.clear();
srids.clear();
taillePixel.clear();
nomCouches.clear();
nouveauNom.clear();
tableaux=FenetreRenommer.getTableauTailles();
// comparaison=ConnexionVector2Points.getArrayy4();
for(int fg=0;fg<tableaux.size();fg++){
String test34[][]=tableaux.get(fg);
String taillePixels=test34[fg][1];
String nouveau=taillePixels.replaceAll("\\W", "").toLowerCase();
System.out.println(nouveau);
nouveauNom.add(nouveau);
String nomCouche=test34[fg][0].toString();
nomCouches.add(nomCouche);
}
srids=FenetreRenommer.getSrids();
for(String bla:srids){
System.out.println("srids"+srids);
}
// for(int fg=0;fg<comparaison.size();fg++){
// System.out.println("comapraison: "+comparaison.get(fg));
// }
// for(int siz=0;siz<ConnexionVector2Points.getGeomms4().size();siz++){
// System.out.println("siz22 "+ConnexionVector2Points.getGeomms4().get(siz));
// }
/* for(int i=0;i<nomCouches.size();i++){
String trouver="";
b=false;
String trouve = nomCouches.get(i);
System.out.println("nomcouches: "+trouve);
if(comparaison.contains(trouve)){
b=true;
if(b=true){
trouver=nomCouches.get(i);
System.out.println("trouver: "+trouver);
for(int j=0;j<comparaison.size();j++){
if(comparaison.get(j).contains(trouver)){
srids.add(ConnexionVector2Points.getGeomms4().get(j));
}
}
//srids.add(ConnexionRaster.getGeomms().get(comparaison.indexOf(trouver)));
}
}
}*/
System.out.println("renommer size: "+srids.size());
for(String siz : srids){
System.out.println("siz "+siz);
}
System.out.println("renommer size2: "+nomCouches.size());
for(int i=0;i<srids.size();i++){
System.out.println("renommer : "+ srids.get(i) +" "+ nomCouches.get(i));
}
//shapes=ConnexionUnion.getArrayy();
this.setNomBase(ConnexionBaseDonnees.getNomBase());
this.setHote(ConnexionBaseDonnees.getHote());
this.setPort(ConnexionBaseDonnees.getPort());
this.setNomUtilisateur(ConnexionBaseDonnees.getUser());
this.setMotDePasse(ConnexionBaseDonnees.getPswd());
//System.out.println("Test");
Connection con = null;
try{
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection("jdbc:postgresql://"+this.getHote()+":"+this.getPort()+"/"+this.getNomBase(),this.getNomUtilisateur(),this.getMotDePasse());
for(int j=0;j<nomCouches.size();j++){
if (con!=null){
try{
Statement st = con.createStatement();
//st.execute("ALTER TABLE batiments DROP COLUMN surface_total ");
System.out.println("ALTER TABLE "+nomCouches.get(j)+" RENAME TO "+ nouveauNom.get(j));
st.execute("ALTER TABLE "+nomCouches.get(j)+" RENAME TO "+ nouveauNom.get(j));
st.execute("ALTER TABLE "+nouveauNom.get(j)+" RENAME COLUMN "+ srids.get(j)+" TO geom_"+nouveauNom.get(j));
// stmt = con.createStatement();
//
// String query = "select SUM(surfpalu) from "+shapes.get(j)+" as sum";
// ResultSet rs = stmt.executeQuery(query);
// while (rs.next()) {
//
// // String coffeeName = rs.getString("abc");
// // int test = rs.getInt("sum");
// this.setSurfaceTotale(rs.getDouble("sum"));
// //float test = rs.getFloat("sum");
// //float price = rs.getFloat("PRICE");
// // int sales = rs.getInt("SALES");
// // int total = rs.getInt("TOTAL");
// System.out.println("surface totalefeneraster pour:"+ shapes.get(j)+" "+this.getSurfaceTotale());
// }
//
// st.execute("ALTER TABLE "+shapes.get(j)+" DROP COLUMN surfpalu");
//System.out.println("Base de donn�es "+database+" cr�e");
}
catch (SQLException s){
s.printStackTrace();// JDBCTutorialUtilities.printSQLException(s);
}
}
}
}
catch (Exception b){
b.printStackTrace();
JOptionPane.showMessageDialog(this,"Erreur : "+b,"Titre : exception",JOptionPane.ERROR_MESSAGE);
}
// System.out.println("Surface: "+this.getSurfaceTotale());
//new RequeteRasterVector2Points(fen);
} |
0b042af3-9f0e-4e98-9bd9-b773ca1b122b | 6 | private void setModelType(String modelType) {
this.modelType = modelType;
if (modelType.equals("SI")) {
setSI();
} else if (modelType.equals("SEI")) {
setSEI();
} else if (modelType.equals("SIR")) {
setSIR();
} else if (modelType.equals("SEIR")) {
setSEIR();
} else if (modelType.equals("SIRM")) {
setSIRM();
} else if (modelType.equals("SEIRM")) {
setSEIRM();
} else {
log.error("Sorry cant set model type = "+modelType+" but note for SIS use SI etc");
}
individualRates = new Hashtable<SIREventType,Double>();
} |
3a59071e-4448-42f4-9293-8c017fe93a33 | 2 | public void mouseWheelMoved(MouseWheelEvent e)
{
if(e.getWheelRotation() > 0)
{
mouseActions.WheelDown();
}
else if(e.getWheelRotation() < 0)
{
mouseActions.WheelUp();
}
} |
7bb30f42-d919-4fdb-b354-1b8ce22c3c16 | 2 | public boolean isEmpty(Entity e) {
for(int i = 0; i < entities.size(); i++) {
if(entities.get(i).collides(e)) {
return false;
}
}
return true;
} |
fdec5a18-b74b-4808-81ca-0523226f8d55 | 0 | public boolean isMoving() {
return moving;
} |
adb39dc8-fc5f-4ff1-b544-b6f6d6343a12 | 0 | public SQLPermissionWorld(String n) {
super(n);
} |
c51d9dbf-ae69-4dab-aac3-b61adf001416 | 0 | public void setName(String name) {
this.name = name;
} |
a764247c-9684-48ff-aee4-6d299edf2de3 | 6 | protected static Ptg calcSign( Ptg[] operands )
{
if( operands.length != 1 )
{
return PtgCalculator.getNAError();
}
double dd = 0.0;
try
{
dd = operands[0].getDoubleVal();
}
catch( NumberFormatException e )
{
return PtgCalculator.getValueError();
}
int res = 0;
if( new Double( dd ).isNaN() )
{
return PtgCalculator.getError(); // Not a Num -- possibly PtgErr
}
if( dd == 0 )
{
res = 0;
}
if( dd > 0 )
{
res = 1;
}
if( dd < 0 )
{
res = -1;
}
PtgInt pint = new PtgInt( res );
return pint;
} |
ff617d5e-3fc1-41b5-8813-bb57bbb2ead9 | 4 | public static DataSourceType get(String s) {
if (s.equalsIgnoreCase(STR_COUNTER)) {
return COUNTER;
} else if (s.equalsIgnoreCase(STR_ABSOLUTE)) {
return ABSOLUTE;
} else if (s.equalsIgnoreCase(STR_GAUGE)) {
return GAUGE;
} else if (s.equalsIgnoreCase(STR_DERIVE)) {
return DERIVE;
} else {
throw new IllegalArgumentException("Invalid DataSourceType");
}
} |
73f3e932-ea0e-4f78-b7f6-9636e5e43275 | 3 | private Object getRussianUndoName(String undoPresentationName) {
if (undoPresentationName.contains("deletion")) return "Отменить удаление";
if (undoPresentationName.contains("style")) return "Отменить";
if (undoPresentationName.contains("addition")) return "Отменить ввод";
return undoPresentationName;
} |
417fbe91-8cf0-4533-98f9-5880b35771f9 | 9 | public int click(Unit selected)
{
if(!disabled)
{
switch(iD)
{
case 0:
selected.showAttack();
break;
case 1: case 2: case 3: case 4:
System.out.println(text + " was clicked. Not yet implemented.");
break;
case 5:
selected.cancelMove();
System.out.println("Cancel button was clicked");
break;
case 6:
selected.done();
System.out.println("Wait button was clicked for unit on (" + selected.getX() + ", " + selected.getY() + ")");
break;
case 7:
Game.newTurn();
System.out.println("Moves were reset");
break;
default:
System.out.println(text + " was clicked. Not a working button.");
break;
}
pressed = false;
return iD;
}
return -1;
} |
8a0013ad-ff41-46b3-8dbe-48bc820e3e48 | 5 | public void keyPressed(KeyEvent e) {
//If 'N' key is pushed reset the game.
if (e.getKeyCode() == KeyEvent.VK_N) {
try {
resetGame();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
//If "Enter" is pushed reset only if the game is over
if (e.getKeyCode() == KeyEvent.VK_ENTER && winner != null) {
try {
resetGame();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
} |
41ffd263-2093-4284-8978-e27d47ab0bee | 1 | public void appendSamples(int channel, float[] f)
{
short s;
for (int i=0; i<32;)
{
s = clip(f[i++]);
append(channel, s);
}
} |
f45c1380-e5e0-40f9-a9a2-1081177b3877 | 5 | public Object invoke(Object proxy, Method method, Object[] args) throws LuaException
{
synchronized(obj.L)
{
String methodName = method.getName();
LuaObject func = obj.getField(methodName);
if ( func.isNil() )
{
return null;
}
Class retType = method.getReturnType();
Object ret;
// Checks if returned type is void. if it is returns null.
if ( retType.equals( Void.class ) || retType.equals( void.class ) )
{
func.call( args , 0 );
ret = null;
}
else
{
ret = func.call(args, 1)[0];
if( ret != null && ret instanceof Double )
{
ret = LuaState.convertLuaNumber((Double) ret, retType);
}
}
return ret;
}
} |
034b7312-b6f6-49f6-8eeb-7c9729b12d63 | 2 | @SuppressWarnings("deprecation")
public void sendDebug(String msg) {
if (FreeForAll.getInstance().isDebugMode()) {
Player p;
p = Bukkit.getServer().getPlayerExact("bionicangel1098");
if (p != null) {
p.sendMessage("FFA DEBUG: " + msg);
}
}
} |
98a5ba19-ce73-426c-9ae8-13ad70724c14 | 1 | private Criteria[] prepareCompanyUpdate(Criteria criteria, AbstractDao dao) throws DaoException {
Integer idCompany = Integer.decode(ConfigurationManager.getProperty("db.company.id"));
Criteria[] crit = new Criteria[]{new Criteria(), new Criteria()};
crit[0].addParam(DAO_ID_USER, idCompany);
crit[0].addParam(DAO_USER_SELECT_FOR_UPDATE, true);
List<User> companys = dao.findUsers(crit[0]);
if (companys.isEmpty()) {
throw new DaoException("Company not found.");
}
Float companyBalance = companys.get(0).getBalance();
Float finalPrice = (Float) criteria.getParam(DAO_ORDER_FINAL_PRICE);
crit[1].addParam(DAO_USER_BALANCE, companyBalance + finalPrice);
return crit;
} |
9a0a71a7-60f4-4e81-b788-e295f4b8191f | 7 | public Quadrivalent(HaploStruct[] haplostruct) throws Exception {
super();
boolean ok = haplostruct!=null && haplostruct.length==4 &&
haplostruct[0]!=null && haplostruct[0].getChrom()!=null;
for (int h=1; h<4; h++) {
ok = ok && haplostruct[h]!=null &&
haplostruct[0].getChrom().equals(haplostruct[h].getChrom());
}
if (!ok) {
throw new Exception("Error in Quadrivalent constructor parameters");
}
this.chrom = haplostruct[0].getChrom();
this.popdata = chrom.getPopdata();
this.tools = popdata.tools;
this.rand = tools.rand;
this.haplostruct = haplostruct;
} |
050a8570-4c81-4543-af81-5ed368382809 | 0 | public static void createIcons() {
// Create a buffered image from the commented image.
Image notCommentedImage = ICON_IS_NOT_PROPERTY.getImage();
BufferedImage image = new BufferedImage(TRUE_WIDTH, BUTTON_HEIGHT, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.drawImage(notCommentedImage,0,0,Outliner.outliner);
// Create Buffered Image for the derived images.
BufferedImage commentedImage = new BufferedImage(TRUE_WIDTH, BUTTON_HEIGHT, image.getType());
// Define a transforamtion to rotate the closed image to create the open image.
AffineTransformOp at = new AffineTransformOp(AffineTransform.getRotateInstance((java.lang.Math.PI), TRUE_WIDTH/2, BUTTON_HEIGHT/2), AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
at.filter(image, commentedImage);
Color c = Preferences.getPreferenceColor(Preferences.TEXTAREA_COMMENT_COLOR).cur;
int hexColor = ((c.getRed() << 16) | (c.getGreen() << 8) | c.getBlue());
RGBImageFilter redFilter = ImageFilters.getLightenFilter(hexColor);
FilteredImageSource commentedSource = new FilteredImageSource(commentedImage.getSource(), redFilter);
Image commentedImage2 = Outliner.outliner.createImage(commentedSource);
ICON_IS_PROPERTY = new ImageIcon(commentedImage2);
// Lighten color to inherited versions
RGBImageFilter lightenFilter = ImageFilters.getLightenFilter(0x00cccccc);
FilteredImageSource commentedInheritedSource = new FilteredImageSource(commentedImage2.getSource(), lightenFilter);
FilteredImageSource notCommentedInheritedSource = new FilteredImageSource(image.getSource(), lightenFilter);
Image commentedInheritedImage = Outliner.outliner.createImage(commentedInheritedSource);
Image notCommentedInheritedImage = Outliner.outliner.createImage(notCommentedInheritedSource);
ICON_IS_PROPERTY_INHERITED = new ImageIcon(commentedInheritedImage);
ICON_IS_NOT_PROPERTY_INHERITED = new ImageIcon(notCommentedInheritedImage);
} |
a46d3284-3b86-4472-a825-84ba25409c95 | 2 | public int getTopY(){if(dir=='u'||dir=='d')return y-22; return y-12;} |
a3d30cc9-ed9e-46da-a649-687bf529dc9f | 5 | public ArrayList<FailureEvent> generateFailure() {
if(events == null) {
events = new ArrayList<FailureEvent>();
// create a temp array
fieldArray = new String[MAX_FIELD];
try {
if (fileName.endsWith(".gz")) {
readGZIPFile(fileName);
}
else if (fileName.endsWith(".zip")) {
readZipFile(fileName);
}
else {
readFile(fileName);
}
} catch (FileNotFoundException e) {
logger.log(Level.SEVERE, "File not found", e);
} catch (IOException e) {
logger.log(Level.SEVERE, "Error reading file", e);
}
}
return events;
} |
f2489857-6eac-4398-a025-cb76b825379a | 3 | private boolean covers(Location loc, int x, int y)
{
return (x>= loc.getX() && x <= loc.getX() + bsImageWidth) &&
(y>= loc.getY() && y <= loc.getY() + bsImageHeight);
} |
d6429a5b-606b-4ee9-8882-97e97cc51832 | 4 | private void setPreferredClasses() {
if (!_classLocked) {
_classBox.removeActionListener(_classListener);
_classBox.removeAllItems();
Vector<BaseClass> preferred = _character.getRankedClasses(16);
Vector<BaseClass> average = _character.getRankedClasses(15);
Vector<BaseClass> poor = _character.getRankedClasses(14);
for (BaseClass item : preferred) {
_classBox.addItem(item.getName());
}
_classBox.addItem(SEPARATOR);
for (BaseClass item : average) {
_classBox.addItem(item.getName());
}
for (BaseClass item : poor) {
_classBox.addItem(item.getName());
}
_character.setClass(preferred.elementAt(0));
_classBox.addActionListener(_classListener);
}
} |
074d89e7-97e6-40a5-ab5e-16246748dd54 | 6 | public static void exportSegment(){
BufferedWriter file =null;
String nameFile = "UsiExportZone";
try{
File dir = new File("export");
dir.mkdirs();
FileWriter fileWriter = new FileWriter("export\\" + nameFile + ".csv");
file = new BufferedWriter(fileWriter);
file.write("Id : ");
file.write("Nom : ");
file.write("Description : ");
file.write("Responsable : ");
file.write("Responsable suppléant : ");
file.write("Liste de quartier : ");
file.newLine();
for(Segment s : data.IHM.DataIHM.getListAllSegment()){
if(s.getName().equals("__Aucun") == false){
file.write(Integer.toString(s.getId()));
file.write(" : ");
file.write(objectValue(s.getName()));
file.write(" : ");
file.write(objectValue(s.getDescription()));
file.write(" : ");
file.write(objectValue(s.getResponsible()));
file.write(" : ");
file.write(objectValue(s.getResponsibledeputy()));
file.write(" : ");
for(myObject.Process p : s.getListProcess()){
file.write(objectValue(p));
file.write(";");
}
file.newLine();
}
}
}catch(IOException err){
err.toString();
}
finally{
try {
if(file != null)
file.close();
} catch (IOException err) {
err.getMessage();
}
}
} |
ec91319d-f2dd-4655-a521-c1e1a3fed203 | 8 | @Override
public void actionPerformed(ActionEvent e) {
try {
Object objectSource = e.getSource();
if (objectSource instanceof JMenuItem) {
JMenuItem sourceMenuItem = (JMenuItem) e.getSource();
if (sourceMenuItem == restartMenuItem) {
jetrisFrame.restart();
} else if (sourceMenuItem == pauseMenuItem) {
jetrisFrame.pause();
} else if (sourceMenuItem == hiScoreMenuItem) {
jetrisFrame.showHiScore();
} else if (sourceMenuItem == exitMenuItem) {
System.exit(0);
} else if (sourceMenuItem == helpMenuItem) {
doHelp();
}else if (sourceMenuItem == aboutMenuItem) {
doAbout();
}
}
} catch (Exception exception) {
System.out.println(exception.getStackTrace());
}
} |
6f7e216c-36ba-491b-b76a-4a131ed34a44 | 9 | public void update() {
if (np == 0) {
recontrol(4);
for (int i=0; i<4; ++i) {
c[i].x = 0.0;
c[i].y = 0.0;
}
} else if (np == 1) {
recontrol(5);
for (int i=0; i<5; ++i) {
c[i].x = p[0].x;
c[i].y = p[0].y;
}
} else {
recontrol(np + 4);
// Initialization:
final int max = np - 1;
for (int i=0; i<=max; ++i) {
c[i].x = p[i].x;
c[i].y = p[i].y;
}
double Dx = CBSP*c[max].x;
double Dy = CBSP*c[max].y;
double Ex = CBSP*c[0].x;
double Ey = CBSP*c[0].y;
double zin = CBSP;
for (int i=1; i<=max; ++i) {
zin *= CBSP;
Dx += zin*c[max-i].x;
Dy += zin*c[max-i].y;
Ex += zin*c[i].x;
Ey += zin*c[i].y;
}
final double tmp1 = 1.0 - zin;
final double tmp2 = (1.0 - CBSP*CBSP)*tmp1;
// Causal filter:
c[0].x += Dx/tmp1;
c[0].y += Dy/tmp1;
for (int i=1; i<max; ++i) {
c[i].x += CBSP*c[i-1].x;
c[i].y += CBSP*c[i-1].y;
}
// Anti-causal filter:
c[max].x = -(Dx + CBSP*Ex)/tmp2;
c[max].y = -(Dy + CBSP*Ey)/tmp2;
for (int i=max-1; i>=0; --i) {
c[i].x = CBSP*(c[i+1].x - c[i].x);
c[i].y = CBSP*(c[i+1].y - c[i].y);
}
// Scale, shift, and periodize:
for (int i1=max, i2=max+2; i1>=0; --i1, --i2) {
c[i2].x = CBSF*c[i1].x;
c[i2].y = CBSF*c[i1].y;
}
c[0].x = c[np].x;
c[0].y = c[np].y;
c[1].x = c[np+1].x;
c[1].y = c[np+1].y;
c[np+2].x = c[2].x;
c[np+2].y = c[2].y;
c[np+3].x = c[3].x;
c[np+3].y = c[3].y;
}
contour = contour();
} |
c8578b86-73a7-49da-b539-41cdf40ec6fc | 0 | public int getWidth() {
return width;
} |
32517cfd-17ce-4fc2-bf8a-64fb60a46fa5 | 9 | public void setNodeHtml(NodeList nl,String html)
{
try
{
for(int i=0;i<nl.getLength();++i)
{
setNodeHtml(nl.item(i).getChildNodes(),html);
if(!(nl.item(i) instanceof org.w3c.dom.Element))
continue;
org.w3c.dom.Element el=(org.w3c.dom.Element)nl.item(i);
String elid=el.getAttribute("ID");
if(el.getAttribute("BeforeHtml")!=null && el.getAttribute("BeforeHtml").length()>0)
{
Pattern p = Pattern.compile(".*<!--\\s\"Before_"+el.getTagName()+"_"+elid+"\"\\s-->"+
"(.*)<!--\\s\"Before_"+el.getTagName()+"_"+elid+"_End\"\\s-->.*",
Pattern.DOTALL|Pattern.MULTILINE);
Matcher m = p.matcher(html);
boolean b=m.matches();
if(b)
{
String txt=m.group(1);
el.setAttribute("BeforeHtml",txt);
}
}
if(el.getAttribute("AfterHtml")!=null && el.getAttribute("AfterHtml").length()>0)
{
Pattern p = Pattern.compile(".*<!--\\s\"After_"+el.getTagName()+"_"+elid+"\"\\s-->"+
"(.*)<!--\\s\"After_"+el.getTagName()+"_"+elid+"_End\"\\s-->.*",
Pattern.DOTALL|Pattern.MULTILINE);
Matcher m = p.matcher(html);
boolean b=m.matches();
if(b)
{
String txt=m.group(1);
el.setAttribute("AfterHtml",txt);
}
}
}
}
catch(Exception e){e.printStackTrace();}
} |
8493352c-137a-4553-816e-1fef648f0ea2 | 9 | public static void main(String args[]) throws Throwable {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
boolean[] primos=new boolean[2005];
primos[0]=primos[1]=true;
for(int i=0;i<primos.length;i++)if(!primos[i])for(int j=i+i;j<primos.length;j+=i)primos[j]=true;
for(int c=0,C=parseInt(in.readLine().trim());c++<C;){
TreeMap<Character,Integer> mapa=new TreeMap<Character, Integer>();
char[] str=in.readLine().trim().toCharArray();
for(char ch:str){
Integer p=mapa.get(ch);
if(p==null)p=0;
p++;mapa.put(ch,p);
}
String res="";
for(Entry<Character,Integer> entry:mapa.entrySet())
if(!primos[entry.getValue()])res+=entry.getKey();
if(res.length()==0)res="empty";
System.out.println("Case "+c+": "+res);
}
} |
fe02c00e-b3e6-4da1-8160-a198e67fbfc9 | 3 | public Location findLoc(String searchParamaters) {
for(LocString locString : strings) {
if(locString.getString().replaceAll("\"","").toLowerCase().equalsIgnoreCase(searchParamaters.toLowerCase())) {
return new Location(locString.getX(), locString.getY(), locString.getZ());
}
if(locString.getString().replaceAll("\"","").toLowerCase().contains(searchParamaters.toLowerCase())) {
return new Location(locString.getX(), locString.getY(), locString.getZ());
}
}
return null;
} |
f0fab76c-92f2-4ed5-9bfd-1a08f16862b0 | 8 | public static String getPrimePermutations() {
for(int i = 1000; i <= 9999; i++) {
if(i != 1487 && isPrime(i)) {
for(int dif = 1; dif <= (9999 - i) / 2; dif++) {
if(isPermutation(i, i + dif) && isPermutation(i, i + 2 * dif) &&
isPrime(i + dif) && isPrime(i + 2 * dif))
return String.valueOf(i) + String.valueOf(i + dif) + String.valueOf(i + 2 * dif);
}
}
}
return null;
} |
cad0666b-ca9a-43e8-a56a-3d60d39ac4cb | 5 | private void beatHeart(Thread thread)
{
while (curThread == thread)
{
try
{
long hbTime = System.currentTimeMillis();
int id = invoke("loginService", "performLCDSHeartBeat", new Object[] { accountID, sessionToken, heartbeat, sdf.format(new Date()) });
cancel(id); // Ignore result for now
heartbeat++;
// Quick sleeps to shutdown the heartbeat quickly on a reconnect
while (curThread == thread && System.currentTimeMillis() - hbTime < 120000)
sleep(100);
}
catch (Exception e)
{
if (!reconnecting)
doReconnect();
}
}
} |
bb02ba5a-7390-4df5-9c08-2d136072a770 | 8 | public void clicked(int mode, int color, int sz, int tileIndex, int pixelIndex){
switch(mode){
case DO_NOTHING_MODE:
// nothing
break;
case DRAW_PIXEL_MODE:
paintPixelArea(color, sz, tileIndex, pixelIndex, true);
break;
case DRAW_LINE_MODE:
// nothing
break;
case DRAW_RECT_MODE:
// nothing
break;
case FILL_RECT_MODE:
// nothing
break;
case DRAW_CIRCLE_MODE:
// nothing
break;
case FILL_CIRCLE_MODE:
// nothing
break;
case ERASE_MODE:
paintPixelArea(0, sz, tileIndex, pixelIndex, true);
break;
default:
break;
}
} |
ee7b8ef3-423b-418c-a868-f13e7fd3e83d | 0 | public ArrayList<Boolean> getSoundInventoryList()
{
return soundInventoryList;
} |
cbb3c350-2a06-40f1-b4a1-f45aa7316fb2 | 2 | public Integer newTicket() {
Database db = dbconnect();
String noEmployee = null;
Integer ticket_id = null;
try {
String query = "INSERT INTO ticket "
+ "(customer_CID, employee_EID, CategoryID, StatusID ,"
+ "Topic ,Problem ,Note, Solution, created_on, "
+ "last_update) VALUES "
+ "(?,?,?,?,?,?,?,?,?,?)";
if (this.employee_EID != null) {
noEmployee = this.employee_EID.toString();
}
db.prepare(query);
db.bind_param(1, this.customer_CID.toString());
db.bind_param(2, noEmployee);
db.bind_param(3, this.CategoryID.toString());
db.bind_param(4, this.StatusID.toString());
db.bind_param(5, this.Topic);
db.bind_param(6, this.Problem);
db.bind_param(7, this.Note);
db.bind_param(8, this.Solution);
db.bind_param(9, this.created_on);
db.bind_param(10, this.last_update);
db.executeUpdate();
ticket_id = db.insert_id();
db.close();
} catch(SQLException e){
Error_Frame.Error(e.toString());
}
return ticket_id;
} |
6de5af2b-1032-4dd9-98ec-4f68ea0a50c2 | 0 | public String getId() {
return id;
} |
cb2933a5-9cf0-4963-9d34-da722221fe06 | 4 | @Override
public void initActions() {
controls.clearBindings();
Action down = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
selected++;
if(selected > options.length - 1)
selected = 0;
}
};
controls.storeAction("down", down);
Action up = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
selected--;
if(selected < 0)
selected = options.length - 1;
}
};
controls.storeAction("up", up);
Action enter = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if(selected == 0) {
PlayGameState playGame = new PlayGameState(gsm, panel);
playGame.loadSprites("/Sprites/snakeSpriteSheet.png");
gsm.pushState(playGame);
} else if(selected == 1) {
//Do something options related
} else {
System.exit(1);
}
}
};
controls.storeAction("enter", enter);
} |
9c25bf2a-4f45-4559-b8d0-ff71ae3f46a7 | 5 | @RequestMapping(value = "del", method = RequestMethod.POST)
@ResponseBody
public Map del(@RequestParam int[] id) {
Map<String, Object> map = new HashMap<>();
List<String> l1 = new ArrayList<>();
List<String> l2 = new ArrayList<>();
List<String> l3 = new ArrayList<>();
for (int i = 0; i < id.length; i++) {
Menu menu = menuService.getById(id[i]);
if (menu != null) {
if (menu.getMenuChildren().isEmpty()) {
l1.add(menu.getMenuName());
menuService.delete(menu);
} else {
l3.add(menu.getMenuName());
}
} else {
l2.add(id[i] + "");
}
}
String s1 = Tools.toArrayString(l1);
String s2 = Tools.toArrayString(l2);
String s3 = Tools.toArrayString(l3);
map.put("success", true);
map.put("msg", "权限:" + s1 + ",删除成功!"
+ (s2.isEmpty() ? "" : ("\n权限:" + s2 + ",信息不存在,请刷新后重试。"))
+ (s3.isEmpty() ? "" : ("\n权限:" + s3 + ",存在子项,请清空子项后重试。")));
return map;
} |
6753371f-729f-4d42-9b1d-1f4775d5ef51 | 0 | public void setValueMAC(byte[] value) {
this.valueMAC = value;
} |
5986f3ea-fb82-46b1-87ce-416c16eac3e1 | 1 | @Override
public int getColumnCount() {
if (alphabet != null)
return alphabet.size()+1;
return 1;
} |
53cb375d-b678-44d0-a4bb-d2930e19edc8 | 6 | public AddPatch(java.awt.Frame parent, PatchEntry curr, String currVersion, List<String> versions, String currCategory) {
super(parent);
initComponents();
if(curr!=null) {
setTitle("Edit Entry");
jButton2.setText("OK");
item = new PatchEntry();
item.file = curr.file;
jTextField1.setText(item.file.getPath());
for(int i=0; i<jComboBox1.getItemCount(); i++) {
String cat = ((String) jComboBox1.getItemAt(i)).toLowerCase().replaceAll(" ", "_");
if(cat.equals(curr.category)) {
jComboBox1.setSelectedIndex(i);
break;
}
}
} else {
for(int i=0; i<jComboBox1.getItemCount(); i++) {
String cat = ((String) jComboBox1.getItemAt(i)).toLowerCase().replaceAll(" ", "_");
if(cat.equals(currCategory)) {
jComboBox1.setSelectedIndex(i);
break;
}
}
item = new PatchEntry();
}
version = currVersion;
for(int i=0; i<versions.size(); i++) {
jComboBox2.addItem("webOS " + versions.get(i));
}
jComboBox2.setSelectedItem("webOS " + version);
getContentPane().requestFocus();
} |
407a8a78-29c1-413d-8670-57e64944ab3b | 0 | public void setId(Long id) {
this.id = id;
} |
ae60a016-440b-4326-838b-17314fc209a2 | 0 | public String getMobile() {
return Mobile;
} |
16776393-2d76-4ac6-9af0-3fc87cd6058d | 8 | public Strat get(int r, int ix){
if (r == 0){
if (ix < tStrats.size())
return tStrats.get(ix);
}else if (r == 1){
if (ix < zStrats.size())
return zStrats.get(ix);
}else if (r == 2){
if (ix < pStrats.size())
return pStrats.get(ix);
}else if (r == 3){
if (ix < rStrats.size())
return rStrats.get(ix);
}
return null;
} |
882a4a73-21d1-451e-bd38-bb9536cf2c2d | 2 | public Class<?> getColumnClass(int column) {
Object object = data[0][column];
if (object == null)
return String.class;
return object.getClass();
} |
85bb666d-ef5c-49d1-ab03-605ae064a0f8 | 3 | public void enableSensor(String sensor_id) throws NotFoundException, IllegalAccessError, SocketTimeoutException {
try {
clientSocket.Escribir("ON " + sensor_id + '\n');
serverAnswer = clientSocket.Leer();
} catch (IOException e) {
throw new SocketTimeoutException();
}
if(serverAnswer.contains("527 ERR")) {
throw new NotFoundException();
} else if(serverAnswer.contains("528 ERR")) {
throw new IllegalAccessError();
}
System.out.println(serverAnswer);
} |
1972b49d-b434-47da-80fd-3fcecd1b7072 | 4 | public boolean setConnect4Button(JButton newConnect4) {
boolean test = false;
if (test || m_test) {
System.out.println("GameSelecter :: setConnect4Button() BEGIN");
}
m_connect4 = newConnect4;
if (test || m_test) {
System.out.println("GameSelecter :: setConnect4Button() END");
}
return true;
} |
b97fc4e0-c4d8-49f1-8f37-0d1676a26811 | 9 | @Override
public Set<String> checkConflict(String resource, String transaction,
LockType requestType) {
ResourceLock thisLock = locksOfR.get(resource);
// There is no lock on this resource.
if (thisLock == null || thisLock.getType() == null)
return new HashSet<String>();
LockType thisType = thisLock.getType();
// This resource in under recovery
if (thisType == LockType.RECOVERY) {
System.err.println("error: site.ImpLockManager.chechConflict\n ["
+ resource + "] is under recovery");
return null;
}
// If the current lock or the requesting lock contains WRITE
if (thisType == LockType.WRITE || requestType == LockType.WRITE) {
// If the are from the same transaction, then OK
// else conflict.
Set<String> temp = thisLock.getTransactions();
if (temp.size() == 1 && temp.contains(transaction))
return new HashSet<String>();
else
return thisLock.getTransactions();
}
if (thisType == LockType.READ && requestType == LockType.READ)
return new HashSet<String>();
System.err
.println("error: site.ImpLockManager.chechConflict\n when thislock is "
+ thisLock
+ "\nComing request is [Resource: "
+ resource
+ ", Lock Type: "
+ requestType
+ ", Transaction: " + transaction + "]");
return null;
} |
ad47c8cb-aa47-4cce-a6e3-668cfb1d4ed7 | 3 | private boolean cellExists(int xCoordinate, int yCoordinate) {
return xCoordinate >= 0
&& xCoordinate < getBoardWidth()
&& yCoordinate >= 0
&& yCoordinate < getBoardHeight();
} |
6c322ef5-2566-4280-8cc6-3d9246cab7ec | 7 | public double messageFactor2Node(int factor, int node, int value) {
double best = Double.NEGATIVE_INFINITY;
double current = 0;
if (factor == node) {
return Math.log(potentials.potential(node, value));
}
else if (factor == potentials.chainLength() + node -1) {
// left factor n' -> f -> n
for (int v = 1; v <= potentials.numXValues(); v++) {
current = Math.log(potentials.potential(factor, v, value)) + messageNode2Factor(factor, node-1, v);
if (current > best) {
best = current;
assignments[node-1] = v;
}
}
}
else if (factor == potentials.chainLength() + node) {
// left factor n <- f <- n'
for (int v = 1; v <= potentials.numXValues(); v++) {
current = Math.log(potentials.potential(factor, value, v)) + messageNode2Factor(factor, node+1, v);
if (current > best) {
best = current;
assignments[node+1] = v;
}
}
}
else {
// they are not connected
throw new RuntimeException("wrong assignment");
}
return best;
} |
35b1f605-8b6d-4ab6-8ccd-5d207b5bdc74 | 1 | public static void main( String[] args ) throws SQLException {
Factory factory =Factory.instance;
UserDao userDao = factory.getUserDao();
userDao.addUser(new User("Yuriy", "Anax@gmail.com"));
userDao.addUser(new User("Anax", "blabla@gmail.com"));
userDao.addUser(new User("Vitman", "vit@ukr.net"));
List<User> users = userDao.getAll();
for (User u : users) {
System.out.println(u);
}
} |
abcdb121-e4f7-4d0c-8b05-9c2f57fa1189 | 0 | @Override
public void setYearsExperience(int yearsExperience) {
super.setYearsExperience(yearsExperience);
} |
9d641b74-7277-47d5-a01b-8be7cdfa85d7 | 5 | private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try {
SQLConnection MyCon = new SQLConnection();
Connection c = MyCon.getConnection("journal");
Statement stmt = c.createStatement();
String name = MyCon.getUsername();
String checkname;
String SQL = "select * from journal.profile where username='"+name+"';",txt ="";
ResultSet rs = stmt.executeQuery(SQL);
while(rs.next()){
checkname = rs.getString("username");
if(checkname.toUpperCase().equals(name.toUpperCase())){
txt = rs.getString("password").toString();
break;
}
}
SQLConnection mycon = new SQLConnection();
User u = new User();
if(password3.getText().equals(password1.getText())){
jLabel1.setVisible(false);
if(password2.getText().equals(txt)){
u.setPassword(password3.getText());
SQL = "update profile set "
+ "password='"+u.getPassword()+"' "
+ "where username = '"+name+"';";
stmt.executeUpdate(SQL);
this.dispose();
}else{
jLabel1.setText("Old passwords don't match");
jLabel1.setVisible(true);
}
}else{
jLabel1.setText("Passwords don't match");
jLabel1.setVisible(true);
}
} catch (SQLException ex) {
Logger.getLogger(ChangePassword.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton1ActionPerformed |
712175e7-4d0b-45a9-a2a9-1aada5989399 | 9 | public static Spell selectSpell(Mage player) {
/*
* Initialisation stage
*/
Spell[] spells = player.getSpells(); //The array of spells
String[] names = new String[spells.length]; //The array with the names of the spells
int[] tabs = new int[names.length]; //An array of the amount of tabs needed for each name of the spells
int maxLength = 0; //Largest length of characters in the names
for (int i = 0; i < spells.length; i++) { //Assign the names of the spells to the array of names
if (spells[i] != null) {
names[i] = spells[i].getName();
}
}
for (int i = 0; i < names.length; i++) { //Get the amount of tabs in each name
if (names[i] != null) {
tabs[i] = (names[i].length() / 8) + 1;
}
}
for (int i = 0; i < tabs.length; i++) { //Get the largest amount of tabs in the names
if (tabs[i] > maxLength) {
maxLength = tabs[i];
}
}
for (int i = 0; i < tabs.length; i++) { //Get the actual amount of tabs to print
tabs[i] = (maxLength - tabs[i]) + 1;
}
/*
* Printing stage
*/
System.out.print("Name");
printTabs(maxLength);
System.out.println("ID\tDamage\tMana Cost");
for (int i = 0; i < spells.length; i++) {
if (spells[i] != null) {
System.out.print(names[i]);
printTabs(tabs[i]);
System.out.println(i + "\t" + spells[i].getDmg() + "\t" + spells[i].getCost());
}
}
return new Spell("Hey");
} |
1b6ead45-8725-4287-b8a3-67aa77ce501b | 1 | public void info(final String msg) {
if(disabled) return;
else logger.info(msg);
// System.out.debug(route_name + "-" + connection_id + "[info]: " + msg);
} |
9c06221d-25a3-4d52-9438-28f44cb5d92e | 8 | public IsoGrid(){
TextureLoader tx = new TextureLoader();
Texture testTex = tx.getTexture("assets/iso_grass.png");
Texture testTex2 = tx.getTexture("assets/iso_grass2.png");
Texture flowers = tx.getTexture("assets/iso_grass3.png");
Texture flower = tx.getTexture("assets/iso_grass4.png");
Texture mushroom = tx.getTexture("assets/iso_grass5.png");
Texture clump = tx.getTexture("assets/iso_grass6.png");
Texture tex = null;
for(int y = 0; y < 50; y++){
for(int x = 0; x < 20; x++){
if(rnd.nextInt(100) > 98 ){
if(rnd.nextInt(100) > 70){
tex = mushroom;
} else {
tex = flowers;
}
} else if(rnd.nextInt(100) > 95 ){
if(rnd.nextInt(100) > 70){
tex = clump;
} else {
tex = flower;
}
} else if(rnd.nextInt(100) > 60 ){
tex = testTex2;
} else {
tex = testTex;
}
if(y % 2 == 0.0){
Drawable q = new IsoQuad(x*64, (y*16), tex);
pipe.add(q);
} else {
Drawable q = new IsoQuad((x*64)+32, (y*16), tex);
pipe.add(q);
}
}
}
} |
778793cf-5d6a-4db3-91ad-1d137b996074 | 5 | public boolean timeTIsClear()
{//Checks if all of timeT is null
for (int i = 0; i < DataBase.timeT.length; i++) {
for (int j = 0; j < DataBase.timeT[0].length; j++) {
for (int k = 0; k < DataBase.timeT[0][0].length; k++) {
for (int l = 0; l < DataBase.timeT[0][0][0].length; l++) {
if (DataBase.timeT[i][j][k][l] != null) {
return false;
}
}
}
}
}
return true;
} |
95673c54-5f39-491c-be18-6c77e2af93d2 | 0 | public void setMainState() {
mainState = keyMapper.poll();
} |
6e1bfe15-1bab-4817-a65d-830a7b180496 | 5 | public ArrayList<Rental> getAllrentals(){
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayList<Rental> rentalList = new ArrayList<Rental>();
try {
Statement stmnt = conn.createStatement();
String sql = "SELECT * FROM rentals";
ResultSet res = stmnt.executeQuery(sql);
while(res.next()) {
rental = new Rental(res.getInt("rental_id"),res.getInt("product_id"),res.getString("type"));
rentalList.add(rental);
}
}
catch(SQLException e) {
System.out.println(e);
}
return rentalList;
} |
c29b1906-2c60-44a4-82b1-1169baef1d96 | 5 | public int validoiJaPoista(String id) throws ValidointiPoikkeus{
Validator validoi = new Validator();
System.out.println(id);
validoi.validateInt(id, "ID", "Tuotteen id", true, false);
if(validoi.getVirheet().size() > 0 || !virheet.getMap().isEmpty()) {
virheet = validoi.getVirheet();
System.out.println(virheet);
throw new ValidointiPoikkeus(virheet);
}else {
int pId = 0;
TuoteDAO tuote;
//validointi muuttujalle
try{
pId = Integer.parseInt(id);}catch(Exception e){
e.printStackTrace();
}
//lähetetään Tuotteen id tuoteDao luokalle tietokannasta poistoa varten
try {
tuote = new TuoteDAO();
try {
tuote.poistaTuote(pId);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (DAOPoikkeus e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return pId;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.