method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
ea03bc44-5c1f-4879-96ef-03736833c6ec | 8 | @Override
public void setMiscText(String newMiscText)
{
onlyRoomDomains.clear();
neverRoomDomains.clear();
skills.clear();
super.setMiscText(newMiscText);
this.message=CMParms.getParmStr(newMiscText, "MESSAGE", "You can't do that here.");
String domains=CMParms.getParmStr(newMiscText, "ONLYROOMS", "");
List<String> domainList=CMParms.parseCommas(domains, true);
for(String domain : domainList)
{
int x=CMParms.indexOf(Room.DOMAIN_INDOORS_DESCS, domain.toUpperCase().trim());
if(x>=0)
onlyRoomDomains.add(Integer.valueOf(Room.INDOORS+x));
else
{
x=CMParms.indexOf(Room.DOMAIN_OUTDOOR_DESCS, domain.toUpperCase().trim());
if(x>=0)
onlyRoomDomains.add(Integer.valueOf(x));
}
}
domains=CMParms.getParmStr(newMiscText, "NEVERROOMS", "");
domainList=CMParms.parseCommas(domains, true);
for(String domain : domainList)
{
int x=CMParms.indexOf(Room.DOMAIN_INDOORS_DESCS, domain.toUpperCase().trim());
if(x>=0)
neverRoomDomains.add(Integer.valueOf(Room.INDOORS+x));
else
{
x=CMParms.indexOf(Room.DOMAIN_OUTDOOR_DESCS, domain.toUpperCase().trim());
if(x>=0)
neverRoomDomains.add(Integer.valueOf(x));
}
}
String skillStr=CMParms.getParmStr(newMiscText, "SKILLS", "");
List<String> skillList=CMParms.parseCommas(skillStr, true);
for(String skill : skillList)
{
final Ability A=CMClass.getAbility(skill);
if(A!=null)
{
skills.add(A.ID());
}
}
} |
1e66d97a-fcfd-43e0-a870-a714698526aa | 6 | public void actionPerformed( ActionEvent e )
{
Object sender = e.getSource() ;
if ( sender == saveButton)
{
if ( fileDialog.showSaveDialog(null) == JFileChooser.APPROVE_OPTION)
{
TGlobal.config.saveToFile(fileDialog.getSelectedFile());
}
}
else if (sender == loadButton)
{
if (fileDialog.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
// load from file
if ( TGlobal.config.loadFromFile( fileDialog.getSelectedFile()) )
{
this.firePropertyChange( "reload", 0, 1 ) ; // no error -> update view
}
else
{
this.firePropertyChange( "save", 0, 1 ) ; // error -> put current settings into database
}
}
}
else if (sender == resetButton)
{
this.firePropertyChange("reset", 0, 1);
}
} |
d5486de0-24f7-4ed8-872d-d42e71fc48a8 | 6 | private void fineAdd(FineNode<T> curr, T t) {
if (curr != root) {
if (curr.getParent() != root) {
curr.getParent().getParent().unlock();
}
curr.lock();
}
try {
switch (t.compareTo(curr.getValue())) {
case -1:
fineInternalAddLeft(curr, t);
break;
case 1:
fineInternalAddRight(curr, t);
break;
case 0:
fineInternalAddLeft(curr, t);
break;
}
} finally {
if (curr.getLock().isHeldByCurrentThread()) {
curr.unlock();
}
}
} |
3aaef767-bd27-4596-a034-f92a231ffac3 | 8 | public static void main(String[] args) {
Params.readConf();
Params.printConf();
Rule r = new Rule(Params.rule, Params.radius);
boolean[][][] e = { getRandomTestCase(r), getTestCase(r), getTestCase2(r) };
GeneticAlgorithmKernel kernel = new GeneticAlgorithmKernel(Params.populationCount, e);
double bestFitness = 0;
Rule bestRule = null;
int i = 0;
for (i = 0; i < Params.maxRunCount; i++) {
kernel.calculateProgressiveFitness();
kernel.setOffset(kernel.getOffset() == 0 ? Params.populationCount : 0);
kernel.reset();
kernel.execute(Params.populationCount / 2);
if (Params.keepBest) {
kernel.moveElite(Params.elite);
}
double tmpBest = kernel.bestFitness();
if (bestFitness < tmpBest) {
bestFitness = tmpBest;
bestRule = new Rule(kernel.bestRule());
}
int best = kernel.bestFitnessIndex();
StringBuilder sb = new StringBuilder(String.format("t=%d, max_f=%f, avg_f=%f, min_f=%f, div=%f, best_rule=%s, {cs=%s}, {ms=%s}, {cms=%s}", i, tmpBest, kernel.avgFitness(), kernel.minFitness(), kernel.getDiversity(), new Rule(
kernel.population[best], kernel.ruleLenTable[best]), printArray(kernel.getCrossStats()), printArray(kernel.getMutationStats()), printArray(kernel.getMutationAndCrossStats())));
int[] dist = new int[Params.maxRadius + 1];
for (int rad = 0; rad < Params.populationCount; rad++) {
dist[kernel.radiusTable[rad + kernel.getOffset()]]++;
}
if (Params.minRadius != Params.maxRadius) {
StringBuilder db = new StringBuilder(", dist:");
double avgRad = 0;
for (int rad = Params.minRadius; rad < Params.maxRadius + 1; rad++) {
double foo = (double) dist[rad] / Params.populationCount;
db.append(String.format("%d = %f, ", rad, foo));
avgRad += rad * foo;
}
sb.append(String.format(", avg_rad=%f", avgRad));
sb.append(db.toString());
}
result(sb.toString());
if (Double.compare(1.0, tmpBest) == 0) {
info("Got ideal solution!");
break;
}
}
info("Simulation finished!");
info("Iterations : " + i);
info("Test rule: " + r);
info("Found rule: " + bestRule);
info("Best fitness: " + bestFitness);
} |
db879e91-8600-4e83-b0a5-6eca87325239 | 7 | public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut())
return false;
// Is metrics already running?
if (task != null)
return true;
// Begin hitting the server with glorious data
task = plugin.getServer().getScheduler()
.runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true;
@Override
public void run() {
try {
// This has to be synchronized or it can collide with the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the server owner decided to opt-out
if (isOptOut() && task != null) {
task.cancel();
task = null;
// Tell all plotters to stop gathering information.
for (final Graph graph : graphs)
graph.onOptOut();
}
}
// We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to false
// Each post thereafter will be a ping
firstPost = false;
} catch (final IOException e) {
if (debug)
Bukkit.getLogger().log(Level.INFO,
"[Metrics] " + e.getMessage());
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
} |
2692ead7-107e-4bc1-afdf-ac63d619088b | 1 | private void compute_pcm_samples0(Obuffer buffer)
{
final float[] vp = actual_v;
//int inc = v_inc;
final float[] tmpOut = _tmpOut;
int dvp =0;
// fat chance of having this loop unroll
for( int i=0; i<32; i++)
{
float pcm_sample;
final float[] dp = d16[i];
pcm_sample = (float)(((vp[0 + dvp] * dp[0]) +
(vp[15 + dvp] * dp[1]) +
(vp[14 + dvp] * dp[2]) +
(vp[13 + dvp] * dp[3]) +
(vp[12 + dvp] * dp[4]) +
(vp[11 + dvp] * dp[5]) +
(vp[10 + dvp] * dp[6]) +
(vp[9 + dvp] * dp[7]) +
(vp[8 + dvp] * dp[8]) +
(vp[7 + dvp] * dp[9]) +
(vp[6 + dvp] * dp[10]) +
(vp[5 + dvp] * dp[11]) +
(vp[4 + dvp] * dp[12]) +
(vp[3 + dvp] * dp[13]) +
(vp[2 + dvp] * dp[14]) +
(vp[1 + dvp] * dp[15])
) * scalefactor);
tmpOut[i] = pcm_sample;
dvp += 16;
} // for
} |
6b856990-9a9c-4c09-833a-638c9f6e78ff | 3 | void createChildWidgets () {
/* Add common controls */
super.createChildWidgets ();
/* Add TableEditors */
comboEditor = new TableEditor (table);
nameEditor = new TableEditor (table);
table.addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent e) {
resetEditors ();
index = table.getSelectionIndex ();
if (index == -1) return;
TableItem oldItem = comboEditor.getItem ();
newItem = table.getItem (index);
if (newItem == oldItem || newItem != lastSelected) {
lastSelected = newItem;
return;
}
table.showSelection ();
combo = new CCombo (table, SWT.READ_ONLY);
createComboEditor (combo, comboEditor);
nameText = new Text(table, SWT.SINGLE);
nameText.setText(((String[])data.elementAt(index))[NAME_COL]);
createTextEditor(nameText, nameEditor, NAME_COL);
}
});
} |
5983fc50-a007-4db0-90db-d8e828073847 | 0 | public void setItemId(int itemId) {
this.itemId = itemId;
} |
28646931-5c08-4ff3-ba20-b8b68f30cb4f | 2 | public void setShutdownButtonBorderthickness(int[] border) {
if ((border == null) || (border.length != 4)) {
this.buttonShutdown_Borderthickness = UIBorderthicknessInits.SHD_BTN.getBorderthickness();
} else {
this.buttonShutdown_Borderthickness = border;
}
somethingChanged();
} |
9b30edab-ac5d-4541-9018-15e15f274d03 | 8 | public void dealClueCards() {
Random hazard = new Random();
int playerIndex = 0;
Card someCard;
dealDeck.addAll(deck);
// create solution set
while (true) {
someCard = dealDeck.get(hazard.nextInt(dealDeck.size()));
if (someCard.type == CardType.PERSON){
dealDeck.remove(someCard);
solution.add(someCard);
break;
}
}
while (true) {
someCard = dealDeck.get(hazard.nextInt(dealDeck.size()));
if (someCard.type == CardType.ROOM){
dealDeck.remove(someCard);
solution.add(someCard);
break;
}
}
while (true) {
someCard = dealDeck.get(hazard.nextInt(dealDeck.size()));
if (someCard.type == CardType.WEAPON){
dealDeck.remove(someCard);
solution.add(someCard);
break;
}
}
// deal out rest of cards
while (!dealDeck.isEmpty()) {
someCard = dealDeck.get(hazard.nextInt(dealDeck.size()));
dealDeck.remove(someCard);
allPlayers.get(playerIndex).cards.add(someCard);
++playerIndex;
if (playerIndex == allPlayers.size()) playerIndex = 0;
}
// for(Card temp : solution) // print solution for testing
// System.out.println(temp.name);
} |
c3f229df-588b-4890-bd13-7b84353cd7ee | 9 | public static void main(String[] args) throws Throwable{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
diccionario = new TreeMap<Integer, ArrayList<char[]>>();
for (int c = 0, C = parseInt(in.readLine().trim()); c < C; c++) {
String str = in.readLine().trim();
if(!diccionario.containsKey(str.length()))
diccionario.put(str.length(), new ArrayList<char[]>());
diccionario.get(str.length()).add(str.toCharArray());
}
for (String ln; (ln = in.readLine()) != null; ) {
StringTokenizer st = new StringTokenizer(ln.trim());
char[] linea = ln.toCharArray();
palabras = new ArrayList<char[]>();
while(st.hasMoreTokens())palabras.add(st.nextToken().toCharArray());
if(function(new TreeSet<Character>(), new TreeMap<Character, Character>(), 0, 0))
/*for (int i = 0; i < palabras.size(); i++) {
for (char ch: palabras.get(i))
sb.append(solucion.get(ch));
sb.append(i < palabras.size() - 1?" ":"");
}
else
for (int i = 0; i < palabras.size(); i++) {
for (char ch: palabras.get(i))
sb.append("*");
sb.append(i < palabras.size() - 1?" ":"");
}*/
for (int i = 0; i < linea.length; i++) {
Character ch = solucion.get(linea[i]);
if(ch != null)sb.append(ch);
else sb.append(linea[i]);
}
else{
for (int i = 0; i < linea.length; i++) {
if(linea[i]!=' ')sb.append("*");
else sb.append(linea[i]);
}
}
sb.append("\n");
}
System.out.print(new String(sb));
} |
9262bed2-48ec-419a-ac82-22a544fb1813 | 7 | private WriteResponseList processRecordDeletesInBatchMode(BaseRef[] refs, String methodName) {
ArrayList<WriteResponse> responses = new ArrayList<WriteResponse>();
BaseRef[] batch = new BaseRef[getDeleteRequestSize()];
for (int i=0; i<refs.length; i++) {
if (i != 0 && (i%getDeleteRequestSize() == 0)) {
processDeleteBatch(batch, responses, methodName);
batch = new BaseRef[getDeleteRequestSize()];
}
batch[i%getDeleteRequestSize()] = refs[i];
}
int leftOverCount = 0;
for (int j=0; j<batch.length; j++)
if (batch[j] != null)
leftOverCount++;
BaseRef[] leftOvers = new BaseRef[leftOverCount];
for (int j=0; j<leftOvers.length; j++)
leftOvers[j] = batch[j];
processDeleteBatch(leftOvers, responses, methodName);
WriteResponseList wrl = new WriteResponseList();
wrl.setWriteResponse(new WriteResponse[refs.length]);
for (int i=0; i<responses.size();i++)
wrl.getWriteResponse()[i] = responses.get(i);
return wrl;
} |
c5446e13-81c9-4c51-8f46-510764b53a8e | 9 | private boolean r_mark_suffix_with_optional_U_vowel() {
int v_1;
int v_2;
int v_3;
int v_4;
int v_5;
int v_6;
int v_7;
// (, line 159
// or, line 161
lab0: do {
v_1 = limit - cursor;
lab1: do {
// (, line 160
// (, line 160
// test, line 160
v_2 = limit - cursor;
if (!(in_grouping_b(g_U, 105, 305)))
{
break lab1;
}
cursor = limit - v_2;
// next, line 160
if (cursor <= limit_backward)
{
break lab1;
}
cursor--;
// (, line 160
// test, line 160
v_3 = limit - cursor;
if (!(out_grouping_b(g_vowel, 97, 305)))
{
break lab1;
}
cursor = limit - v_3;
break lab0;
} while (false);
cursor = limit - v_1;
// (, line 162
// (, line 162
// not, line 162
{
v_4 = limit - cursor;
lab2: do {
// (, line 162
// test, line 162
v_5 = limit - cursor;
if (!(in_grouping_b(g_U, 105, 305)))
{
break lab2;
}
cursor = limit - v_5;
return false;
} while (false);
cursor = limit - v_4;
}
// test, line 162
v_6 = limit - cursor;
// (, line 162
// next, line 162
if (cursor <= limit_backward)
{
return false;
}
cursor--;
// (, line 162
// test, line 162
v_7 = limit - cursor;
if (!(out_grouping_b(g_vowel, 97, 305)))
{
return false;
}
cursor = limit - v_7;
cursor = limit - v_6;
} while (false);
return true;
} |
0d2ecce0-edc2-4d89-b179-d813a8bb869f | 1 | public void upgrade() {
if(tier < 19) {
fuelCapacity += 20;
fuelLevel += 20;
tier++;
} else {
tier = 20;
fuelCapacity = 500;
fuelLevel = 480;
}
} |
4dc8b16e-4530-43b6-b8bc-459030753ed4 | 8 | public static int[] twoSum(int[] numbers, int target) {
int[] result = new int[2];
result[0] = -1;
result[1] = -1;
HashMap<Integer, Integer> table = new HashMap<Integer, Integer>();
int other = 0; //start from 1
for(int m=0;m<numbers.length;m++) {
Integer otherPart = table.get(target-numbers[m]);
if(otherPart == null) {
table.put(numbers[m], target-numbers[m]);
} else {
other = otherPart;
break;
}
}
for(int m=0;m<numbers.length;m++) {
if(numbers[m] == other && result[0] == -1) {
result[0] = m+1;
}else if(numbers[m] == target-other && result[1] == -1) {
result[1] = m+1;
}
}
if(result[0] > result[1]) {
int tmp = result[1];
result[1] = result[0];
result[0] = tmp;
}
return result;
} |
ac63fa06-9741-4d2e-a07c-c107fa099b23 | 5 | @Override
protected void init() {
try {
// check to see if the user is using a File or InputStream. This is
// here for backwards compatability
if (dataSourceStream != null) {
final Reader r = new InputStreamReader(dataSourceStream);
setDataSourceReader(r);
addToCloseReaderList(r);
} else if (dataSource != null) {
final Reader r = new FileReader(dataSource);
setDataSourceReader(r);
addToCloseReaderList(r);
}
final List cmds = ParserUtils.buildMDFromSQLTable(con, getDataDefinition(), this);
addToMetaData(cmds);
if (cmds.isEmpty()) {
throw new FileNotFoundException("DATA DEFINITION CAN NOT BE FOUND IN THE DATABASE " + getDataDefinition());
}
setInitialised(true);
} catch (final SQLException e) {
throw new InitialisationException(e);
} catch (final FileNotFoundException e) {
throw new InitialisationException(e);
}
} |
0971f6c5-bd3f-485b-b15b-6a82c71e131d | 4 | private boolean handleMessage(SelectionKey key, SocketChannel socketChannel, ProtocolHeader protocolHeader) {
long numRead;
numRead = 0;
int offset = 1;
buffer[offset] = ByteBuffer.allocate(ProtocolUtils.getBodySize(protocolHeader));
numRead = readBuffer(key, offset);
if (socketChannel.isOpen()) {
byteReceived.inc(numRead);
try {
buffer[1].flip();
switch (protocolHeader.getCommandType()) {
case Protocol.HEADER_COMMAND_PUBLISH: {
onPublish(buffer[1],key);
break;
}
case Protocol.HEADER_COMMAND_SUBSCRIBE: {
onRegisterSubscribe(buffer[1], key);
break;
}
}
} catch (Exception ex) {
log.severe("Error on read, cause: " + ex.getMessage());
}
return true;
}
return false;
} |
7640543c-7906-43ff-8f95-b2b1a3d0f67e | 5 | public static int[] sort(int[] list){
if(list == null || list.length <= 0){
return list;
}
boolean changed;
do {
changed = false;
for(int i=1; i<list.length; i++){
if(list[i-1] > list[i]){
swap(list, i-1, i);
changed = true;
}
}
} while(changed);
return list;
} |
46742d28-17fd-4899-b0cb-83a76dedda49 | 0 | public String getCivilState() {
return CivilState;
} |
080c487e-524b-423b-b543-4661fd39aaeb | 4 | @Override
public int compareTo(DBUpdateTimestamp o) {
int t = this.year - o.year;
int u = this.month - o.month;
int v = this.day - o.day;
int w = this.count - o.count;
if (t != 0)
return t;
if (u != 0)
return u;
if (v != 0)
return v;
if (w != 0)
return w;
return 0;
} |
f6aeeed4-1d4a-46d9-9d80-c089ac934887 | 3 | public DistributionSkew(int rack_size, int max_card, double skew){
super(rack_size, max_card);
//Clamp skew value, so we can keep the error weights normalized between 0-1
if (skew > 1) skew = 1;
else if (skew < -1) skew = -1;
//Compute skew line
offset = skew > 0 ? skew : 0;
slope = -skew / (double) rack_size;
} |
c86f3480-fb51-4fb3-9f6b-0f1c71d53e30 | 2 | @Override
public String getParameter(String name) {
String custom = (String)this.customParameters.get(name);
if (custom != null)
return custom;
try{
return super.getParameter(name);
}catch(Exception e){
this.customParameters.put(name, null);
}
return null;
} |
5ddfcc45-e859-4b77-971a-b7e0180323c3 | 0 | public static void main(String[] args) {
Sleeper sleepy = new Sleeper("Sleepy", 1500), grumpy = new Sleeper("Grumpy", 1500);
Joiner dopey = new Joiner("Dopey", sleepy), doc = new Joiner("Doc",grumpy);
grumpy.interrupt();
} |
f7c40aeb-b3a5-4205-8c0e-deee3846c43e | 2 | public boolean dateConcorde(DateTime d){
if(dateDepart.minusHours(4).isBefore(d) && dateDepart.plusHours(4).isAfter(d))
return true;
return false;
} |
01640f23-8e78-4e90-a500-ea51fb6f0a01 | 9 | public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html;charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("<!DOCTYPE html>\n");
out.write("<html>\n");
out.write(" <head>\n");
out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
out.write(" <title>JSP Page</title>\n");
out.write(" </head>\n");
out.write(" <body>\n");
out.write(" \n");
out.write(" </body>\n");
out.write(" ");
String username = request.getParameter("username");
String password = request.getParameter("password");
out.println("Checking login<br>");
if (username == null || password == null) {
out.print("Invalid paramters ");
}
// Here you put the check on the username and password
if (username.toLowerCase().trim().equals("admin") && password.toLowerCase().trim().equals("admin")) {
out.println("Welcome " + username + " <a href=\"index.jsp\">Back to main</a>");
session.setAttribute("username", username);
}
else
{
out.println("Invalid username and password");
}
out.write("\n");
out.write("\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
} |
f145b3a1-54d8-4f7c-a13e-01edd0c4c60b | 9 | private int requestEngineMove() {
int move = Game.NULL_MOVE;
int ponder = Game.NULL_MOVE;
try {
if (client.isPondering()) {
client.send("stop");
while (client.isPondering())
client.receive();
}
client.send(getPositionCommand(game));
client.send(getGoCommand(movetime));
while (client.isThinking())
client.receive();
move = client.getBestMove();
ponder = client.getPonderMove();
int length = game.length();
try {
if (move != Game.NULL_MOVE)
performMove(game, move);
if (ponder != Game.NULL_MOVE)
performMove(game, ponder);
client.send(getPositionCommand(game));
client.send("go ponder");
} catch (Exception e) { }
while (length < game.length())
game.unmakeMove();
} catch (Exception e) {
writer.format("%s%n", e.getMessage());
}
if (move != Game.NULL_MOVE) {
writer.format(
"My move is: %s%n",
start.toAlgebraic(move)
);
}
return move;
} |
3544f696-8614-49b6-8b21-db303ea5b1a5 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ReproductorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ReproductorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ReproductorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ReproductorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ReproductorGUI().setVisible(true);
}
});
} |
8c8bc368-4127-4977-8abc-d3052a447195 | 1 | private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked
this.jPanel1.setVisible(false);
this.jPanel2.setVisible(false);
if (this.jPanel3.isVisible())
this.jPanel3.setVisible(false);
else
{
this.jPanel3.setVisible(true);
}
}//GEN-LAST:event_jButton3MouseClicked |
9b536ce9-27de-4042-94da-c7e41c03c071 | 3 | private void fxInitErrorHandler()
{
webEngine.getLoadWorker().exceptionProperty().addListener(
new ChangeListener<Throwable>() {
public void changed(
ObservableValue<? extends Throwable> o,
Throwable old,
final Throwable value
)
{
if( webEngine.getLoadWorker().getState() == FAILED )
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run()
{
String msg = webEngine.getLocation();
if( value != null )
{
msg += "\n" + value.getMessage();
} else {
msg += "\nUnexpected error.";
}
ApplicationLogger.logError(
"JFXWebView Loading Error.\n" + msg
);
JOptionPane.showMessageDialog(
JFXWebView.this,
msg,
"Lade Fehler ...",
JOptionPane.ERROR_MESSAGE
);
}
});
}
}
});
} |
39b28188-37f7-44fe-b9e3-d1eebbfed2bf | 3 | public static DataType getType(String type) {
if (type.equalsIgnoreCase("YAML")) {
return YAML_SHARED;
}
for (DataType dt : DataType.values()) {
if (dt.name().equalsIgnoreCase(type)) {
return dt;
}
}
return null;
} |
71c53beb-b446-460a-9f24-e422d79db5ee | 9 | public final WaiprParser.machine_return machine() throws RecognitionException {
WaiprParser.machine_return retval = new WaiprParser.machine_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token string_literal2=null;
Token ID3=null;
Token char_literal4=null;
Token char_literal6=null;
ParserRuleReturnScope block5 =null;
CommonTree string_literal2_tree=null;
CommonTree ID3_tree=null;
CommonTree char_literal4_tree=null;
CommonTree char_literal6_tree=null;
RewriteRuleTokenStream stream_22=new RewriteRuleTokenStream(adaptor,"token 22");
RewriteRuleTokenStream stream_25=new RewriteRuleTokenStream(adaptor,"token 25");
RewriteRuleTokenStream stream_26=new RewriteRuleTokenStream(adaptor,"token 26");
RewriteRuleTokenStream stream_ID=new RewriteRuleTokenStream(adaptor,"token ID");
RewriteRuleSubtreeStream stream_block=new RewriteRuleSubtreeStream(adaptor,"rule block");
try {
// Waipr.g:18:9: ( 'Machine' ID '{' ( block )* '}' -> ^( ID ( block )* ) )
// Waipr.g:18:11: 'Machine' ID '{' ( block )* '}'
{
string_literal2=(Token)match(input,22,FOLLOW_22_in_machine52);
stream_22.add(string_literal2);
ID3=(Token)match(input,ID,FOLLOW_ID_in_machine54);
stream_ID.add(ID3);
char_literal4=(Token)match(input,25,FOLLOW_25_in_machine56);
stream_25.add(char_literal4);
// Waipr.g:18:28: ( block )*
loop2:
while (true) {
int alt2=2;
int LA2_0 = input.LA(1);
if ( ((LA2_0 >= 19 && LA2_0 <= 21)||(LA2_0 >= 23 && LA2_0 <= 24)) ) {
alt2=1;
}
switch (alt2) {
case 1 :
// Waipr.g:18:28: block
{
pushFollow(FOLLOW_block_in_machine58);
block5=block();
state._fsp--;
stream_block.add(block5.getTree());
}
break;
default :
break loop2;
}
}
char_literal6=(Token)match(input,26,FOLLOW_26_in_machine61);
stream_26.add(char_literal6);
// AST REWRITE
// elements: ID, block
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null);
root_0 = (CommonTree)adaptor.nil();
// 18:39: -> ^( ID ( block )* )
{
// Waipr.g:18:42: ^( ID ( block )* )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(stream_ID.nextNode(), root_1);
// Waipr.g:18:47: ( block )*
while ( stream_block.hasNext() ) {
adaptor.addChild(root_1, stream_block.nextTree());
}
stream_block.reset();
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
} |
41050787-5ce9-48a6-b1da-e9994bca9eda | 5 | public void handleKeyPress(int value) {
System.out.println(this.name + ": Keyboard key " + value + " was pressed.");
switch(value) {
case MinuetoKeyboard.KEY_Q:
this.closing = true;
window.close();
break;
case MinuetoKeyboard.KEY_W:
window.setCursorVisible(true);
break;
case MinuetoKeyboard.KEY_E:
window.setCursorVisible(false);
break;
case MinuetoKeyboard.KEY_A:
window.registerMouseHandler(this, eventQueue);
break;
case MinuetoKeyboard.KEY_S:
window.unregisterKeyboardHandler(this, eventQueue);
break;
}
} |
5eeee084-8ab2-4961-9bd6-4eca093770cd | 4 | public Server() {
try {
serverSocket = new ServerSocket(11111);
} catch (IOException ioe) {
System.out
.println("Not create server socket. WTF?.");
System.exit(-1);
}
while (ServerOn) {
try {
Socket clientSocket = serverSocket.accept();
ClientThread cliThread = new ClientThread(
clientSocket, this);
cliThread.start();
} catch (IOException ioe) {
System.out
.println("Socket is fall :");
ioe.printStackTrace();
}
}
try {
serverSocket.close();
System.out.println("Server Stopped.");
} catch (Exception ioe) {
System.out.println("Problem stopping server.");
System.exit(-1);
}
} |
c853bd2f-b6bd-444a-ac25-2f42a4c2f676 | 5 | public void write( SelectionKey key ) throws IOException {
SocketChannel chan = (SocketChannel) key.channel();
TcpConnection tcp = getConnection(key);
ByteBuffer buf = null;
// find something to write
while( tcp.hasWrite() ){
buf = tcp.fetchWrite();
if( buf != null && buf.hasRemaining() ){
break;
}
}
if( buf != null ){
if( ! buf.isReadOnly() ){
logger.debug("Writing to {}. Data {}", chan.getRemoteAddress(), buf.array() );
}else{
logger.debug("Writing to {}", chan.getRemoteAddress() );
}
chan.write( buf );
}
} |
160a0682-f9e6-4265-aa21-510869fb5d1c | 6 | private int decodeBlackCodeWord() {
int current;
int entry;
int bits;
int isT;
int code = -1;
int runLength = 0;
boolean isWhite = false;
while (!isWhite) {
current = nextLesserThan8Bits(4);
entry = initBlack[current];
// Get the 3 fields from the entry
isT = entry & 0x0001;
bits = (entry >>> 1) & 0x000f;
code = (entry >>> 5) & 0x07ff;
if (code == 100) {
current = nextNBits(9);
entry = black[current];
// Get the 3 fields from the entry
isT = entry & 0x0001;
bits = (entry >>> 1) & 0x000f;
code = (entry >>> 5) & 0x07ff;
if (bits == 12) {
// Additional makeup codes
updatePointer(5);
current = nextLesserThan8Bits(4);
entry = additionalMakeup[current];
bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111
code = (entry >>> 4) & 0x0fff; // 12 bits
runLength += code;
updatePointer(4 - bits);
} else if (bits == 15) {
// EOL code
throw new RuntimeException(
"EOL code word encountered in Black run."); //$NON-NLS-1$
} else {
runLength += code;
updatePointer(9 - bits);
if (isT == 0) {
isWhite = true;
}
}
} else if (code == 200) {
// Is a Terminating code
current = nextLesserThan8Bits(2);
entry = twoBitBlack[current];
code = (entry >>> 5) & 0x07ff;
runLength += code;
bits = (entry >>> 1) & 0x0f;
updatePointer(2 - bits);
isWhite = true;
} else {
// Is a Terminating code
runLength += code;
updatePointer(4 - bits);
isWhite = true;
}
}
return runLength;
} |
d73da8d3-54ae-4e2c-bd0f-ac7ef5678ad8 | 7 | public void print(Byte[] jeu){
for (int i=0; i < 37; i++){
if (i==4 || i==9 || i==15 || i==22 || i==28 || i==33)
System.out.println();
System.out.print(jeu[i]);
}
System.out.println();
} |
16302016-a555-4bb1-9092-3f79ad4c0b4e | 6 | public void pathSumRec(TreeNode root, int sum, Stack<Integer> tmp) {
if(root == null) return;
if(root.left == null && root.right == null) {
if(root.val == sum){
res.add(new ArrayList(tmp));
}
}
if(root.left != null){
tmp.add(root.left.val);
pathSumRec(root.left, sum - root.val, tmp);
tmp.pop();
}
if(root.right != null){
tmp.add(root.right.val);
pathSumRec(root.right, sum - root.val, tmp);
tmp.pop();
}
} |
a27977fc-8e2e-4949-a9c1-c1521b6e192b | 6 | public int oppDir(int dir) {
switch (dir) {
case 0:
return 2;
case 1:
return 3;
case 2:
return 0;
case 3:
return 1;
case 4:
return 5;
case 5:
return 4;
default:
return -1;
}
} |
dcc8492a-478c-4565-b9ac-4d27fc94ddd0 | 8 | private final int appendPostings(final FormatPostingsTermsConsumer termsConsumer, SegmentMergeInfo[] smis, int n)
throws CorruptIndexException, IOException {
final FormatPostingsDocsConsumer docConsumer = termsConsumer.addTerm(smis[0].term.text);
int df = 0;
for (int i = 0; i < n; i++) {
SegmentMergeInfo smi = smis[i];
TermPositions postings = smi.getPositions();
assert postings != null;
int base = smi.base;
int[] docMap = smi.getDocMap();
postings.seek(smi.termEnum);
while (postings.next()) {
df++;
int doc = postings.doc();
if (docMap != null)
doc = docMap[doc]; // map around deletions
doc += base; // convert to merged space
final int freq = postings.freq();
final FormatPostingsPositionsConsumer posConsumer = docConsumer.addDoc(doc, freq);
if (!omitTermFreqAndPositions) {
for (int j = 0; j < freq; j++) {
final int position = postings.nextPosition();
final int payloadLength = postings.getPayloadLength();
if (payloadLength > 0) {
if (payloadBuffer == null || payloadBuffer.length < payloadLength)
payloadBuffer = new byte[payloadLength];
postings.getPayload(payloadBuffer, 0);
}
posConsumer.addPosition(position, payloadBuffer, 0, payloadLength);
}
posConsumer.finish();
}
}
}
docConsumer.finish();
return df;
} |
a4be2a17-5b81-4ce9-9d78-aa5b102b0be7 | 2 | public void mezclarTodosLosNodos(){
Nodo<E> cambiandoNodoA = cabeza;
Nodo<E> cambiandoNodoB;
for (int i = 0; i < talla; i++){
int posicionAzar = (int )(1+(Math.random() * (talla-1))); //numeros [1 , talla-1]
cambiandoNodoB = cabeza;
while( posicionAzar >= 1 ){
cambiandoNodoB = cambiandoNodoB.getSiguiente();
posicionAzar--;
}
this.intercambiarNodos(cambiandoNodoA, cambiandoNodoB);
cambiandoNodoA = cambiandoNodoA.getSiguiente();
}
} |
498105ae-adb8-442f-91ac-03612d6d6556 | 9 | @Override
public synchronized void run() {
String msg;
try {
while(!Thread.currentThread().isInterrupted()){
while(!messageQueue.isEmpty()){
try{
msg = messageQueue.removeFirst();
if(msg.contains(" JOIN ") || msg.contains((" PART "))){
messageDisplay.output(msg);
}
else if(msg.contains(":USERCOLOR")){
chatDisplay.setNextNickColor((msg.split(" "))[5]);
}
else if(msg.contains(":SPECIALUSER")){
}
else if(msg.contains(":EMOTESET")){
}
else{
chatDisplay.output(msg);
}
}catch(NoSuchElementException e){
chatDisplay.output("NOSUCHELEMTNEXCEPTION HAHA\n");
continue;
}
}
Thread.sleep(11);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
} |
a943543d-6aa4-4ede-8b0e-b05a2dde6e84 | 6 | public String stripLineBackup(String navigationLine) {
String arrow = " <-+-- ";
String vertical = " | ";
String corner = " +-- ";
String navigationLine2 = navigationLine;
if (navigationLine2.contains(corner))
navigationLine2 = navigationLine2.replaceAll(" \\+--", " ");
boolean hasVertical = navigationLine2.contains(vertical);
boolean hasArrow = navigationLine2.contains(arrow);
boolean hasCorner = navigationLine2.contains(corner);
if (hasVertical && !hasCorner && !hasArrow){
System.out.print(navigationLine2);
}
if (navigationLine2.contains(vertical)) {
int lastVertical = navigationLine2.lastIndexOf(vertical);
navigationLine2 = navigationLine2.substring(0, lastVertical) + corner;
navigationLine2 = navigationLine2.substring(0, lastVertical + 7); // laatste nl.sogyo.jesper.itemfusion.Item er af knippen
}
if (navigationLine.contains(arrow))
navigationLine2 = navigationLine2.replaceAll("<-\\+--", " \\| ");
navigationLine2 = navigationLine2.replaceAll("\\p{L}", " ");
navigationLine2 = navigationLine2.replaceAll("\\(\\)", " ");
System.out.println();
return navigationLine2;
} |
6de7fd07-4d7c-4aaa-99ad-c9f4ebe68615 | 2 | public void typeKeycode(int keyCode) {
if( keyMap.containsKey((char)keyCode) ){
ShiftIndex shi = keyMap.get((char)keyCode);
if(shi.shift){
keyType(shi.keyVal, KeyEvent.VK_SHIFT);
}else{
keyType(shi.keyVal);
}
} else {
keyType(keyCode);
}
} |
2da2d35f-8dca-4fe6-a2db-fbcf9072a525 | 0 | public static void start() {
Rooms.currentRoom = 1;
Rooms.ChangeRoom("", -1, true);
showRoomInfo(1);
} |
9fa46730-8cf9-4cd0-89e1-d5663f38c4de | 1 | public static void main(String[] args) {
Main mainContext = new Main();
try {
mainContext.loadFileActions();
mainContext.performFileActions();
mainContext.deobfuscateAndDecompile(args);
mainContext.downloadCache(args);
} catch(Exception exception) {
exception.printStackTrace();
}
Logger.getAnonymousLogger().info("Complete!");
} |
eb55fb65-3eff-46ee-afc2-7d4341881e15 | 1 | public DefaultItem( DefaultUmlDiagram diagram, ItemKey<T> key ) {
this.diagram = diagram;
contextCapability = new DefaultItemContextCapability( diagram, this );
setCapability( CapabilityName.CONTEXT_MENU, contextCapability );
if( key == null ) {
key = createKey( diagram );
}
this.key = key;
} |
23979970-5dd2-4dce-b771-31ecbde8358a | 4 | public void mouseClicked(int button, int x, int y, int clickCount){
if(this.playButton.contains(x, y)){
PlayerData.resetPlayer();
PlayerData.setLevel(this.currentLevel + 1);
this.sbg.enterState(TowerDefense.GAMEPLAYSTATE);
}
else if (this.prevButton.contains(x, y)){
if (this.currentLevel == 0)
this.currentLevel = this.levels.length - 1;
else
this.currentLevel--;
}
else if (this.nextButton.contains(x, y)){
this.currentLevel = (this.currentLevel+1)%this.levels.length;
}
} |
0db95869-95d9-4999-88b0-7ea6594ac3cf | 5 | private Point pickBestMove(Point pointA, Point pointB) {
Point best = pointA;
Item itemA = _worldMemory.get(pointA).getKey();
Item itemB = _worldMemory.get(pointB).getKey();
if (greenEnergy <= pinkEnergy) {
if (itemB != null) {
best = itemA.greenGain * itemA.quantity > itemB.greenGain * itemB.quantity /* && (_worldMemory.get(pointA).getValue() > _worldMemory.get(pointB).getValue() && itemB.greenGain * itemB.quantity > 0) */ ? pointA : pointB;
}
} else {
if (itemB != null) {
best = itemA.pinkGain * itemA.quantity > itemB.pinkGain * itemB.quantity /* && (_worldMemory.get(pointA).getValue() > _worldMemory.get(pointB).getValue() && itemB.pinkGain * itemB.quantity > 0) */ ? pointA : pointB;
}
}
return best;
} |
6ee9af56-12c9-4769-a172-53aa73f097b0 | 6 | public int findPivot(int array[], int start, int end) {
int mid = (start+end)/2;
if(mid<end && array[mid] > array[mid+1])
return mid;
else if(mid>start && array[mid] < array[mid-1])
return mid-1;
else if(array[mid] < array[start])
return findPivot(array, start, mid-1);
else if(array[mid] > array[end])
return findPivot(array, mid, end);
else return -1;
} |
fc493388-e908-47ca-a474-9b6b155fc72b | 7 | private void updateFromNonCachableResponse(HttpRequest currentRequest, HttpResponse currentResponse) {
//update from 304 NOT MODIFIED responses
CachedResponse cached = responseCache.get(currentRequest.getUri());
if (currentResponse.getStatus().code() == 304) {
long lastModified = determineLastModified(currentResponse);
if (lastModified > 0) {
if (cached != null) {
if (cached.getLastModified() < lastModified) {
if (logger.isDebugEnabled()) {
logger.debug("Removing " + currentRequest.getUri() + " - reason: expired Last-Modified");
}
removeFromCache(currentRequest, cached);
}
}
}
} else if (cached != null) {
if (logger.isDebugEnabled()) {
logger.debug("Removing " + currentRequest.getUri() + " - reason: non-cashable request received");
}
removeFromCache(currentRequest, cached);
}
} |
87db7851-82e8-43a6-b1ea-90b3108b4e18 | 8 | public static String inferDialectName(String url) {
return match(url, name -> {
switch (name) {
case "h2":
return "h2";
case "hsqldb":
return "hsqldb";
case "sqlite":
return "sqlite";
case "mysql":
return "mysql";
case "postgresql":
return "postgres";
case "sqlserver":
return "mssql";
case "oracle":
return "oracle";
case "db2":
return "db2";
default:
return null;
}
});
} |
d65c7f84-d3fa-4f97-8b24-6b931acde7ff | 8 | private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportButtonActionPerformed
int colCnt = loanScheduleTable.getColumnCount();
int rowCnt = loanScheduleTable.getRowCount();
File csvFile = null;
File renCsvFile = null;
String newFileName = "";
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
csvFile = fc.getSelectedFile();
newFileName = csvFile.getPath() + ".csv";
renCsvFile = new File(newFileName);
PrintWriter pw = new PrintWriter(renCsvFile);
for (int i = 0; i < colCnt; ++i) {
pw.print(loanScheduleTable.getColumnName(i));
if ((i + 1) == colCnt) {
pw.print("\n");
} else {
pw.print(",");
}
}
for (int row = 0; row < rowCnt; ++row) {
for (int col = 0; col < colCnt; ++col) {
String value = String.valueOf(loanScheduleTable.getValueAt(row, col));
if (value.equalsIgnoreCase("null")) {
pw.print("");
} else {
pw.print(value);
}
if ((col + 1) == colCnt) {
pw.print("\n");
} else {
pw.print(",");
}
}
}
pw.flush();
pw.close();
JOptionPane.showMessageDialog(rootPane, "Successfully Saved to " + newFileName, "Information",
JOptionPane.INFORMATION_MESSAGE);
} catch (IOException ex) {
printErrorMsg(ex, "unable to export file");
}
} else {
// nothing to do
}
}//GEN-LAST:event_exportButtonActionPerformed |
4ed21c37-5191-4bb1-95cd-3c60fc67cc9a | 7 | void pack(Object i, Buffer opb){
InfoFloor1 info=(InfoFloor1)i;
int count=0;
int rangebits;
int maxposit=info.postlist[1];
int maxclass=-1;
/* save out partitions */
opb.write(info.partitions, 5); /* only 0 to 31 legal */
for(int j=0; j<info.partitions; j++){
opb.write(info.partitionclass[j], 4); /* only 0 to 15 legal */
if(maxclass<info.partitionclass[j])
maxclass=info.partitionclass[j];
}
/* save out partition classes */
for(int j=0; j<maxclass+1; j++){
opb.write(info.class_dim[j]-1, 3); /* 1 to 8 */
opb.write(info.class_subs[j], 2); /* 0 to 3 */
if(info.class_subs[j]!=0){
opb.write(info.class_book[j], 8);
}
for(int k=0; k<(1<<info.class_subs[j]); k++){
opb.write(info.class_subbook[j][k]+1, 8);
}
}
/* save out the post list */
opb.write(info.mult-1, 2); /* only 1,2,3,4 legal now */
opb.write(Util.ilog2(maxposit), 4);
rangebits=Util.ilog2(maxposit);
for(int j=0, k=0; j<info.partitions; j++){
count+=info.class_dim[info.partitionclass[j]];
for(; k<count; k++){
opb.write(info.postlist[k+2], rangebits);
}
}
} |
666a1cd3-c92a-4e46-8660-6ab77ea1daaa | 3 | private static Method getMethod(Class<?> theClass, String methodName, Class<?>... params) {
try {
Method method = theClass.getDeclaredMethod(methodName, params);
method.setAccessible(true);
return method;
} catch (Exception exception) {
Log.error(exception);
return null;
}
} |
912bd8f5-bb53-4305-837c-d19548d61a4a | 9 | public AlarmPanel() {
setLayout(new FormLayout(new ColumnSpec[] {
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("left:max(221dlu;default)"),},
new RowSpec[] {
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
RowSpec.decode("4dlu:grow"),
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,}));
JPanel panelGust = new JPanel();
panelGust.setBorder(new TitledBorder(null, "GUST", TitledBorder.LEADING, TitledBorder.TOP, new Font("Tahoma", Font.BOLD, 11)));
add(panelGust, "2, 2, fill, fill");
panelGust.setLayout(new FormLayout(new ColumnSpec[] {
ColumnSpec.decode("max(72dlu;default)"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(13dlu;default)"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("left:max(13dlu;default)"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(76dlu;default)"),},
new RowSpec[] {
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,}));
float floor, ceiling, value;
JLabel lblCurrentWindSpeed = new JLabel("Current wind speed is higher by");
lblCurrentWindSpeed.setFont(new Font("Tahoma", Font.PLAIN, 11));
panelGust.add(lblCurrentWindSpeed, "1, 1");
try {
floor = Float.parseFloat(WindMill.propertyFile.getProperty("Gust.FLOOR", "1"));
ceiling = Float.parseFloat(WindMill.propertyFile.getProperty("Gust.CEILING", "12"));
value = Float.parseFloat(WindMill.propertyFile.getProperty("Gust.DIFFERENCE", "3.5"));
} catch (Exception e) {
floor = 1;
ceiling =12;
value=3.5f;
}
if (value < floor || value > ceiling) {
floor = 1;
ceiling =12;
value=3.5f;
}
spinnerGustSpeed = new JSpinner(new SpinnerNumberModel(
value, floor, ceiling, 0.5));
spinnerGustSpeed.setFont(new Font("Tahoma", Font.PLAIN, 11));
panelGust.add(spinnerGustSpeed, "3, 1, 3, 1");
JLabel lblMsec = new JLabel("m/sec from the lowest");
lblMsec.setFont(new Font("Tahoma", Font.PLAIN, 11));
panelGust.add(lblMsec, "7, 1, left, center");
JLabel lblMSec1 = new JLabel("wind speed observed in the last");
lblMSec1.setFont(new Font("Tahoma", Font.PLAIN, 11));
panelGust.add(lblMSec1, "1, 3, left, default");
spinnerGustTime = new JSpinner(new SpinnerNumberModel(
Integer.parseInt(WindMill.propertyFile.getProperty("Gust.TIMEWINDOW", "10")), 1, 20, 1));
spinnerGustTime.setFont(new Font("Tahoma", Font.PLAIN, 11));
panelGust.add(spinnerGustTime, "3, 3, 3, 1");
JLabel lblMinutes = new JLabel("minutes");
lblMinutes.setFont(new Font("Tahoma", Font.PLAIN, 11));
panelGust.add(lblMinutes, "7, 3");
JPanel panelHigh = new JPanel();
panelHigh.setBorder(new TitledBorder(null, "HIGH", TitledBorder.LEADING, TitledBorder.TOP, new Font("Tahoma", Font.BOLD, 11)));
add(panelHigh, "2, 4, fill, fill");
panelHigh.setLayout(new FormLayout(new ColumnSpec[] {
ColumnSpec.decode("max(72dlu;default)"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(14dlu;default)"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("left:max(13dlu;default)"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(76dlu;default)"),},
new RowSpec[] {
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,}));
JLabel lblCurrentWindSpeed2 = new JLabel("Average wind speed in the last");
lblCurrentWindSpeed2.setFont(new Font("Tahoma", Font.PLAIN, 11));
panelHigh.add(lblCurrentWindSpeed2, "1, 1");
spinnerHighTime = new JSpinner(new SpinnerNumberModel(
Integer.parseInt(WindMill.propertyFile.getProperty("High.TIMEWINDOW", "10")), 1, 20, 1));
spinnerHighTime.setFont(new Font("Tahoma", Font.PLAIN, 11));
panelHigh.add(spinnerHighTime, "3, 1, 3, 1");
JLabel lblMsec2 = new JLabel("minutes");
lblMsec2.setFont(new Font("Tahoma", Font.PLAIN, 11));
panelHigh.add(lblMsec2, "7, 1, left, center");
JLabel lblMSec3 = new JLabel("is higher than");
lblMSec3.setFont(new Font("Tahoma", Font.PLAIN, 11));
panelHigh.add(lblMSec3, "1, 3, right, default");
try {
floor = Float.parseFloat(WindMill.propertyFile.getProperty("High.FLOOR", "1"));
ceiling = Float.parseFloat(WindMill.propertyFile.getProperty("High.CEILING", "14.5"));
value = Float.parseFloat(WindMill.propertyFile.getProperty("High.AVG", "10.0"));
} catch (Exception e) {
floor = 1;
ceiling =14.5f;
value=10.0f;
}
if (value < floor || value > ceiling) {
floor = 1;
ceiling =14.5f;
value=10.0f;
}
spinnerHighSpeed = new JSpinner(new SpinnerNumberModel(
value, floor, ceiling, 0.5));
spinnerHighSpeed.setFont(new Font("Tahoma", Font.PLAIN, 11));
panelHigh.add(spinnerHighSpeed, "3, 3, 3, 1");
JLabel lblMinutes2 = new JLabel("m/sec");
lblMinutes2.setFont(new Font("Tahoma", Font.PLAIN, 11));
lblMinutes.setFont(new Font("Tahoma", Font.PLAIN, 11));
panelHigh.add(lblMinutes2, "7, 3");
JPanel panelHigher = new JPanel();
panelHigher.setBorder(new TitledBorder(null, "HIGHER", TitledBorder.LEADING, TitledBorder.TOP, new Font("Tahoma", Font.BOLD, 11)));
add(panelHigher, "2, 6, fill, fill");
panelHigher.setLayout(new FormLayout(new ColumnSpec[] {
ColumnSpec.decode("max(72dlu;default)"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(13dlu;default)"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("left:max(13dlu;default)"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(76dlu;default)"),},
new RowSpec[] {
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,}));
JLabel lblCurrentWindSpeed3 = new JLabel("Average wind speed in the last");
lblCurrentWindSpeed3.setFont(new Font("Tahoma", Font.PLAIN, 11));
panelHigher.add(lblCurrentWindSpeed3, "1, 1");
spinnerHigherTime = new JSpinner(new SpinnerNumberModel(
Integer.parseInt(WindMill.propertyFile.getProperty("Higher.TIMEWINDOW", "10")), 1, 20, 1));
spinnerHigherTime.setFont(new Font("Tahoma", Font.PLAIN, 11));
panelHigher.add(spinnerHigherTime, "3, 1, 3, 1");
JLabel lblMsec3 = new JLabel("minutes");
lblMsec3.setFont(new Font("Tahoma", Font.PLAIN, 11));
lblMsec3.setFont(new Font("Tahoma", Font.PLAIN, 11));
panelHigher.add(lblMsec3, "7, 1, left, top");
JLabel lblMSec4 = new JLabel("is higher than");
lblMSec4.setFont(new Font("Tahoma", Font.PLAIN, 11));
panelHigher.add(lblMSec4, "1, 3, right, default");
try {
floor = Float.parseFloat(WindMill.propertyFile.getProperty("Higher.FLOOR", "14.5"));
ceiling = Float.parseFloat(WindMill.propertyFile.getProperty("Higher.CEILING", "25"));
value = Float.parseFloat(WindMill.propertyFile.getProperty("Higher.AVG", "15"));
} catch (Exception e) {
floor = 14.5f;
ceiling =25;
value =15;
}
if (value < floor || value > ceiling) {
floor = 14.5f;
ceiling =25;
value =15;
}
spinnerHigherSpeed = new JSpinner(new SpinnerNumberModel(
value, floor, ceiling, 0.5));
spinnerHigherSpeed.setFont(new Font("Tahoma", Font.PLAIN, 11));
panelHigher.add(spinnerHigherSpeed, "3, 3, 3, 1");
JLabel lblMinutes3 = new JLabel("m/sec");
lblMinutes3.setFont(new Font("Tahoma", Font.PLAIN, 11));
panelHigher.add(lblMinutes3, "7, 3");
} |
9370da01-ac15-420d-b228-ee09a49c789e | 7 | public boolean[] getAction()
{
double[] inputs;// = new double[numberOfInputs];
// byte[][] scene = observation.getLevelSceneObservation(/*1*/);
// byte[][] enemies = observation.getEnemiesObservation(/*0*/);
inputs = new double[numberOfInputs];
int which = 0;
for (int i = -3; i < 4; i++) {
for (int j = -3; j < 4; j++) {
inputs[which++] = probe(i, j, levelScene);
}
}
for (int i = -3; i < 4; i++) {
for (int j = -3; j < 4; j++) {
inputs[which++] = probe(i, j, enemies);
}
}
inputs[inputs.length - 3] = isMarioOnGround ? 1 : 0;
inputs[inputs.length - 2] = isMarioAbleToJump ? 1 : 0;
inputs[inputs.length - 1] = 1;
double[] outputs = srn.propagate (inputs);
boolean[] action = new boolean[numberOfOutputs];
for (int i = 0; i < action.length; i++) {
action[i] = outputs[i] > 0;
}
return action;
} |
dc4bf95b-814f-4067-bd73-59428c27665e | 9 | private Filter.FilterAction buildExtractionTreeForFollow(ExtractedNode node, Cmd cmd)
throws Exception
{
if (cmd.getType() != Cmd.CmdType.FOLLOW) {
throw new Exception("Expected FOLLOW command");
}
CmdArg link = cmd.getArg("FOLLOW");
CmdArg with = cmd.getArg("WITH");
CmdArg populate = cmd.getArg("POPULATE");
CmdArg filterCmdArg = cmd.getArg("FILTER");
CmdArg filterArgs = cmd.getArg("FILTER_ARGS");
EvalContext evalContext = new EvalContext();
populateEvalContext(evalContext, node);
FileDownload fd = FileDownload.getInst();
String nextURL = fd.createValidURL(thisURL, link.evaluate(evalContext));
Filter.FilterAction ok = Filter.FilterAction.VISIT;
Filter filter = null;
nextURL = fd.normalizeURL(nextURL);
// apply filter
if (filterCmdArg != null) {
FilterLoader filterLoader = FilterLoader.getFilterLoader();
filter = filterLoader.loadFilter(filterCmdArg.toString());
filter.init(filterArgs.toString());
ok = filter.doVisit(nextURL, depth, childNum);
}
if (ok != Filter.FilterAction.VISIT) return ok;
String file = null;
try {
file = fd.getDownloadedFile(nextURL);
String fwdUrl = getMetaRefreshNextUrl(nextURL, file);
if (fwdUrl != null) {
nextURL = fwdUrl;
file = fd.getDownloadedFile(nextURL);
}
} catch (Exception ex) {
// do nothing. just make sure we continue
// with remaining links
return Filter.FilterAction.DONT_VISIT;
}
childNum++;
if (filter != null) {
filter.visit(file);
}
String newRuleFile = with.evaluate(evalContext);
File rf = new File(newRuleFile);
if (!rf.isFile()) {
// file not present. try out file in parent rules file's dir
File pf = new File(currRuleFile);
String dir = pf.getParent();
if (dir == null) {
throw new Exception("Can't find rule file " + newRuleFile);
}
rf = new File(dir, newRuleFile);
if (!rf.isFile()) {
throw new Exception("Can't find rule file " + newRuleFile);
}
newRuleFile = rf.getPath();
}
RuleTreeExtractor rex = new RuleTreeExtractor(newRuleFile,
depth + 1);
ExtractedNode child = rex.collect(nextURL, file);
// now merge the new tree in the correct scope
populateCorrectScope(child, populate);
return ok;
} |
1c366ebc-f810-4f3d-9367-1824228048c0 | 4 | public void mouseMoved(MouseEvent e) {
if (isInside(e.getX(), e.getY()) && !highlighted) {
highlight();
}
if (!isInside(e.getX(), e.getY()) && highlighted) {
deHighlight();
}
} |
bbc80fe7-00a0-4e10-ab0d-e0c0cd782b3f | 8 | public void keyReleased(int k) {
if(k == KeyEvent.VK_A) player.setLeft(false);
if(k == KeyEvent.VK_D) player.setRight(false);
if(k == KeyEvent.VK_UP) player.setUp(false);
if(k == KeyEvent.VK_DOWN) player.setDown(false);
if(k == KeyEvent.VK_SPACE) player.setJumping(false);
if(k == KeyEvent.VK_W) player.setGliding(false);
if(k == KeyEvent.VK_E) player.setScratching();
if(k == KeyEvent.VK_R) player.setFiring();
} |
86751774-380d-4ef5-b4a8-fe74041d1956 | 4 | public void saveWorldInfo(WorldInfo var1) {
NBTTagCompound var2 = var1.getNBTTagCompound();
NBTTagCompound var3 = new NBTTagCompound();
var3.setTag("Data", var2);
try {
File var4 = new File(this.saveDirectory, "level.dat_new");
File var5 = new File(this.saveDirectory, "level.dat_old");
File var6 = new File(this.saveDirectory, "level.dat");
CompressedStreamTools.writeGzippedCompoundToOutputStream(var3, new FileOutputStream(var4));
if(var5.exists()) {
var5.delete();
}
var6.renameTo(var5);
if(var6.exists()) {
var6.delete();
}
var4.renameTo(var6);
if(var4.exists()) {
var4.delete();
}
} catch (Exception var7) {
var7.printStackTrace();
}
} |
7964fdbb-2de1-438a-9dbd-7693432f0741 | 3 | public void setValue(String s) {
for (int i = 0; i < values.length; i++) {
if (values[i].equals(s) && values[i] != null) {
value = i;
break;
}
}
} |
55192a7f-56f3-4650-b7b1-f85daec90676 | 2 | double t(int N1[], int N2[], double weight[]) {
int R1 = 0, R2 = 0;
int k = N1.length;
for (int i = 0; i < k; i++) {
R1 += N1[i];
R2 += N2[i];
}
double t = 0;
for (int i = 0; i < N1.length; i++)
t += weight[i] * ((N1[i] * R2) - (N2[i] * R1));
return t;
} |
ea483c62-17ee-46fa-849a-e5a2b0f459d2 | 7 | public void initconfig() {
BufferedReader bin;
boolean foundcmd;
String[] str;
String cfile;
cfile = fileName;
mytotmsg = 0;
// determine self process id
mypid = Integer.parseInt(cfile.substring("Server".length(),cfile.indexOf(".")));
try {
bin = new BufferedReader(new FileReader(cfile));
rline = bin.readLine();
str = rline.split(" ");
numservers = Integer.parseInt(str[0]);
numBooks = Integer.parseInt(str[1]);
sa = new sAddress[numservers+1];
lm = new lamportMutex();
// get list of server addresses
for (int i=1; i<=numservers; i++) {
rline = bin.readLine();
str = rline.split(":");
sa[i] = new sAddress (str[0], str[1]);
}
// read rest of the file & command for this server
rline = bin.readLine();
foundcmd = false;
while ((rline != null) && !foundcmd) {
str = rline.split(" ");
if (str[0].equals("s"+Integer.toString(mypid)) &&
(str.length >= 2)) {
foundcmd = true;
mykmsg = Integer.parseInt(str[1]);
myunrespt = Integer.parseInt(str[2]);
}
rline = bin.readLine();
}
if (!foundcmd) { // no command for this server
mykmsg = 0;
myunrespt = 0;
}
} catch (java.io.IOException e) {
System.out.println(e);
}
} |
c837c181-1a7e-4205-bc1c-46fd38b7177e | 7 | public static void parseJSONResponse(HttpsURLConnection conn, String json_response){
try {
if (conn.getResponseCode() == 200 && json_response.contains("transaction")) //http status 200
{
Gson gson = new Gson();
TransactionResponse transaction_response = gson.fromJson(json_response, TransactionResponse.class);
if (transaction_response.result_code != null && transaction_response.result_code.equals("0000"))
{
System.out.println("-----------------------------------------------------");
System.out.println("TRANSACTION APPROVED: " + transaction_response.authorization_code);
}
else
{
String code = "";
if (transaction_response.error_code != null)
code = transaction_response.error_code;
if (transaction_response.result_code != null)
code = transaction_response.result_code;
System.out.println("-----------------------------------------------------");
System.out.println("TRANSACTION ERROR: Code=" + code + " Message=" + transaction_response.display_message);
}
}
else{
System.out.println("-----------------------------------------------------");
System.out.println("INVALID RESPONSE");
}
} catch (IOException e) {
System.out.println("-----------------------------------------------------");
System.out.println("EXCEPTION: " + e.getMessage());
}
} |
e9866236-7e5c-4c1a-8ddc-57afc83041c1 | 4 | public static <A, B, C, D, E> Equal<P5<A, B, C, D, E>> p5Equal(final Equal<A> ea, final Equal<B> eb,
final Equal<C> ec, final Equal<D> ed,
final Equal<E> ee) {
return equal(p1 -> p2 -> ea.eq(p1._1(), p2._1()) && eb.eq(p1._2(), p2._2()) && ec.eq(p1._3(), p2._3()) &&
ed.eq(p1._4(), p2._4()) && ee.eq(p1._5(), p2._5()));
} |
9cc55128-5988-4ed8-9fe9-0920d11f1050 | 4 | public ExtDecimal log10(int scale) {
// Not yet customized
if (compareTo(ZERO) < 0) {
throw new ArithmeticException("Logarithm of a negative number in a real context");
} else if (compareTo(ZERO) == 0) {
throw new ArithmeticException("Logarithm of 0");
} else if (compareTo(ONE) == 0) {
return ZERO;
} else if (compareTo(E) == 0) {
return ONE;
} else {
// Verfahren noch unbekannt
// Arithmetisch-geometrisches Mittel angestrebt.
throw new UnsupportedOperationException("Not yet implemented");
}
} |
efbd55a8-4851-4c8f-9f7d-ec74118e3852 | 3 | public boolean jsFunction_waitStartMove(int timeout) {
deprecated();
int curr = 0; if(timeout == 0) timeout = 10000;
while(!JSBotUtils.isMoving())
{
if(curr > timeout)
return false;
Sleep(25);
curr += 25;
}
return true;
} |
57f40f53-cbee-468c-a0f6-d458d9cb9e43 | 0 | @Override
public void restoreTemporaryToCurrent() {
copyHashMap(cur,tmp);
} |
22bdf803-a8ec-4cad-bb9d-fbf6407b1b37 | 1 | @Override
public boolean equals(Object ob) {
if (ob.hashCode() == this.hashCode()) {
return true;
}
return false;
} |
a64206fc-fd8b-48fa-9d23-cd3ffdf14145 | 0 | public boolean isMaximized() {
return maximized;
} |
b7b57807-a506-4893-a8c8-d7793ef78671 | 8 | public SQLite(Logger log, String prefix, String directory, String filename) {
super(log,prefix,"[SQLite] ");
if (directory == null || directory.length() == 0)
throw new DatabaseException("Directory cannot be null or empty.");
if (filename == null || filename.length() == 0)
throw new DatabaseException("Filename cannot be null or empty.");
if (filename.contains("/") || filename.contains("\\") || filename.endsWith(".db"))
throw new DatabaseException("The database filename cannot contain: /, \\, or .db.");
File folder = new File(directory);
if (!folder.exists())
folder.mkdir();
db = new File(folder.getAbsolutePath() + File.separator + filename + ".db");
this.driver = DBMS.SQLite;
} |
4749b20e-d926-43de-92ee-e9166811a135 | 5 | @Override
public void run() {
try {
while (running) {
Message m = messages.take();
String message = m.getMessage();
int command = Protocol.CheckMessage.registrerProtocolType(message);
switch (command) {
case 1:
connect(m);
break;
case 2:
send(m);
break;
case 3:
close(m);
break;
default:
Logger.getLogger(ClientHandler.class.getName()).log(Level.INFO, ("invalid message: " + message));
}
}
} catch (InterruptedException ex) {
Logger.getLogger(ClientHandler.class.getName()).log(Level.INFO, ex.toString());
}
} |
075adb2f-e37c-4143-968c-fde414c245b1 | 8 | private int detectPacket0(byte[] buffer, int i) {
// if (buffer.length <= i)
// return PACKET_MAYBE;
// if (buffer[i] != (byte)0xAA)
// return PACKET_NO;
if (buffer.length <= i+1)
return PACKET_MAYBE;
if (buffer[i+1] != (byte)0xAA)
return PACKET_NO;
if (buffer.length <= i+2)
return PACKET_MAYBE;
int pLength = 0xFF & (int)buffer[i+2];
if (pLength > 169) {
badPacketCount++;
return PACKET_NO;
}
if (buffer.length < i+4+pLength)
return PACKET_MAYBE;
byte sum = 0;
for (int j=0; j<pLength; j++)
sum += buffer[i+3+j];
if ((sum ^ buffer[i+3+pLength]) != (byte)0xFF) {
badPacketCount++;
if (mode < MODE_RAW)
gui.log("CSUMERROR "+sum+" vs "+buffer[i+3+pLength]);
return PACKET_NO;
}
return 4+pLength;
} |
732e29af-66b9-4601-ba71-afa5eed89c5c | 0 | public static void main(String[] args) {
new Ship();
new Ship("Varangian");
} |
680d054e-5dc5-44f5-b252-0bf8b252810a | 7 | private void VerEntradaSeleccionadaConsultaControloResultados() {
int linha = jTableConsultaEntradas.getSelectedRow();
int contaLinhas = 0;
String nomeTabela = "ENTRADA";
if (linha == -1) {
JOptionPane.showMessageDialog(jDialogConsultaEntradas, "Seleccione a Linha de uma Entrada!");
} else {
//DEVOLVE O NOME DO EQUIPAMENTO
String nomeFuncionario = (String) jTableConsultaEntradas.getValueAt(linha, 1);
int idFuncionario = selectId("FUNCIONARIO", "NOME", nomeFuncionario, "IDFUNCIONARIO");
String nomeFornecedor = (String) jTableConsultaEntradas.getValueAt(linha, 2);
idFornecedorDevolucao = selectId("FORNECEDOR", "NOME", nomeFornecedor, "IDFORNECEDOR");
String matPrima = (String) jTableConsultaEntradas.getValueAt(linha, 3);
idMateriaPrimaDevolucao = selectId("MATERIA_PRIMA", "NOME", matPrima, "IDMATERIAPRIMA");
String dataEntrega = (String) jTableConsultaEntradas.getValueAt(linha, 4);
String lote = (String) jTableConsultaEntradas.getValueAt(linha, 5);
String peso = (String) jTableConsultaEntradas.getValueAt(linha, 6);
String devolucao = (String) jTableConsultaEntradas.getValueAt(linha, 7);
//DEVOLVER O ID DA ENTRADA COMPARANDO TODOS OS CAMPOS
if (devolucao.equals("Sim")) {
devolucao = "S";
} else if (devolucao.equals("Não")) {
devolucao = "N";
}
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch (ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
System.out.println("O driver expecificado nao foi encontrado.");
}
try {
con = DriverManager.getConnection(url);
String sql = "SELECT * FROM " + nomeTabela + " WHERE DEVOLUCAO='" + devolucao + "' and IDFORNECEDOR=" + idFornecedorDevolucao + " and IDFUNCIONARIO=" + idFuncionario + " and IDMATERIAPRIMA=" + idMateriaPrimaDevolucao + " and LOTEORIGEM='" + lote + "'";
PreparedStatement st = (PreparedStatement) con.prepareStatement(sql);
ResultSet rs = st.executeQuery();
while (rs.next()) {
idEntradaSeleccionada = rs.getInt("IDENTRADA");
quantidadeEntradaTotalSelecionada = rs.getFloat("QUANTIDADETOTALDISPONIVEL");
contaLinhas++;
}
st.close();
con.close();
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
if(contaLinhas == 0){
//MOSTRAR MENSAGEM DE ERRO A DIZER KE N TEM
JOptionPane.showMessageDialog(jDialogConsultaEntradas, "NAO EXISTEM NÃO CONFORMIDADES ASSOCIADAS", "NÃO EXISTE", JOptionPane.WARNING_MESSAGE);
}else{
LimpaTabelaControloResultados();
ConsultaControloResultadosEntradas();
jDialogConsultarControlos.setLocationRelativeTo(this);
jDialogConsultarControlos.setVisible(true);
}
System.out.println("\n\nSELECT * FROM " + nomeTabela + " WHERE QUANTIDADE=" + devolucao + " and IDFORNECEDOR=" + idFornecedorDevolucao + " and IDFUNCIONARIO=" + idFuncionario + " and IDMATERIAPRIMA=" + idMateriaPrimaDevolucao + " and LOTEORIGEM='" + lote + "'");
System.out.println("\n\nNOME FUNCIO: " + nomeFuncionario);
System.out.println("ID FUNCIO: " + idFuncionario);
System.out.println("NOME FORNECEDOR: " + nomeFornecedor);
System.out.println("ID FORNECEDOR: " + idFornecedorDevolucao);
System.out.println("NOME MATERIA PRIM: " + matPrima);
System.out.println("ID MATERIA PRIMA: " + idMateriaPrimaDevolucao);
System.out.println("DATA ENTREGA: " + dataEntrega);
System.out.println("LOTE: " + lote);
System.out.println("QUANTIDADE: " + peso);
System.out.println("ID ENTRADA SELECIONADO : " + idEntradaSeleccionada);
System.out.println("QUANTIDADE ENTRADA : " + quantidadeEntradaTotalSelecionada);
}
} |
01a30665-ebea-4f7d-8a4a-c85b96b8f78d | 2 | public int size() {
if(packetList != null) {
return packetList.size();
} else {
if(singlePacket != null) {
return 1;
} else {
return 0;
}
}
} |
e7a26851-d347-4069-9e09-452edbcf5b88 | 2 | private void find(Map<String,PriorityQueue<String>> tickets, String cur,List<String> result){
while (tickets.containsKey(cur) && !tickets.get(cur).isEmpty()) {
find(tickets, tickets.get(cur).poll(), result);
}
result.add(0,cur);
return;
} |
9cc3f71c-1628-40a2-8d86-93c8527790d5 | 8 | public void setVolume(float volume) {
if (Debug.video) System.out.println("VideoPlayer -> setVolume called with " + volume);
if ((null != player) && (realizeComplete)) {
// Verify the input
if (80 < volume){
if (Debug.video) System.out.println("VideoPlayer -> setVolume -> vol over limit");
volume = 80;
}
if (0 > volume){
if (Debug.video) System.out.println("VideoPlayer -> setVolume -> vol under limit");
volume = 0;
}
// setLevel takes a float value between 0 and 1
gainControl.setLevel(volume/100);
if (Debug.video) System.out.println("VideoPlayer -> setVolume -> volume set by setVolume");
}
} |
a663fe54-ec74-4f58-9adc-52919bb4ba04 | 7 | private static void qsort(MilkFarmer[] milkFarmers, int start, int end) {
if (start >= end) return;
int l = start;
int r = end;
int pivot = milkFarmers[(l + r) / 2].p;
while (l <= r) {
while (milkFarmers[l].p < pivot) l++;
while (milkFarmers[r].p > pivot) r--;
if (l <= r) {
MilkFarmer tmp = milkFarmers[l];
milkFarmers[l] = milkFarmers[r];
milkFarmers[r] = tmp;
l++; r--;
}
}
if (l < end) qsort(milkFarmers, l, end);
if (r > start) qsort(milkFarmers, start, r);
} |
98efefe1-7ad1-4133-8698-0626494f46a4 | 8 | @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Department d = (Department) obj;
if (hashCode() != d.hashCode()) {
return false;
}
if (((Department) obj).getDepartmentName().equals(departmentName) && ((Department) obj).getChief().equals(chief)) {
return true;
}
if (this.getDepartmentName().equals("") && (this.getChief().equals(new Employe()))){
return false;
}
return true;
} |
c0fa4f61-f7e2-4e0d-9959-7410e78ccd12 | 4 | public void kill()
{
try {
this.playerAcceptor.interrupt();
worldHandle.interrupt();
expander.interrupt();
SocialSecurity.close();
try
{
if (!playerList.isEmpty())
{
for (PlayerOnline p:playerList)
p.killMe();
}
}
catch (Exception e)
{
}
gameRunning = false;
playerList.clear();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
} |
69f430f1-ac88-4990-9b05-9b083e6398d6 | 6 | public final List<MonsterDropEntry> retrieveDrop(final int monsterId) {
if (drops.containsKey(monsterId)) {
return drops.get(monsterId);
}
final List<MonsterDropEntry> ret = new LinkedList<MonsterDropEntry>();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = DatabaseConnection.getConnection().prepareStatement("SELECT * FROM drop_data WHERE dropperid = ?");
ps.setInt(1, monsterId);
rs = ps.executeQuery();
while (rs.next()) {
ret.add(
new MonsterDropEntry(
rs.getInt("itemid"),
rs.getInt("chance"),
rs.getInt("minimum_quantity"),
rs.getInt("maximum_quantity"),
rs.getShort("questid")));
}
} catch (SQLException e) {
return ret;
} finally {
try {
if (ps != null) {
ps.close();
}
if (rs != null) {
rs.close();
}
} catch (SQLException ignore) {
return ret;
}
}
drops.put(monsterId, ret);
return ret;
} |
9b097800-6a5a-44cc-94e8-8621cef77f7a | 1 | public String getText(String key) {
String retVal = (String) textResources.get(key);
if (retVal == null) {
System.out.println("Invalid text resource key: " + key);
}
return retVal;
} |
a526e3ed-1189-4bb9-ac81-f0b562927dff | 1 | @Override
public void setVisible(boolean state) {
if (state) {
}
super.setVisible(state);
} |
e08bb136-c1d7-463b-8fed-d467e4ff795b | 7 | public void mouseClicked(MouseEvent me) {
int x, y;
Rectangle r = new Rectangle(0, 0, (int) (m_nPaddedNodeWidth * m_fScale), (int) (m_nNodeHeight * m_fScale));
x = me.getX();
y = me.getY();
for (int iNode = 0; iNode < m_BayesNet.getNrOfNodes(); iNode++) {
r.x = (int) (m_BayesNet.getPositionX(iNode) * m_fScale);
r.y = (int) (m_BayesNet.getPositionY(iNode) * m_fScale);
if (r.contains(x, y)) {
m_nCurrentNode = iNode;
if (me.getButton() == MouseEvent.BUTTON3) {
handleRightNodeClick(me);
}
if (me.getButton() == MouseEvent.BUTTON1) {
if ((me.getModifiersEx() & MouseEvent.CTRL_DOWN_MASK) != 0) {
m_Selection.toggleSelection(m_nCurrentNode);
} else if ((me.getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0) {
m_Selection.addToSelection(m_nCurrentNode);
} else {
m_Selection.clear();
m_Selection.addToSelection(m_nCurrentNode);
}
repaint();
}
return;
}
}
if (me.getButton() == MouseEvent.BUTTON3) {
handleRightClick(me, (int)(x/m_fScale), (int)(y/m_fScale));
}
} |
3b643278-6963-4367-a08b-840a240754fb | 9 | public String simplifyPath(String path) {
if (path == null || path.length() < 2) {
return "/";
}
Stack<String> s = new Stack<String>();
for(String p: path.split("/")) {
if (p.length() == 0 || p.equals(".")) {
continue;
} else if (p.equals("..")) {
if (!s.empty()) {
s.pop();
}
} else {
s.push(p);
}
}
if (s.empty()) {
return "/";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.size(); i ++) {
sb.append("/").append(s.get(i));
}
return sb.toString();
} |
dd9379a7-5de9-4c5f-bd37-e524ffeccaa8 | 3 | public void processGridletReturn(Sim_event ev)
{
Object obj = (Object) ev.get_data();
Gridlet gl = null;
int glID;
if (obj instanceof Gridlet)
{
gl = (Gridlet) obj;
glID = gl.getGridletID();
System.out.println("<<< " + super.get_name() +
": Receiving Gridlet #" + glID + " with status " +
gl.getGridletStatusString() + " at time = " + GridSim.clock() +
" from " + GridSim.getEntityName(gl.getResourceID()) );
// Write into a file
write(super.get_name(), "Receiving", glID,
GridSim.getEntityName(gl.getResourceID()),
gl.getGridletStatusString(), GridSim.clock());
receivedGridletCounter++;
// find out the total execution time, from the submission time
gridletLatencyTime[glID] = GridSim.clock() -
gridletSubmissionTime[glID];
// get the latest status of a gridlet
gridletStatus[glID] = gl.getGridletStatusString();
// remove the gridlet
removeGridletFromGridletSubmittedList(glID);
gl = null;
// We have received all the gridlets. So, finish the simulation.
if ((receivedGridletCounter == NUM_GRIDLETS) ||
(receivedGridletCounter + droppedGridletsCounter == NUM_GRIDLETS))
{
super.finishSimulation();
//System.out.println("**** " + super.get_name() + ": FINISHED!!");
}
System.out.println("<<< " + super.get_name() +
": Finished processing the return of Gridlet # " +
glID + "\nReceived: " + receivedGridletCounter +
". Dropped: " + droppedGridletsCounter +
". NUM_GRIDLETS: " + NUM_GRIDLETS);
} // if (obj instanceof Gridlet)
} |
0a916f64-1e3b-4d2b-90ed-fc0ca190efc5 | 6 | public void removeSpace(char[] arr, int length){
if(arr==null)
return;
int spaceCount=0;
for(int i=0; i<arr.length ;i++){
if(arr[i]==' '){
spaceCount++;
}
}
char newarr[]=new char[arr.length+(spaceCount*2)];
for(int i=arr.length-1; i>=0;i-- ){
int k=i+spaceCount*2;
if(arr[i]==' '){
newarr[k]='0';
newarr[k-1]='2';
newarr[k-2]='%';
spaceCount--;
}else{
newarr[k]=arr[i];
}
}
for(int i=0; i<newarr.length ;i++){
System.out.println(newarr[i]+" ");
}
} |
2b402f0e-c23c-4bb0-a1f7-55ac896228d3 | 5 | final void method2670(int i) {
anInt4222++;
if (archiveLoaders != null) {
for (int i_0_ = 0; ((archiveLoaders.length ^ 0xffffffff) < (i_0_ ^ 0xffffffff)); i_0_++) {
if (archiveLoaders[i_0_] != null)
archiveLoaders[i_0_].method2342(0);
}
for (int i_1_ = i; i_1_ < archiveLoaders.length; i_1_++) {
if (archiveLoaders[i_1_] != null)
archiveLoaders[i_1_].method2343(-1);
}
}
} |
eadd1b8c-56a4-4cc0-be6e-92d03279182b | 7 | @Override
public String toString() {
StringBuilder string = new StringBuilder();
if (this.operator.getNumOperands() > 1) {
string.append(this.operands.get(0)).append(" ");
}
string.append(this.operator).append(" ");
String prefix = "";
for (int curOperand = this.operator.getNumOperands() > 1 ? 1 : 0; curOperand < this.operator.getNumOperands(); curOperand++) {
string.append(prefix);
Operand operand = this.operands.get(curOperand);
if (operand instanceof QueryRelation && ((QueryRelation)operand).getAlias() == null) {
string.append("(");
}
string.append(operand.toString());
if (operand instanceof QueryRelation && ((QueryRelation)operand).getAlias() == null) {
string.append(")");
}
prefix = " AND ";
}
return string.toString();
} |
867e03e2-3daf-4eb0-bef7-b7ba10527265 | 6 | public int alloc(int size) {
int i, prev_i = 0;
for (i = this.head.s_free.next; i != 0; i = this.nf[i].free.next) {
if (this.nf[i].free.size >= size)
break;
prev_i = i;
}
// there is no free node
if (i == 0) {
System.err.format("alloc:NO FREE NODE\n");
return 0;
}
if (prev_i == 0) { // the head node
if (size == this.nf[i].free.size)
this.head.s_free.next = this.nf[i].free.next;
else {
this.nf[i + size].free.size = this.nf[i].free.size - size;
this.head.s_free.next = i + size;
this.nf[i + size].free.next = this.nf[i].free.next;
}
}
else { // not the head node
if (size == this.nf[i].free.size)
this.nf[prev_i].free.next = this.nf[i].free.next;
else {
this.nf[i + size].free.size = this.nf[i].free.size - size;
this.nf[prev_i].free.next = i + size;
this.nf[i + size].free.next = this.nf[i].free.next;
}
}
this.head.f_size -= size;
return i;
} |
c457e547-3432-40e8-9c16-b707418cc1ce | 4 | private String binaryCode(int cellAdress, int nbrVar) {
byte bt[] = new byte[nbrVar];
String binaryAdress = "";
for (int i = 0; i < nbrVar; i++)
bt[i] = 0;
if (cellAdress != 0) {
while (cellAdress != 0) {
bt[nbrVar - 1] = (byte) (cellAdress % 2);
cellAdress = cellAdress / 2;
nbrVar--;
}
}
for (int i = 0; i < bt.length; i++)
binaryAdress = binaryAdress + bt[i];
return binaryAdress;
} |
9fbee1ac-a992-4e4e-bf8a-e3a964026a46 | 2 | private void writeShipUnlocks(OutputStream out, boolean[] unlocks) throws IOException {
for (int i = 0; i < unlocks.length; i++) {
writeInt(out, unlocks[i] ? 1 : 0);
}
} |
bc2328c7-a35e-4b0e-814d-a15be7010a2e | 5 | public static String long2TimeString(final long time) {
long ms = time % 1000;
long sec = (time / 1000);
long min = (sec / 60);
sec = sec % 60;
long hr = min / 60;
min = min % 60;
StringBuilder sbTime = new StringBuilder();
if (hr > 0) sbTime.append(hr).append(" hr ");
if (min == 0) {
if (sbTime.length() > 0) sbTime.append("0 min ");
} else {
sbTime.append(min).append(" min ");
}
DecimalFormat nf = null;
if (sec == 0 && sbTime.length() == 0) {
nf = new DecimalFormat("##0 ms");
sbTime.append(nf.format(ms));
} else {
nf = new DecimalFormat("0.000 sec");
sbTime.append(nf.format(sec + 1.0 * ms / 1000));
}
return sbTime.toString();
} |
fc5a6dcc-535c-476f-b244-26da30f668e2 | 5 | @Override
public boolean equals(Object obj){
if (obj == null) return false;
if (!(obj instanceof Point)) return false;
Point point = (Point)obj;
if (!(getX() == point.getX())) return false;
if (!(getY() == point.getY())) return false;
if (!(getZ() == point.getZ())) return false;
return true;
} |
39538ca3-dead-40be-a9a2-4766ab9ee985 | 0 | @Override
public String getRealName() {
return name();
} |
0d87f1cd-8277-4335-9856-e553bf9939fb | 1 | public void testSet_DateTimeFieldType_int2() {
MutableDateTime test = new MutableDateTime(TEST_TIME1);
try {
test.set(null, 0);
fail();
} catch (IllegalArgumentException ex) {}
assertEquals(TEST_TIME1, test.getMillis());
} |
6ac88b7e-a55b-4e05-85cf-2d0c823ca205 | 5 | public static void main(String[] args)
{
VideoPlayer player = new VideoPlayer();
ServerSocket server = null;
int port = getPort(args);
try
{
server = new ServerSocket(port);
}
catch(SecurityException e)
{
System.out.println("It appears you cannot use the port: "+port);
System.out.println("Please rerun the application with a new port as the argument.");
System.out.println("Example: -d <port>");
System.exit(1);
}
catch(IOException e)
{
System.out.println("Error connecting to the port "+port+", maybe something else is using it?");
System.exit(1);
}
catch(IllegalArgumentException e)
{
System.out.println("Out of port range! The range is between 0 and 65535");
System.exit(1);
}
while(true)
{
try
{
Thread connection = new Thread(new ClientConnection(server.accept(), player));
connection.start();
}
catch(IOException e)
{
System.out.println("Error with connection");
}
}
} |
e4d4e5b2-2107-47eb-a2ee-8e5f706f2d87 | 7 | @SideOnly(Side.CLIENT)
public Icon getIcon(int par1, int par2)
{
int i = par2 & 7;
if (i == 0){ return Block.cobblestone.getBlockTextureFromSide(1);}
else if (i == 1){ return Block.stoneSingleSlab.getBlockTextureFromSide(par1);}
else if (i == 2){ return Block.stoneBrick.getBlockTextureFromSide(1);}
else if (i == 3){ return Block.sandStone.getBlockTextureFromSide(1);}
else if (i == 4){ return Block.brick.getBlockTextureFromSide(1);}
else if (i == 5){ return Block.netherBrick.getBlockTextureFromSide(1);}
else if (i == 6){ return Block.blockNetherQuartz.getBlockTextureFromSide(1);}
else {return Block.blockIron.getBlockTextureFromSide(1);}
} |
d83ae272-4ed1-423f-ba7c-3f44be9a892c | 2 | public static void main(String[] args) throws InterruptedException {
long startTime;
long endTime;
// Test case #1:
// start up WORKER_THREAD_NUM worker threads (each of which will request
// TRANSACTION_NUM transactions from the server)
System.out.println("Benchmarking server performance with "
+ BananaBankBenchmark.WORKER_THREAD_NUM
+ " concurrent client connections...");
ClientWorkerThread workers[] = new ClientWorkerThread[BananaBankBenchmark.WORKER_THREAD_NUM];
startTime = System.currentTimeMillis();
for (int i = 0; i < BananaBankBenchmark.WORKER_THREAD_NUM; i++) {
workers[i] = new ClientWorkerThread();
workers[i].start();
}
// wait until the worker threads finish
for (int i = 0; i < BananaBankBenchmark.WORKER_THREAD_NUM; i++) {
workers[i].join();
}
endTime = System.currentTimeMillis();
System.out.println(WORKER_THREAD_NUM
+ " concurrent clients finished in " + (endTime - startTime)
+ " milliseconds");
System.out.println(1.0*(WORKER_THREAD_NUM*TRANSACTIONS_NUM)/(endTime - startTime)*1000.0 + " requests per second served");
// Test case #2:
// Start up just one client thread (which will request
// TRANSACTION_NUM transactions from the server)
System.out
.println("Benchmarking server performance with a single client connections...");
startTime = System.currentTimeMillis();
ClientWorkerThread worker = new ClientWorkerThread();
worker.start();
worker.join();
endTime = System.currentTimeMillis();
System.out.println("A single client finished in "
+ (endTime - startTime) + " milliseconds");
System.out.println(1.0*TRANSACTIONS_NUM/(endTime - startTime)*1000.0 + " requests per second served");
// start up a thread that sends "SHUTDOWN" to the server
new ShutdownWorkerThread().start();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.