method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
dae1b0af-5ee0-4ba2-9035-4e1484a91327
| 3 |
public FTPItemList(String hostname, String username, String password, String workingDirectory) throws IOException {
super(workingDirectory);
fTPConnector = new FTPConnector(hostname, username, password, workingDirectory);
this.workingDirectory = workingDirectory;
for (String item : fTPConnector.getNames()) {
if (item.endsWith(".jpg") || item.endsWith(".jpeg")) {
items.add(item);
}
}
}
|
2aa0f52e-2a38-4381-a51b-011f2feab287
| 3 |
@Override
public int filterRGB(int x, int y, int rgb) {
g = 0x0000FF00;
r = 0x00FF0000;
a = rgb & 0xFF000000;
if(percent >= 50)
{
r = 0;
if(percent < 80)
{
r = (int)((0xFF)* (1f - ((percent-50)/30f)) )* 0x10000;
}
}
else
{
g = 0;
if(percent > 30)
{
g = (int)((0xFF)* ((percent - 30)/30f) )* 0x100;
}
}
//return color
return (a|r|g);
}
|
dd9afd2e-997e-422c-af53-af505029e6d0
| 8 |
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String nonce = req.getParameter("nonce");
String echostr = req.getParameter("echostr");
String remoteSig = req.getParameter("signature");
String timestamp = req.getParameter("timestamp");
if (StringUtils.isBlank(remoteSig) || StringUtils.isBlank(timestamp) || StringUtils.isBlank(nonce)) return;
boolean pass = false;
try {
pass = WechatSignatureChecker.check(timestamp, nonce, remoteSig);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
if (pass) {
if (StringUtils.isNotEmpty(echostr)) {
PrintWriter out = resp.getWriter();
out.print(echostr);
closeIO(out);
return;
}
BufferedReader reader = req.getReader();
String xml = "";
String s;
while ((s = reader.readLine()) != null){
xml += s;
}
System.out.println(xml);
try {
xml = new String(xml.getBytes("ISO8859-1"), "UTF-8");
resp.setContentType("text/xml");
resp.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
String messageReturn = handleFactory.handle(xml);
out.write(messageReturn);
closeIO(out);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
1fc7bba1-b1ae-4120-9752-71c1d990d3e9
| 3 |
@Override
public boolean equals(Object obj) {
OBJIndex index = (OBJIndex) obj;
return vertexIndex == index.vertexIndex
&& texCoordIndex == index.texCoordIndex
&& normalIndex == index.normalIndex
&& tangentIndex == index.tangentIndex;
}
|
3e309aae-8461-4f82-aaf1-1809702456ee
| 5 |
public void add(String gram) {
if (name == null || gram == null) return; // Illegal
int len = gram.length();
if (len < 1 || len > NGram.N_GRAM) return; // Illegal
++n_words[len - 1];
if (freq.containsKey(gram)) {
freq.put(gram, freq.get(gram) + 1);
} else {
freq.put(gram, 1);
}
}
|
6fe1adfd-2ab9-4928-886c-275f5346990c
| 0 |
public static void main(String[] args)
{
MenuTest frame = new MenuTest();
frame.MenuFrame();
}
|
7b11f899-9757-494a-a609-da82b2e0ee44
| 3 |
public void wallSound() {
try {
Clip hit = AudioSystem.getClip();
hit.open(AudioSystem.getAudioInputStream
(Ball.class.getResource("Hit.wav")));
hit.start();
} catch (LineUnavailableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
}
}
|
cf398b9d-f3a2-4601-8821-efe581c6541b
| 4 |
public static double lorentzianInverseCDF(double mu, double gamma, double prob) {
if (prob < 0.0 || prob > 1.0) throw new IllegalArgumentException("Entered cdf value, " + prob + ", must lie between 0 and 1 inclusive");
double icdf = 0.0D;
if (prob == 0.0) {
icdf = Double.NEGATIVE_INFINITY;
} else {
if (prob == 1.0) {
icdf = Double.POSITIVE_INFINITY;
} else {
icdf = mu + gamma * Math.tan(Math.PI * (prob - 0.5)) / 2.0;
}
}
return icdf;
}
|
3f7cb13b-9aab-4378-b2c6-8047e637cf93
| 1 |
public void test_add_long_int() {
assertEquals(567L, iField.add(567L, 0));
assertEquals(567L + 1234L * 90L, iField.add(567L, 1234));
assertEquals(567L - 1234L * 90L, iField.add(567L, -1234));
try {
iField.add(LONG_MAX, 1);
fail();
} catch (ArithmeticException ex) {}
}
|
6e54a1e9-fc86-40b4-a7d6-5944d1910304
| 1 |
public static void main(String[] args) throws ClientProtocolException,
IOException, ParseException {
ConfModel confModel = null;
try {
confModel = readConf(args[0]);
} catch (Exception e) {
System.out.println("設定ファイルの読み込みに失敗しました。" + e.toString());
}
System.out.println("set OK");
String affiliate_url = "http://atq.ck.valuecommerce.com/servlet/atq/referral?sid=2219441&pid=877510753&vcptn="
+ confModel.getYahooAuctionModel().getAffiliatId() + "&vc_url=";
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost post = new HttpPost(YAHOO_AUCTION_URL);
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("appid", confModel
.getYahooAuctionModel().getApplicationKey()));
params.add(new BasicNameValuePair("sort", confModel.getSearchQuery()
.getSort()));
params.add(new BasicNameValuePair("order", confModel.getSearchQuery()
.getOrder()));
params.add(new BasicNameValuePair("page", confModel.getSearchQuery()
.getPage()));
params.add(new BasicNameValuePair("query", confModel.getSearchQuery()
.getQuery()));
post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse response = httpclient.execute(post);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
String contenString = IOUtils.toString(content);
System.out.println(contenString);
String json = jsonp2json(contenString);
readRestResult(affiliate_url, json);
}
|
52dc2c42-bc93-46be-b959-2df278503114
| 3 |
public static SeverityEnumeration fromString(String v) {
if (v != null) {
for (SeverityEnumeration c : SeverityEnumeration.values()) {
if (v.equalsIgnoreCase(c.toString())) {
return c;
}
}
}
throw new IllegalArgumentException(v);
}
|
aeee598c-09b2-4550-98a8-47e785b80dcb
| 6 |
private void update() {
if (game_started) {
try {
//pass player rectangles to pong
this.pong.update(this.playerA.getPlayerRectangle(), this.playerB.getPlayerRectangle());
this.notifyAll("pongUpdate", this.pong.getPongCoordinates());
//now get player updates
//this.playerA.getPlayerPosition()
if (pong.isOutOfLeftBound()) {
//server.onMessage("playerScore", 2);
rightScore++;
stop();
} else if (pong.isOutOfRightBound()) {
//server.onMessage("playerScore", 1);
leftScore++;
stop();
} else {
notifyAll("pongUpdate", this.pong.getPongCoordinates());
}
if (leftScore == 5) {
server.onMessage("someoneWon", 1);
stop();
} else if (rightScore == 5) {
server.onMessage("someoneWon", 2);
stop();
}
} catch (RemoteException ex) {
Logger.getLogger(PongGame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
786a06ed-d466-4bbe-be1b-7109d0f0f5a9
| 0 |
@Override
public void destroy() {
undoable = null;
node = null;
}
|
11b65661-c088-4d7b-b8c6-1c20de7ee073
| 1 |
public List<Monitor.Stats.Stat.Validate> getValidate() {
if (validate == null) {
validate = new ArrayList<Monitor.Stats.Stat.Validate>();
}
return this.validate;
}
|
f6bbaa4c-9b14-44ce-800f-050ba57a6460
| 9 |
public void writeBits(long value, int n) throws IOException
{
// Note: As this method is called quite frequently, I'm
// optimizing for speed instead of code readability. Consult
// your local C, Assembler or other bit fiddling wizard if you
// have trouble understanding it.
value = (value & (-1L >>> (64-n))) | (((long)buffer) << n);
n += bitsLeft;
int remaining = n%8;
int bytes = n/8;
switch (bytes) {
case 8:
bufferTmp[0] = (byte)(value >> (56+remaining));
case 7:
bufferTmp[1] = (byte)(value >> (48+remaining));
case 6:
bufferTmp[2] = (byte)(value >> (40+remaining));
case 5:
bufferTmp[3] = (byte)(value >> (32+remaining));
case 4:
bufferTmp[4] = (byte)(value >> (24+remaining));
case 3:
bufferTmp[5] = (byte)(value >> (16+remaining));
case 2:
bufferTmp[6] = (byte)(value >> (8+remaining));
case 1:
bufferTmp[7] = (byte)(value >> remaining);
out.write(bufferTmp, 8-bytes, bytes);
case 0:
bitsLeft = remaining;
// Store the remaining bits. Don't bother with masking out
// the 8-remaining bits in the low order byte of value -
// we're simply ignoring them the next time around...
buffer = (byte)value;
break;
default:
throw new IndexOutOfBoundsException(Integer.toString(n));
}
}
|
ce03ff2f-0bfc-4d61-ac5d-b21876e14279
| 6 |
public void quickSort(int start, int end) {
int i = start, j = end;
// find pivot, middle element
int pivot = numbers[start + (end - start) / 2];
//iterate till we are left with values which need
//to be exchanged
while (i <= j) {
while (numbers[i] < pivot) {
i++;
}
while (numbers[j] > pivot) {
j--;
}
//exchange is value is larger than the pivot in
//the left list and
//smaller than the pivot in the right list
if (i <= j) {
exchange(i, j);
i++;
j--;
}
}
if (start < end) {
quickSort(start, j);
}
if (i < end) {
quickSort(i, end);
}
}
|
07432e43-3f97-41d1-a71d-a74db846d403
| 0 |
public boolean isLeft() {
return left;
}
|
bcfd10e2-c459-4c43-a803-1aa21f056700
| 8 |
public void checkCollisions()
{
// Check for collisions with walls.
if (objects.isWallAtPosition(x, y))
{
x = oldX;
y = oldY;
inputDelay = 0;
// Bounce off of any walls that the player runs into.
switch (facing)
{
case UP:
facing = Direction.DOWN;
break;
case DOWN:
facing = Direction.UP;
break;
case LEFT:
facing = Direction.RIGHT;
break;
case RIGHT:
facing = Direction.LEFT;
break;
}
}
// Check for collisions with rupees.
for (int i = 0; i < objects.rupees.size(); i++)
{
Rupee rupee = objects.rupees.get(i);
if (!rupee.increaseY && isCollidingWithPrecise(rupee))
{
// Start the collection animation for the rupee.
rupee.increaseY = true;
objects.audioManager.playRupeeSound();
}
}
}
|
b15c8bf4-324b-487c-b2dd-da76b77e4b56
| 7 |
void copy (TextPosition Start, TextPosition End)
{
if (Start == null || End == null) return;
TextPosition P1, P2;
if (Start.before(End))
{
P1 = Start;
P2 = End;
}
else if (End.before(Start))
{
P1 = End;
P2 = Start;
}
else return;
String s = "";
ListElement e = P1.L;
while (e != null && e != P2.L)
{
s = s + ((Line)e.content()).getblock() + "\n";
e = e.next();
}
if (e != null) s = s + ((Line)e.content()).getblock();
new ClipboardCopy(this, this, s);
}
|
c6670627-8f1b-4eef-bf66-5131bfd73cf9
| 5 |
public boolean isDone() {
if (line.contains("|")) {
String connect = line.split("\\|")[1];
String[] parameter = connect.split(",");
if (parameter[0].equals("ACTIVATE")) {
level.connect(parameter[1]).active = true;
}
return true;
} else {
if (count < line.length()) {
fnt.drawString(200, 550, line.substring(0, count));
if (strat==0){
count++;
strat=2;
}else{
strat--;
}
return false;
} else if (magic > 0) {
fnt.drawString(200, 550, line.substring(0, count));
magic--;
return false;
} else {
return true;
}
}
}
|
c6fbdd5b-fd3f-4a70-83f5-eb5320dc0421
| 7 |
public void saveControle() {
facesContext = FacesContext.getCurrentInstance();
try {
if(valorTotal.equals("")){
valorTotal = "0";
}
if(valorUnitario.equals("")){
valorUnitario = "0";
}
controle.setCtrl_limiteUnitario(Integer.parseInt(valorUnitario));
controle.setCtrl_limiteValor(Float.parseFloat(valorTotal));
if(controle.getCtrl_limiteUnitario()>0){
if(controle.getCtrl_limiteValor()==0){
controle.setCtrl_limiteValor(controle.getCtrl_limiteUnitario()* procedimento.getDes_valor());
}
else if(controle.getCtrl_limiteValor()>0){
if(controle.getCtrl_limiteUnitario()==0){
controle.setCtrl_limiteUnitario((Integer) controle.getCtrl_limiteValor().intValue() / procedimento.getDes_valor().intValue());
}
}
}
controle.setExame(procedimento);
genericDAO.save(controle);
facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Sucesso","Restrição salva com Sucesso"));
} catch (Exception ex) {
Logger.getLogger(ControleMB.class.getName()).log(Level.SEVERE, null, ex);
}
}
|
010f9da2-88cc-4bc0-832c-289d800d313b
| 3 |
@Override
public List<Study> getStudies() {
if(studies != null)
return studies;
File[] imageFiles = directory.listFiles();
Arrays.sort(imageFiles);
studies = new ArrayList<Study>();
for(File f : imageFiles)
if(f.isDirectory())
studies.add(new LocalStudy(f));
return studies;
}
|
85558874-12cc-4553-8aaa-eaedfe544b31
| 4 |
public void clickBlock(int var1, int var2, int var3, int var4) {
this.mc.theWorld.onBlockHit(this.mc.thePlayer, var1, var2, var3, var4);
int var5 = this.mc.theWorld.getBlockId(var1, var2, var3);
if(var5 > 0 && this.curBlockDamage == 0.0F) {
Block.blocksList[var5].onBlockClicked(this.mc.theWorld, var1, var2, var3, this.mc.thePlayer);
}
if(var5 > 0 && Block.blocksList[var5].blockStrength(this.mc.thePlayer) >= 1.0F) {
this.sendBlockRemoved(var1, var2, var3, var4);
}
}
|
bae0cb28-2204-4a75-ba1c-3d4231630695
| 5 |
protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) {
int b,c;
int remaining = in.remaining();
while (remaining-- > 0) {
if (out.remaining() < 1)
return CoderResult.OVERFLOW;
b = in.get();
if (b == ESCAPE) {
if (remaining-- == 0) {
in.position(in.position() - 1);
return CoderResult.UNDERFLOW;
}
b = in.get();
c = BYTE_TO_CHAR_ESCAPED[b & 0xFF];
} else {
c = BYTE_TO_CHAR[b & 0xFF];
}
if (c == -1) {
in.position(in.position() - 1);
return CoderResult.malformedForLength(1);
}
out.put((char)c);
}
return CoderResult.UNDERFLOW;
}
|
bd79ec1f-5a26-4647-a838-0aea2ff5d8f1
| 6 |
public static void main(String[] args) {
if(args.length > 0){
String IP;
if(args.length == 2){
FloodlightProvider.setPort(args[1]);
}
IP = args[0];
try {
if (InetAddress.getByName(IP).isReachable(5000)) {
// Here we dispose this screen and launch the GUI
new Gui(IP);
} else {
System.out.println("Could not reach controller from parameter specified, going to main screen.");
try {
new Startup();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException e) {
//Fail silently
}
}
else{
try {
new Startup();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
55efa0da-2138-4f18-9496-6de4160ee952
| 3 |
public void filledSquare(double x, double y, double r) {
if (r < 0) throw new RuntimeException("square side length can't be negative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*r);
double hs = factorY(2*r);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.fill(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
}
|
ca1dba1b-046e-45b3-a42a-c23b88dc4836
| 4 |
private synchronized void processEvent(Sim_event ev) {
double currentTime = GridSim.clock();
boolean success = false;
if(ev.get_src() == myId_) {
if (ev.get_tag() == UPT_SCHEDULE) {
if(currentTime > lastSchedUpt) {
// updates the schedule, finish jobs, etc.
updateSchedule();
lastSchedUpt = currentTime;
}
success = true;
}
}
if(!success) {
processOtherEvent(ev);
}
}
|
33063a42-bd5f-494c-a9b3-43cd24d3aaa2
| 6 |
public int[][][] getCubes() {
int[][][] copy = new int[length][width][height - SAFE_HEIGHT];
for(int x = 0; x < length; x++) {
for(int y = 0; y < width; y++) {
for(int z = 0; z < height - SAFE_HEIGHT; z++) {
copy[x][y][z] = cubes[x][y][z];
}
}
}
if(fallingPiece != null) {
for(int i = 0; i < 4; i++) {
IntPoint p = fallingPiece.getBlocks()[i];
if(p.getZ() < height - SAFE_HEIGHT) {
copy[p.getX()][p.getY()][p.getZ()] = fallingPiece
.getColor();
}
}
}
return copy;
}
|
aae151d4-dcbd-44c3-9976-a333bd10fa12
| 0 |
public static int getSize(){
return size;
}
|
f08d87ea-1fb6-4b06-a156-58916bde8697
| 8 |
void setStyle(Widget widget) {
Point sel = text.getSelectionRange();
if ((sel == null) || (sel.y == 0)) return;
StyleRange style;
for (int i = sel.x; i<sel.x+sel.y; i++) {
StyleRange range = text.getStyleRangeAtOffset(i);
if (range != null) {
style = (StyleRange)range.clone();
style.start = i;
style.length = 1;
} else {
style = new StyleRange(i, 1, null, null, SWT.NORMAL);
}
if (widget == boldButton) {
style.fontStyle ^= SWT.BOLD;
} else if (widget == italicButton) {
style.fontStyle ^= SWT.ITALIC;
} else if (widget == underlineButton) {
style.underline = !style.underline;
} else if (widget == strikeoutButton) {
style.strikeout = !style.strikeout;
}
text.setStyleRange(style);
}
text.setSelectionRange(sel.x + sel.y, 0);
}
|
0dd2e74f-93d5-460b-84b6-780de31bd31b
| 8 |
@Override
public List<Point> startPathfinder(boolean diagonalAllowed) {
begin.setWaveNum(0);
setWaveNums();
// System.out.println("----------------");
// for (int i = 0; i < cells.length; i++) {
// for (int j = 0; j < cells.length; j++) {
// if (begin.getX() == j && begin.getY() == i) {
// System.out.print("<" + cells[j][i].getWavenum() + ">");
// continue;
// }
// if (end.getX() == j && end.getY() == i) {
// System.out.print(">" + cells[j][i].getWavenum() + "<");
// continue;
// }
// if (cells[j][i] != null) {
// System.out.print(cells[j][i].getWavenum() + " ");
// }
// else
// {
// System.out.print(-1);
// }
// }
// System.out.println("");
// }
//End of marking
//bactracking
ArrayList<Point> arr = new ArrayList<>();
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};
int d = end.getWavenum();
Cell curCell = end;
while (d > 0) {
for (int i = 0; i < 4; ++i) {
if (curCell.getX() + dx[i] < cells.length
&& curCell.getY() + dy[i] < cells.length
&& curCell.getX() + dx[i] >= 0
&& curCell.getY() + dy[i] >= 0
&& cells[curCell.getX() + dx[i]][curCell.getY() + dy[i]] != null
&& d - 1 == cells[curCell.getX() + dx[i]][curCell.getY() + dy[i]].getWavenum()) {
arr.add(new Point(cells[curCell.getX() + dx[i]][curCell.getY() + dy[i]].getX(), cells[curCell.getX() + dx[i]][curCell.getY() + dy[i]].getY()));
curCell = cells[curCell.getX() + dx[i]][curCell.getY() + dy[i]];
break;
}
}
d--;
}
Collections.reverse(arr);
return arr;
}
|
6d1d2b39-fab3-4287-9952-7dc099405d3c
| 0 |
private void start() {
new Thread(this).start();
}
|
e802ba18-ff8d-455c-a9cc-91d17a4a540a
| 5 |
public ReplacingInputStream( InputStream in,
Map<byte[],byte[]> replacementMap
)
throws NullPointerException {
super();
if( in == null )
throw new NullPointerException( "Cannot create ReplacingInputStreams from null-streams." );
if( replacementMap == null )
throw new NullPointerException( "Cannot create ReplacingInputStreams with null-map." );
// Convert key set to list
List<byte[]> keyList = new ArrayList<byte[]>( replacementMap.size() );
Iterator<Map.Entry<byte[],byte[]>> iter = replacementMap.entrySet().iterator();
while( iter.hasNext() ) {
Map.Entry<byte[],byte[]> entry = iter.next();
byte[] key = entry.getKey();
byte[] value = entry.getValue();
if( key == null )
throw new NullPointerException( "Cannot create ReplacingInputStreams with null-keys." );
if( value == null )
throw new NullPointerException( "Cannot create ReplacingInputStreams with null-replacements." );
keyList.add( key );
}
this.multiIn = new MultiStopMarkInputStream( in, keyList );
this.replacementMap = replacementMap;
}
|
7432b9b6-aa69-4fd9-9160-e66b190a8b97
| 8 |
void register_init(IFCModel __model) throws Exception {
JButton[] buttons;
JMenuItem[] items;
JMenu menu;
int _MAX;
_model = __model;
_persistence = new HashMap();
_objectfile = new File(_CDEFAULT_OBJECT_FILE);
_message = new MessagePanel();
_tournament = new TournamentPanel();
_frame = new JFrame();
_menubar = new JMenuBar();
menu = _model.exportMenu();
if (menu != null) {
_menubar.add(menu);
}
menu = _tournament.exportMenu();
if (menu != null) {
_menubar.add(menu);
}
menu = new JMenu("Storage");
_save = new JMenuItem("Save State");
_save.addActionListener(this);
_load = new JMenuItem("Load State");
_load.addActionListener(this);
menu.add(_save);
menu.add(_load);
_menubar.add(menu);
_toolbar = new JToolBar();
buttons = _model.exportTools();
if (buttons != null) {
_MAX = buttons.length;
for (int i=0; i < _MAX; i++) {
_toolbar.add(buttons[i]);
}
}
buttons = _message.exportTools();
if (buttons != null) {
_MAX = buttons.length;
for (int i=0; i < _MAX; i++) {
_toolbar.add(buttons[i]);
}
}
_saveb = new JButton(_CSAVE_ICON);
_saveb.addActionListener(this);
_toolbar.add(_saveb);
_loadb = new JButton(_CLOAD_ICON);
_loadb.addActionListener(this);
_toolbar.add(_loadb);
buttons = _tournament.exportTools();
if (buttons != null) {
_MAX = buttons.length;
for (int i=0; i < _MAX; i++) {
_toolbar.add(buttons[i]);
}
}
_view = _model.exportViewPanel();
_control = _model.exportControlPanel();
_display = new JTabbedPane();
_display.addTab("View", _view);
_display.addTab("Tournament", _tournament.exportViewPanel());
_splitv = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
_splitv.setLeftComponent(_control);
_splitv.setRightComponent(_message);
_splitv.setOneTouchExpandable(true);
_splith = new JSplitPane();
_splith.setLeftComponent(_display);
_splith.setRightComponent(_splitv);
_splith.setOneTouchExpandable(true);
resetViewSize();
_frame.getContentPane().setLayout(new BorderLayout());
_frame.setTitle(_model.name());
_frame.setJMenuBar(_menubar);
_frame.getContentPane().add(_toolbar, BorderLayout.NORTH);
_frame.getContentPane().add(_splith, BorderLayout.CENTER);
_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
_frame.pack();
_frame.setVisible(true);
}
|
f32f9b4f-9420-4cc4-9cb4-e4b0dc1a4173
| 4 |
private int startReservations() {
double refTime = GridSim.clock();
LinkedList<ScheduleItem> startedRes = new LinkedList<ScheduleItem>();
int numStartRes = 0;
for (ServerReservation sRes : reservTable.values()) {
if(sRes.getStartTime() <= refTime &&
sRes.getReservationStatus() == ReservationStatus.COMMITTED) {
sRes.setStatus(ReservationStatus.IN_PROGRESS);
startedRes.add(sRes);
numStartRes++;
super.sendInternalEvent(sRes.getActualFinishTime()-refTime,
ConservativeBackfill.UPT_SCHEDULE);
}
}
//------------- USED FOR DEBUGGING PURPOSES ONLY ------------------
if(numStartRes > 0) {
visualizer.notifyListeners(this.get_id(), ActionType.ITEM_STATUS_CHANGED,
true, startedRes);
visualizer.notifyListeners(this.get_id(), ActionType.SCHEDULE_CHANGED, true);
}
//------------------------------------------------------------------
return numStartRes;
}
|
c235d927-482e-4100-b8c1-60b4e83c0955
| 5 |
public void firemaking_process() {
for(int i = 0; i < MaxObjects; i++) {
if (ObjectFireID[i] > -1) {
if (ObjectFireDelay[i] < ObjectFireMaxDelay[i]) {
ObjectFireDelay[i]++;
} else {
for (int j = 1; j < server.playerHandler.maxPlayers; j++) {
if (server.playerHandler.players[j] != null) {
server.playerHandler.players[j].FireDelete[i] = true;
}
}
}
}
}
}
|
c6cbd733-573f-4ed7-8513-4b57abc332f5
| 2 |
public static void add(AObject object) throws Exception // add an object to the stage
{
if (object instanceof FailBox)
{
endZone = (FailBox) object;
}
else
{
if(object instanceof Pinball)
{
pinball = (Pinball) object;
}
else
{
throw new Exception("Object not supported");
}
}
}
|
e549ae99-a949-47bc-913a-49097cff5320
| 4 |
public void run() {
info("Route-" + hashCode() + " entering run()");
try {
while (!stopped()) {
try {
if (serverSocket == null) {
info("Thread-" + Thread.currentThread().hashCode() + " Route-" + hashCode() + " constructing new ServerSocket on port " + local_port);
serverSocket = new ServerSocket(local_port);
}
Socket localSocket, remoteSocket;
try {
info("waiting for connection to serversocket on port " + local_port);
info("Thread-" + Thread.currentThread().hashCode() + " Route-" + hashCode() + " calling accept()");
localSocket = serverSocket.accept();
info("connection received on port " + local_port);
info("connecting to remote socket: host: " + remote_hostname + ", port: " + remote_port);
remoteSocket = new Socket(remote_hostname, remote_port);
info("remote socket connected, constructing connection processor ...");
final ConnectionProcessorImpl proc = new ConnectionProcessorImpl(localSocket.getInputStream(),
localSocket.getOutputStream(),
remoteSocket.getInputStream(),
remoteSocket.getOutputStream(),
this.name,
this.log_dir,
filterConfigs);
synchronized(processors) { processors.add(proc); }
info("starting connection processor impl thread for " + proc.hashCode() + " ...");
new Thread(proc).start();
info("connection processor impl thread started.");
//proc.run();
} catch (java.net.SocketException ignored) {
// happens if the serverSocket is closed while we're blocking on accept()
}
} catch (IOException e) {
// thrown by ServerSocket construction
warn("Route-" + hashCode() + " run() catch #2: " + e.getMessage());
}
}
} finally {
info("Route-" + hashCode() + " leaving run()");
}
}
|
1be1fba6-2316-40a1-852f-9b8dd244b8c6
| 7 |
public void run(){
output.println("Connected");
String inputLine;
try {
while ((inputLine = input.readLine()) != null) {
if (inputLine.equals("Combine file.")){
System.out.println("Combining file.");
ShamirShare fileShares = getAllFileSlice();
ShamirShare toCombine = new ShamirShare();
toCombine.combine(fileShares);
break;
}
if (inputLine.equals("Split file.")){
System.out.println("Splitting file.");
String fileName = input.readLine();
int fileSize = Integer.parseInt(input.readLine());
splitFile(fileName, fileSize, socket);
output.println("File splitting done.");
break;
}
if (inputLine.equals("Sending shares.")){
System.out.println("Receiving shares from "+socket.getInetAddress());
ShamirShare secretShare = new ShamirShare();
secretShare.setFileName(input.readLine());
secretShare.setNoOfShares(Integer.parseInt((input.readLine())));
secretShare.setPrime(new BigInteger(input.readLine().getBytes()));
secretShare.setThreshold(Integer.parseInt((input.readLine())));
BigInteger tempPrime = new BigInteger(input.readLine().getBytes());
int tempIndex = Integer.parseInt((input.readLine()));
Share tempShare = new Share(tempIndex, tempPrime);
ArrayList<Share> tempArray = new ArrayList<Share>();
tempArray.add(tempShare);
secretShare.setShareArr(tempArray);
output.println("Acknowledged.");
localFileSlice(secretShare);
break;
}
if (inputLine.equals("Give me slice.")){
System.out.println("Sending file slice.");
ShamirShare local = getLocalSlice();
output.println(""+local.getShareArr().get(0).getShareIndex());
output.println(new String(local.getShareArr().get(0).getShare().toByteArray()));
break;
}
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
48b0426c-1cae-4a1c-9ded-0f0d7b9cb1a6
| 7 |
protected int findPrototypeId(String s)
{
int id;
// #generated# Last update: 2007-05-09 08:15:24 EDT
L0: { id = 0; String X = null; int c;
int s_length = s.length();
if (s_length==11) {
c=s.charAt(0);
if (c=='c') { X="constructor";id=Id_constructor; }
else if (c=='i') { X="importClass";id=Id_importClass; }
}
else if (s_length==13) { X="importPackage";id=Id_importPackage; }
if (X!=null && X!=s && !X.equals(s)) id = 0;
break L0;
}
// #/generated#
return id;
}
|
9bbcc530-28e7-4ff0-a82e-478bafdca593
| 6 |
static String getCharsetFromContentType(String contentType) {
if (contentType == null) return null;
Matcher m = charsetPattern.matcher(contentType);
if (m.find()) {
String charset = m.group(1).trim();
charset = charset.replace("charset=", "");
if (charset.isEmpty()) return null;
try {
if (Charset.isSupported(charset)) return charset;
charset = charset.toUpperCase(Locale.ENGLISH);
if (Charset.isSupported(charset)) return charset;
} catch (IllegalCharsetNameException e) {
// if our advanced charset matching fails.... we just take the default
return null;
}
}
return null;
}
|
de27bf31-4d7a-4d69-b9cd-3f156a2441e9
| 7 |
private boolean hasFFmpegArgumentsName(String name)
{
boolean ret = false;
if (connection == null || name == null)
return ret;
PreparedStatement pstat = null;
try {
pstat = connection.prepareStatement("SELECT COUNT(*) FROM " + FFmpegArgumentsTableName + " WHERE Name = ?");
pstat.setString(1, name);
ResultSet rs = pstat.executeQuery();
if (rs.next() && rs.getInt(1) == 1)
ret = true;
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (pstat != null)
try {
pstat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return ret;
}
|
66571540-a2fd-4b2e-89fc-6590d3f14334
| 5 |
private void clearBuffer(){
if (isFirstLine && document.getLength() != 0){
buffer.insert(0, "\n");
}
isFirstLine = false;
String line = buffer.toString();
try{
if (isAppend){
int offset = document.getLength();
document.insertString(offset, line, attributes);
textComponent.setCaretPosition( document.getLength() );
}
else{
document.insertString(0, line, attributes);
textComponent.setCaretPosition( 0 );
}
}
catch (BadLocationException ble) {}
if (printStream != null){
printStream.print(line);
}
buffer.setLength(0);
}
|
952f6724-edcb-4ff0-b14b-f51214608f77
| 5 |
private static boolean check(World world, int x0, int y0, int z0)
{
for(int y = 0; y < _blocks.length; y++)
{
for(int z = 0; z < _blocks[y].length; z++)
{
for(int x = 0; x < _blocks[y][z].length; x++)
{
if(_blocks[y][z][x] == null)
{
continue;
}
if(!_blocks[y][z][x].matches(world.getBlockAt(x0 + x, y0 + y, z0 + z)))
{
return false;
}
}
}
}
return true;
}
|
f4cbc790-2c37-4039-a941-6d2f88c3341a
| 7 |
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void registerSuccMsg(Map<String, String> record, int type) {
// ***@LiWei***以下为解决超过4000字符,保存异常添加代码***//
// 如果消息内容过长,截取一部分保存
String body = record.get("body");
if (body == null) {
body = "";
} else {
try {
byte[] bytes = body.getBytes();
if (bytes.length > 3800) {
body = new String(bytes, 0, 3800);
System.out.println(body);
}
} catch (Exception e) {
e.printStackTrace();
}
}
record.put("body", body);
// ***@LiWei***以上为解决超过4000字符,保存异常添加代码***//
// 是否发邮件
boolean isMailActived = (Integer.valueOf(Integer.toHexString(type)) &
Integer.valueOf(Integer.toHexString(1))) > 0 ? true : false;
// 是否发短信
boolean isSmsActived = (Integer.valueOf(Integer.toHexString(type)) &
Integer.valueOf(Integer.toHexString(2))) > 0 ? true : false;
if (isMailActived) {
registerMailLog(record);
}
if (isSmsActived) {
registerSmsLog(record);
}
registerMsgLog(record);
}
|
41c01e9e-4f1b-460e-9968-88ffc56d9bb3
| 2 |
private void breakUp(final EntityHandler handler) {
this.kill();
// smallest asteroids don't break anymore
if (this.size <= 2)
return;
// if EntityLimit is reached no more new asteroids
if (!handler.isUnderEntityLimit())
return;
// FIXME: causes game to freeze
handler.getFactory().addLater().createAsteroid(this.pos.copy(), new Vector2d(), this.size / 2, getClientId());
handler.getFactory().addLater().createAsteroid(this.pos.copy(), new Vector2d(), this.size / 2, getClientId());
}
|
b6748ab2-0cac-4069-8cbb-813d79e558d4
| 9 |
public static int kthSmallest(int[][] matrix, int k) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int m = matrix.length;
int n = matrix[0].length;
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
return b - a;
}
});
for (int i = 0; i < m; i++) {
printPQ(new PriorityQueue<>(pq));
if (pq.size() == k && matrix[i][0] > pq.peek()) {
break;
}
for (int j = 0; j < n; j++) {
if (pq.size() == k) {
if (pq.peek() > matrix[i][j]) {
pq.poll();
pq.offer(matrix[i][j]);
}
} else {
pq.offer(matrix[i][j]);
}
}
}
return pq.peek();
}
|
8b74c9bc-b462-49f9-96bb-c7b600841d1c
| 8 |
public static DNSRecord Parse(ByteBuffer aBuffer) throws IOException {
DNSRecord record = null;
DNSEntry internalEntry = DNSEntry.Parse(aBuffer);
int ttl = aBuffer.getInt();
int len = DNSEntry.getUnsignedShort(aBuffer);
assert(len != 0);
switch(internalEntry._eType) {
case A:
case AAAA:
record = new Address();
break;
case CNAME:
case PTR:
record = new Pointer();
break;
case TXT:
record = new Text();
break;
case SRV:
record = new Service();
break;
case HINFO:
// Maybe we should do something with those
break;
default :
break;
}
if(record != null) {
record._Entry = internalEntry;
record._iTTL = ttl;
record.parseInstance(aBuffer, len);
}
else
aBuffer.position(aBuffer.position() + len);
return record;
}
|
8f008724-d902-4b9d-92b9-f78d2b75f06b
| 1 |
public void del()
{
try
{
mesh.delTriangles( triangles );
}
catch ( Exception e )
{
e.printStackTrace();
System.exit( 0 );
}
}
|
d0927437-f8f0-46ec-8e9f-f280251dcb98
| 2 |
public void test_set_RP_int_intarray_String_Locale() {
BaseDateTimeField field = new MockPreciseDurationDateTimeField();
int[] values = new int[] {10, 20, 30, 40};
int[] expected = new int[] {10, 20, 30, 40};
int[] result = field.set(new TimeOfDay(), 2, values, "30", null);
assertEquals(true, Arrays.equals(result, expected));
values = new int[] {10, 20, 30, 40};
expected = new int[] {10, 20, 29, 40};
result = field.set(new TimeOfDay(), 2, values, "29", Locale.ENGLISH);
assertEquals(true, Arrays.equals(result, expected));
values = new int[] {10, 20, 30, 40};
expected = new int[] {10, 20, 30, 40};
try {
field.set(new TimeOfDay(), 2, values, "60", null);
fail();
} catch (IllegalArgumentException ex) {}
assertEquals(true, Arrays.equals(values, expected));
values = new int[] {10, 20, 30, 40};
expected = new int[] {10, 20, 30, 40};
try {
field.set(new TimeOfDay(), 2, values, "-1", null);
fail();
} catch (IllegalArgumentException ex) {}
assertEquals(true, Arrays.equals(values, expected));
}
|
1ba3ffac-dfb0-4604-bb4c-a43cfcd5d411
| 0 |
public Set<String> getGroups() throws DataLoadFailedException {
return dataHolder.getGroups();
}
|
70a5f4b1-39c3-490f-a846-754851a42ca2
| 7 |
private void jButtonConstruction_CreateLevelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonConstruction_CreateLevelActionPerformed
String tag = jTextFieldUID.getText();
if (tag.length() == 0) {
JOptionPane.showMessageDialog(null, "UID tag required for level\n", "EDUCacheSim: " + "Create configuration", JOptionPane.INFORMATION_MESSAGE);
return;
}
int result = JOptionPane.YES_OPTION;
if (createdElements.containsKey(tag)) {
result = JOptionPane.showConfirmDialog(null, "Specified UID exists, replace?", "EDUCacheSim: Create configuration", JOptionPane.YES_NO_OPTION);
}
if (result == JOptionPane.NO_OPTION) {
return;
}
ReplacementPolicy rp = getReplacementPolicyChosen();
try {
int assoc = Integer.parseInt(jTextFieldAssoc.getText());
int size = Integer.parseInt(jTextFieldSize.getText());
int linew = Integer.parseInt(jTextFieldLineW.getText());
String sizeRange = (String) jComboBoxConstruction_SizeRange.getSelectedItem();
switch (sizeRange) {
case "KB":
size *= 1024;
break;
case "MB":
size *= 1024 * 1024;
break;
}
if (size < assoc * linew) {
JOptionPane.showMessageDialog(null, "Cache Size must be at least (LineWidth*Associativity) Bytes\n", "EDUCacheSim: " + "Create configuration", JOptionPane.INFORMATION_MESSAGE);
return;
}
CacheLevel cl = new CacheLevelImpl(tag, rp, size, assoc, linew);
createdElements.put(tag, cl);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Numbers only required in fields Associativity, Size and Line width\n", "EDUCacheSim: " + "Create configuration", JOptionPane.INFORMATION_MESSAGE);
}
refreshTable();
}//GEN-LAST:event_jButtonConstruction_CreateLevelActionPerformed
|
0eaed0d7-4691-4ae6-9dc3-a770e11ce0d2
| 3 |
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String namet = stack.peek();
if("姓名".equals(namet))
{
name = new String(ch,start,length);
}if("性别".equals(namet)){
sex = new String(ch,start,length);
}
if("年龄".equals(namet))
{
age = new String(ch,start,length);
}
}
|
7bb1f7c3-d302-4ec8-9ddc-03698004027c
| 4 |
public boolean anvilReady() {
if (!ctx.skillingInterface.getAction().equalsIgnoreCase("Smith")) {
if (ctx.skillingInterface.opened() && ctx.skillingInterface.close()) {
return false;
}
if (ctx.skillingInterface.isProductionInterfaceOpen()) {
ctx.skillingInterface.cancelProduction();
return false;
}
anvil.clickAnvil();
}
return ctx.skillingInterface.getAction().equalsIgnoreCase("Smith");
}
|
d0e42ef7-3623-41ac-b1de-5d12186eef80
| 0 |
public Account removeAccount(Account account) {
getAccounts().remove(account);
account.setClient(null);
return account;
}
|
dde1ebeb-c773-451f-aa48-af924500f9cd
| 4 |
@Override
public void run()
{
while (true)
{
try
{ Thread.sleep(20); }
catch (Exception e)
{ }
if (creator != null && !creator.acceptingUserInput())
{
// bg.clearSelection();
creator = null;
}
repaint();
}
}
|
6f582adf-6028-468b-a314-7673becc2b83
| 6 |
private static final boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2)
{
switch(hiByte)
{
case 0:
return ((jjbitVec2[i2] & l2) != 0L);
case 48:
return ((jjbitVec3[i2] & l2) != 0L);
case 49:
return ((jjbitVec4[i2] & l2) != 0L);
case 51:
return ((jjbitVec5[i2] & l2) != 0L);
case 61:
return ((jjbitVec6[i2] & l2) != 0L);
default :
if ((jjbitVec0[i1] & l1) != 0L)
return true;
return false;
}
}
|
35a5bbe2-837c-4235-9ee4-69d845ceb1fb
| 7 |
public Item buildFungus(MOB mob, Room room)
{
final Item newItem=CMClass.getItem("GenFoodResource");
newItem.setMaterial(RawMaterial.RESOURCE_MUSHROOMS);
switch(CMLib.dice().roll(1,6,0))
{
case 1:
newItem.setName(L("a mushroom"));
newItem.setDisplayText(L("a mushroom is here."));
newItem.setDescription("");
break;
case 2:
newItem.setName(L("a shiitake mushroom"));
newItem.setDisplayText(L("a shiitake mushroom grows here."));
newItem.setDescription("");
break;
case 3:
newItem.setName(L("a cremini mushroom"));
newItem.setDisplayText(L("a cremini mushroom grows here"));
newItem.setDescription("");
break;
case 4:
newItem.setName(L("a white mushroom"));
newItem.setDisplayText(L("a white mushroom grows here."));
newItem.setDescription("");
break;
case 5:
newItem.setName(L("a portabello mushroom"));
newItem.setDisplayText(L("a portabello mushroom grows here."));
newItem.setDescription("");
break;
case 6:
newItem.setName(L("a wood ear"));
newItem.setDisplayText(L("a wood ear grows here."));
newItem.setDescription("");
break;
}
newItem.setSecretIdentity(mob.Name());
newItem.setMiscText(newItem.text());
Druid_MyPlants.addNewPlant(mob, newItem);
room.addItem(newItem);
final Chant_SummonFungus newChant=new Chant_SummonFungus();
newItem.basePhyStats().setLevel(10+newChant.getX1Level(mob));
newItem.basePhyStats().setWeight(1);
newItem.setExpirationDate(0);
CMLib.materials().addEffectsToResource(newItem);
room.showHappens(CMMsg.MSG_OK_ACTION,CMLib.lang().L("Suddenly, @x1 sprouts up here.",newItem.name()));
newChant.plantsLocationR=room;
newChant.littlePlantsI=newItem;
if(CMLib.law().doesOwnThisLand(mob,room))
{
newChant.setInvoker(mob);
newChant.setMiscText(mob.Name());
newItem.addNonUninvokableEffect(newChant);
}
else
newChant.beneficialAffect(mob,newItem,0,(newChant.adjustedLevel(mob,0)*240)+450);
room.recoverPhyStats();
return newItem;
}
|
89a54bb9-b06b-4df2-a43f-2dc2ebd67d13
| 4 |
public String getClipboardData() {
Transferable clip = null;
try {
Clipboard cp = Toolkit.getDefaultToolkit().getSystemClipboard();
clip = cp.getContents(this);
}
catch (Exception e) {
}
if (clip == null) {
return "";
}
String text = null;
try {
text = (String) clip.getTransferData(DataFlavor.stringFlavor);
} catch (Exception e) {
}
if (text == null) {
return "";
}
return text;
}
|
1c5f18e0-71e6-44eb-8004-e76349a325c1
| 1 |
public static PlayersConnectedMessage createPlayersConnectedMessage(String playerNames) {
if (playerNames == null) throw new IllegalArgumentException("PlayerName is null");
return new PlayersConnectedMessage(playerNames);
}
|
f850600e-83bd-4f8e-951d-a826e66e2a4e
| 3 |
private synchronized void incrementLSN() {
FileWriter writer = null;
try
{
writer = new FileWriter("logSequenceNumber");
writer.write(Integer.toString(logSequenceNumber + 1));
} catch (Exception e)
{
e.printStackTrace();
} finally
{
if (writer != null)
{
try
{
writer.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
this.logSequenceNumber++;
}
|
c82a8717-2d94-4347-8b31-d6dbd40b71c4
| 2 |
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
Map<String, String[]> param = request.getParameterMap();
if (param != null) {
Path logfile = FileSystems.getDefault().getPath("G:\\workspace\\TelephoneBook-v2\\file.log");
byte buf[] = param.toString().getBytes();
try {
Files.write(logfile, buf, StandardOpenOption.APPEND);
} catch (IOException e) {
e.printStackTrace();
}
}
chain.doFilter(request, response);
}
|
0195e91b-c3a8-4037-9202-815a91541f71
| 2 |
public boolean validate(SkiPass sp) {
int id = sp.getID();
if (id < 0 || id >= skiPassIDCounter) {
return false;
} else {
return true;
}
}
|
e9b893aa-b55e-4162-a1d1-f0f7ab3e9e80
| 9 |
public WebElement getElementByAttribute(String Attribute,
String AttributeType) {
try {
if (AttributeType.equalsIgnoreCase("css")) {
testObjects = driver.findElements(By.cssSelector(Attribute));
} else if (AttributeType.equalsIgnoreCase("id")) {
testObjects = driver.findElements(By.id(Attribute));
} else if (AttributeType.equalsIgnoreCase("name")) {
testObjects = driver.findElements(By.name(Attribute));
} else if (AttributeType.equalsIgnoreCase("xpath")) {
testObjects = driver.findElements(By.xpath(Attribute));
} else if (AttributeType.equalsIgnoreCase("class")) {
testObjects = driver.findElements(By.className(Attribute));
} else if (AttributeType.equalsIgnoreCase("text")) {
testObjects = driver.findElements(By.linkText(Attribute));
} else {
throw new Exception("Incorrect Attribute type mentioned");
}
if (testObjects.size() == 0) {
throw new NoSuchElementException("Element couldn't be located");
} else {
testObject = testObjects.get(0);
// TODO add code for parsing between different objects returned.
}
return testObject;
} catch (NoSuchElementException e) {
return null;
}
catch (Exception e) {
// TODO: handle exception
return null;
}
}
|
949aafb4-2af6-4cf2-9f00-a6df17c2f211
| 1 |
public void setPos4(int val){ if (val == 1){p4 = true;} else { p4 = false; }}
|
81387e53-19e1-40ff-8af8-5a86de019456
| 1 |
@Override
public void removeItem( GraphItem item ) {
if( graph == null ){
throw new IllegalStateException( "cannot remove items because there is no graph set" );
}
graph.removeItem( item );
}
|
0d9b2223-1729-41e8-9209-672c6d645823
| 4 |
public void move(){
super.move();
if (x < 50){
x = 1180;
}
if (y < 50){
y = 840;
}
if (x > 1180){
x = 50;
}
if (y > 840){
y = 50;
}
}
|
62db01cc-85ed-45e2-94dd-6940a4e6ee87
| 4 |
public void run(){
if (time!=0){time=time-1;}
GosLink.dw.append("HeartBeat Started.");
while (true){
try {
Thread.sleep(60000);
checkserver(1);
checkserver(2);
if (Boolean.valueOf(GosLink.prps("bot"))){gosbot.enterchk();}
} catch (Exception e) {e.printStackTrace();}
}
}
|
6cbca5c5-75e4-49dc-90b4-b675ca5d3e8c
| 8 |
public void putAll( Map<? extends Long, ? extends Integer> map ) {
Iterator<? extends Entry<? extends Long,? extends Integer>> it =
map.entrySet().iterator();
for ( int i = map.size(); i-- > 0; ) {
Entry<? extends Long,? extends Integer> e = it.next();
this.put( e.getKey(), e.getValue() );
}
}
|
3c30b8d9-98c7-4f3d-a6c0-4298822c33db
| 1 |
public DefaultItemContextCapability( DefaultUmlDiagram diagram, DefaultItem<?> item ){
this.diagram = diagram;
this.item = item;
}
|
d7242831-b4e9-4475-afb6-ee9be71afa47
| 9 |
@Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode())
{
case KeyEvent.VK_W:
case KeyEvent.VK_UP: maincanvas.vport.scroll(Directions.N); break;
case KeyEvent.VK_S:
case KeyEvent.VK_DOWN: maincanvas.vport.scroll(Directions.S); break;
case KeyEvent.VK_A:
case KeyEvent.VK_LEFT: maincanvas.vport.scroll(Directions.W); break;
case KeyEvent.VK_D:
case KeyEvent.VK_RIGHT: maincanvas.vport.scroll(Directions.E); break;
case KeyEvent.VK_SPACE: pause(); break;
}
maincanvas.repaint();
// throw new UnsupportedOperationException("Not supported yet.");
}
|
fa3e6ac1-503b-497a-9668-af25afea6580
| 5 |
public void onEnable() {
playerListener.loadPlayers();
inventoryManager.load();
pm = new PluginManager(this);
pm.registerEvents(creatureListener);
pm.registerEvents(entityListener);
pm.registerEvents(playerListener);
pm.registerEvents(pluginListener);
pm.registerEvents(weatherListener);
pm.registerEvents(worldListener);
File serverconfigFile = new File("server.properties");
if (!serverconfigFile.exists()) {
log.severe(getNameBrackets() + "unable to load server.properties.");
} else {
try {
serverconfig.load(new FileInputStream(serverconfigFile));
} catch (Exception ex) {
log.severe(getNameBrackets() + "error loading " + serverconfigFile);
ex.printStackTrace();
}
}
config = getConfig(getConfigFile("config.yml"));
try {
setConfigDefaults();
} catch (IOException e) {
e.printStackTrace();
}
worlds.load();
gates.load();
getServer().getScheduler().scheduleSyncRepeatingTask(this, new RunCreatureLimit(), 600, 600);
getServer().getScheduler().scheduleSyncRepeatingTask(this, new RunTimeFrozen(), 200, 200);
getServer().getScheduler().runTaskTimerAsynchronously(this, new Runnable() {
public void run() {
saveAll();
}
}, 12000, 12000);
if (config.getBoolean("dynworld.enabled", false)) {
getServer().getScheduler().scheduleSyncRepeatingTask(this, new RunCheckWorldInactive(), config.getInt("dynworld.checkInterval", 60) * 20, config.getInt("dynworld.checkInterval", 60) * 20);
}
getServer().getScheduler().scheduleSyncDelayedTask(this, new RunLoadAllWorlds());
getServer().getScheduler().scheduleSyncDelayedTask(this, pm);
try {
getCommand("gate").setExecutor(new CommandHandlerGate(this));
getCommand("gworld").setExecutor(new CommandHandlerWorld(this));
} catch (Exception ex) {
log.warning(getNameBrackets() + "getCommand().setExecutor() failed! Seems I got enabled by another plugin. Nag the bukkit team about this!");
}
}
|
9dee9aa1-5506-40ea-833e-b6781d2299e7
| 1 |
public void append(String msg) {
if (win==true){textarea.append(msg+"\n");}
else{System.out.println(msg);}
}
|
4d931eeb-55d6-45cf-96b7-c752623ff9dc
| 1 |
public char value(int level) {
if (path_.length() < level) {
throw new IndexOutOfBoundsException();
}
return path_.charAt(level);
}
|
38463c75-680a-4bb1-97e5-04ad44e7a0d8
| 1 |
public static void main(String[] args) throws Exception {
InputStream isInput = new FileInputStream("D:/aaa/221.txt");
byte[] buffer = new byte[200];
int length = 0;
while(-1 != (length = isInput.read(buffer,0,200)))
{
String str = new String(buffer,0,length);
System.out.println(str);
}
isInput.close();
}
|
fbeb5f71-a2bd-49cb-ba76-354c52bebacf
| 0 |
public boolean getDead(){
return dead;
}
|
e4094697-5ca7-424e-8820-136b94cccba9
| 5 |
private void dfs(Digraph G, int v)
{
marked[v] = true;
onStack[v] = true;
for (int w : G.adj(v))
{
if (hasCycle())
return;
else if (!marked[w])
{
edgeTo[w] = v;
dfs(G, w);
}
else if (onStack[w])
{
cycle = new Stack<Integer>();
for (int x = v; x != w; x = edgeTo[x])
cycle.push(x);
cycle.push(w);
cycle.push(v); // starting and ending vertex of a cycle are the
// same
}
}
onStack[v] = false;
}
|
e66b8b10-a4d1-4fd0-b40c-97cda52c0448
| 2 |
public Enemies(Transform transform)
{
if (textures == null)
{
textures = new ArrayList<Texture>();
textures.add(new Texture("SSWVA1.png")); // Walking
textures.add(new Texture("SSWVB1.png"));
textures.add(new Texture("SSWVC1.png"));
textures.add(new Texture("SSWVD1.png"));
textures.add(new Texture("SSWVE0.png")); //Shooting
textures.add(new Texture("SSWVF0.png"));
textures.add(new Texture("SSWVG0.png"));
textures.add(new Texture("SSWVH0.png"));//Dying
textures.add(new Texture("SSWVI0.png"));
textures.add(new Texture("SSWVJ0.png"));
textures.add(new Texture("SSWVK0.png"));
textures.add(new Texture("SSWVL0.png"));
textures.add(new Texture("SSWVM0.png")); //Dead
}
if(mesh == null)
{
Vertex[] vertices = new Vertex[]{new Vertex(new Vector3f(-SIZEX, START, START), new Vector2f(TEX_MAX_X,TEX_MAX_Y)),
new Vertex(new Vector3f(-SIZEX, SIZEY, START), new Vector2f(TEX_MAX_X,TEX_MIN_Y)),
new Vertex(new Vector3f(SIZEX, SIZEY, START), new Vector2f(TEX_MIN_X,TEX_MIN_Y)),
new Vertex(new Vector3f(SIZEX, START, START), new Vector2f(TEX_MIN_X,TEX_MAX_Y))};
int[] indices = new int[]{0,1,2,
0,2,3};
mesh = new Mesh(vertices, indices);
}
this.transform = transform;
this.material = new Material(textures.get(0));
this.state = STATE_IDLE;
this.random = new Random();
this.health = MAX_HEALTH;
this.canShoot = false;
this.deathTime = 0;
}
|
fdfe805c-406e-4aca-b541-246998ce26cf
| 3 |
private static ListNode buildList(int[] arr) {
ListNode head = new ListNode(0);
ListNode curr = head;
for (int i : arr) {
curr.next = new ListNode(i);
curr = curr.next;
}
curr = head;
while (curr.next != null) {
curr = curr.next;
if (curr.next == null) {
curr.next = head.next.next.next.next;
break;
}
}
return head.next;
}
|
937edb5c-4c9c-45f9-999b-a484338062e9
| 5 |
public void updatePatient(int health_care_no, String field, String value) {
// UPDATE table_name
// SET column1=value1,column2=value2,...
// WHERE some_column=some_value;
String patientUpdate = "";
if (field.equals("name") || field.equals("address")
|| field.equals("phone")) {
patientUpdate = "UPDATE patient SET " + field + "='" + value
+ "' WHERE health_care_no=" + health_care_no;
} else if (field.equals("birth_day")) {
patientUpdate = "UPDATE patient SET " + field + "=to_date('"
+ value + "', 'YYYY-MM-DD') WHERE health_care_no="
+ health_care_no;
}
try {
stmt.executeUpdate(patientUpdate);
con.commit();
System.out.println("Patient updated.");
} catch (SQLException e) {
System.out.println("Sorry, could not update " + field);
}
}
|
cc3e6bca-cffa-4b2e-b854-029abbdfc18c
| 9 |
@Override
boolean startSamples(int loopCount, float leftGain, float rightGain,
int leftDelay, int rightDelay) {
// loop count is ignored for Stream and MIDI
// TODO: loop count isn't implemented for MIDI yet
// left and rightDelay parameters are in terms of Samples
if (debugFlag) {
debugPrint("JSClip: startSamples ");
debugPrintln("start stream for Left called with ");
debugPrintln(" gain = " + leftGain +
" delay = " + leftDelay);
debugPrintln("start stream for Right called with ");
debugPrintln(" gain = " + rightGain +
" delay = " + rightDelay);
}
// This is called assuming that the Stream is allocated for a
// Positional sample, but if it is not then fall back to
// starting the single sample associated with this Stream
if (otherChannel == null || reverbChannel == null)
startSample(loopCount, leftGain, leftDelay);
/*
* ais for Left and Right streams should be same so just get ais
* left stream
*/
if (ais == null) {
if (debugFlag) {
debugPrint("JSClip: Internal Error startSamples: ");
debugPrintln("either left or right ais is null");
}
return false;
}
Clip leftLine;
Clip rightLine;
leftLine = line;
rightLine = otherChannel;
// left line only for background sounds...
// TODO:
/***********
for now just care about the left
if (leftLine == null || rightLine == null) {
if (debugFlag) {
debugPrint("JSClip: startSamples Internal Error: ");
debugPrintln("either left or right line null");
}
return false;
}
************/
// we know that were processing TWO channels
double ZERO_EPS = 0.0039; // approx 1/256 - twice MIDI precision
double leftVolume = (double)leftGain;
double rightVolume = (double)rightGain;
// TODO: if not reading/writing done for Clips then I can't do
// stereo trick (reading mono file and write to stereo buffer)
// Save time sound started, only in left
startTime = System.currentTimeMillis();
if (debugFlag)
debugPrintln("*****start Stream with new start time " +
startTime);
try {
// QUESTION: Offset clip is done how???
/*******
// TODO:
offset delayed sound
set volume
set pan??
set reverb
boolean reverbLeft = false; // off; reverb has it own channel
boolean reverbRight = reverbLeft;
if (leftDelay < rightDelay) {
XXXX audioLeftStream.start(leftVolume, panLeft, reverbLeft);
XXXX audioRightStream.start(rightVolume, panRight, reverbRight);
}
else {
XXXX audioRightStream.start(rightVolume, panRight, reverbRight);
XXXX audioLeftStream.start(leftVolume, panLeft, reverbLeft);
}
******/
line.setLoopPoints(0, -1); // Loop the entire sound sample
line.loop(loopCount); // plays clip loopCount + 1 times
line.start(); // start the sound
}
catch (Exception e) {
if (debugFlag) {
debugPrint("JSClip: startSamples ");
debugPrintln("audioInputStream.read failed");
}
e.printStackTrace();
startTime = 0;
return false;
}
if (debugFlag)
debugPrintln("JSClip: startSamples returns");
return true;
} // end of startSamples
|
9a6f08d1-cbd5-4252-89dd-b527775754a9
| 1 |
public int compareTo(Object object) {
if (!(object instanceof CycVariable)) {
throw new ClassCastException("Must be a CycVariable object");
}
return this.name.compareTo(((CycVariable) object).name);
}
|
7f683c25-a98b-4169-aa81-cf1bf6002d50
| 4 |
public static void addLibrary( Class libraryClass )
throws SoundSystemException
{
if( libraryClass == null )
throw new SoundSystemException(
"Parameter null in method 'addLibrary'",
SoundSystemException.NULL_PARAMETER );
if( !Library.class.isAssignableFrom( libraryClass ) )
throw new SoundSystemException( "The specified class does not " +
"extend class 'Library' in method 'addLibrary'" );
if( libraries == null )
libraries = new LinkedList<Class>();
if( !libraries.contains( libraryClass ) )
libraries.add( libraryClass );
}
|
bb67954c-5ebc-43e6-b668-3671545e0423
| 8 |
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0)
return "";
if (strs.length == 1)
return strs[0];
for (int j = 0; j < strs.length; j++)
if(strs[j].length() == 0)
return "";
for (int i = 0; i < strs[0].length(); i++) {
for (int j = 1; j < strs.length; j++) {
if (strs[j].length() <= i || strs[j].charAt(i) != strs[0].charAt(i))
return strs[0].substring(0, i);
}
}
return strs[0];
}
|
1afd764b-4045-47b8-85f3-46453d6fd489
| 6 |
private PDFObject readObjectDescription(
ByteBuffer buf, int objNum, int objGen, PDFDecrypter decrypter) throws IOException {
// we've already read the 4 0 obj bit. Next thing up is the object.
// object descriptions end with the keyword endobj
long debugpos = buf.position();
PDFObject obj= readObject(buf, objNum, objGen, decrypter);
// see if it's a dictionary. If so, this could be a stream.
PDFObject endkey= readObject(buf, objNum, objGen, decrypter);
if (endkey.getType() != PDFObject.KEYWORD) {
throw new PDFParseException("Expected 'stream' or 'endobj'");
}
if (obj.getType() == PDFObject.DICTIONARY && endkey.getStringValue().equals("stream")) {
// skip until we see \n
readLine(buf);
ByteBuffer data = readStream(buf, obj);
if (data == null) {
data = ByteBuffer.allocate(0);
}
obj.setStream(data);
endkey= readObject(buf, objNum, objGen, decrypter);
}
// at this point, obj is the object, keyword should be "endobj"
String endcheck = endkey.getStringValue();
if (endcheck == null || !endcheck.equals("endobj")) {
System.out.println("WARNING: object at " + debugpos + " didn't end with 'endobj'");
//throw new PDFParseException("Object musst end with 'endobj'");
}
obj.setObjectId(objNum, objGen);
return obj;
}
|
a1a3f844-2e94-405e-ab9b-04c5a4613384
| 2 |
public boolean initHouse(House house, int floor) {
try {
loadImages();
} catch (MissingResourceException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return changeHouse(house, floor);
}
|
f07ad4bd-3140-461a-baf4-94632799d153
| 1 |
public void update() {
input.update(player);
Cinput.update(creature);
if(mousey.buttonDown(MouseEvent.BUTTON1))
System.out.println(String.format("Mouse Down: (X:%f, Y:%f)",mousey.getPosition().getX(),mousey.getPosition().getY()));
}
|
088fc6e5-68e1-42e4-bb02-7e627319c051
| 2 |
public static Method findSuperMethod(Object self, String name, String desc) {
Class clazz = self.getClass();
Method m = findSuperMethod2(clazz.getSuperclass(), name, desc);
if (m == null)
m = searchInterfaces(clazz, name, desc);
if (m == null)
error(self, name, desc);
return m;
}
|
3a3edbf9-8e5a-4a81-9152-710c0e9e0793
| 2 |
public void disable() throws IOException {
// This has to be synchronized or it can collide with the check in the task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set it.
if (!isOptOut()) {
configuration.set("opt-out", true);
configuration.save(configurationFile);
}
// Disable Task, if it is running
if (task != null) {
task.cancel();
task = null;
}
}
}
|
1afbeee7-22cf-4015-8871-84ca48f899f9
| 9 |
public static int search2(int[] A, int target) {
if (A.length == 0)
return -1;
int l = 0;
int r = A.length - 1;
int m;
while (l <= r) {
m = (l + r) / 2;
if (target == A[m]) {
return m;
} else if (A[l] <= A[m] && A[m] >= A[r]) {
// left sorted, right unsorted
if (target < A[m] && target >= A[l]) {
r = m - 1;
} else {
l = m + 1;
}
} else {
// right sorted, left unsorted
if (target <= A[r] && target > A[m]) {
l = m + 1;
} else {
r = m - 1;
}
}
// }else if(A[l] < A[r]){
// //list sorted
// if(target < A[m]) r =m -1;
// else l = m +1;
// }
}
return -1;
}
|
7999baa8-77f0-426f-9d5d-8c3fc6e3ff60
| 2 |
public void eat(ArrayList<ParkerPaulChicken> chickens) {
/// guard clause - no chickens to eat
if (chickens.isEmpty()) {
return;
}
// guard clause - didn't catch a chicken
if (!canCatchChicken()) {
return;
}
// select a chicken to eat and update weight and collection of chickens
ParkerPaulChicken chicken = chickens.get(random.nextInt(chickens.size()));
fattenUp(chicken.getWeight());
chickens.remove(chicken);
} // end of eat
|
81603218-1af1-4e4b-b549-e32b6d026ad0
| 1 |
public boolean removeModerator(User user){
if (moderators.size() <= 1) return false;
moderators.remove(user);
save();
return true;
}
|
2579a547-964c-4259-a480-a813bd2befe6
| 4 |
private void completeTabFrequence ()
{
for (final int code : this.encoding) {
boolean write = false;
for (ArrayList<Integer> tabFreq : this.tabFrequence) {
if (tabFreq.get(0) == code) {
tabFreq.set(1, tabFreq.get(1) + 1);
write = true;
}
}
if (!write) {
ArrayList<Integer> tabFreq = new ArrayList<Integer>() {{ add(code); add(1); }};
this.tabFrequence.add(tabFreq);
}
}
}
|
3077d96a-b41d-4f6f-9275-1b43e4eafc8e
| 1 |
public short[] decodeShorts() {
short[] res = new short[decodeInt()];
for (int i = 0; i < res.length; i++) {
res[i] = decodeShort();
}
return res;
}
|
4ff052e5-fdce-4c53-899e-c4b36fe05766
| 7 |
private static <T extends Comparable<? super T>> T[] merge(T[] front, T[] rear) {
T[] result = Arrays.copyOf(front, front.length + rear.length);
int i = 0;
int j = 0;
int k = 0;
for(; j < front.length && k < rear.length; i++) {
T first = front[j];
T second = rear[k];
if (first.compareTo(second) < 0) {
result[i] = first;
j++;
} else {
result[i] = second;
k++;
}
}
T[] remainingData = (k == rear.length) ? front : rear;
int value = (k == rear.length) ? j : k;
for (int q = value; i < result.length; i++, q++)
result[i] = remainingData[q];
return result;
}
|
19a106ad-43de-4041-a2cc-df431e00a4f4
| 9 |
private void desenhaProximaPeca(GL gl, IntBuffer idsTextura) {
if (proximaPeca != null) {
// desenha a próxima peça
double[][] matrizProximaPeca = proximaPeca.getMatrizAtual();
if (proximaPeca.getTipoPeca() == TipoPeca.T) {
matrizProximaPeca = proximaPeca.getMatrizRotacao();
matrizProximaPeca = new Matrix(matrizProximaPeca).transpose().getArray();
matrizProximaPeca = Peca.reflect(matrizProximaPeca);
} else if (proximaPeca.getTipoPeca() == TipoPeca.Z || proximaPeca.getTipoPeca() == TipoPeca.S) {
matrizProximaPeca = Peca.reflect(matrizProximaPeca);
} else if (proximaPeca.getTipoPeca() == TipoPeca.L) {
matrizProximaPeca = proximaPeca.getMatrizRotacao();
matrizProximaPeca = new Matrix(matrizProximaPeca).transpose().getArray();
} else if (proximaPeca.getTipoPeca() == TipoPeca.J) {
matrizProximaPeca = proximaPeca.getMatrizRotacao();
matrizProximaPeca = new Matrix(matrizProximaPeca).transpose().getArray();
Peca.reflect(matrizProximaPeca);
}
int textura = proximaPeca.getTipoPeca().getId() - 1;
for (int i = 0; i < matrizProximaPeca.length; i++) {
for (int j = 0; j < matrizProximaPeca[0].length; j++) {
if (matrizProximaPeca[i][j] != 0) {
desenhaCubo(gl, idsTextura, j + 10, i + 10, textura, proximaPeca.getTipoPeca().getCor());
}
}
}
}
}
|
b5a8bdb4-51db-42fb-9977-a336416de127
| 1 |
public void stop_run() {
try {
open_port = false;
ssocket.close();
} catch (IOException e) {
}
}
|
2e90b4c1-303a-4be5-bef4-fefc1f232a44
| 5 |
double kernel_function(int i, int j)
{
switch(kernel_type)
{
case svm_parameter.LINEAR:
return dot(x[i],x[j]);
case svm_parameter.POLY:
return powi(gamma*dot(x[i],x[j])+coef0,degree);
case svm_parameter.RBF:
return Math.exp(-gamma*(x_square[i]+x_square[j]-2*dot(x[i],x[j])));
case svm_parameter.SIGMOID:
return Math.tanh(gamma*dot(x[i],x[j])+coef0);
case svm_parameter.PRECOMPUTED:
return x[i][(int)(x[j][0].value)].value;
default:
return 0; // java
}
}
|
64251790-c06a-4a94-b3ac-dcca1fb54a15
| 7 |
public void moveDown(boolean isUserTriggered) {
if (freezing || !isGameOn) {
return;
}
if (!checkMovable("DOWN")) {
for (int i = 0; i < currentTokens.length; i++) {
int x = currentTokens[i][0];
int y = currentTokens[i][1];
tokens[y][x].setFrozen(true);
}
if (!checkBlowLines()) {
placeTokenWithFlash();
nextMove(0);
setChanged();
notifyObservers("Place");
}
return;
}
setCurrentTokens(0);
if (isUserTriggered) {
increaseScore(1);
setChanged();
notifyObservers("Move");
}
for (int i = 0; i < currentTokens.length; i++) {
int x = currentTokens[i][0];
int y = currentTokens[i][1] + 1;
tokens[y][x].setType(currentType);
currentTokens[i][1] = y;// move position down 1 point
}
refresh();
}
|
7ceba314-974a-4313-a671-36d3b9b34afc
| 0 |
public void onDisable() {
saveUsers();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.