method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
b8aca764-ee43-4d4a-bc8c-f1cbdc8be70f | 5 | public ConstOperator deobfuscateString(ConstOperator op) {
ClassAnalyzer clazz = methodAnalyzer.getClassAnalyzer();
MethodAnalyzer ma = clazz.getMethod(methodName, methodType);
if (ma == null)
return null;
Environment env = new Environment("L"
+ methodAnalyzer.getClazz().getName().replace('.', '/') + ";");
Interpreter interpreter = new Interpreter(env);
env.interpreter = interpreter;
String result;
try {
result = (String) interpreter.interpretMethod(ma.getBytecodeInfo(),
null, new Object[] { op.getValue() });
} catch (InterpreterException ex) {
if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_INTERPRT) != 0) {
GlobalOptions.err.println("Warning: Can't interpret method "
+ methodName);
ex.printStackTrace(GlobalOptions.err);
}
return null;
} catch (InvocationTargetException ex) {
if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_INTERPRT) != 0) {
GlobalOptions.err.println("Warning: Interpreted method throws"
+ " an uncaught exception: ");
ex.getTargetException().printStackTrace(GlobalOptions.err);
}
return null;
}
return new ConstOperator(result);
} |
d28af614-62de-4780-9bb0-8f05dcf6031b | 7 | int clear(){
vb.clear();
vd.clear();
os.clear();
if(vi!=null && links!=0){
for(int i=0;i<links;i++){
vi[i].clear();
vc[i].clear();
}
vi=null;
vc=null;
}
if(dataoffsets!=null)dataoffsets=null;
if(pcmlengths!=null)pcmlengths=null;
if(serialnos!=null)serialnos=null;
if(offsets!=null)offsets=null;
oy.clear();
//if(datasource!=null)(vf->callbacks.close_func)(vf->datasource);
//memset(vf,0,sizeof(OggVorbis_File));
return(0);
} |
649c57cd-5d5d-4ab9-b47e-f2be89d7d75c | 4 | public boolean put(int key,int value){
LinkedNode root = this;
if(root == null){
return false;
}
while(root.getNext()!=null){
if(root.getKey() == key)
return false;
root = root.getNext();
}
if(root.getKey() == key)
return false;
root.setNext(new LinkedNode(key,value));
return true;
} |
1f413bf3-5c2f-449d-879d-f8ff02087339 | 8 | @Override
public Move makeMove()
{
String input = null;
Boolean inputError = false;
do
{
try
{
if (inputError)
{
_writer.write("Invalid input. Try again.");
_writer.newLine();
}
input = _reader.readLine();
if (input != null && input.charAt(0) == 'q')
return new Move();
inputError = (
input == null ||
input.length() < 2 ||
!Columns.containsKey(input.charAt(0)) ||
!Rows.containsKey(input.charAt(1))
);
}
catch (IOException e)
{
inputError = true;
}
} while(inputError);
return new Move(Columns.get(input.charAt(0)), Rows.get(input.charAt(1)));
} |
86d1a230-bfc9-4e06-8b11-3fe83e08bfff | 3 | private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
if (estaModoEdicao() && exclusaoConfirmada()) {
try {
excluir();
} catch (ValidacaoException ex) {
_unitOfWork.rollback();
JOptionPane.showMessageDialog(this, ex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
}
}
}//GEN-LAST:event_btnExcluirActionPerformed |
a34bed55-4537-4a63-9f2a-528955f258e9 | 1 | public char getItemType(Position position) {
if (!isOccupied(position)) {
return ' ';
}
return field.get(position).getType();
} |
cf0f75c1-7616-46fe-b210-f5be48e6fdcc | 4 | private String pickItem() {
Random rand = new Random();
int num = rand.nextInt(config.getPoorChance() + config.getAverageChance() + config.getGoodChance() + config.getTopChance()) + 1;
if (num <= config.getPoorChance()) {
itemQuality = quality.poor;
return config.getPoorItems().get(rand.nextInt(config.getPoorItems().size()));
} else if (num <= (config.getPoorChance() + config.getAverageChance())) {
itemQuality = quality.average;
return config.getAverageItems().get(rand.nextInt(config.getAverageItems().size()));
} else if (num <= (config.getPoorChance() + config.getAverageChance() + config.getGoodChance())) {
itemQuality = quality.good;
return config.getGoodItems().get(rand.nextInt(config.getGoodItems().size()));
} else if (num <= (config.getPoorChance() + config.getAverageChance() + config.getGoodChance() + config.getTopChance())) {
itemQuality = quality.top;
return config.getTopItems().get(rand.nextInt(config.getTopItems().size()));
}
return null;
} |
c9b3e185-0bf9-4a46-84f2-32d7dabc2ef4 | 5 | public void paint(Graphics g) {
Clan clan = clan();
if(clan==null){return;}
super.paint(g);
int r = 0;
String S;
for(Quest q : clan.MB.QuestStack) { //reverse order?
g.drawString(S = q.description(), 2, BHGT+BHGT*r++);
refreshWid(g, S);
}
r = REPORTSTART;
g.drawString("GobLog:", 2, BHGT+BHGT*r++);
Reportable[] report = clan.getLog();
int d = -1;
for (Reportable R : report) {
int rd = R.getDate();
if (rd != d) {d = rd; g.drawString("Day " + rd, 2, BHGT+BHGT*r++);}
S = R.toString();
if (S != "") {g.drawString(S, 2, BHGT+BHGT*r++);}
}
} |
aa7596ab-a9dc-4bb2-8d26-8b7ad74e77a2 | 1 | public String getOutput(State state)
{
if(myMap.get(state) == null)
return "";
else
return (String) myMap.get(state);
} |
1c5fc65f-06cd-4045-8664-a145b25e6f1a | 1 | public void update()
{
if ( oldPos != null )
{
oldPos.set( pos );
oldRot.set( rot );
oldScale.set( scale );
}
else
{
oldPos = new Vector3f( 0, 0, 0 ).set( pos ).add( 1.0f );
oldRot = new Quaternion( 0, 0, 0, 0 ).set( rot ).mul( 0.5f );
oldScale = new Vector3f( 0, 0, 0 ).set( scale ).add( 1.0f );
}
} |
653a2a4f-b08b-4c9c-9d39-dd02139a78de | 6 | public Component getTableCellRendererComponent
(JTable table, Object value, boolean selected, boolean focused, int row, int column)
{
setEnabled(table == null || table.isEnabled());
setBackground(null);
setForeground(null);
if(column==0) {
setHorizontalAlignment(SwingConstants.CENTER);
}
else {
setHorizontalAlignment(SwingConstants.LEFT);
}
if(row==instructionIndex)
setBackground(Color.yellow);
else {
HVMInstruction currentInstruction = instructions[row];
String op = (currentInstruction.getFormattedStrings())[0];
if (op.equals("function") && (column == 1 || column == 2))
setBackground(new Color(190,171,210));
}
super.getTableCellRendererComponent(table, value, selected, focused, row, column);
return this;
} |
e9195428-079f-48dc-a834-be6219088129 | 6 | public void calculate(float num)
{
switch(oper)
{
case "+":
total += num;
break;
case "-":
total -= num;
break;
case "*":
total *= num;
break;
case "/":
total /= num;
break;
case " ":
total = num;
case "=":
default:
}
} |
a2f02a44-e42d-44c6-be6f-a6d2226fdde4 | 9 | protected void readAndSaveFile(MultipartStreamHandler aStream, String aBoundary, String aFilename) throws IOException
{
File f = new File(fSaveDir + File.separator + aFilename);
FileOutputStream fout = new FileOutputStream(f);
BufferedOutputStream bout = new BufferedOutputStream(fout, 8196);
byte[] bbuf = new byte[8196];
int result;
String line;
// ServletInputStream adds /r/n to the last line -- we need to clip those
boolean rnflag = false;
while ((result = aStream.readLine(bbuf, 0, bbuf.length)) != -1)
{
if (result > 2 && bbuf[0] == '-' && bbuf[1] == '-') // look for boundary
{
line = new String(bbuf, 0, result, "ISO-8859-1");
if (line.startsWith(aBoundary)) break;
}
if (rnflag) // pending deferred "\r\n" for all but last line
{
bout.write('\r');
bout.write('\n');
rnflag = false;
}
if (result >= 2 && bbuf[result-2] == '\r' && bbuf[result-1] == '\n')
{
bout.write(bbuf, 0, result-2); // clip "\r\n"
rnflag = true; // indicate deferred write is pending
}
else
{
bout.write(bbuf, 0, result);
}
}
bout.flush();
bout.close();
fout.close();
} |
31621c3e-3808-4a99-9bce-5a7eeb2c99ba | 0 | public int size() {
return queue.size();
} |
c687cea8-dc3f-4bad-a459-09e82e9a1bb3 | 4 | public static void deleteDirectory(File file) {
if (file.exists()) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
if (f.isDirectory()) {
deleteDirectory(f);
} else {
f.delete();
}
}
}
file.delete();
}
} |
3c1d1f16-b612-42bb-928f-2b73e95e58b7 | 4 | @Override
public Value evaluate(Value... arguments) throws Exception {
// Check the number of argument
if (arguments.length == 1) {
// get Value
Value value = arguments[0];
// If numerical
if (value.getType().isNumeric()) {
return new Value(new Double(Math.acos(value.getDouble())));
}
if (value.getType() == ValueType.ARRAY) {
Value[] vector = value.getValues();
Value result[] = new Value[vector.length];
for (int i = 0; i < vector.length; i++) {
result[i] = evaluate(vector[i]);
}
return new Value(result);
}
// the type is incorrect
throw new EvalException(this.name() + " function does not handle "
+ value.getType().toString() + " type");
}
// number of argument is incorrect
throw new EvalException(this.name()
+ " function only allows one numerical parameter");
} |
34fe77cc-4422-4a10-8be4-76c3fe6f843f | 4 | @Override
public double evaluate(int[][] board) {
int max = 0, secondMax = 0;
int maxX = -1, maxY = -1, sMaxX = -1, sMaxY = -1;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if(board[i][j] > max) {
secondMax = max;
sMaxX = maxX;
sMaxY = maxY;
max = board[i][j];
maxX = i;
maxY = j;
}
}
}
if(secondMax == 0) {
return 0;
}
return dist(maxX, maxY, sMaxX, sMaxY);
} |
5bd477b7-eaef-4216-b18d-b18923e4233a | 3 | public static String trimAllWhitespace(String str) {
if (!hasLength(str)) {
return str;
}
StringBuilder sb = new StringBuilder(str);
int index = 0;
while (sb.length() > index) {
if (Character.isWhitespace(sb.charAt(index))) {
sb.deleteCharAt(index);
}
else {
index++;
}
}
return sb.toString();
} |
203e9463-c7b6-4a7a-846e-35e38e3baa80 | 5 | @Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Option)) {
return false;
}
Option other = (Option) object;
if ((this.idOption == null && other.idOption != null) || (this.idOption != null && !this.idOption.equals(other.idOption))) {
return false;
}
return true;
} |
ac8817d7-4842-4dfe-b938-73ce13ec44fb | 9 | private void parse(String json) throws JsonException {
final String res = json.trim();
// Try trivial variants
if ("{}".equals(res) || "{ }".equals(res)) { // Empty Object
this.type = JsonType.OBJECT;
objectData = new HashMap<>();
return;
}
if ("[]".equals(res) || "[ ]".equals(res)) { // Empty Array
this.type = JsonType.ARRAY;
arrayData = new ArrayList<>();
return;
}
try {
final String firstChar = res.substring(0, 1);
switch (firstChar) {
case "{":
parseObject(res); // JSON Object { key1 : value1, key2 : value2, ... }
break;
case "[":
parseArray(res); // JSON Array [value1, value2, ...]
break;
case "\"":
parseString(res); // JSON String "some STRING"
break;
default:
parseOther(res); // Any other
break;
}
} catch (JsonException ex) {
throw ex;
} catch (Exception ex) {
throw new JsonException("JSON Parse error: " + ex.getMessage());
}
} |
c2205b7e-e808-4c3e-b9e8-1c174331954e | 7 | public void doRunKeys(int run) throws Exception {
if (m_ResultProducer == null) {
throw new Exception("No ResultProducer set");
}
if (m_ResultListener == null) {
throw new Exception("No ResultListener set");
}
if (m_Instances == null) {
throw new Exception("No Instances set");
}
// Tell the resultproducer to send results to us
m_ResultProducer.setResultListener(this);
m_ResultProducer.setInstances(m_Instances);
// For each subsample size
if (m_LowerSize == 0) {
m_CurrentSize = m_StepSize;
} else {
m_CurrentSize = m_LowerSize;
}
while (m_CurrentSize <= m_Instances.numInstances() &&
((m_UpperSize == -1) ||
(m_CurrentSize <= m_UpperSize))) {
m_ResultProducer.doRunKeys(run);
m_CurrentSize += m_StepSize;
}
} |
020b7af4-ccf0-4f58-99ed-8050ee564a6a | 3 | @WebMethod(operationName = "ReadStock")
public ArrayList<Stock> ReadStock(@WebParam(name = "stock_id") String stock_id) {
Stock stock = new Stock();
ArrayList<Stock> stocks = new ArrayList<Stock>();
ArrayList<QueryCriteria> qc = new ArrayList<QueryCriteria>();
if(!stock_id.equals("-1")){
qc.add(new QueryCriteria("stock_id", stock_id, Operand.EQUALS));
}
ArrayList<String> fields = new ArrayList<String>();
ArrayList<QueryOrder> order = new ArrayList<QueryOrder>();
try {
stocks = stock.Read(qc, fields, order);
} catch (SQLException ex) {
Logger.getLogger(JAX_WS.class.getName()).log(Level.SEVERE, null, ex);
}
if(stocks.isEmpty()){
return null;
}
return stocks;
} |
ec4bb458-f183-4844-9915-953d2c48fbf2 | 4 | public static String readPropeties() {
System.out.println("Entering readProperties() in "+DATE_FORMAT.format(new Date()));
Thread.currentThread().setName("ReadProperties-"+COUNT++);
Properties protoProp = new Properties();
String propLoc = "message.properties";
String root = "C:\\test\\";
InputStream is = null;
if(new File(root + "myfolder").exists()) {
propLoc = root + "myfolder\\" + propLoc;
} else {
propLoc = root + "otherFolder\\" + propLoc;
}
try {
System.out.println("Instatiating input stream from "+propLoc);
is = new FileInputStream(propLoc);
protoProp.load(is);
String message = protoProp.getProperty("message");
System.out.println(message);
Thread.sleep(2500);
} catch (InterruptedException | IOException e) {
System.out.println("ReadProperties was interrupted.");
} finally {
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Exiting readProperties() in "+DATE_FORMAT.format(new Date()));
return propLoc;
} |
dd54412d-20f8-4a3d-b501-143d75ce4a72 | 7 | public void load()
{
ready=false;
BufferedImage temp = getImage( FileName );
if( temp!=null )
{
int xFrame = temp.getWidth(null);
int yFrame = temp.getHeight(null);
int counter_x, counter_y ;
boolean set=false;
if( scale )
{
xSize=(short)xFrame; ySize=(short)yFrame;
xHalf=(short)(xSize/2); yHalf=(short)(ySize/2);
counter_x = 1; counter_y = 1;
}
else{
counter_x = xFrame/xSize; // Число кадров в строке
counter_y = yFrame/ySize; // Число кадров в столбце
set=true;
}
Frames = counter_x*counter_y;
if( Frames>0 && Frames<1000000 )// страшно представить анимацию с таким числом кадров...
{ // Вернее представить то не проблема, но учитывая что я всё делаю из рассчёта на небольшие игры - это не нужно.
if( Frames==1 && set )
System.out.println("WARNING: passible incorrect frame scale selected!");
img = new BufferedImage[Frames];
for( int f=0 ; f<Frames ; f++ )
img[f] = temp.getSubimage( (f%counter_x)*xSize, (f/counter_x)*ySize, xSize, ySize );
ready=true;
}
else{
error=100;
img=null;
wreck=true;
}
}
else{
error=1;
img=null;
wreck=true;
}
} |
2905638d-b4b1-4391-b49d-0c135b7abad6 | 3 | private int readLength() throws StreamCorruptedException {
StringBuffer lenStr = new StringBuffer();
while (input.remaining() > 0) {
char ch = input.get();
if (ch == ':') {
//indexPlus(1);
break;
} else {
lenStr.append(ch);
}
}
int arrayLen = 0;
try {
arrayLen = Integer.valueOf(lenStr.toString());
} catch (Throwable e) {
throw new StreamCorruptedException("Integer of length failed to serialize");
}
return arrayLen;
} |
cddcc67c-1020-4fe5-9477-ed41fd7953c0 | 1 | public void addAccount(BankAccount account) throws IllegalArgumentException {
if (! canHaveAsAccount(account))
throw new IllegalArgumentException();
accounts.add(account);
} |
08e309b9-b5c9-467b-84c2-3ba5843e6b85 | 7 | private boolean processCommand(Command command)
{
boolean wantToQuit = false;
CommandWord commandWord = command.getCommandWord();
switch (commandWord) {
case UNKNOWN:
System.out.println("I don't know what you mean...");
tryMoveCharacters();
break;
case HELP:
printHelp();
tryMoveCharacters();
break;
case GO:
tryMoveCharacters(); // This must be before moving to prevent character position being different from what the room prints
wantToQuit = goRoom(command);
break;
case TAKE:
takeItem(command);
tryMoveCharacters();
break;
case DROP:
dropItem(command);
tryMoveCharacters();
break;
case FIGHT:
wantToQuit = fight(command);
tryMoveCharacters(); // This must be after fighting so that character cant move before being attacked
break;
case QUIT:
wantToQuit = quit(command);
tryMoveCharacters();
break;
}
return wantToQuit;
} |
4ae45c89-7462-4f30-a0a7-9ae2c246db1a | 2 | @Override
public boolean startVideoProcessing(File videoFile) {
if (this.window == null || this.adFinder == null)
return false;
return this.adFinder.startVideoProcessing(videoFile);
} |
fa666416-cfb6-4874-817e-7a60bcc9786c | 3 | public void addBestModel(List<CartsModel> toadd) {
for (CartsModel cm : toadd) {
if (locm.isEmpty()
|| locm.get(0).getModel_bandwith() > cm.getModel_bandwith()) {
locm.clear();
locm.add(cm);
}
}
} |
3d813f70-4ed7-4f34-84be-28b39da8b4a4 | 8 | public boolean search(String word) {
Queue<TrieNode> queue = new LinkedList<TrieNode>();
TrieNode node = root;
queue.add(node);
int index = 0;
while (!queue.isEmpty()) {
if (index == word.length())
return true;
TrieNode curr = queue.poll();
if (index == word.length() - 1)
return curr.flag;
if (word.charAt(index) == '.') {
for (int i = 0; i < 26; i++) {
if (curr.children[i] != null)
queue.add(curr.children[i]);
}
} else {
if (curr != null && curr.children[word.charAt(index) - 'a'] == null)
break;
else
queue.add(curr.children[word.charAt(index) - 'a']);
}
index++;
}
return false;
} |
da81d728-3048-4da7-9dbe-c3c461393e78 | 0 | protected Component getView() {
return view;
} |
31af69ce-0848-4c23-b834-954e73dfc795 | 8 | public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
if(head == null) {
return null;
}
if(head.next == null) {
return null;
}
if(head.next.equals(head)) {
return head;
}
int fastSpeed = 2;
boolean firstMeet = true;
while(fast.next != null) {
for(int i=0;i<fastSpeed;i++) {
fast = fast.next;
}
slow = slow.next;
if(fast.equals(slow)) {
if(firstMeet) {
firstMeet = false;
fastSpeed = 1;
fast = head;
if(fast.equals(slow)) {
return slow;
}
} else {
return slow;
}
}
}
return null;
} |
06ca9a10-6f62-4921-8728-06bbafe6e9df | 4 | @Override
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
DatabaseManager manager=DatabaseManager.getManager();
String begin=request.getParameter(Booking.BEGIN);
String end=request.getParameter(Booking.END);
try {
if(!MyServlet.isEmpty(begin) && !MyServlet.isEmpty(end)){
SimpleDateFormat df=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
QueryBuilder<Booking, Integer> query=manager.getBookingDao().queryBuilder();
query.where().ge("begin", df.parse(begin))
.and().lt("end", df.parse(end));
ServletResult.sendResult(response, new GetResult(
ServletResult.SUCCESS, fill(manager, query.query())));
}
else{
ServletResult.sendResult(response, new GetResult(
ServletResult.SUCCESS, fill(manager, manager.getBookingDao().queryForAll())));
}
} catch (SQLException e) {
e.printStackTrace();
ServletResult.sendResult(response, ServletResult.ERROR);
} catch (ParseException e) {
e.printStackTrace();
ServletResult.sendResult(response, ServletResult.BAD_DATE_FORMAT);
}
} |
0d0e4285-0b09-4850-bdf0-9a1756f22dda | 9 | public String nextToken() throws JSONException {
char c;
char q;
StringBuffer sb = new StringBuffer();
do {
c = next();
} while (Character.isWhitespace(c));
if (c == '"' || c == '\'') {
q = c;
for (;;) {
c = next();
if (c < ' ') {
throw syntaxError("Unterminated string.");
}
if (c == q) {
return sb.toString();
}
sb.append(c);
}
}
for (;;) {
if (c == 0 || Character.isWhitespace(c)) {
return sb.toString();
}
sb.append(c);
c = next();
}
} |
15c10b1a-facb-4441-9cfd-d34ab079dbd2 | 2 | public void menuUpdate(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException{
if(playTheme ==true){
theme.playAsSoundEffect(1.0f, 1.0f, false);
playTheme=false;
Mouse.setGrabbed(false);
}
else{}
if(Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)){
Screen=0;
}
} |
f744c95b-e453-4385-ace8-026454d3feff | 7 | public JComponent createAbsolute_Position()
{
JTabbedPane tabbedPane = new JTabbedPane();
// Pos tab
final JPanel posPanel = createTabPanel(new MigLayout());
posPanel.add(createButton(), "pos 0.5al 0al");
posPanel.add(createButton(), "pos 1al 0al");
posPanel.add(createButton(), "pos 0.5al 0.5al");
posPanel.add(createButton(), "pos 5in 45lp");
posPanel.add(createButton(), "pos 0.5al 0.5al");
posPanel.add(createButton(), "pos 0.5al 1.0al");
posPanel.add(createButton(), "pos 1al .25al");
posPanel.add(createButton(), "pos visual.x2-pref visual.y2-pref");
posPanel.add(createButton(), "pos 1al -1in");
posPanel.add(createButton(), "pos 100 100");
posPanel.add(createButton(), "pos (10+(20*3lp)) 200");
posPanel.add(createButton("Drag Window! (pos 500-container.xpos 500-container.ypos)"),
"pos 500-container.xpos 500-container.ypos");
// Bounds tab
JPanel boundsPanel = createTabPanel(new MigLayout());
String constr = "pos (visual.x+visual.w*0.1) visual.y2-40 (visual.x2-visual.w*0.1) visual.y2";
JLabel southLabel = createLabel(constr, SwingConstants.CENTER);
southLabel.setBorder(new LineBorder(Color.LIGHT_GRAY, 1));
southLabel.setBackground(new Color(200, 200, 255, benchRuns == 0 ? 70 : 255));
southLabel.setOpaque(true);
southLabel.setFont(southLabel.getFont().deriveFont(Font.BOLD));
boundsPanel.add(southLabel, constr);
boundsPanel.add(createButton(), "pos 0 0 container.x2 n");
boundsPanel.add(createButton(), "pos visual.x 40 visual.x2 70");
boundsPanel.add(createButton(), "pos visual.x 100 visual.x2 p");
boundsPanel.add(createButton(), "pos 0.1al 0.4al n (visual.y2 - 10)");
boundsPanel.add(createButton(), "pos 0.9al 0.4al n visual.y2-10");
boundsPanel.add(createButton(), "pos 0.5al 0.5al, pad 3 0 -3 0");
boundsPanel.add(createButton(), "pos n n 50% 50%");
boundsPanel.add(createButton(), "pos 50% 50% n n");
boundsPanel.add(createButton(), "pos 50% n n 50%");
boundsPanel.add(createButton(), "pos n 50% 50% n");
tabbedPane.addTab("X Y Positions", posPanel);
tabbedPane.addTab("X1 Y1 X2 Y2 Bounds", boundsPanel);
// Glass pane tab
if (benchRuns == 0) {
final JPanel glassPanel = createTabPanel(new MigLayout("align c c, ins 0"));
final JButton butt = createButton("Press me!!");
glassPanel.add(butt);
butt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
butt.setEnabled(false);
final JPanel bg = new JPanel(new MigLayout("align c c,fill")) {
public void paint(Graphics g)
{
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
super.paint(g);
}
};
bg.setOpaque(OPAQUE);
configureActiveComponet(bg);
final JLabel label = createLabel("You don't need a GlassPane to be cool!");
label.setFont(label.getFont().deriveFont(30f));
label.setForeground(new Color(255, 255, 255, 0));
bg.add(label, "align 50% 30%");
glassPanel.add(bg, "pos visual.x visual.y visual.x2 visual.y2", 0);
final long startTime = System.nanoTime();
final long endTime = startTime + 500000000L;
glassPanel.revalidate();
final javax.swing.Timer timer = new Timer(25, null);
timer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
long now = System.nanoTime();
int alpha = (int) (((now - startTime) / (double) (endTime - startTime)) * 300);
if (alpha < 150)
bg.setBackground(new Color(100, 100, 100, alpha));
if (alpha > 150 && alpha < 405) {
label.setForeground(new Color(255, 255, 255, (alpha - 150)));
bg.repaint();
}
if (alpha > 405)
timer.stop();
}
});
timer.start();
}
});
tabbedPane.addTab("GlassPane Substitute", glassPanel);
addComponentListener(new ComponentAdapter() {
public void componentMoved(ComponentEvent e) {
if (posPanel.isDisplayable()) {
posPanel.revalidate();
} else {
removeComponentListener(this);
}
}
});
}
// Disregard. Just forgetting the source code text close to the source code.
setSource("JTabbedPane tabbedPane = new JTabbedPane();\n" +
"\n" +
"// Pos tab\n" +
"final JPanel posPanel = createTabPanel(new MigLayout());\n" +
"\n" +
"posPanel.add(createButton(), \"pos 0.5al 0al\");\n" +
"posPanel.add(createButton(), \"pos 1al 0al\");\n" +
"posPanel.add(createButton(), \"pos 0.5al 0.5al\");\n" +
"posPanel.add(createButton(), \"pos 5in 45lp\");\n" +
"posPanel.add(createButton(), \"pos 0.5al 0.5al\");\n" +
"posPanel.add(createButton(), \"pos 0.5al 1.0al\");\n" +
"posPanel.add(createButton(), \"pos 1al .25al\");\n" +
"posPanel.add(createButton(), \"pos visual.x2-pref visual.y2-pref\");\n" +
"posPanel.add(createButton(), \"pos 1al -1in\");\n" +
"posPanel.add(createButton(), \"pos 100 100\");\n" +
"posPanel.add(createButton(), \"pos (10+(20*3lp)) 200\");\n" +
"posPanel.add(createButton(\"Drag Window! (pos 500-container.xpos 500-container.ypos)\"),\n" +
" \"pos 500-container.xpos 500-container.ypos\");\n" +
"\n" +
"// Bounds tab\n" +
"JPanel boundsPanel = createTabPanel(new MigLayout());\n" +
"\n" +
"String constr = \"pos (visual.x+visual.w*0.1) visual.y2-40 (visual.x2-visual.w*0.1) visual.y2\";\n" +
"JLabel southLabel = createLabel(constr, SwingConstants.CENTER);\n" +
"southLabel.setBorder(new LineBorder(Color.LIGHT_GRAY, 1));\n" +
"southLabel.setBackground(new Color(200, 200, 255, 70));\n" +
"southLabel.setOpaque(true);\n" +
"southLabel.setFont(southLabel.getFont().deriveFont(Font.BOLD));\n" +
"boundsPanel.add(southLabel, constr);\n" +
"\n" +
"boundsPanel.add(createButton(), \"pos 0 0 container.x2 n\");\n" +
"boundsPanel.add(createButton(), \"pos visual.x 40 visual.x2 70\");\n" +
"boundsPanel.add(createButton(), \"pos visual.x 100 visual.x2 p\");\n" +
"boundsPanel.add(createButton(), \"pos 0.1al 0.4al n visual.y2-10\");\n" +
"boundsPanel.add(createButton(), \"pos 0.9al 0.4al n visual.y2-10\");\n" +
"boundsPanel.add(createButton(), \"pos 0.5al 0.5al, pad 3 0 -3 0\");\n" +
"boundsPanel.add(createButton(), \"pos n n 50% 50%\");\n" +
"boundsPanel.add(createButton(), \"pos 50% 50% n n\");\n" +
"boundsPanel.add(createButton(), \"pos 50% n n 50%\");\n" +
"boundsPanel.add(createButton(), \"pos n 50% 50% n\");\n" +
"\n" +
"// Glass pane tab\n" +
"final JPanel glassPanel = createTabPanel(new MigLayout(\"align c c, ins 0\"));\n" +
"final JButton butt = createButton(\"Press me!!\");\n" +
"glassPanel.add(butt);\n" +
"\n" +
"butt.addActionListener(new ActionListener()\t\t{\n" +
"\tpublic void actionPerformed(ActionEvent e)\n" +
"\t{\n" +
"\t\tbutt.setEnabled(false);\n" +
"\t\tfinal JPanel bg = new JPanel(new MigLayout(\"align c c,fill\")) {\n" +
"\t\t\tpublic void paint(Graphics g)\n" +
"\t\t\t{\n" +
"\t\t\t\tg.setColor(getBackground());\n" +
"\t\t\t\tg.fillRect(0, 0, getWidth(), getHeight());\n" +
"\t\t\t\tsuper.paint(g);\n" +
"\t\t\t}\n" +
"\t\t};\n" +
"\t\tbg.setOpaque(OPAQUE);\n" +
"\t\tconfigureActiveComponet(bg);\n" +
"\n" +
"\t\tfinal JLabel label = createLabel(\"You don't need a GlassPane to be cool!\");\n" +
"\t\tlabel.setFont(label.getFont().deriveFont(30f));\n" +
"\t\tlabel.setForeground(new Color(255, 255, 255, 0));\n" +
"\t\tbg.add(label, \"align 50% 30%\");\n" +
"\n" +
"\t\tglassPanel.add(bg, \"pos visual.x visual.y visual.x2 visual.y2\", 0);\n" +
"\t\tfinal long startTime = System.nanoTime();\n" +
"\t\tfinal long endTime = startTime + 500000000L;\n" +
"\n" +
"\t\tglassPanel.revalidate();\n" +
"\n" +
"\t\tfinal javax.swing.Timer timer = new Timer(25, null);\n" +
"\n" +
"\t\ttimer.addActionListener(new ActionListener() {\n" +
"\t\t\tpublic void actionPerformed(ActionEvent e)\n" +
"\t\t\t{\n" +
"\t\t\t\tlong now = System.nanoTime();\n" +
"\t\t\t\tint alpha = (int) (((now - startTime) / (double) (endTime - startTime)) * 300);\n" +
"\t\t\t\tif (alpha < 150)\n" +
"\t\t\t\t\tbg.setBackground(new Color(100, 100, 100, alpha));\n" +
"\n" +
"\t\t\t\tif (alpha > 150 && alpha < 405) {\n" +
"\t\t\t\t\tlabel.setForeground(new Color(255, 255, 255, (alpha - 150)));\n" +
"\t\t\t\t\tbg.repaint();\n" +
"\t\t\t\t}\n" +
"\t\t\t\tif (alpha > 405)\n" +
"\t\t\t\t\ttimer.stop();\n" +
"\t\t\t}\n" +
"\t\t});\n" +
"\t\ttimer.start();\n" +
"\t}\n" +
"});\n" +
"\n" +
"tabbedPane.addTab(\"X Y Positions\", posPanel);\n" +
"tabbedPane.addTab(\"X1 Y1 X2 Y2 Bounds\", boundsPanel);\n" +
"tabbedPane.addTab(\"GlassPane Substitute\", glassPanel);\n" +
"\n" +
"addComponentListener(new ComponentAdapter() {\n" +
"\tpublic void componentMoved(ComponentEvent e) {\n" +
"\t\tif (posPanel.isDisplayable()) {\n" +
"\t\t\tposPanel.revalidate();\n" +
"\t\t} else {\n" +
"\t\t\tremoveComponentListener(this);\n" +
"\t\t}\n" +
"\t}\n" +
"});");
return tabbedPane;
} |
33db2fab-d890-44d6-8fae-445dcf3aa1b8 | 0 | public String getName() {
return name;
} |
f11227a3-36a7-4301-8047-1b69b92bab2d | 8 | public static ArrayList<ArrayList<Integer>> zigzagLevelOrder2(TreeNode root) {
ArrayList<ArrayList<Integer>> resultLists = new ArrayList<ArrayList<Integer>>();
if (root == null) {
return resultLists;
}
Stack<TreeNode> currentLevel = new Stack<TreeNode>();
currentLevel.push(root);
Boolean leftToRight = false;
while (!currentLevel.isEmpty()) {
Stack<TreeNode> nextLevel = new Stack<TreeNode>();
ArrayList<Integer> newList = new ArrayList<Integer>();
while(!currentLevel.isEmpty()){
TreeNode node = currentLevel.pop();
newList.add(node.val);
if(leftToRight){
if(node.right != null) nextLevel.add(node.right);
if(node.left != null) nextLevel.add(node.left);
}else{
if(node.left != null) nextLevel.add(node.left);
if(node.right != null) nextLevel.add(node.right);
}
}
leftToRight = !leftToRight;
resultLists.add(newList);
currentLevel = nextLevel;
}
return resultLists;
} |
923cbdda-006d-40bb-a4d4-ec6fb11b942a | 1 | public boolean replaceSubBlock(StructuredBlock oldBlock,
StructuredBlock newBlock) {
if (bodyBlock == oldBlock)
bodyBlock = newBlock;
else
return false;
return true;
} |
37dd4181-00c2-4faf-9a48-2d586b16dd23 | 0 | public Object GetConfig(String section, String option)
{
//get hashtable for the section
Hashtable tmp = (Hashtable)configSections.get(section.toUpperCase());
//get the value of the option
return tmp.get(option.toUpperCase());
} |
0fe9a8fb-05b5-44b5-be72-445bf85a7805 | 5 | public int nextSetBit(int fromIndex)
{
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
checkInvariants();
int u = wordIndex(fromIndex);
if (u >= wordsInUse)
return -1;
long word = words[u] & (WORD_MASK << fromIndex);
while (true)
{
if (word != 0)
return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word);
if (++u == wordsInUse)
return -1;
word = words[u];
}
} |
d76f7808-7036-469d-9614-2fecaa2c421e | 8 | private boolean checaTipoDaVariavelEmRegistro(String nomeVariavel, String tipoDoRetorno) {
if(!listaVariveisRegistro.isEmpty()){
if(!listaDeBlocos.isEmpty()){
for(int j=0;j< listaDeBlocos.size();j++){
String [] tabela1 = listaDeBlocos.get(j).split("~");
String nomeReg = tabela1[1];
if(nomeReg.equals(tipoDoToken[1])){
String [] tabela2 = tabela1[2].split(":");
for(int i=0;i< tabela2.length;i++){
String indice = tabela2[i];
for(int z=0;z<listaVariveisRegistro.size();z++){
String ind = listaVariveisRegistro.get(z).split(":")[0];
if(indice.equals(ind)){
String tipoVar = listaVariveisRegistro.get(z).split(":")[1];
if(tipoVar.equals(tipoDoRetorno)){
return true;
}
}
}
}
}
}
}
}
return false;
} |
64641987-74a1-4e5f-9129-09c7547a33a3 | 3 | private Integer[][] goDijkstra(int x, int y) {
int profondeur = 0;
Integer dijkstra[][] = new Integer[taille_envi][taille_envi];
Stack<Point> toDo = new Stack<Point>();
toDo.add(new Point(x, y));
for (int j = 0; j < taille_envi; j++) {
for (int i = 0; i < taille_envi; i++) {
dijkstra[i][j] = -1;
}
}
dijkstra[x][y] = profondeur;
while (!toDo.isEmpty()) {
profondeur++;
Point p = toDo.pop();
toDo.addAll(uneEpaisseur(p.x, p.y, dijkstra[p.x][p.y] + 1, dijkstra));
}
return dijkstra;
} |
15b81d2c-328c-4282-a979-32d612969599 | 7 | private boolean isConstant(String token) throws Exception {
//check if character constant
if ( token.startsWith("'") ) {
if (token.endsWith("'") && token.length()<=3) {
return true;
} else {
throw new Exception("Wrong chacter constant!");
}
}
//check if string constant
if ( token.startsWith("\"") ) {
if (token.endsWith("\"") && !token.substring(1, token.length()-1).contains("\"")) {
return true;
} else {
throw new Exception("Wrong string constant!");
}
}
//Integer constant
try {
Integer.parseInt(token);
return true;
} catch (NumberFormatException exc) {
return false;
}
} |
3db3f826-f53a-43a0-b81e-1b47b22324d6 | 7 | private String principalComponentsSummary() {
StringBuffer result = new StringBuffer();
double cumulative = 0.0;
Instances output = null;
int numVectors=0;
try {
output = setOutputFormat();
numVectors = (output.classIndex() < 0)
? output.numAttributes()
: output.numAttributes()-1;
} catch (Exception ex) {
}
//tomorrow
result.append("Correlation matrix\n"+matrixToString(m_correlation)
+"\n\n");
result.append("eigenvalue\tproportion\tcumulative\n");
for (int i = m_numAttribs - 1; i > (m_numAttribs - numVectors - 1); i--) {
cumulative+=m_eigenvalues[m_sortedEigens[i]];
result.append(Utils.doubleToString(m_eigenvalues[m_sortedEigens[i]],9,5)
+"\t"+Utils.
doubleToString((m_eigenvalues[m_sortedEigens[i]] /
m_sumOfEigenValues),
9,5)
+"\t"+Utils.doubleToString((cumulative /
m_sumOfEigenValues),9,5)
+"\t"+output.attribute(m_numAttribs - i - 1).name()+"\n");
}
result.append("\nEigenvectors\n");
for (int j = 1;j <= numVectors;j++) {
result.append(" V"+j+'\t');
}
result.append("\n");
for (int j = 0; j < m_numAttribs; j++) {
for (int i = m_numAttribs - 1; i > (m_numAttribs - numVectors - 1); i--) {
result.append(Utils.
doubleToString(m_eigenvectors[j][m_sortedEigens[i]],7,4)
+"\t");
}
result.append(m_trainInstances.attribute(j).name()+'\n');
}
if (m_transBackToOriginal) {
result.append("\nPC space transformed back to original space.\n"
+"(Note: can't evaluate attributes in the original "
+"space)\n");
}
return result.toString();
} |
83c5d43c-46c6-43f6-b129-d75d0d085b75 | 4 | @Test
public void testThrowsOnIncorrectSignatur() {
try {
assertNotNull(Sx.mk(new SxController() {
@Selector("s")
void f1() {
}
}));
fail("Should throw");
} catch (RuntimeException ex) {
}
try {
assertNotNull(Sx.mk(new SxController() {
@Selector("s")
void f2(String a1, HashMap<?,?> map) {
}
}));
fail("Should throw");
} catch (RuntimeException ex) {
}
} |
57e651d7-d27e-4c58-9db9-7392689af035 | 2 | @Override
public void run(ListIterator<Instruction> iter)
throws Exception {
Instruction i = iter.next();
if(i instanceof ArrayIndex) {
iter.remove(); // remove instruction i
ArrayList<Instruction> code = ((ArrayIndex)i).getIndexingCalculation();
BasicBlock containing = i.getContainingBB();
// link into the dominator tree as we add it to the instruciton list
Instruction dominator = i.getDominating();
i.setDominating(null);
for(Instruction c : code) {
c.setDominating(dominator);
c.setContainingBB(containing);
dominator = c;
iter.add(c);
}
// there will always be a load or store after the array indexing
// can return with the iterator advanced since we are only
// looking for ArrayIndex instructions
Instruction ls = iter.next();
ls.setDominating(code.get(code.size() - 1));
// delete for the last instruction in code list. This
// should always be an Adda, so put the cast to make this clear.
i.delete((Adda)code.get(code.size() -1));
}
} |
54589ac4-6991-4659-8e10-d3ae7d819fa2 | 3 | private void downloadSong(final SongConfig song, final FolderConfig folderConfig) {
String trackString = null;
try {
final HttpResponse trackResponse = getApi().get(new Request(String.format(Constants.TRACK_URL, song.getTrackId(), Constants.CLIENT_ID)));
trackString = EntityUtils.toString(trackResponse.getEntity());
} catch (final Exception e) {
e.printStackTrace();
}
final JSONObject obj = new JSONObject(trackString);
final boolean streamable = obj.getBoolean("streamable");
if (streamable) {
final Downloader downloader = SCUtilFactory.getDownloader(song.getSongUrl());
// Use the song's mp3 metadata if populated, otherwise use the folder's mp3 metadata
final Mp3Metadata metadata = song.getMp3Metadata() != null ? song.getMp3Metadata() : folderConfig.getMp3Metadata();
song.setLocalSong(downloader.downloadSong(obj.getString("permalink_url"), folderConfig.getDownloadFolder(), metadata));
song.setSyncOn(false);
} else {
System.out.println("Track is not streamable, no way to sync song from URL " + song.getSongUrl());
}
} |
febc3ffe-e28e-4a9d-9f74-1cbbbd201ac0 | 2 | static void decompress(BitInputStream in, OutputStream out) throws IOException {
FrequencyTable freq = new SimpleFrequencyTable(new FlatFrequencyTable(257)); // Initialize with all symbol frequencies at 1
ArithmeticDecoder dec = new ArithmeticDecoder(in);
while (true) {
int symbol = dec.read(freq);
if (symbol == 256) // EOF symbol
break;
out.write(symbol);
freq.increment(symbol);
}
} |
38c4a5b9-29e4-456a-802e-af9f8ac59801 | 8 | private boolean readTape(InputStream stream) {
byte[] start = new byte[32];
dirNames.clear();
dirEntries.clear();
type = TAPE;
try {
DataInputStream reader = new DataInputStream(stream);
reader.readFully(start);
String st = new String(start);
if (st.startsWith("C64")) {
System.out.println("Tape Archive found:");
reader.readFully(start);
int max = start[3]*256 + start[2];
int used = start[5]*256 + start[4];
if (used == 0) used = 1;
String name = "";
System.out.println("Type: " + start[0]*256 + start[1]);
System.out.println("Max Entries: " + max);
System.out.println("Used Entries: " + used);
for (int i = 8; i < 32; i++)
name = name + (char) start[i];
System.out.println("Name: " + name);
int startAdr, endAdr, offset;
for (int i = 0; i < used; i++) {
reader.readFully(start);
startAdr = (start[2]&0xff) +
(start[3]&0xff) * 256;
endAdr = (start[4]&0xff) +
(start[5]&0xff) * 256;
offset = (start[8]&0xff) +
(start[9]&0xff) * 256;
System.out.println("---------------------");
System.out.println("Entry: " + i);
System.out.println("File Type: " + start[0]);
System.out.println("1541 Type: " + start[1]);
System.out.println("Start Adr: " + startAdr);
System.out.println("End Adr: " + endAdr + " -> size = " +
(endAdr - startAdr));
System.out.println("Offset: " + offset);
name = "";
for (int j = 16; j < 32; j++)
name = name + (char) start[j];
System.out.println("File Name: " + name);
DirEntry entry = new DirEntry(name, offset -
32 * (max + 2), startAdr,
endAdr - startAdr, start[1]);
dirNames.add(entry);
dirEntries.put(name, entry);
}
// Skip all empty entries!!!
for (int i = used; i < max; i++) {
reader.readFully(start);
}
int sector = 0;
int numRead;
while((numRead = readSector(reader, sector)) == 256)
sector++;
noBytes = sector * 256 + numRead;
System.out.println("Read " + noBytes + " program data");
// dumpSector(sectors[0]);
}
return true;
} catch (Exception e) {
System.out.println("Error while reading tape");
}
return false;
} |
a57a1ecf-ba56-4b00-a9cc-6116656327bb | 1 | public void addWay(int pos, long wayId){
if (!ways.contains(wayId))
ways.add(wayId);
} |
861304ee-e3e3-48d9-b1d5-f9b67a4f4480 | 4 | public static void main(String[] args) throws Exception
{
int p[] = { 30, 35, 15, 5, 10, 20, 25 };
TDMatrixChainMultiplication td = new TDMatrixChainMultiplication(p);
System.out.println("Number of scalar multiplications");
for (int i = 1; i < p.length; i++)
{
for (int j = i; j < p.length; j++)
System.out.print(td.minCost(i, j) + " ");
System.out.println();
}
System.out.println("\nSplit");
for (int i = 1; i < p.length; i++)
{
for (int j = i + 1; j < p.length; j++)
System.out.print(td.split(i, j) + " ");
System.out.println();
}
} |
301e08c2-f158-42c2-895b-2a03a4b7ec11 | 4 | @Override
public void draw(SpriteBatch batch, float parentAlpha) {
if (MyStage.isCameraView(stage, x, y)) {
update(Gdx.graphics.getDeltaTime());
if (isDead) {
batch.draw(deadTexture, x - 32, y - 32, originX, originY, width, height, 1, 1, rotation);
} else {
batch.draw(texture, x - 32, y - 32, originX, originY, width, height, 1, 1, rotation);
}
if (hitpoint != MAX_HITPOINTS && !isDead) {
Engine.font.draw(batch, hitpoint + "", x - 32, y + 64);
}
}
} |
96d15e1a-92b0-4c2d-ba7d-91b400ccce6e | 9 | @Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
super.executeMsg(myHost,msg);
if((msg.source().location()!=null)
&&(msg.targetMinor()==CMMsg.TYP_DAMAGE)
&&((msg.value())>0)
&&(msg.tool()==this)
&&(msg.target() instanceof MOB)
&&(!((MOB)msg.target()).amDead())
&&(CMLib.flags().isEvil((MOB)msg.target())))
{
final CMMsg msg2=CMClass.getMsg(msg.source(),msg.target(),new HolyAvenger(),CMMsg.MSG_OK_ACTION,CMMsg.MSK_MALICIOUS_MOVE|CMMsg.TYP_UNDEAD,CMMsg.MSG_NOISYMOVEMENT,null);
if(msg.source().location().okMessage(msg.source(),msg2))
{
msg.source().location().send(msg.source(), msg2);
int damage=CMLib.dice().roll(1,15,0);
if(msg.value()>0)
damage=damage/2;
msg.addTrailerMsg(CMClass.getMsg(msg.source(),msg.target(),CMMsg.MSG_OK_ACTION,L("@x1 dispels evil within <T-NAME> and @x2 <T-HIM-HER>>!",name(),CMLib.combat().standardHitWord(Weapon.TYPE_BURSTING,damage))));
final CMMsg msg3=CMClass.getMsg(msg.source(),msg.target(),null,CMMsg.MSG_OK_VISUAL,CMMsg.MSG_DAMAGE,CMMsg.NO_EFFECT,null);
msg3.setValue(damage);
msg.addTrailerMsg(msg3);
}
}
} |
989e6219-5fb1-4455-8e70-409a5fb849e7 | 1 | public static JSONObject showNotFound() {
JSONObject jo = new JSONObject();
try
{
jo.put("rtnCode", "404 not found");
} catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return jo;
} |
0799b243-0835-43f8-a13b-ebc502b1f7db | 2 | public String toString()
{
StringBuilder s = new StringBuilder("[");
for(T x : this)
s.append(Objects.toString(x) + ", ");
if(size > 0)
s.setLength(s.length() - 2);
s.append("]");
return new String(s);
} |
4f1f76d1-fdfb-46b9-a8a7-35fa6ef45b94 | 4 | public void buscarNome(String nome){
ResultSet rs;
String sql = "SELECT * FROM alunos";
String nomes="Matric | Nome | Endereco\n\n";
try{
rs = meuState.executeQuery(sql);
while(rs.next()){
if(rs.getString("nome").toUpperCase().equals(nome.toUpperCase())){
nomes+=" "+rs.getString("matricula")+" | "+rs.getString("nome")+
" | "+rs.getString("endereco")+" | "+rs.getString("data")+"\n";
}
}
} catch (SQLException ex) {
Logger.getLogger(ConsultaSQL.class.getName()).log(Level.SEVERE, null, ex);
}
if(nomes.equals("Matric | Nome | Endereco\n\n")){
JOptionPane.showMessageDialog(null, "Nenhum nome encontrado!", "Erro", JOptionPane.PLAIN_MESSAGE);
}else{
JOptionPane.showMessageDialog(null, nomes.toUpperCase(), "Resultado da Pesquisa", JOptionPane.PLAIN_MESSAGE);
}
} |
1c2dee96-7165-444f-903d-7021df454512 | 7 | public void func_50020_b(int par1)
{
if (this.text.length() != 0)
{
if (this.field_50048_p != this.field_50042_o)
{
this.func_50031_b("");
}
else
{
boolean var2 = par1 < 0;
int var3 = var2 ? this.field_50042_o + par1 : this.field_50042_o;
int var4 = var2 ? this.field_50042_o : this.field_50042_o + par1;
String var5 = "";
if (var3 >= 0)
{
var5 = this.text.substring(0, var3);
}
if (var4 < this.text.length())
{
var5 = var5 + this.text.substring(var4);
}
this.text = var5;
if (var2)
{
this.func_50023_d(par1);
}
}
}
} |
9aa96667-4956-49f6-b763-3c08e61f564f | 4 | public static Object getValue(Object object, String fieldName) throws JStrykerException, IllegalArgumentException {
if (object == null) {
throw new IllegalArgumentException("Object cannot be null.");
}
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null.");
}
try {
Field field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(object);
} catch (NoSuchFieldException e) {
String message = String.format("%s does not have field %s.", object.getClass(), fieldName);
throw new JStrykerException(message, e);
} catch (IllegalAccessException e) {
throw new JStrykerException(e.getMessage(), e);
}
} |
a5e7ceb5-1782-46c0-9f08-c7435b7046ef | 6 | private void DownloadFormButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DownloadFormButtonActionPerformed
//Get selected value and split it to get the first integer
// which is the ID of the form
String ID = (String) FormsList.getSelectedValue();
String[] test = ID.split(" ");
Integer formID = Integer.parseInt(test[0]);
DatabaseConnection db = new DatabaseConnection();
Connection conn = db.connectToDB();
InputStream inStream = null;
String title = "";
String sql = "Select * From `HDForms` where ID = '"+formID+"'";
ResultSet rs = db.getResults(conn, sql);
try {
if (rs.next())
{
inStream = rs.getBinaryStream("Content");
title = rs.getString("Title");
}
} catch (SQLException ex) {
Logger.getLogger(AllForms.class.getName()).log(Level.SEVERE, null, ex);
}
OutputStream outStream;
try {
int read = 0;
byte[] bytes = new byte[1024];
String curDir = System.getProperty("user.dir");
outStream = new FileOutputStream(new File(title+".pdf"));
try {
while ((read = inStream.read(bytes)) != -1)
{
outStream.write(bytes, 0, read);
}
} catch (IOException ex) {
Logger.getLogger(AllForms.class.getName()).log(Level.SEVERE, null, ex);
}
try {
inStream.close();
outStream.flush();
outStream.close();
JOptionPane.showMessageDialog(frame,
"File downloaded to: " + curDir);
} catch (IOException ex) {
Logger.getLogger(AllForms.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(AllForms.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_DownloadFormButtonActionPerformed |
dae2e567-3020-4f46-8b43-bcf020370f99 | 2 | public String toString() {
StringBuilder s = new StringBuilder();
String NEWLINE = System.getProperty("line.separator");
s.append(V + " vertices, " + E + " edges " + NEWLINE);
for (int v = 0; v < V; v++) {
s.append(String.format("%d: ", v));
for (int w : adj[v]) {
s.append(String.format("%d ", w));
}
s.append(NEWLINE);
}
return s.toString();
} |
de8f3d2e-402f-465b-8b4c-6c81dffe1e91 | 0 | @Override
public IEmailKontakt create() {
EmailKontakt ek = new EmailKontakt();
return ek;
} |
1145726a-9e85-43f4-9d79-7137a2955b4d | 5 | private void createChromaticityCombo(PrintRequestAttributeSet set) {
Chromaticity[] chromacities = (Chromaticity[]) mService.getSupportedAttributeValues(Chromaticity.class, DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
if (chromacities != null && chromacities.length > 0) {
HashSet<Chromaticity> possible = new HashSet<>();
for (Chromaticity one : chromacities) {
possible.add(one);
}
ArrayList<InkChromaticity> choices = new ArrayList<>();
for (InkChromaticity chromaticity : InkChromaticity.values()) {
if (possible.contains(chromaticity.getChromaticity())) {
choices.add(chromaticity);
}
}
mChromaticity = new JComboBox<>(choices.toArray(new InkChromaticity[0]));
mChromaticity.setSelectedItem(PrintUtilities.getChromaticity(mService, set, true));
UIUtilities.setOnlySize(mChromaticity, mChromaticity.getPreferredSize());
LinkedLabel label = new LinkedLabel(CHROMATICITY, mChromaticity);
add(label, new PrecisionLayoutData().setEndHorizontalAlignment());
add(mChromaticity);
} else {
mChromaticity = null;
}
} |
568fd1a5-a410-4b2a-861e-a3d86c0399a9 | 3 | @Override
public boolean equals(Object obj) {
ItemSet itemSet = (ItemSet) obj;// necessary casting
if (this.itemSet.size() == itemSet.getItemSet().size()) {
for (int i = 0; i < this.itemSet.size(); i++) {
if (!this.itemSet.get(i).getItem()
.equals(itemSet.getItemSet().get(i).getItem())) {
return false;
}
}
return true;
}
return false;
} |
0caac513-4eba-4f98-9afd-a7aa154104c2 | 9 | protected void processRequest(HttpServletRequest request, HttpServletResponse response) {
ArrayList<Producto> lista = null;
String strChkCategoria = request.getParameter("chkCategoria");
String strChkMarca = request.getParameter("chkMarca");
boolean filtrarCategoria = false;
boolean filtrarMarca = false;
if (strChkCategoria != null && strChkCategoria.equals("true")) {
filtrarCategoria = true;
}
if (strChkMarca != null && strChkMarca.equals("true")) {
filtrarMarca = true;
}
try {
BeanDatos datos = new BeanDatos();
if (filtrarCategoria) {
if (filtrarMarca) {
lista = datos.getProductosPorCategoriaYMarca(new Integer(request.getParameter("categoria")), new Integer(request.getParameter("marca")));
} else {
lista = datos.getProductosPorCategoria(new Integer(request.getParameter("categoria")));
}
} else {
if (filtrarMarca) {
lista = datos.getProductosPorMarca(new Integer(request.getParameter("marca")));
} else {
lista = datos.getProductosSinFiltro();
}
}
request.setAttribute("Lista", lista);
} catch (Exception ex) {
ex.printStackTrace();
}
try {
request.getRequestDispatcher("/index.jsp").forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
} |
0659d49f-5284-406d-b157-5ed7e6224137 | 6 | public static MethodSlot createEvaluatorWrapperUnit(MethodSlot method) {
{ boolean variableargumentsP = ((BooleanWrapper)(KeyValueList.dynamicSlotValue(method.dynamicSlots, Stella.SYM_STELLA_METHOD_VARIABLE_ARGUMENTSp, Stella.FALSE_WRAPPER))).wrapperValue;
boolean evaluateargumentsP = method.methodEvaluateArgumentsP();
Cons wrappertree = MethodSlot.yieldEvaluatorWrapperTree(method);
MethodSlot wrappermethod = null;
if (method.methodReturnTypeSpecifiers().length() > 1) {
{ Object old$PrintreadablyP$000 = Stella.$PRINTREADABLYp$.get();
try {
Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true);
Stella.signalTranslationWarning();
if (!(Stella.suppressWarningsP())) {
Stella.printErrorContext(">> WARNING: ", Stella.STANDARD_WARNING);
{
Stella.STANDARD_WARNING.nativeStream.println();
Stella.STANDARD_WARNING.nativeStream.println(" During interpreted command evaluation only the");
Stella.STANDARD_WARNING.nativeStream.println(" first return value will be usable.");
}
;
}
} finally {
Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$000);
}
}
}
if (!evaluateargumentsP) {
KeyValueList.setDynamicSlotValue(method.dynamicSlots, Stella.SYM_STELLA_METHOD_EVALUATE_ARGUMENTSp, Stella.TRUE_WRAPPER, Stella.FALSE_WRAPPER);
}
if (variableargumentsP) {
KeyValueList.setDynamicSlotValue(method.dynamicSlots, Stella.SYM_STELLA_METHOD_VARIABLE_ARGUMENTSp, Stella.FALSE_WRAPPER, Stella.FALSE_WRAPPER);
}
wrappermethod = ((MethodSlot)(Cons.helpWalkAuxiliaryTree(wrappertree, true).theObject));
if (!evaluateargumentsP) {
KeyValueList.setDynamicSlotValue(method.dynamicSlots, Stella.SYM_STELLA_METHOD_EVALUATE_ARGUMENTSp, Stella.FALSE_WRAPPER, Stella.FALSE_WRAPPER);
}
if (variableargumentsP) {
KeyValueList.setDynamicSlotValue(method.dynamicSlots, Stella.SYM_STELLA_METHOD_VARIABLE_ARGUMENTSp, Stella.TRUE_WRAPPER, Stella.FALSE_WRAPPER);
}
return (wrappermethod);
}
} |
2d7c5c32-b9a8-4945-b597-93f03e692c48 | 2 | public boolean matchesNumber(String text) {
int numberCount = this.numberList.size();
for(int i = 0;i<numberCount;i++) {
String currentNumber = this.numberList.get(i).getLiteral();
boolean isMatchingExpression = text.equals(currentNumber);
if (isMatchingExpression) {
return true;
}
}
return false;
} |
c03eb898-a3c0-4f60-b646-12cf475851a0 | 2 | private void paintGrille(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
// Paint le grillage selon la dimension
g2d.setColor(Color.black);
int separattion;
// Lignes Horizontale
for(separattion=0 ; coordonneJeu.getNombreColonne()> separattion; separattion++)
g2d.draw(new Line2D.Double((dimension.getWidth()/coordonneJeu.getNombreColonne())*separattion,0,
(dimension.getWidth()/coordonneJeu.getNombreColonne())*separattion, dimension.getHeight()));
// Lignes Verticales
for(separattion=0 ; coordonneJeu.getNombreRangee()> separattion; separattion++)
g2d.draw(new Line2D.Double(0,(dimension.getHeight()/coordonneJeu.getNombreRangee())*separattion,
dimension.getWidth(),(dimension.getHeight()/coordonneJeu.getNombreRangee())*separattion));
} |
146b8482-e9be-4c36-ab46-2cfd00c50178 | 3 | protected static String convertColorToWebColorValue(Color c) {
String red = Integer.toHexString(c.getRed());
if (red.length() == 1) {
red = "0" + red;
}
String green = Integer.toHexString(c.getGreen());
if (green.length() == 1) {
green = "0" + green;
}
String blue = Integer.toHexString(c.getBlue());
if (blue.length() == 1) {
blue = "0" + blue;
}
return new StringBuffer().append("#").append(red).append(green).append(blue).toString();
} |
2000a1ee-54d4-4c62-9898-7f56ab26e4c3 | 4 | public static void copyDirectory(File sourceLocation , File targetLocation) throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists())
targetLocation.mkdir();
String[] children = sourceLocation.list();
for (int i=0; i<children.length; i++)
copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]));
} else {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from in stream to out stream.
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
in.close();
out.close();
}
} |
c088d1e3-0f0c-4e80-adeb-cb480705bde0 | 0 | public void insert(String name) {
Occurrence newOcc = new Occurrence(name);
newOcc.next = head;
head = newOcc;
} |
0555e59a-820f-446f-beab-a89e8438beae | 5 | public float advanceUpgrade(float progress) {
if (upgradeIndex == -1) upgradeIndex = nextUpgradeIndex() ;
if (upgradeIndex == -1) return 0 ;
//
// Update progress, and store the change for return later-
final int US = upgradeStates[upgradeIndex] ;
final float oldP = upgradeProgress ;
upgradeProgress = Visit.clamp(upgradeProgress + progress, 0, 1) ;
float amount = upgradeProgress - oldP ;
if (US == STATE_SALVAGE) amount *= -0.5f ;
//
// If progress is complete, change the current upgrade's state:
if (upgradeProgress >= 1) {
final float condition = integrity * 1f / maxIntegrity() ;
if (US == STATE_SALVAGE) deleteUpgrade(upgradeIndex) ;
else upgradeStates[upgradeIndex] = STATE_INTACT ;
upgradeProgress = 0 ;
upgradeIndex = -1 ;
integrity = maxIntegrity() * condition ;
}
return amount ;
} |
420c701b-1811-46d9-92f3-6f0f75f3d3ab | 1 | @Test public void checkImageGeneration() {
try {
reduct.setSourceImage(ImageIO.read(new File("src/test/resources/Mario.png")));
reduct.setDestBitDepth(3);
reduct.generateImage();
assertTrue(reduct.getReducedImage() != null);
} catch (IOException e) {
e.printStackTrace();
}
} |
d500a94e-2bb4-4913-8968-8578d5522e7b | 3 | public double getMinValue() {
if(times.length == 0) {
return -1;
}
double minval = times[0];
for(int i = 1; i < times.length; i++) {
if(times[i] < minval) {
minval = times[i];
}
}
return minval;
//returns minimum value of times-array
} |
9826c37a-c37b-43f2-ab90-c6039b6c5e09 | 9 | public static boolean isCubeInFrustum(float x, float z, float y, float size) {
for(int p=0;p<6;p++) {
if(frustum[p][0]*(x-size) + frustum[p][1]*(y-size) + frustum[p][2]*(z-size) + frustum[p][3]>0)
continue;
if(frustum[p][0]*(x+size) + frustum[p][1]*(y-size) + frustum[p][2]*(z-size) + frustum[p][3]>0)
continue;
if(frustum[p][0]*(x-size) + frustum[p][1]*(y+size) + frustum[p][2]*(z-size) + frustum[p][3]>0)
continue;
if(frustum[p][0]*(x+size) + frustum[p][1]*(y+size) + frustum[p][2]*(z-size) + frustum[p][3]>0)
continue;
if(frustum[p][0]*(x-size) + frustum[p][1]*(y-size) + frustum[p][2]*(z+size) + frustum[p][3]>0)
continue;
if(frustum[p][0]*(x+size) + frustum[p][1]*(y-size) + frustum[p][2]*(z+size) + frustum[p][3]>0)
continue;
if(frustum[p][0]*(x-size) + frustum[p][1]*(y+size) + frustum[p][2]*(z+size) + frustum[p][3]>0)
continue;
if(frustum[p][0]*(x+size) + frustum[p][1]*(y+size) + frustum[p][2]*(z+size) + frustum[p][3]>0)
continue;
return false;
}
return true;
} |
66d2d553-db25-4fd9-8560-8da8d17ca715 | 8 | public static void main(String[] args) {
try {
Console console = System.console();
if (console == null) {
System.err.println("Error : No console ! Please run it with command line :).");
System.exit(1);
}
// System.setSecurityManager(new java.rmi.RMISecurityManager());
ILoginModule lm = (ILoginModule) Naming.lookup("LoginModule");
IClient client = new Client();
String login = console.readLine("Please enter your login \t: ");
String password = console.readLine("Please enter room's password \t: ");
client.setName(login);
SPClient spClient = new SPClient(client);
final SPClient c2 = new SPClient(client);
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
c2.getChatroom().logout(c2);
} catch (RemoteException e1) {
e1.printStackTrace();
}
}
});
client.setFrame(new ClientFrame(spClient));
IChatroom cr = lm.login(spClient, password);
if (cr != null) {
client.setChatroom(cr);
client.getFrame().visible(true);
client.setConnected(true);
}
while (!client.isConnected()) {
System.out
.println("Connection failed : incorrect password or login already in use.");
login = console.readLine("Please enter your login \t: ");
password = console.readLine("Please enter room's password \t: ");
client.setName(login);
spClient = new SPClient(client);
cr = lm.login(spClient, password);
if (cr != null) {
client.setChatroom(cr);
client.getFrame().visible(true);
client.setConnected(true);
}
}
return;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
} |
500b0c5e-4c84-4294-8b17-c6b54cdbabb4 | 9 | @Override
protected boolean validateNode(Node<T> node) {
boolean bst = super.validateNode(node);
if (!bst)
return false;
AVLNode<T> avlNode = (AVLNode<T>) node;
int balanceFactor = avlNode.getBalanceFactor();
if (balanceFactor > 1 || balanceFactor < -1) {
return false;
}
if (avlNode.isLeaf()) {
if (avlNode.height != 1)
return false;
} else {
AVLNode<T> avlNodeLesser = (AVLNode<T>) avlNode.lesser;
int lesserHeight = 1;
if (avlNodeLesser != null)
lesserHeight = avlNodeLesser.height;
AVLNode<T> avlNodeGreater = (AVLNode<T>) avlNode.greater;
int greaterHeight = 1;
if (avlNodeGreater != null)
greaterHeight = avlNodeGreater.height;
if (avlNode.height == (lesserHeight + 1)
|| avlNode.height == (greaterHeight + 1))
return true;
return false;
}
return true;
} |
fed273d9-11c7-4649-a171-f5d5384fbbd6 | 7 | public static void drawWave (Graphics g, Wave wave,
int x, int y, int width, int height,
int viewStart, int viewEnd,
boolean selected,
int selectStart, int selectEnd)
{
double[] w;
if (wave != null && (w = wave.getWave()) != null) {
double samplePosition = viewStart;
double sampleIncrement = (viewEnd - viewStart + 1) / (double) width;
double amplitudeRatio = -(height/2-1) / wave.getMaxAmplitude();
if (selected) {
int x1 = sampleNoToCoord (selectStart, width,
wave.length(), viewStart, viewEnd);
if (x1 < width) {
if (x1 < 0) x1 = 0;
int x2 = sampleNoToCoord (selectEnd, width, wave.length(),
viewStart, viewEnd);
if (x2 >= width) x2 = width - 1;
g.setColor (selectedBgColor);
g.fillRect (x + x1, y, x2 - x1 + 1, height - 1);
}
}
g.setColor (axisColor);
g.drawLine (x, y+height/2, x+width-1, y+height/2);
g.setColor (waveColor);
double sum;
int oldV = (int)(w[(int)samplePosition] * amplitudeRatio) +
height/2;
int cx = x;
for (int i = 1; i < width; i++, cx++) {
samplePosition += sampleIncrement;
int v = (int)(w[(int)samplePosition] * amplitudeRatio) +
height/2;
g.drawLine (cx, oldV + y, cx+1, v + y);
oldV = v;
}
}
else {
g.setColor (axisColor);
g.drawLine (x, y+height/2, x+width-1, y+height/2);
}
} |
1d384206-68d7-45f6-9d7b-53595dbabe5c | 7 | void init(Molecule molec, EnergyFunction ef, double cutoff, DoubleMatrix1D dv,
ContSCObjFunction of, DoubleMatrix1D[] samples){
//Take the VDW interactions with distances below distCutoff
//if of and samples aren't null then count distances below distCutoff in any of the samples
//(from the DOFs of of)
//if they are null then just check distances in the current geometry
DOFVals = dv;
m = molec;
distCutoff = cutoff;
double VDWMultiplier = ef.getAmber96ext().vdwMultiplier;
V6 = VDWMultiplier*VDWMultiplier;//square then cube
V6=V6*V6*V6;
V12 = V6*V6;
if(includeElec){
Amber96ext a96ff = ef.getAmber96ext();//to get general parameters
distDepDielec = a96ff.distDepDielect;
coulombFactor = a96ff.constCoulomb / a96ff.dielectric;
}
//now traverse ef to get all VDW terms with specified distance, and their coefficients in ef
HashMap<Integer,double[]> terms = new HashMap<Integer,double[]>();
//will record pair of molecule atom numbers (as (lower number)*m.numberOfAtoms+(higherNumber) )
//mapped to the pair (coefficient for r^-12, coefficient for r^-6)
if(of==null){
getTerms(ef,terms,1);
}
else{
for(DoubleMatrix1D samp : samples){
of.setDOFs(samp);
HashMap<Integer,double[]> sampTerms = new HashMap<Integer,double[]>();
getTerms(ef,sampTerms,1);
//merge sampTerms into terms
for( int pair : sampTerms.keySet() ){
terms.put(pair, sampTerms.get(pair));
//coefficients will be the same for each of the samples
//since these come from the energy function, not geometry
}
}
}
//now fill in atomNums and coeffs accordingly
numTerms = terms.size();
atomNums = new int[2*numTerms];
coeffs = new double[2*numTerms];
resNums = new int[2*numTerms];
//resAtomNums = new int[2*numTerms];
atomNames = new String[2*numTerms];
if(includeElec)
elecCoeffs = new double[numTerms];
int count = 0;
for( int index : terms.keySet() ){
int atom1 = index / m.numberOfAtoms;
int atom2 = index % m.numberOfAtoms;
double termCoeffs[] = terms.get(index);
atomNums[2*count] = atom1;
atomNums[2*count+1] = atom2;
coeffs[2*count] = termCoeffs[0];
coeffs[2*count+1] = termCoeffs[1];
if(includeElec)
elecCoeffs[count] = termCoeffs[2];
getResBasedNums(2*count);
getResBasedNums(2*count+1);
count++;
}
System.out.println("Created SVE with "+numTerms+" terms");
} |
3bfff184-5184-4ae3-a5c9-23cd63d12ebf | 8 | @Override
public HashSet<Square> calcMoves(ChessBoard board) {
moves = new HashSet<Square>();
for(int i = 1; checkMove(board.getSquare(x+i, y)); i++) {}
for(int i = 1; checkMove(board.getSquare(x-i, y)); i++) {}
for(int i = 1; checkMove(board.getSquare(x, y+i)); i++) {}
for(int i = 1; checkMove(board.getSquare(x, y-i)); i++) {}
for(int i = 1; checkMove(board.getSquare(x+i, y+i)); i++) {}
for(int i = 1; checkMove(board.getSquare(x+i, y-i)); i++) {}
for(int i = 1; checkMove(board.getSquare(x-i, y+i)); i++) {}
for(int i = 1; checkMove(board.getSquare(x-i, y-i)); i++) {}
return moves;
} |
e56a5c8d-512a-4809-bebe-06d4538e9550 | 4 | public void addCustomer(Customer cust) {
Connection con = null;
PreparedStatement pstmt = null;
try {
DBconnection dbCon = new DBconnection();
Class.forName(dbCon.getJDBC_DRIVER());
con = DriverManager.getConnection(dbCon.getDATABASE_URL(),
dbCon.getDB_USERNAME(), dbCon.getDB_PASSWORD());
pstmt = con.prepareStatement("Insert Into customer "
+ "(cst_username, cst_password, cst_firstname, cst_lastname, cst_gender_id, cst_maritalstatus, cst_dateofbirth, cst_address, cst_phone, cst_mobile, cst_email, cst_remarks, cst_isactive) "
+ "Values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
pstmt.setString(1, cust.getUsername());
pstmt.setString(2, cust.getPassword());
pstmt.setString(3, cust.getFirstname());
pstmt.setString(4, cust.getLastname());
pstmt.setInt(5, cust.getGender());
pstmt.setInt(6, cust.getMaritalstatus());
pstmt.setDate(7, (Date) cust.getDateofbirth());
pstmt.setString(8, cust.getAddress());
pstmt.setString(9, cust.getPhone());
pstmt.setString(10, cust.getMobile());
pstmt.setString(11, cust.getEmail());
pstmt.setString(12, cust.getRemarks());
pstmt.setBoolean(13, cust.getIsactive());
pstmt.execute();
} catch (SQLException | ClassNotFoundException ex) {
System.err.println("Caught Exception: " + ex.getMessage());
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.err.println("Caught Exception: " + ex.getMessage());
}
}
} |
f59539b7-47bb-4ff5-8526-d543c3b99bd7 | 0 | @Override
public void keyTyped(KeyEvent e) {
} |
dea56863-7846-4921-a36e-e9c4301eecfc | 6 | private static void quickSort(char[] arr, int low, int high) {
int i = low, j = high;
int pivot = arr[low + (high - low)/2];
while(i <= j) {
while(arr[i] < pivot)
i++;
while(arr[j] > pivot)
j--;
if(i <= j) {
exchange(arr, i, j);
i++;
j--;
}
}
if(low < j)
quickSort(arr, low, j);
if(i < high)
quickSort(arr, i, high);
} |
ddaeb4e2-2dbd-4d8e-979e-3df934b894c9 | 5 | public double[] estimateGlobalLM(){
double[] lm = new double[getLMFeatureSize()];
double sum = 0;
for(_User u: m_users){
for(_Review r: u.getReviews()){
for(_SparseFeature fv: r.getLMSparse()){
lm[fv.getIndex()] += fv.getValue();
sum += fv.getValue();
}
}
}
for(int i=0; i<lm.length; i++){
lm[i] /= sum;
if(lm[i] == 0)
lm[i] = 0.0001;
}
return lm;
} |
dedc3dce-7084-4927-96c0-caed1e5e9dcc | 8 | protected static Ptg calcDCountA( Ptg[] operands )
{
if( operands.length != 3 )
{
return new PtgErr( PtgErr.ERROR_NA );
}
DB db = getDb( operands[0] );
Criteria crit = getCriteria( operands[2] );
if( (db == null) || (crit == null) )
{
return new PtgErr( PtgErr.ERROR_NUM );
}
int fNum = db.findCol( operands[1].getString().trim() );
if( fNum == -1 )
{
return new PtgErr( PtgErr.ERROR_NUM );
}
int count = 0;
// this is the colname to match
String colname = operands[1].getValue().toString();
for( int i = 0; i < db.getNRows(); i++ )
{ // loop thru all db rows
// check if current row passes criteria requirements
if( crit.passes( colname, db.getRow( i ), db ) )
{
// passes; now do action
String s = db.getCell( i, fNum ).getValue().toString();
if( (s != null) && !s.trim().equals( "" ) )
{
count++; // if field is not blank, increment count
}
}
}
return new PtgNumber( count );
} |
0bf08dc4-313c-40a0-97ca-4de0fe661c48 | 2 | public int dropHeight(Piece piece, int x) {
int[] skirt = piece.getSkirt();
int minDistIndex = 0;
int dist = height + 10;
for (int row = 0; row < skirt.length; row++) {
int checkDist = height - getColumnHeight(x + row) + skirt[row];
if (checkDist < dist) {
dist = checkDist;
minDistIndex = row;
}
}
int rHeight = getColumnHeight(x + minDistIndex) - skirt[minDistIndex];
return rHeight;
} |
d393ecbe-4811-42fa-9b32-5bee7a029ca1 | 2 | public static void main(String[] args) {
AuctionSystemServer server = new AuctionSystemServer();
AuctionConsole console = new AuctionConsole();
Alerter.setHandler(console);
server.init();
String input;
// Read input and repeat until "stop" is entered.
do {
input = console.readLine();
} while (input == null || !input.equals("stop"));
server.close();
} |
daac5c0c-cc71-4745-ad29-95d44f56f773 | 8 | public ArrayList<Position> inNeighboring(char[][] board, Position p, char x, int xSize, int ySize) {
ArrayList<Position> neighbor = new ArrayList<Position>();
if (p.x + 1 < xSize && board[p.x + 1][p.y] == x) {
neighbor.add(new Position(p.x + 1, p.y));
}
if (p.x - 1 >= 0 && board[p.x - 1][p.y] == x) {
neighbor.add(new Position(p.x - 1, p.y));
}
if (p.y + 1 < ySize && board[p.x][p.y + 1] == x) {
neighbor.add(new Position(p.x, p.y + 1));
}
if (p.y - 1 >= 0 && board[p.x][p.y - 1] == x) {
neighbor.add(new Position(p.x, p.y - 1));
}
return neighbor;
} |
aa6e7960-8c5d-4255-a16d-47c228531ace | 0 | public AttemptClientConnectEvent(Object source, ISocketServerConnection socketServerConnection) {
super(source);
this.setSocketServerConnection(socketServerConnection);
} |
f7a2b1dc-eed4-40b5-9129-9010503c3455 | 4 | private Box getDominantBox()
{
Box best = null;
int bestDim = 0;
for (Box b : boxes)
{
int dim = b.dominantDimension();
if ((dim > bestDim || best == null) && b.canSplit())
{
bestDim = dim;
best = b;
}
}
return best;
} |
1fa083f8-494e-4480-9cc0-b6ba61bef07a | 2 | private boolean find(int n, int k) {
boolean result = false;
while (n > 0) {
if (n % 10 == k) {
result = true;
break;
} else
n = n / 10;
}
return result;
} |
d556d8cf-282e-478b-864d-e58938c9bc8d | 4 | public void simulateRound() {
List<MovableObject> movableSnapshot = new ArrayList<>(mMovableObjects);
//iterate over snapshot since some interactions can modify movable list
for (MovableObject movable : movableSnapshot) {
Point2D nextPosition = movable.move();
if (!isInsideField(nextPosition) || movable.isOnSamePosition(nextPosition)) {
continue;
}
FieldObject fo = getObjectOnPos(nextPosition);
if (fo == null) {
movable.setNewPosition(nextPosition.x, nextPosition.y);
} else {
movable.interact(fo);
}
}
} |
9cf9b9ea-18a1-4a8f-8dbb-d2f0e863f1f9 | 0 | public double getSimilarity()
{
return _similarity;
} |
72c49b0e-40b6-47ba-b006-ac5fa261007c | 9 | @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
WeaponPerKiller other = (WeaponPerKiller) obj;
if (killer == null) {
if (other.killer != null) {
return false;
}
} else if (!killer.equals(other.killer)) {
return false;
}
if (weapon == null) {
if (other.weapon != null) {
return false;
}
} else if (!weapon.equals(other.weapon)) {
return false;
}
return true;
} |
8669f8a6-9306-4bd7-83f3-34b79f46fafc | 4 | @Override
public void mouseWheelMoved(MouseWheelEvent arg0)
{
//how much does the wheel turned?
int howMuch = arg0.getWheelRotation();
//how loud is the sound at the moment?
int percentage = audioSlider.getValue();
//no decision about how much the wheels turns
//use for every event just one step
//here forward -> louder
if(howMuch < 0)
{
percentage += 10;
if(percentage > 100)
{
percentage = 100;
}
}
//here backwards -> quieter
if(howMuch > 0)
{
percentage -= 10;
if(percentage < 0)
{
percentage = 0;
}
}
//change volume local:
audioSlider.setValue(percentage);
// //change the volume and the slider in the whole application
// vm.changeVolume(VolumeControlGUI.this,percentage);
} |
bd5b0a33-986f-4c42-ad13-90c5ed61e2c1 | 0 | public Transition[] getTransitions() {
return transitions;
} |
5ac290cc-8576-4a7a-87a5-0acfc0b62877 | 2 | public void setDAO(String daoLine) {
if (daoLine.equals("Mock")) {
dao = new MockDAO();
}
else if (daoLine.equals("MySQL")) {
dao = new MySQLDAO();
}
} |
f753c84a-f3bf-4224-a01b-4bbd9364381b | 6 | @Override
public void crash(final HTML container, final CSSClass cssClass) {
if ( Constants.fdebug )
Constants.logger.info("Logging " + this.getName( ));
final HTML h4 = HTML.create("h4", container);
h4.setValue("Dump of Registry");
final HTML table = HTML.create("table", container);
HTML tr = null;
tr = HTML.create("tr", table);
HTML.create("th", tr).setValue("Key");
HTML.create("th", tr).setValue("Value");
if ( Constants.fdebug )
Constants.logger.info("Generating Table");
final HashMap<Player, HashMap<String, String>> plainMap = this.registry.getPlainMap( );
final Set<Player> playerKeySet = plainMap.keySet( );
for (final Player player : playerKeySet) {
tr = HTML.create("tr", table);
if ( Constants.fdebug )
Constants.logger.info("A new Line");
final HashMap<String, String> valueMap = plainMap.get(player);
final Set<String> mapKeySet = valueMap.keySet( );
for (final String key : mapKeySet) {
if ( Constants.fdebug )
Constants.logger.info("Set Line");
final String value = valueMap.get(key);
HTML.create("td", tr).setValue(player.getName( ) + "." + key);
HTML.create("td", tr).setValue(value);
}
table.addChilds(tr);
}
} |
212f7405-88c4-49b4-9641-e757e1876b21 | 8 | @Override
public String getString()
{
try
{
try
{
// Object o= ((Formula) this.getParentRec()).getInternalRecords().get(0); PARENT REC of ARRAY or SHRFMLA is determined by referent (record) NOT necessarily same as actual Parent Rec
Boundsheet sht = getParentRec().getSheet();
// Formula pr= (Formula) sht.getCell(this.getReferent());
Formula f = ((Formula) getParentRec());
Object o;
if( f.isSharedFormula() )
{
o = FormulaParser.getExpressionString( f.shared.instantiate( f ) );
if( (o != null) && o.toString().startsWith( "=" ) )
{
return o.toString().substring( 1 );
}
return o.toString();
}
Formula pr = (Formula) sht.getCell( getReferent() );
o = pr.getInternalRecords().get( 0 );
if( o instanceof Array )
{
Array a = (Array) o;
return a.getFormulaString();
}
if( o instanceof StringRec )
{
//if this is a shared formula the attached string is the RESULT, not the formula string itself
if( ((Formula) getParentRec()).isSharedFormula() )
{
throw new IndexOutOfBoundsException( "parse it" );
}
StringRec s = (StringRec) o;
return s.getStringVal();
}
}
catch( IndexOutOfBoundsException e )
{ // subsequent formulas use same shared formula rec so find
throw new UnsupportedOperationException( "Shared formulas must be instantiated for calculation" );
}
}
catch( Exception e )
{
return "Array-Entered or Shared Formula";
}
return "Array-Entered or Shared Formula";
} |
2d15aa6a-59cd-4a91-a91d-d1e13184c453 | 9 | public void run()
{
synchronized(taskList)
{
while( true )
{
long time = System.currentTimeMillis();
if( nextTime <= time )
{
nextTask.getTask().runWatchdogTask(time);
nextTask.setLastExecMillis(time);
updateNextTask();
}
if( nextTask != null && taskList.size() > 0 )
{
time = System.currentTimeMillis();
long timeToSleep = nextTime - time;
if( timeToSleep > 0 )
{
try
{
taskList.wait(timeToSleep);
}
catch(InterruptedException e)
{
}
continue;
}
else if( timeToSleep == 0 || nextTime == 0 )
continue;
}
try
{
taskList.wait();
}
catch(InterruptedException e)
{
}
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.