method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
9a9e9396-bb1f-4c18-ba0d-c517b03db05a | 4 | public int arrowKeyValue() {
switch (key) {
case Input.KEY_UP:
return Entity.UP;
case Input.KEY_DOWN:
return Entity.DOWN;
case Input.KEY_LEFT:
return Entity.LEFT;
case Input.KEY_RIGHT:
return Entity.RIGHT;
}
return 0;
} |
16f9fbe7-e14c-40b2-b2bf-537c5d144ea4 | 0 | public CircularArrayQueue(int capacity)
{
elements = new Object[capacity];
count = 0;
head = 0;
tail = 0;
} |
bfcaaca3-f2f2-4b8f-ab49-5943545ac648 | 0 | public void setTotalNoOfSeats(int totalNoOfSeats) {
this.totalNoOfSeats = totalNoOfSeats;
} |
ad7186b3-60a5-4a07-a06a-95dc87437364 | 0 | private void startGUI()
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
appFrame = new CustomFrame("Drools fusion lighter");
appFrame.init();
}
});
} |
275f626f-71ee-4412-8171-4485c546a5d1 | 2 | private static String getStringOutputLine(String titel, String referenz, JSONObject obj) throws JSONException,
IOException {
if (obj.has(referenz)) {
if (obj.get(referenz).toString().length() < 35) {
return titel + ": " + obj.get(referenz) + "\n";
} else {
JSONObject childobj = fetchObject(referenz + "s", obj.get(referenz).toString());
JSONObject result = childobj.getJSONObject("result");
return getStringOutputLine(titel, "name", result);
}
}
return null;
} |
311f5fc9-9242-4c95-ae52-b14acfa50d50 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TestTableIT.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TestTableIT.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TestTableIT.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TestTableIT.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame fen = new TestTableIT();
fen.setVisible(true);
}
});
} |
f9bee759-f7f7-4a22-861d-310d22dbe8fd | 4 | public static void main(String[] CHEESE) {
int[] ans = new int[]{ 1, -1};
for(int den = 1; den < 1000; den++) {
int count = -1;
ArrayList<Integer> xs = new ArrayList<Integer>();
ArrayList<Integer> top = new ArrayList<Integer>();
int x = 1;
while( x != 0 ) {
xs.add(x);
top.add(x/den);
x = (x - den*(x/den))*10;
int i = xs.indexOf(x);
if( i >= 0 ) {
count = top.size()-i;
break;
}
}
if(count > ans[1]) {
ans[0] = den;
ans[1] = count;
}
}
System.out.println(ans[0] +", "+ ans[1]);
} |
b0cd986e-200e-4e91-8aed-218067ed8e01 | 2 | public String getStringId(){
if (id == 0){
return "Bullet";
}else if (id == 1){
return "Artillery";
}else{
return "Laser";
}
} |
5acde443-85df-4a12-8ea3-349a5f2b0d98 | 2 | public void display(Integer level) {
String space = "";
for (int i = 0; i < level; i++) {
space += "-";
}
System.out.println(space + name);
for (Root branch : branchs) {
// 递归调用
branch.display(level + 2);
}
} |
b752b719-a14f-4ae4-9c21-e5454c3e39a4 | 2 | @Override
public boolean canOpenSelection() {
if (mOpenableProxy != null && !mSelectedRows.isEmpty()) {
return mOpenableProxy.canOpenSelection();
}
return false;
} |
199ac9e8-f356-4a3a-b23d-caf76a728bf6 | 8 | public static String simpleReadFile(String filePath){
FileInputStream fis=null;
InputStreamReader isr = null;
BufferedReader br=null;
try{
StringBuilder sb=new StringBuilder();
File file = new File(filePath);
fis = new FileInputStream(file);
isr= new InputStreamReader(fis);
br= new BufferedReader(isr);
String readLine = null;
while((readLine = br.readLine()) != null){
sb.append(readLine).append("\n");
}
return sb.toString();
}
catch(Exception e){
System.out.println("Erreur pour lire : "+ filePath);
e.printStackTrace();
return null;
}
finally{
if(fis !=null)
{
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(isr != null){
try {
isr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(br!=null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} |
5f3cb757-e5d5-4a68-8c33-eb1298dc1b9f | 2 | private void clearEntities() {
for (int i = 0; i < entities.size(); i++) {
Entity e = entities.get(i);
if (e.isRemoved()) {
entities.remove(i);
}
}
} |
b8b3cbd9-0c30-4798-beff-bc366b6e9e47 | 9 | @Override
public Faction getFaction(String factionID)
{
if(factionID==null)
return null;
Faction F=factionSet.get(factionID.toUpperCase());
if((F==null)&&(!factionID.toLowerCase().endsWith(".ini")))
{
F=getFaction(factionID+".ini");
}
if(F!=null)
{
if(F.isDisabled())
return null;
if(!F.amDestroyed())
return F;
factionSet.remove(F.factionID().toUpperCase());
Resources.removeResource(F.factionID());
return null;
}
final CMFile f=new CMFile(Resources.makeFileResourceName(makeFactionFilename(factionID)),null,CMFile.FLAG_LOGERRORS);
if(!f.exists())
return null;
final StringBuffer buf=f.text();
if((buf!=null)&&(buf.length()>0))
{
return buildFactionFromXML(buf, factionID);
}
return null;
} |
7a620710-3574-4101-9e26-f64e64ac5e18 | 7 | private static HashMap<String, String> getKeyValue(HashMap<String, String> map, int pos,
String allNameValuePairs, String listDelimiter, String nameValueSeparator) {
if (pos >= allNameValuePairs.length()) {
// dp("end as "+pos+" >= "+allNameValuePairs.length() );
return map;
}
int equalsPos = allNameValuePairs.indexOf(nameValueSeparator, pos);
int delimPos = allNameValuePairs.indexOf(listDelimiter, pos);
if (delimPos == -1) {
delimPos = allNameValuePairs.length();
}
if (equalsPos == -1) {
// dp("no more equals...");
return map;
}
if (delimPos == (equalsPos + 1)) {
// dp("Ignoring as nothing between delim and equals...
// delim:"+delimPos+" eq:"+equalsPos);
return getKeyValue(map, delimPos + 1, allNameValuePairs, listDelimiter,
nameValueSeparator);
}
if (equalsPos > delimPos) {
// there is a key without a value?
String key = allNameValuePairs.substring(pos, delimPos);
key = key.trim();
if (key.length() > 0) {
map.put(key, null);
}
return getKeyValue(map, delimPos + 1, allNameValuePairs, listDelimiter,
nameValueSeparator);
}
String key = allNameValuePairs.substring(pos, equalsPos);
if (delimPos > -1) {
String value = allNameValuePairs.substring(equalsPos + 1, delimPos);
// dp("cont "+key+","+value+" pos:"+pos+"
// len:"+allNameValuePairs.length());
key = key.trim();
map.put(key, value);
pos = delimPos + 1;
// recurse the rest of the values...
return getKeyValue(map, pos, allNameValuePairs, listDelimiter, nameValueSeparator);
} else {
// dp("ERROR: delimPos < 0 ???");
return map;
}
} |
dd3e10cf-c8e4-4eb6-a017-df967d4c2bfa | 2 | public ClassAnalyzer getInnerClassAnalyzer(String name) {
/** require name != null; **/
int innerCount = inners.length;
for (int i = 0; i < innerCount; i++) {
if (inners[i].name.equals(name))
return inners[i];
}
return null;
} |
9beb28d9-2c02-48b4-9789-d08828e1f273 | 1 | @Test
public void testTimeStep_DAILY() throws Exception {
printDebug("----------------------------");
printDebug("DAILY: " + this.toString());
printDebug("----------------------------");
CSTable t = DataIO.table(r, "obs");
Assert.assertNotNull(t);
// 1 YEAR
Date start = Conversions.convert("1981-1-01", Date.class);
Date end = Conversions.convert("1981-1-14", Date.class);
printDebug("Start = " + start.toString() + "; End = " + end.toString());
double[] obsval = DataIO.getColumnDoubleValuesInterval(start, end, t, "runoff[0]", DataIO.DAILY);
printDebug("# values = " + obsval.length);
Assert.assertTrue(obsval.length == 14);
// Values directly from table
double[] goldenVal = new double[14];
goldenVal[0] = 72;
goldenVal[1] = 70;
goldenVal[2] = 83;
goldenVal[3] = 80;
goldenVal[4] = 75;
goldenVal[5] = 65;
goldenVal[6] = 64;
goldenVal[7] = 64;
goldenVal[8] = 65;
goldenVal[9] = 66;
goldenVal[10] = 66;
goldenVal[11] = 68;
goldenVal[12] = 71;
goldenVal[13] = 73;
// goldenVal[14] = 75;
for (int i = 0; i < obsval.length; i++) {
printDebug("obs[" + i + "] = " + obsval[i] + ";\tGolden = " + goldenVal[i]);
}
Assert.assertArrayEquals(goldenVal, obsval, 0);
} |
3034f0dd-0ea4-4e7e-8920-c4086997073d | 9 | public void processLoginMessage(OMMMsg respMsg)
{
// *_log<< "Received login response" << endl;
myCallback.notifyStatus("Received login response");
if (respMsg.has(OMMMsg.HAS_ATTRIB_INFO))
{
OMMAttribInfo attribInfo = respMsg.getAttribInfo();
if (attribInfo.has(OMMAttribInfo.HAS_SERVICE_NAME))
// *_log<<"Service Name: : " <<
// attribInfo.getServiceName()<<endl;
System.out.println("");
if (attribInfo.has(OMMAttribInfo.HAS_NAME))
// *_log<<"Name : " << attribInfo.getName()<<endl;
System.out.println("");
// *_log<< "response type : " <<
// msgRespTypeToString(respMsg.getRespType()) << endl;
}
if (respMsg.has(OMMMsg.HAS_STATE))
{
OMMState respState = respMsg.getState();
StringBuffer buffer = new StringBuffer();
buffer.append("Login state: ");
// buffer.append(streamStateToString (respState.getStreamState()));
buffer.append("; code: ");
// buffer.append(statusCodeToString (respState.getCode()));
buffer.append(" status: " + respState.getText());
// *_log<<buffer.toString();
myCallback.notifyStatus(buffer.toString());
if ((respMsg.getState().getStreamState() == OMMState.Stream.OPEN)
&& (respMsg.getState().getDataState() == OMMState.Data.OK))
{
System.out.println("Login successful...");
// Now we can send the directory request
if (!_loggedIn)
{
// send service request only once.
_loggedIn = true;
sendRequest(RDMMsgTypes.DIRECTORY, null);
}
}
else if (respMsg.getMsgType() == OMMMsg.MsgType.STATUS_RESP)
{
if (respMsg.getState().getStreamState() == OMMState.Stream.CLOSED)
{
// Check for connection loss, recovery and cleanup
System.out.println("Login denied");
// cleanup();
_loggedIn = false;
}
}
}
} |
f36de40d-2ac3-4a16-b93f-fee02d11091a | 5 | public static void computeOperator(Stack<Float> stack, String operator) {
//Be careful with the order you pop things off here.
//Choose an order and stick with it.
float b = stack.pop();
float a = stack.pop();
float result;
//If we had more operators, we wouldn't use cascading if/else statements
if (operator.equals("+")) {
result = a + b;
} else if (operator.equals("-")) {
result = a - b;
} else if (operator.equals("*")) {
result = a * b;
} else if (operator.equals("/")) {
result = a / b;
} else if (operator.equals("^")) {
result = (float) Math.pow((double) a, (double) b);
} else {
//We've encountered an unknown operator.
//We'll ignore it and move on, pushing the operands back onto the stack.
//Be careful you push the numbers back in the right order.
stack.push(a);
stack.push(b);
//Return here so we don't push a zero onto the stack.
return;
}
stack.push(result);
} |
76d1c209-f961-47ea-89e0-4e8ad5f55752 | 9 | public void actionPerformed(ActionEvent e){
String option = e.getActionCommand();
if(option.equals("back")){
PhotoDisplay.this.setVisible(false);
PhotoDisplay.this.photosScreen.setVisible(true);
}
else if(option.equals("move photo")){
Hashtable<String,Album> albumsHT = control.listAlbums();
String[] albums = new String[albumsHT.size()];
int i=0;
for(Album album:albumsHT.values()){
albums[i] = album.getAlbumName();
i++;
}
PhotoDisplay.this.movePopUp = new movePhotoPopUp(albums, PhotoDisplay.this);
PhotoDisplay.this.movePopUp.setVisible(true);
}
else if(option.equals("edit")){
editBtn.setIcon(new ImageIcon("resources/saveUP.jpg"));
editBtn.setPressedIcon(new ImageIcon("resources/saveDN.jpg"));
editBtn.setActionCommand("save");
captionTxtF.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.red));
captionTxtF.setEditable(true);
captionTxtF.setOpaque(true);
captionTxtF.setForeground(Color.black);
buttons = new JPanel();
buttons.setOpaque(false);
buttons.setLayout(new FlowLayout());
addTagBtn = new ImageButton(new ImageIcon("resources/addTagsUP.jpg"));
addTagBtn.setPressedIcon(new ImageIcon("resources/addTagsDN.jpg"));
addTagBtn.setAlignmentX(Component.RIGHT_ALIGNMENT);
addTagBtn.setActionCommand("add Tags");
addTagBtn.addActionListener(ol);
removeTagBtn = new ImageButton(new ImageIcon("resources/removeTagUP.jpg"));
removeTagBtn.setPressedIcon(new ImageIcon("resources/removeTagDN.jpg"));
removeTagBtn.setAlignmentX(Component.LEFT_ALIGNMENT);
removeTagBtn.setActionCommand("remove Tag");
removeTagBtn.addActionListener(ol);
buttons.add(removeTagBtn);
buttons.add(addTagBtn);
tagsPanel.add(buttons);
tagsPanel.revalidate();
tagsPanel.repaint();
buttonsPanel.revalidate();
buttonsPanel.repaint();
}
else if(option.equals("save")){
save();
}
else if(option.equals("add Tags")){
PhotoDisplay.this.tagsPopUp = new addTagsPopUp(PhotoDisplay.this.control, PhotoDisplay.this, PhotoDisplay.this.photo.getFilename());
PhotoDisplay.this.tagsPopUp.setVisible(true);
}
else if(option.equals("remove Tag")){
String selected = (String) tagList.getSelectedValue();
if(selected!=null&&!selected.equals("")){
String[] split1= new String[2];
split1= selected.split(":");
String type = split1[0];
String value = split1[1];
value = value.substring(1);
value = value.substring(0, value.length()-1);
control.deleteTag(PhotoDisplay.this.photo.getFilename(), type, value);
tagsModel.removeElement(selected);
filltagsModel();
tagList.revalidate();
tagList.repaint();
tagListSP.revalidate();
tagListSP.repaint();
tagsPanel.revalidate();
tagsPanel.repaint();
buttonsPanel.revalidate();
buttonsPanel.repaint();
}
else{
final JFrame error = new JFrame("Important Message!");
JOptionPane.showMessageDialog(error, "No Tag Selected.");
}
}
} |
9385cf7b-6f2d-4c6b-a33c-6af67069c0e2 | 3 | public static void unbanPlayer( String sender, String player ) throws SQLException {
if ( !PlayerManager.playerExists( player ) ) {
PlayerManager.sendMessageToPlayer( sender, Messages.PLAYER_DOES_NOT_EXIST );
return;
}
if ( !isPlayerBanned( player ) ) {
PlayerManager.sendMessageToPlayer( sender, Messages.PLAYER_NOT_BANNED );
return;
}
SQLManager.standardQuery( "DELETE FROM BungeeBans WHERE player ='" + player + "'" );
if ( BansConfig.broadcastBans ) {
PlayerManager.sendBroadcast( Messages.PLAYER_UNBANNED.replace( "{player}", player ).replace( "{sender}", sender ) );
} else {
PlayerManager.sendMessageToPlayer( sender, Messages.PLAYER_UNBANNED.replace( "{player}", player ).replace( "{sender}", sender ) );
}
} |
7e7df36a-c70b-4d76-ae09-6455c4af0321 | 0 | public void setOperator(Operator<Boolean> operator) {
this.operator = operator;
} |
afe8123e-f49d-47d9-b92c-1794c38ed19b | 3 | public boolean matches(final Context context) {
if (this.handler.actions.size() == 1) return true;
final int generation = this.getGeneration();
if (context.arguments.size() <= generation) return false;
if (context.arguments.get(generation).equalsIgnoreCase(this.name)) return true;
return false;
} |
65ba137b-c7a5-4818-86c0-ed5621ac433d | 5 | public void tarjanSCC(int u) {
dfs_num[u] = dfs_low[u] = dfsNumberCounter++;
s.push(u);
visited[u] = true;
for (int i = 0; i < ady[u].size(); i++) {
int v = ady[u].get(i);
if (dfs_num[v] == -1)
tarjanSCC(v);
if (visited[v])
dfs_low[u] = Math.min(dfs_low[u], dfs_low[v]);
}
if (dfs_low[u] == dfs_num[u]) {
int v;
do {
v = s.pop();
visited[v] = false;
} while (u != v);
numSCC++;
}
} |
00d907d9-5861-450b-9945-a32fc1b2dea2 | 3 | public boolean intersects(Rectangle rect)
{
return !(rect.getLeft() > getRight() ||
rect.getRight() < getLeft() ||
rect.getTop() < getBottom() ||
rect.getBottom() > getTop());
} |
2b114cad-f7fa-4402-8672-ebef76452328 | 5 | public void disconnect(Vertex a, Vertex b){
if(isConnected(a,b)){
int edgeWeight = this.weight.get(new Edge(a,b));
if(edgeWeight!=1){
this.withWeight--;
}
if(edgeWeight<0){
this.withNegativeWeight--;
}
this.weight.remove(new Edge(a,b));
LinkedList<Vertex> adjacencyVertices = a.getAdjencyVertices();
Iterator<Vertex> i = new Iterator<Vertex>(adjacencyVertices);
while(i.hasNext()){
Vertex v = i.getNext();
if(v.equals(b)){
i.remove();
}
}
}
} |
8b74f6b4-ca27-4358-8a84-9537ce4db950 | 3 | public void switch_in(Point p) {
if (!outerBorder.remove(p)) {
return;
}
addToInnerBorder(p);
for (Point n : n4(p)) {
if (tita.getValue(n) == 3) {
addToOuterBorder(n);
}
}
} |
5e30dd06-f7d6-4da0-98c7-ffd35f7beb01 | 2 | public ResultSet execute(String query) {
try {
Statement stm = this.con.createStatement();
if(stm.execute(query)){
return stm.getResultSet();
}
return null;
} catch (SQLException e) {
LogHandler.writeStackTrace(log, e, Level.SEVERE);
return null;
}
} |
9275098d-f458-419e-9455-4e765ca8b58c | 8 | private void main_declaration(){
main = true;
type_specifier(); // pregunta por el especificador de tipo
tokenActual = analizadorLexico.consumirToken();
if(!tokenActual.obtenerLexema().equals("main")){
error(16,tokenActual.obtenerLexema(),tokenActual.obtenerLinea());
}
tokenActual = analizadorLexico.consumirToken(); // consume el siguiente token para identificar la regla de produccion que sera aplicada a continuciacion
switch(tokenActual.obtenerLexema()){
case "(": // si el siguiente token es la apertura de un parentesis nos encontramos con la declaracion de una funcion
tokenActual = analizadorLexico.consumirToken(); // el parametro siguiente podria ser void (vacio)
if(!tokenActual.obtenerLexema().equals("void")){ // si no es void deberia seguir una lista de parametros o bien el cierre del parentesis
if(!tokenActual.obtenerLexema().equals(")")){
analizadorLexico.retroceso();
param("main");
param_list("main");
}else{
analizadorLexico.retroceso();
}
}
tokenActual = analizadorLexico.consumirToken();
if(tokenActual.obtenerLexema().equals(")")){ // cierre de parentesis de la declaracion de la funcion
tokenActual = analizadorLexico.consumirToken();
if(tokenActual.obtenerLexema().equals("{")){ // se abren llaves
COUNTER_SCOPE++;
CURRENT_SCOPE = COUNTER_SCOPE;
compound_stmt(); // se busca un conjunto de sentencias (cuerpo de funcion)
tokenActual = analizadorLexico.consumirToken();
if(tokenActual!=null){
if(tokenActual.obtenerLexema().equals("}")){ // fin de declaracion de funcion
CURRENT_SCOPE = CURRENT_SCOPE - COUNTER_SCOPE;
}else{
error(10,tokenActual.obtenerLexema(),tokenActual.obtenerLinea());
}
}else{
error(10,tokenActual.obtenerLexema(),tokenActual.obtenerLinea());
}
}else{
error(9,tokenActual.obtenerLexema(),tokenActual.obtenerLinea());
}
}else{
error(8,tokenActual.obtenerLexema(),tokenActual.obtenerLinea()); // falta el parentesis de cierre de la declaracion de la funcion
}
break;
default:
error(11,tokenActual.obtenerLexema(),tokenActual.obtenerLinea()); // no se encontro ni ";", "(" o "[" lanzamos un error preguntando por el ";"
}
} |
0d5c20ae-0434-41ea-b156-f845852499fc | 0 | @Test(expected = ParkException.class)
public void out_a_car_when_all_park_is_empty() {
parkBoy.out(new Ticket());
} |
3223a4e5-ccc1-4a30-a4ff-84522017053c | 0 | public Date getDefaultTime() {
return defaultTime;
} |
85c4dbea-b2b5-45ff-87b1-cf7c4b56a12b | 8 | public static void dec0_custom_memory()
{
GAME=0;
//i8751_timer=NULL;
if (strcmp(Machine.gamedrv.name,"hbarrelw")==0) hbarrel_custom_memory();
if (strcmp(Machine.gamedrv.name,"hbarrel")==0) hbarrelu_custom_memory();
if (strcmp(Machine.gamedrv.name,"baddudes")==0) GAME=2;
if (strcmp(Machine.gamedrv.name,"drgninja")==0) GAME=2;
if (strcmp(Machine.gamedrv.name,"birdtry")==0) GAME=3;
if (strcmp(Machine.gamedrv.name,"robocop")==0) robocop_custom_memory();
if (strcmp(Machine.gamedrv.name,"hippodrm")==0) hippodrm_custom_memory();
if (strcmp(Machine.gamedrv.name,"ffantasy")==0) hippodrm_custom_memory();
} |
f7d2ce52-19f8-4ab3-aaca-c04e96c5b716 | 5 | public void onRender(GameContainer gc, Graphics g, StateBasedGame game){
float mouseX = gc.getInput().getMouseX();
float mouseY = gc.getInput().getMouseY();
if(mouseX >= x && mouseX <= x + width && mouseY >= y && mouseY <= y+height){
highlightFont.drawString(x, y, text, highlightColor);
if(gc.getInput().isMousePressed(0)){
this.onClick(gc,g,game);
}
} else {
font.drawString(x + (highlightWidth - width) / 2, y + (highlightHeight - height) / 2, text, standardColor);
}
} |
753663bf-6f62-482d-bb40-158c1140e606 | 5 | public int score(String[] cards)
{
int c = 0;
String a;
for(int i = 0; i < cards.length; i++)
{
a = cards[i].substring(0, 1);
if(a.equalsIgnoreCase("A"))
c += 11;
else
if(a.equalsIgnoreCase("K") || a.equalsIgnoreCase("Q") || a.equalsIgnoreCase("T"))
c += 10;
else
c += Integer.parseInt(a);
}
return c;
} |
fe3a23d6-93c3-4258-b09c-266e17afb4ae | 1 | @Test
public void getLeegKnooppunt() {
Knooppunt knooppunt = null;
for (int i = 0; i < 100; i++) {
knooppunt = eenSpeelveld1.getLeegKnooppunt();
assertEquals(eenVeldType1[knooppunt.rij][knooppunt.kol], VeldType.LEEG) ;
}
} |
952ab419-fc8f-44c0-bdc2-76dfc948b0f4 | 3 | private JSONWriter end(char m, char c) throws JSONException {
if (this.mode != m) {
throw new JSONException(m == 'o' ? "Misplaced endObject." :
"Misplaced endArray.");
}
this.pop(m);
try {
this.writer.write(c);
} catch (IOException e) {
throw new JSONException(e);
}
this.comma = true;
return this;
} |
655c149f-a910-4b8c-8652-ff3e0773b3f1 | 9 | private List<String> ParseMIX(String lines[], int end_idx) {
StringBuilder record = new StringBuilder(RECORD_INIT_SIZE);
List<String> records = new ArrayList<String>();
for (int i = 0; i < end_idx; i++) {
boolean match_first = first_line_pattern_.matcher(lines[i]).matches();
boolean match_last = last_line_pattern_.matcher(lines[i]).matches();
if (LOG.isDebugEnabled()) {
LOG.debug("Process Line: " + lines[i]);
}
if (match_first) {
if (record.length() > 0) {
// means the previous line is also the end line of current record
records.add(record.toString());
if (LOG.isDebugEnabled()) {
LOG.debug("MATCH START, Get a new record(which miss its end line):"
+ record.toString());
}
}
// create a new record
record = new StringBuilder(RECORD_INIT_SIZE);
if (match_last) {
// current line is a record(first last both matched);
// records.add(lines[i] + FlumeConstants.LINE_SEP);
// we use our Split method, no need to add LINE_SEP
records.add(lines[i]);
if (LOG.isDebugEnabled()) {
LOG.debug("MATCH START-LAST, Get a new record:" + lines[i]);
}
} else {
record.append(lines[i]);
// record.append(FlumeConstants.LINE_SEP);
}
} else if (match_last) {
record.append(lines[i]);
// record.append(FlumeConstants.LINE_SEP);
records.add(record.toString());
if (LOG.isDebugEnabled()) {
LOG.debug("MATCH LAST, Get a new record:" + record.toString());
}
record = null;
record = new StringBuilder(RECORD_INIT_SIZE);
} else {
record.append(lines[i]);
// this is a middle line, we recovery it's '\n' character
// in parserecord, new Split called
// record.append(FlumeConstants.LINE_SEP);
}
}
HandleSpecialSituation(record, records);
record = null;
return records;
} |
40b13fb1-78fd-4443-a1f8-cf480831c666 | 2 | public Piece getPiece(int index) {
if (this.pieces == null) {
throw new IllegalStateException("Torrent not initialized yet.");
}
if (index >= this.pieces.length) {
throw new IllegalArgumentException("Invalid piece index!");
}
return this.pieces[index];
} |
97d3c684-272b-485f-ba58-24653dd73e4a | 9 | static int multiplications(int target)
{
LinkedList<ArrayList<Integer>> sets = new LinkedList<ArrayList<Integer>>();
ArrayList<Integer> starterSet = new ArrayList<Integer>();
starterSet.add(1);
sets.addFirst(starterSet);
int currentRound = 1;
while (true)
{
boolean found = false;
int numSets = sets.size();
for (int i = 0; i < numSets; i++)
{
ArrayList<Integer> currentSet = sets.removeFirst();
int setSize = currentSet.size();
for (int j = 0; j < setSize; j++)
for (int k = 0; k < setSize; k++)
{
int product = currentSet.get(j) + currentSet.get(k);
if (product == target)
found = true;
else if (product < target && !currentSet.contains(product))
{
ArrayList<Integer> nextSet = copy(currentSet);
nextSet.add(product);
if (unique(sets, nextSet))
sets.addLast(nextSet);
}
}
}
if (found)
break;
currentRound++;
}
return currentRound;
} |
f03a03b1-0be5-4127-9d8a-b23ff8ac9d30 | 4 | public static String join(Collection<?> c, String deli) {
StringBuilder sb = new StringBuilder();
if (c.size() > 0) {
boolean first = true;
for (Object o : c) {
if (!first) {
sb.append(deli);
} else {
first = false;
}
sb.append(o.toString());
}
}
return sb.toString();
} |
7586009f-d5d1-4847-a4d1-fa4a53adf9f5 | 7 | public void input() {
mouseX = Mouse.getX();
mouseY = Display.getHeight() - Mouse.getY();
mouseLeft = Mouse.isButtonDown(0);
mouseRight = Mouse.isButtonDown(1);
while(Keyboard.next()){
if(Keyboard.getEventKeyState()){}else{
if (Keyboard.getEventKey() == Keyboard.KEY_S && Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) {
Creature p = new Creature(Color.YELLOW);
p.x = playerX;
p.y = playerY;
p.name = Molybdenum.settings.PLAYER_NAME;
mio.saveMap(mapData);
}
if (Keyboard.getEventKey() == Keyboard.KEY_L && Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) {
mapData = mio.loadMap();
}
if (Keyboard.getEventKey() == Keyboard.KEY_SPACE) {
System.out.print(mapData.map[mouseY/th][mouseX/tw].character);
}
}
}
} |
62dd43ad-4ec5-4556-b025-12f0e84ab2a6 | 0 | private CarJsonConverter() {
} |
add7a863-907d-48a9-a63f-103ee210bf27 | 6 | public static void main(String[] args) {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Midi files", "mid");
chooser.setFileFilter(filter);
System.out.println("Enter operation (grt/w/b): ");
Scanner scanIn = new Scanner(System.in);
String input = scanIn.nextLine();
input = input.toLowerCase();
//old read method, use gr now
/*
if(input.equals("r")){
File bpath = new File("Songs/Bach");
File [] bfiles = bpath.listFiles();
File cpath = new File("Songs/Chopin");
File [] cfiles = cpath.listFiles();
for (int i = 0; i < bfiles.length && i < cfiles.length; i++){
if (bfiles[i].isFile()&&cfiles[i].isFile()){
Reader.buildLibrary(bfiles[i].getPath(),cfiles[i].getPath());
Reader.weightRhythms("trees.txt", "percents.txt");
}
}
}
*/
//really old, use b or w
/*
else if(input.equals("s")){
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
String filePath = chooser.getSelectedFile().getAbsolutePath();
SinglePhraseSelector.read(filePath, 100, 1, 0, 0);
}
}
*/
//use for single song, use b for a folder of songs
if(input.equals("w")){
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
//choose your song with this
String filePath = chooser.getSelectedFile().getAbsolutePath();
WholeSongAnalysisBigram.analisisTrigramMethod(filePath);
}
}
//calls the GeneralReader class to analyze a library of music
//only does bigrams
/*
else if(input.equals("gr")){
System.out.println("Enter Composer Name: ");
input = scanIn.nextLine();
//path just needs to point at the folder containing
//the library of songs for a composer. Was set up this ways
//just from how I organized music into the folder "Songs/[composer]"
File path = new File("Songs/"+input);
File [] files = path.listFiles();
for (int i = 0; i < files.length; i++){
if (files[i].isFile()){
GeneralReader.read(files[i].getPath(),input);
}
}
}
*/
//tests a batch of music against the data from libraries
else if(input.equals("b")){
System.out.println("Enter Composer Name: ");
input = scanIn.nextLine();
File path = new File("Songs/"+input+" Test Songs");
File[] files = path.listFiles();
BatchTester.test(files, input);
}
//calls GeneralReaderTrigram to analyze a library
else if(input.equals("grt")){
System.out.println("Enter Composer Name: ");
input = scanIn.nextLine();
//path just needs to point at the folder containing
//the library of songs for a composer. Was set up this ways
//just from how I organized music into the folder "Songs/[composer]"
File path = new File("Songs/"+input);
File [] files = path.listFiles();
for (int i = 0; i < files.length; i++){
if (files[i].isFile()){
GeneralReaderTrigram.read(files[i].getPath(),input);
}
}
}
else{
//default
}
scanIn.close();
} |
508a61d4-5a2b-48b2-9e63-26d520c6a5c2 | 4 | protected int match(int c, int pos, CodeIterator iterator,
int typedesc, ConstPool cp) throws BadBytecode
{
if (newIndex == 0) {
int nt = cp.addNameAndTypeInfo(cp.addUtf8Info(newMethodname),
typedesc);
int ci = cp.addClassInfo(newClassname);
if (c == INVOKEINTERFACE)
newIndex = cp.addInterfaceMethodrefInfo(ci, nt);
else {
if (newMethodIsPrivate && c == INVOKEVIRTUAL)
iterator.writeByte(INVOKESPECIAL, pos);
newIndex = cp.addMethodrefInfo(ci, nt);
}
constPool = cp;
}
iterator.write16bit(newIndex, pos + 1);
return pos;
} |
7dbb5ae4-003b-46dd-9c31-fc4615f8ee82 | 0 | protected void interrupted() {
end();
} |
5b7b080d-dffb-45d0-96b9-37de30212837 | 1 | public void processEvent(AWTEvent e) {
if (e.getID() == Event.WINDOW_DESTROY) {
dispose();
} else {
super.processEvent(e);
}
} |
6035a32a-1461-4bc1-9336-96c0a2c0ec8d | 4 | public static boolean renderItemIn3d(int i) {
return i == 0 ? true : (i == 13 ? true : (i == 10 ? true : (i == 11 ? true : i == 16)));
} |
5b008150-c73b-41ca-9685-938c3eaa685b | 1 | public void create(String query){
try {
this.statement.executeQuery(query);
} catch (SQLException ex) {
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
}
} |
24c69517-e472-4dc2-9998-8044191d2b9c | 1 | public final void visitTableSwitchInsn(final int min, final int max,
final Label dflt, final Label[] labels) {
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute("", "min", "min", "", Integer.toString(min));
attrs.addAttribute("", "max", "max", "", Integer.toString(max));
attrs.addAttribute("", "dflt", "dflt", "", getLabel(dflt));
String o = AbstractVisitor.OPCODES[Opcodes.TABLESWITCH];
addStart(o, attrs);
for (int i = 0; i < labels.length; i++) {
AttributesImpl att2 = new AttributesImpl();
att2.addAttribute("", "name", "name", "", getLabel(labels[i]));
addElement("label", att2);
}
addEnd(o);
} |
664743ee-1226-4b6e-b634-b4359da4ec98 | 3 | @Override
public Funcao listById(int id) {
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
Funcao f = new Funcao();
try {
conn = ConnectionFactory.getConnection();
pstm = conn.prepareStatement(LISTBYID);
pstm.setInt(1, id);
rs = pstm.executeQuery();
while (rs.next()) {
f.setCodigo(rs.getInt("codigo"));
f.setNome(rs.getString("nome"));
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Erro ao listar" + ex.getMessage());
} finally {
try {
ConnectionFactory.closeConnection(conn, pstm, rs);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Erro ao fechar conexão" + ex.getMessage());
}
}
return f;
} |
439cbaa6-7ca4-48bd-a80d-82f9cd80c662 | 3 | @Override
protected void initializeCPointer() {
assert this.cPointer != 0;
assert tracer != null;
assert name != null;
final int r = ppaml_phase_init(tracer.cPointer, this.cPointer, name);
switch (r) {
case 0:
break;
case -1:
throw new java.lang.OutOfMemoryError(
"failed to convert Java string to C string");
case 1:
throw new OTFWriterPhaseDefinitionException();
default:
throw new UnexpectedReturnValueError(r);
}
} |
4a287d9b-9419-4f13-acc9-49fbd9c2db29 | 8 | protected void setInstancesFromDBaseQuery() {
try {
if (m_InstanceQuery == null) {
m_InstanceQuery = new InstanceQuery();
}
String dbaseURL = m_InstanceQuery.getDatabaseURL();
String username = m_InstanceQuery.getUsername();
String passwd = m_InstanceQuery.getPassword();
/*dbaseURL = (String) JOptionPane.showInputDialog(this,
"Enter the database URL",
"Query Database",
JOptionPane.PLAIN_MESSAGE,
null,
null,
dbaseURL);*/
DatabaseConnectionDialog dbd= new DatabaseConnectionDialog(null,dbaseURL,username);
dbd.setVisible(true);
//if (dbaseURL == null) {
if (dbd.getReturnValue()==JOptionPane.CLOSED_OPTION) {
m_FromLab.setText("Cancelled");
return;
}
dbaseURL=dbd.getURL();
username=dbd.getUsername();
passwd=dbd.getPassword();
m_InstanceQuery.setDatabaseURL(dbaseURL);
m_InstanceQuery.setUsername(username);
m_InstanceQuery.setPassword(passwd);
m_InstanceQuery.setDebug(dbd.getDebug());
m_InstanceQuery.connectToDatabase();
if (!m_InstanceQuery.experimentIndexExists()) {
System.err.println("not found");
m_FromLab.setText("No experiment index");
m_InstanceQuery.disconnectFromDatabase();
return;
}
System.err.println("found");
m_FromLab.setText("Getting experiment index");
Instances index = m_InstanceQuery.retrieveInstances("SELECT * FROM "
+ InstanceQuery.EXP_INDEX_TABLE);
if (index.numInstances() == 0) {
m_FromLab.setText("No experiments available");
m_InstanceQuery.disconnectFromDatabase();
return;
}
m_FromLab.setText("Got experiment index");
DefaultListModel lm = new DefaultListModel();
for (int i = 0; i < index.numInstances(); i++) {
lm.addElement(index.instance(i).toString());
}
JList jl = new JList(lm);
jl.setSelectedIndex(0);
int result;
// display dialog only if there's not just one result!
if (jl.getModel().getSize() != 1) {
ListSelectorDialog jd = new ListSelectorDialog(null, jl);
result = jd.showDialog();
}
else {
result = ListSelectorDialog.APPROVE_OPTION;
}
if (result != ListSelectorDialog.APPROVE_OPTION) {
m_FromLab.setText("Cancelled");
m_InstanceQuery.disconnectFromDatabase();
return;
}
Instance selInst = index.instance(jl.getSelectedIndex());
Attribute tableAttr = index.attribute(InstanceQuery.EXP_RESULT_COL);
String table = InstanceQuery.EXP_RESULT_PREFIX
+ selInst.toString(tableAttr);
setInstancesFromDatabaseTable(table);
} catch (Exception ex) {
// 1. print complete stacktrace
ex.printStackTrace();
// 2. print message in panel
m_FromLab.setText("Problem reading database: '" + ex.getMessage() + "'");
}
} |
85dcb865-3726-4616-a3bd-ef241adc1f84 | 1 | public void releaseRemoteLock(String source){
synchronized (this) {
if(lockedBy.equalsIgnoreCase(source)){
isLOcked = false;
lockedBy = null;
}
}
} |
a804e701-c3e1-4863-add3-cfe5f64d7463 | 4 | @Override
public State transition(TransitionContext context)
{
if(context.isLetter() || context.value() == '_' || context.isDigit())
{
context.pushChar();
return this;
}
String word = context.accumulated();
context.emit(context.getKeywords().containsKey(word)
? context.getKeywords().get(word)
: Kind.IDENTIFIER);
return StartState.instance().transition(context);
} |
b2821fc2-11bf-4fd8-8a4f-86294d5bb229 | 4 | @SuppressWarnings({ "rawtypes", "unchecked" })
public boolean validate(T t) {
Class classType = t.getClass();
Class fieldType = isValidField(classType);
String accessorMethod = null;
Object actualValue = null;
Object validatorValue = null;
if (fieldType.toString() == Boolean.class.getSimpleName()) {
accessorMethod = new StringBuilder(IS_METHOD_PREFIX).append(field)
.toString();
} else {
accessorMethod = new StringBuilder(GET_METHOD_PREFIX).append(WordUtils.capitalize(field))
.toString();
}
if (fieldType == Integer.class) {
validatorValue = Integer.parseInt(value);
} else if (fieldType == Boolean.class) {
validatorValue = Boolean.valueOf(value);
} else if (fieldType == String.class) {
validatorValue = value;
}
actualValue = fetchFieldValue(t, accessorMethod, actualValue);
return operator.operate(validatorValue, actualValue);
} |
56820ec4-2fd6-4792-a3ec-2359888a04a7 | 2 | private void displayOneLiner(CommandSender sender, CodCommand meta) {
String cmd = getCommand(meta);
if (meta.usage().length == 1) {
sender.sendMessage(meta.usage()[0].replace("<command>", cmd));
} else {
StringBuilder sb = new StringBuilder();
sb.append("§2");
sb.append(getCommand(meta));
sb.append(" §f=§b '/");
sb.append(parentCommand);
sb.append(" help ");
sb.append(meta.command());
if (!meta.subcommand().isEmpty()) {
sb.append(' ');
sb.append(meta.subcommand());
}
sb.append("' for full usage.");
sender.sendMessage(sb.toString());
}
} |
69932443-9642-46bf-ad9a-38431a5ec620 | 9 | public String receiveMessage() {
throw_exception();
if(block_channel==1){
return null;
}
if(reorder_msg==0){
synchronized(test_network.test_queues[test_index]) {
if(lose_msg==1){
while(!test_network.test_queues[test_index].isEmpty())
test_network.test_queues[test_index].remove();
}
else{
if (!test_network.test_queues[test_index].isEmpty()){
String msg=test_network.test_queues[test_index].remove();
update_MessageTrace(" Recv <- "+msg);
return msg;
}
else
return null;
}
}
}
if(reorder_msg==1){
synchronized(test_network.test_stacks[test_index]) {
if(lose_msg==1){
while(!test_network.test_stacks[test_index].isEmpty())
test_network.test_stacks[test_index].pop();
}
else{
if (!test_network.test_stacks[test_index].isEmpty()){
String msg=test_network.test_stacks[test_index].pop();
update_MessageTrace(" Recv <- "+msg);
return msg;
}
else
return null;
}
}
}
return null;
} |
a04887a3-528f-47f9-9bef-8581da1657df | 7 | public void buildClassifier(Instances data) throws Exception {
// can classifier handle the data?
getCapabilities().testWithFail(data);
// remove instances with missing class
data = new Instances(data);
data.deleteWithMissingClass();
if (!(m_Classifier instanceof weka.classifiers.meta.nestedDichotomies.ND) &&
!(m_Classifier instanceof weka.classifiers.meta.nestedDichotomies.ClassBalancedND) &&
!(m_Classifier instanceof weka.classifiers.meta.nestedDichotomies.DataNearBalancedND)) {
throw new IllegalArgumentException("END only works with ND, ClassBalancedND " +
"or DataNearBalancedND classifier");
}
m_hashtable = new Hashtable();
m_Classifiers = Classifier.makeCopies(m_Classifier, m_NumIterations);
Random random = data.getRandomNumberGenerator(m_Seed);
for (int j = 0; j < m_Classifiers.length; j++) {
// Set the random number seed for the current classifier.
((Randomizable) m_Classifiers[j]).setSeed(random.nextInt());
// Set the hashtable
if (m_Classifier instanceof weka.classifiers.meta.nestedDichotomies.ND)
((weka.classifiers.meta.nestedDichotomies.ND)m_Classifiers[j]).setHashtable(m_hashtable);
else if (m_Classifier instanceof weka.classifiers.meta.nestedDichotomies.ClassBalancedND)
((weka.classifiers.meta.nestedDichotomies.ClassBalancedND)m_Classifiers[j]).setHashtable(m_hashtable);
else if (m_Classifier instanceof weka.classifiers.meta.nestedDichotomies.DataNearBalancedND)
((weka.classifiers.meta.nestedDichotomies.DataNearBalancedND)m_Classifiers[j]).
setHashtable(m_hashtable);
// Build the classifier.
m_Classifiers[j].buildClassifier(data);
}
} |
941294db-ccab-4bfd-b1ef-af26b91a65b5 | 1 | public void zoomOut(double mouseXCoord, double mouseYCoord)
{
if (visibleArea.getyLength() + quadTreeToDraw.getQuadTreeLength() / 10 >= quadTreeToDraw.getQuadTreeLength())
{
return;
}
double mouseMapXCoord = convertMouseXToMap(mouseXCoord);
double mouseMapYCoord = convertMouseYToMap(mouseYCoord);
double mouseLengthX = mouseMapXCoord - visibleArea.getxCoord();
double mouseLengthY = mouseMapYCoord - visibleArea.getyCoord();
double xPct = mouseLengthX / visibleArea.getxLength();
double yPct = mouseLengthY / visibleArea.getyLength();
double xZoomLength = visibleArea.getxLength() * zoomOutConstant;
double yZoomLength = visibleArea.getyLength() * zoomOutConstant;
double deltaXLength = visibleArea.getxLength() - xZoomLength;
double deltaYLength = visibleArea.getyLength() - yZoomLength;
visibleArea.setCoord(visibleArea.getxCoord() + deltaXLength * xPct, visibleArea.getyCoord() + deltaYLength * yPct, xZoomLength, yZoomLength);
} |
61475b8c-4b8c-40d4-bb7b-9784facbf649 | 9 | @Override
public boolean isEnspelled(Physical F)
{
for(int a=0;a<F.numEffects();a++) // personal affects
{
final Ability A=F.fetchEffect(a);
if((A!=null)&&(A.canBeUninvoked())&&(!A.isAutoInvoked())&&(!A.isSavable())
&&(((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_SPELL)
||((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_PRAYER)
||((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_CHANT)
||((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_SONG)))
return true;
}
return false;
} |
f5aeb411-581d-467d-9750-7a759e584a6f | 1 | final void load() throws IOException {
if (!isLoaded) {
HtmlPage page = loadPage(url);
resources = fetchResources(page);
articleHtml = fetchArticleHtml(page, resources);
articleTitle = fetchArticleTitle(page);
isLoaded = true;
LOG.info(format("Загружена статья: \"%s\"", getName()));
}
} |
02a05dbe-3cb8-4cc8-ab41-ee921bc3533f | 1 | public void showPortrait(boolean s) {
if (portraitHUD != null) {
portraitHUD.setShouldRender(s);
}
} |
3cf83c4f-357f-4500-ad0e-702fec4f1b28 | 8 | private void filterButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_filterButtonActionPerformed
String keyword = searchTextField.getText().toLowerCase();
Date from = (Date) dateFromSpinner.getValue();
Date to = (Date) dateToSpinner.getValue();
if (from.after(to)) {
Date temp = to;
to = from;
from = temp;
}
Vector<NotePad> vector = new Vector<>();
for (NotePad notePad : NotePadManager.getInstance().getNotepads()) {
boolean isFilterSuccess = false;
if (!keyword.isEmpty()) {
// Фильтр по значению
if (notePad.getDescription().toLowerCase().indexOf(keyword) >= 0) {
isFilterSuccess = true;
}
if (notePad.getName().toLowerCase().indexOf(keyword) >= 0) {
isFilterSuccess = true;
}
}
// Фильтр по дате
Date current = notePad.getDate();
if (from.before(current) && to.after(current)) {
isFilterSuccess = true;
}
if (isFilterSuccess) vector.add(notePad);
}
noteList.setListData(vector);
}//GEN-LAST:event_filterButtonActionPerformed |
ade5fdc0-25ec-4d23-bd81-253bc2c6cb23 | 5 | public static StompFrame factory(String wholeMessage){
HashMap<String, String> headers= parseHeaders(wholeMessage);
if (headers == null)
return ErrorFrame.factory(wholeMessage, "cannot read headers");
if (headers.get("accept-version") == null)
return ErrorFrame.factory(wholeMessage, "invalid connection: no accept-version entered");
if (headers.get("host") == null)
return ErrorFrame.factory(wholeMessage, "invalid connection: no host entered");
if (headers.get("login") == null)
return ErrorFrame.factory(wholeMessage, "invalid connection: no username entered");
if (headers.get("passcode") == null)
return ErrorFrame.factory(wholeMessage, "invalid connection: no passcode entered");
return new ConnectFrame(wholeMessage);
} |
d8dd88be-7941-4561-a544-b16b660bc229 | 6 | @Override
public boolean processObjectClick2(WorldObject object) {
int id = object.getId();
if (id == 36579 || id == 36586) {
player.getInventory().addItem(new Item(4049, 5));
return false;
} else if (id == 36575 || id == 36582) {
player.getInventory().addItem(new Item(4053, 5));
return false;
} else if (id == 36577 || id == 36584) {
player.getInventory().addItem(new Item(4045, 5));
return false;
}
return true;
} |
81467a05-9e66-4572-8755-62bb3897f294 | 5 | public double maf() {
double maf = -1;
// Do we have it annotated as AF or MAF?
if (hasField("AF")) maf = getInfoFloat("AF");
else if (hasField("MAF")) maf = getInfoFloat("MAF");
else {
// No annotations, we have to calculate
int ac = 0, count = 0;
for (VcfGenotype gen : this) {
count += 2;
int genCode = gen.getGenotypeCode();
if (genCode > 0) ac += genCode;
}
maf = ((double) ac) / count;
}
// Always use the Minor Allele Frequency
if (maf > 0.5) maf = 1.0 - maf;
return maf;
} |
c5918b51-e10f-4917-8b96-6d3f95318994 | 1 | public boolean register(String userID, String password, String email) {
// TODO Auto-generated method stub
ClientDB c = new ClientDB(userID, password, email);
if(getFact.addUser(c)){
return true;
}
else
return false;
} |
85f68ffd-fb32-49c6-9d02-5ef5bb58cdf0 | 8 | public final void list_iter() throws RecognitionException {
try {
// Python.g:419:11: ( list_for | list_if )
int alt120=2;
int LA120_0 = input.LA(1);
if ( (LA120_0==82) ) {
alt120=1;
}
else if ( (LA120_0==85) ) {
alt120=2;
}
else {
if (state.backtracking>0) {state.failed=true; return;}
NoViableAltException nvae =
new NoViableAltException("", 120, 0, input);
throw nvae;
}
switch (alt120) {
case 1 :
// Python.g:419:13: list_for
{
pushFollow(FOLLOW_list_for_in_list_iter3742);
list_for();
state._fsp--;
if (state.failed) return;
}
break;
case 2 :
// Python.g:420:13: list_if
{
pushFollow(FOLLOW_list_if_in_list_iter3756);
list_if();
state._fsp--;
if (state.failed) return;
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
// do for sure before leaving
}
} |
dec1d121-4b0d-47ff-aa5d-0c9413db2810 | 5 | public void update() {
switch(Keyboard.getEventKey()) {
case Keyboard.KEY_W:
setUp(Keyboard.getEventKeyState());
break;
case Keyboard.KEY_A:
setLeft(Keyboard.getEventKeyState());
break;
case Keyboard.KEY_S:
setDown(Keyboard.getEventKeyState());
break;
case Keyboard.KEY_D:
setRight(Keyboard.getEventKeyState());
break;
case Keyboard.KEY_SPACE:
setAttack(Keyboard.getEventKeyState());
break;
default:
break;
}
setTime();
} |
82e474e4-4a75-43d0-ba1f-e9941c73f22c | 9 | public VariableStack mapStackToLocal(VariableStack stack) {
if (type == DOWHILE) {
VariableStack afterBody = bodyBlock.mapStackToLocal(stack);
if (afterBody != null)
mergeContinueStack(afterBody);
if (continueStack != null) {
VariableStack newStack;
int params = cond.getFreeOperandCount();
if (params > 0) {
condStack = continueStack.peek(params);
newStack = continueStack.pop(params);
} else
newStack = continueStack;
if (cond != TRUE)
mergeBreakedStack(newStack);
if (cond != FALSE)
stack.merge(newStack);
}
} else {
continueStack = stack;
VariableStack newStack;
int params = cond.getFreeOperandCount();
if (params > 0) {
condStack = stack.peek(params);
newStack = stack.pop(params);
} else
newStack = stack;
if (cond != TRUE)
breakedStack = newStack;
VariableStack afterBody = bodyBlock.mapStackToLocal(newStack);
if (afterBody != null)
mergeContinueStack(afterBody);
}
return breakedStack;
} |
35b2950e-d01a-4b6b-9b93-ed56e9f9f113 | 9 | private void collectWordInfo(String path, Searcher wid, String prefix,
ArrayList<ArrayList<WordInfo>> ws) throws ParseException, IOException {
final ReadLine rl = new ReadLine(path, encoding);
try {
for(String s=rl.read(); s!=null; s=rl.read()) {
final boolean iscomma = s.startsWith("\",\",");
final int p1 = iscomma ? 3 : s.indexOf(delim,1); // key
final int p2 = s.indexOf(delim,p1+1); // left id
final int p3 = s.indexOf(delim,p2+1); // right id
final int p4 = s.indexOf(delim,p3+1); // cost
if(p1==-1) throw parseException("Word surface must be terminated with '"+delim+"'.",path,rl);
if(p2==-1) throw parseException("Word left context id must be terminated with '"+delim+"'.",path,rl);
if(p3==-1) throw parseException("Word right context id must be terminated with '"+delim+"'.",path,rl);
if(p4==-1) throw parseException("Word cost must be terminated with '"+delim+"'.",path,rl);
final String data = s.substring(p4+1); // data
final int id = wid.search(prefix+(iscomma ? "," : s.substring(0,p1)));
if(id < 0)
throw parseException("Word '"+s.substring(0,p1)+"' is unregistered in trie",path,rl);
ws.get(id).add(new WordInfo(Short.valueOf(s.substring(p1+1,p2)),
Short.valueOf(s.substring(p2+1,p3)),
Short.valueOf(s.substring(p3+1,p4)),
data));
}
} catch (NumberFormatException e) {
throw parseException("Parse short integer failed. "+e.getMessage(),path,rl);
} finally {
rl.close();
}
} |
e401e5cd-0f35-42c9-ad04-a35c54795f5b | 3 | public void visitForceChildren(final TreeVisitor visitor) {
if (visitor.reverse()) {
for (int i = dimensions.length - 1; i >= 0; i--) {
dimensions[i].visit(visitor);
}
} else {
for (int i = 0; i < dimensions.length; i++) {
dimensions[i].visit(visitor);
}
}
} |
700b76b5-f919-43ae-9fe4-4010126d4cf9 | 0 | @Override
public void onDisable() {
Utils.Info("Version " + this.getDescription().getVersion() + " disabled.");
} |
09b7a6fe-c866-44a5-b655-03535b78bb6e | 0 | private void setDecisionQuest(DecisionQuest quest,
ArrayList<String> answerList, ArrayList<String> goToList) {
quest.setDecisionAnswer(answerList, goToList);
} |
d8830a27-9064-490c-9743-7f3cc2ef10de | 3 | private int LoadMapFromFile(String mapFilename) {
StringBuffer s = new StringBuffer();
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(mapFilename));
String line;
while ((line = in.readLine()) != null) {
s.append(line);
s.append("\n");
}
} catch (Exception e) {
return 0;
} finally {
try {
in.close();
} catch (Exception e) {
// Fucked.
}
}
return ParseGameState(s.toString());
} |
0454b1ff-56f4-445a-a34e-ef589bc02efd | 2 | public int yCoordToRowNumber(int y) {
Insets insets = getInsets();
if (y < insets.top)
return -1;
double rowHeight = (double)(getHeight()-insets.top-insets.bottom) / rows;
int row = (int)( (y-insets.top) / rowHeight);
if (row >= rows)
return rows;
else
return row;
} |
ca42e00d-a0c6-4a1c-bc0e-0846c5db8050 | 0 | public static void question11() {
/*
QUESTION PANEL SETUP
*/
questionLabel.setText("What kind of music do you listen to?");
questionNumberLabel.setText("11");
/*
ANSWERS PANEL SETUP
*/
//resetting
radioButton1.setSelected(false);
radioButton2.setSelected(false);
radioButton3.setSelected(false);
radioButton4.setSelected(false);
radioButton5.setSelected(false);
radioButton6.setSelected(false);
radioButton7.setSelected(false);
radioButton8.setSelected(false);
radioButton9.setSelected(false);
radioButton10.setSelected(false);
radioButton11.setSelected(false);
radioButton12.setSelected(false);;
radioButton13.setSelected(false);
radioButton14.setSelected(false);
//enability
radioButton1.setEnabled(true);
radioButton2.setEnabled(true);
radioButton3.setEnabled(true);
radioButton4.setEnabled(true);
radioButton5.setEnabled(false);
radioButton6.setEnabled(false);
radioButton7.setEnabled(false);
radioButton8.setEnabled(false);
radioButton9.setEnabled(false);
radioButton10.setEnabled(false);
radioButton11.setEnabled(false);
radioButton12.setEnabled(false);
radioButton13.setEnabled(false);
radioButton14.setEnabled(false);
//setting the text
radioButton1.setText("I love rock music.");
radioButton2.setText("I'm into classical music.");
radioButton3.setText("Modern music is the way to go.");
radioButton4.setText("All music is good.");
radioButton5.setText("No used");
radioButton6.setText("No used");
radioButton7.setText("No used");
radioButton8.setText("No used");
radioButton9.setText("No used");
radioButton10.setText("No used");
radioButton11.setText("No used");
radioButton12.setText("No used");
radioButton13.setText("No used");
radioButton14.setText("No used");
// Calculating the best guesses and showing them.
Knowledge.calculateAndColorTheEvents();
} |
7373fa20-6787-4955-8c5c-b4069f412747 | 3 | @Override
public void run() {
addSystemMessage("请选择备付金报表存放的文件夹");
while (true) {
// 如果队列里有消息,显示并移除
if (Main1.list.size() > 0) {
CheckResultMessage message = Main1.list.remove(0);
addMessage(message);
}
// 需要sleep
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |
533abc82-69ac-4c15-8d3b-728d0ecde057 | 8 | public List<DateWithDayCount> calculateFixingDates(List<DateWithDayCount> adjustedDates, ResetDates resetDates, HolidayCalendarContainer allCalendars) {
HolidayCalendarContainer resetCalendars = new HolidayCalendarContainer(allCalendars, resetDates.getResetDatesAdjustments().getBusinessCenters());
RelativeDateOffset initialFixingDate = resetDates.getInitialFixingDate();
RelativeDateOffset fixingDates = resetDates.getFixingDates();
HolidayCalendarContainer initialFixingCalendar = initialFixingDate == null ? null : new HolidayCalendarContainer(allCalendars, initialFixingDate.getBusinessCenters());
HolidayCalendarContainer fixingCalendars = new HolidayCalendarContainer(allCalendars, fixingDates.getBusinessCenters());
List<DateWithDayCount> result = new ArrayList<DateWithDayCount>(adjustedDates.size() - 1);
boolean resetInArrears = resetDates.getResetRelativeTo() == ResetRelativeToEnum.CALCULATION_PERIOD_END_DATE;
DateWithDayCount temp = new DateWithDayCount(0);
for(int first = resetInArrears ? 1 : 0, i = first, last = adjustedDates.size() - (resetInArrears ? 1 : 2); i <= last; i++) {
DateWithDayCount adjusted = adjustedDates.get(i);
temp.setDayCount(adjusted.getDayCount());
adjustDate(temp, resetDates.getResetDatesAdjustments().getBusinessDayConvention(), resetCalendars);
boolean isInitialFixing = initialFixingDate != null && i == first;
RelativeDateOffset offset = isInitialFixing ? initialFixingDate : fixingDates;
shift(temp, offset.getPeriodMultiplier(), offset.getPeriod(), offset.getDayType(), offset.getBusinessDayConvention(), isInitialFixing ? initialFixingCalendar : fixingCalendars);
// todo initial fixing date
if(temp.compareTo(adjusted) == 0) {
result.add(adjusted);
} else {
result.add(temp);
temp = new DateWithDayCount(0);
}
}
return result;
} |
27a9ac0e-201f-4fea-bd39-0bbef1fa9053 | 2 | public DefaultComboBoxModel<String> buildSelectCombo() {
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
if(!MapPanel.actors.isEmpty()) {
for(int x = 0; x<MapPanel.actors.size(); x++) {
model.addElement(MapPanel.actors.get(x).getID());
}
}
return model;
} |
23fa0f03-7a82-44c8-b095-3af348dfff3f | 9 | public void commit() throws IOException {
//write all uncommited free records
Iterator<Long> rowidIter = freeBlocksInTransactionRowid.iterator();
PageCursor curs = new PageCursor(pageman, Magic.FREELOGIDS_PAGE);
//iterate over filled pages
while (curs.next() != 0) {
long freePage = curs.getCurrent();
BlockIo curBlock = file.get(freePage);
FreeLogicalRowIdPage fp = FreeLogicalRowIdPage.getFreeLogicalRowIdPageView(curBlock, blockSize);
int slot = fp.getFirstFree();
//iterate over free slots in page and fill them
while(slot!=-1 && rowidIter.hasNext()){
long rowid = rowidIter.next();
short freePhysRowId = fp.alloc(slot);
fp.setLocationBlock(freePhysRowId, Location.getBlock(rowid));
fp.setLocationOffset(freePhysRowId, Location.getOffset(rowid));
slot = fp.getFirstFree();
}
file.release(freePage, true);
if(!rowidIter.hasNext())
break;
}
//now we propably filled all already allocated pages,
//time to start allocationg new pages
while(rowidIter.hasNext()){
//allocate new page
long freePage = pageman.allocate(Magic.FREELOGIDS_PAGE);
BlockIo curBlock = file.get(freePage);
FreeLogicalRowIdPage fp = FreeLogicalRowIdPage.getFreeLogicalRowIdPageView(curBlock, blockSize);
int slot = fp.getFirstFree();
//iterate over free slots in page and fill them
while(slot!=-1 && rowidIter.hasNext()){
long rowid = rowidIter.next();
short freePhysRowId = fp.alloc(slot);
fp.setLocationBlock(freePhysRowId, Location.getBlock(rowid));
fp.setLocationOffset(freePhysRowId, Location.getOffset(rowid));
slot = fp.getFirstFree();
}
file.release(freePage, true);
if(!rowidIter.hasNext())
break;
}
if(rowidIter.hasNext())
throw new InternalError();
freeBlocksInTransactionRowid.clear();
} |
e6993f0b-04a9-496d-aa2f-65d335f651fe | 6 | private void useBank() {
if (Util.inBank() && !Players.getLocal().isMoving()) {
if (Bank.open()) {
if (Bank.depositInventory()) {
int time = 0;
while (Inventory.isFull() && time <= 4000) {
time += 50;
Time.sleep(50);
}
}
}
}
} |
08d44ba8-09e3-49c4-b0a2-c8c90506306f | 6 | public void sendZMessages() throws PostServiceNotSetException{
if (this.postservice == null){
throw new PostServiceNotSetException();
}
switch (Athena.shuffleMessage){
case 1:
Object[] arrayx = this.getVariables().toArray();
arrayx = Utils.shuffleArrayFY(arrayx);
for (Object nodeVariable : arrayx) {
this.op.updateZ((NodeVariable)nodeVariable, postservice);
}
break;
case 0:
default:
for (NodeVariable nodeVariable:this.getVariables()){
if (debug>=3) {
String dmethod = Thread.currentThread().getStackTrace()[2].getMethodName();
String dclass = Thread.currentThread().getStackTrace()[2].getClassName();
System.out.println("---------------------------------------");
System.out.println("[class: "+dclass+" method: " + dmethod+ "] agent "+this+"" + "preparing to update ZMessage for "+nodeVariable);
System.out.println("---------------------------------------");
}
this.op.updateZ(nodeVariable, postservice);
}
}
} |
a1ccee03-a6ec-4d82-8330-50c4b2c32718 | 2 | @Override
public void init(ServletConfig config) throws ServletException {
try {
// Create a JNDI Initial context to be able to lookup the DataSource
InitialContext ctx = new InitialContext();
// Lookup the DataSource.
pool = (DataSource)ctx.lookup("java:comp/env/jdbc/mysql_ebookshop");
if (pool == null)
throw new ServletException("Unknown DataSource 'jdbc/mysql_ebookshop'");
} catch (NamingException ex) {
Logger.getLogger(EntryServlet.class.getName()).log(Level.SEVERE, null, ex);
}
} |
fefd72da-5801-4e80-8b02-3ced43dd8a36 | 0 | public void setCuenta(String cuenta) {
this.cuenta = cuenta;
} |
26665bb1-625b-45ca-9661-bfa6c8dfdb26 | 0 | public StringResource(String value) {
this.value = value;
} |
fe434555-9c5f-436a-8c4c-d30dfffc9a77 | 0 | public static void setFrameInfoList(Vector list) {
frameInfoList = list;
} |
6d9cc51a-6c9d-43d1-b56a-dd8c12d26942 | 0 | public String toLowerCase(String input){
return input.toLowerCase();
} |
8cd353c0-6187-4f47-8194-c21a175ebbd3 | 1 | public boolean isLambdaTransition(Transition transition) {
FSATransition trans = (FSATransition) transition;
if (trans.getLabel().equals(LAMBDA))
return true;
return false;
} |
698db84b-744e-42f8-9fb0-04ff094f8224 | 7 | public void run() {
int frameCount = 0;
while(_soundSupported){
// if(bufferReady) {
if(oldWay) {
soundInputLine.write(soundBuffer, soundBufferOffset, soundBufferChunkSize);
notifyBufferUpdates( soundBufferOffset, soundBufferChunkSize);
soundBufferOffset += soundBufferChunkSize;
if(soundBufferOffset >= soundBuffer.length) {
soundBufferOffset = 0;
}
System.out.println("Count:" + lastCount + " Index: " + soundBufferIndex + " Written:" + soundInputLine.write(soundBuffer, 0, soundBuffer.length));
lastCount = 0;
if(drainMode) {
frameCount++;
if(frameCount == 10){
frameCount = 0;
soundInputLine.drain();
}
}
} else if(soundInputLine.available() > soundBufferChunkSize) {
// if(soundInputLine.available() >= soundBuffer.length){
int written = soundInputLine.write(soundBuffer, soundBufferOffset, soundBufferChunkSize);
//int written = soundInputLine.write(soundBuffer, 0, soundBuffer.length);
System.out.println("Wrote:" + written + " had:" + lastCount);
lastCount -= soundBufferChunkSize;
if(lastCount > actualBufferSize){
soundInputLine.write(soundBuffer, 0, actualBufferSize);
soundInputLine.drain();
lastCount = 0;
}
}
}
} |
b8bd7971-ea50-445a-8458-a67169ce933f | 7 | private void startClustersMonitor(){
try{
// Create a new selector
Selector selector = Selector.open();
// Create a new non-blocking server socket channel
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
InetSocketAddress isa = new InetSocketAddress(this.clustersPort);// 集群端口
serverChannel.socket().bind(isa);
// Register the server socket channel, indicating an interest in
// accepting new connections
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
log.info("集群服务器准备就绪,等待集群请求到来");
while(noStopRequested){
try {
int num = 0;
// Wait for an event one of the registered channels
num = selector.select(100);
if (num > 0) {
// Iterate over the set of keys for which events are available
Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
while (selectedKeys.hasNext()) {
SelectionKey key = (SelectionKey) selectedKeys.next();
selectedKeys.remove();
if (!key.isValid()) {
continue;
}
// Check what event is available and deal with it
if (key.isAcceptable()) {
this.accept(key,true);// 注册集群连接
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
serverChannel.close();// 关闭服务器
}catch(Exception e){
e.printStackTrace();
System.out.println("Clusters Server start up fail");
}
} |
b04e1c67-e6db-4948-8470-1199371e9a8e | 8 | protected void processMinMaxRecordTime(final LineTermInfoHandler termInfo) {
if (termInfo == null) {
return;
}
if (termInfo.javaDate == null) {
return;
}
final Calendar cal = GregorianCalendar.getInstance();
cal.setTime(termInfo.javaDate);
if (this.minRecordTime == null) {
this.minRecordTime = termInfo.javaDate;
} else {
final Calendar calchk2 = GregorianCalendar.getInstance();
calchk2.setTime(this.minRecordTime);
if (calchk2.after(cal)) {
this.minRecordTime = termInfo.javaDate;
}
}
if (this.maxRecordTime == null) {
this.maxRecordTime = termInfo.javaDate;
} else {
final Calendar calchk2 = GregorianCalendar.getInstance();
calchk2.setTime(this.maxRecordTime);
if (calchk2.before(cal)) {
this.maxRecordTime = termInfo.javaDate;
}
}
if (this.maxRecordTime != null && this.minRecordTime != null) {
final long diff = this.maxRecordTime.getTime() - this.minRecordTime.getTime();
this.diffTimeHours = (diff / 1000.0) / (60.0 * 60.0);
}
} |
90bbde2f-8f33-48f2-945d-be468e4dae55 | 7 | public int removeEdge(Integer source, Integer target) {
if (!directed) {
for (Iterator<AdjacencyListElement> iter = lists[source].iterator(); iter.hasNext();) {
AdjacencyListElement e = iter.next();
if (e.target.equals(target)) {
iter.remove();
}
}
for (Iterator<AdjacencyListElement> iter = lists[target].iterator(); iter.hasNext();) {
AdjacencyListElement e = iter.next();
if (e.target.equals(source)) {
iter.remove();
return e.weight;
}
}
} else {
for (Iterator<AdjacencyListElement> iter = lists[source].iterator(); iter.hasNext();) {
AdjacencyListElement e = iter.next();
if (e.target.equals(target)) {
iter.remove();
return e.weight;
}
}
}
return Integer.MAX_VALUE;
} |
b5d00b57-30c8-42fd-84b4-1a7afada101a | 9 | short wrapResponseAPDU(byte[] ssc, APDU aapdu,
short plaintextOffset, short plaintextLen, short sw1sw2) {
byte[] apdu = aapdu.getBuffer();
short apdu_p = 0;
// smallest multiple of 8 strictly larger than plaintextLen
short do87DataLen = SmartIDUtil.lengthWithPadding(plaintextLen);
// for 0x01 marker (indicating padding is used)
do87DataLen++;
short do87DataLenBytes = (short) (do87DataLen > 0xff ? 2 : 1);
short do87HeaderBytes = getApduBufferOffset(plaintextLen);
short do87Bytes = (short) (do87HeaderBytes + do87DataLen - 1); // 0x01
// is
// counted
// twice
boolean hasDo87 = plaintextLen > 0;
incrementSSC(ssc);
short ciphertextLength = 0;
short possiblyPaddedPlaintextLength = 0;
if (hasDo87) {
// put ciphertext in proper position.
possiblyPaddedPlaintextLength = encryptInit(PAD_INPUT, apdu,
plaintextOffset, plaintextLen);
ciphertextLength = encryptFinal(apdu, plaintextOffset,
possiblyPaddedPlaintextLength, apdu, do87HeaderBytes);
}
// sanity check
// note that this check
// (possiblyPaddedPlaintextLength != (short)(do87DataLen -1))
// does not always hold because some algs do the padding in the final,
// some in the init.
if (hasDo87 && (((short) (do87DataLen - 1) != ciphertextLength)))
ISOException.throwIt((short) 0x6d66);
if (hasDo87) {
// build do87
apdu[apdu_p++] = (byte) 0x87;
if (do87DataLen < 0x80) {
apdu[apdu_p++] = (byte) do87DataLen;
} else {
apdu[apdu_p++] = (byte) (0x80 + do87DataLenBytes);
for (short i = (short) (do87DataLenBytes - 1); i >= 0; i--) {
apdu[apdu_p++] = (byte) ((do87DataLen >>> (i * 8)) & 0xff);
}
}
apdu[apdu_p++] = 0x01;
}
if (hasDo87) {
apdu_p = do87Bytes;
}
// build do99
apdu[apdu_p++] = (byte) 0x99;
apdu[apdu_p++] = 0x02;
Util.setShort(apdu, apdu_p, sw1sw2);
apdu_p += 2;
// calculate and write mac
initMac(Signature.MODE_SIGN);
updateMac(ssc, (short) 0, (short) ssc.length);
createMacFinal(apdu, (short) 0, apdu_p, apdu, (short) (apdu_p + 2));
// write do8e
apdu[apdu_p++] = (byte) 0x8e;
apdu[apdu_p++] = 0x08;
apdu_p += 8; // for mac written earlier
// Reset the secure messaging keys after successful EAC Chip Authentication
if (eacChangeKeys[0]) {
eacChangeKeys[0] = false;
keyStore.setSecureMessagingKeys(keyStore.tmpKeys, (short) 0,
keyStore.tmpKeys, (short) 16);
Util.arrayFillNonAtomic(keyStore.tmpKeys, (short) 0, (short) 32,
(byte) 0x00);
Util.arrayFillNonAtomic(ssc, (short) 0, (short) ssc.length,
(byte) 0x00);
}
return apdu_p;
} |
8d8b2401-6313-4ff9-9d8c-5c0f53997181 | 6 | public static void main(String[] args) {
int k = 0;
try {
k = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.out.println("Expected an argument with the number of elements to print.");
System.out.println("USAGE: Subset k - to print k values from the input.");
System.out.println("EXAMPLE: echo A B C D E F G H I | java Subset 3 => prints out 3 values from the input.");
}
int n = 0;
RandomizedQueue<String> rq = new RandomizedQueue<String>();
while (!StdIn.isEmpty()) {
String s = StdIn.readString();
n++;
if (rq.size() == k) {
final double rnd = StdRandom.uniform(1, n + 1);
if (rnd <= k) {
rq.dequeue();
rq.enqueue(s);
}
} else {
rq.enqueue(s);
}
}
for (int i = 0; i < k && !rq.isEmpty(); i++) {
System.out.println(rq.dequeue());
}
} |
39aa594b-e85d-43d5-8993-b53dacb829c4 | 1 | public void enableAction() {actionEnabled = true; if (hover) showBorder();} |
20855337-34a4-4606-a8d1-99083ae2986f | 3 | public static void saveItemData()
{
String output ="savedata/"+idString+"_"+area+".itemData";
try
{
PrintWriter fout=new PrintWriter(new FileWriter(output));
if(VERSION.equals("Peaches"))
fout.println("PDAE"+idString);
else
fout.println("CDAE"+idString);
int length=foundItem.length;
fout.println(length);
for (boolean aFoundItem : foundItem) {
fout.println(aFoundItem);
}
fout.close();
saveEncryptionKey(output,encrypt(output));
System.out.println("Item data saved.");
}
catch(Exception ignored){}
} |
4f68a53a-1596-48dd-8bdc-b4287e24f718 | 4 | @SuppressWarnings("resource")
public static ZipEntry[] getZipEntriesIn(File zipFile)
{
final ArrayList<ZipEntry> entries = new ArrayList<ZipEntry>();
if (!zipFile.toString().endsWith(".zip")) throw new IllegalArgumentException("File isn't a Zip! " + zipFile.toString());
try
{
final ZipFile zip = new ZipFile(zipFile);
final Enumeration<? extends ZipEntry> zes = zip.entries();
while (zes.hasMoreElements())
{
entries.add(zes.nextElement());
}
}
catch (final IOException e)
{
System.err.println("Error Loading Zip Entries from " + zipFile.toString());
e.printStackTrace();
}
return entries.toArray(new ZipEntry[0]);
} |
3ab6595d-e7af-4277-87fa-e9c30971a2e0 | 8 | private void setPolarProjectionOptions() {
JTextField field_real = new JTextField();
double temp_xcenter = xCenter - rotation_center[0];
double temp_ycenter = yCenter - rotation_center[1];
double temp3 = temp_xcenter * rotation_vals[0] - temp_ycenter * rotation_vals[1] + rotation_center[0];
if(temp3 == 0) {
field_real.setText("" + 0.0);
}
else {
field_real.setText("" + temp3);
}
field_real.addAncestorListener(new RequestFocusListener());
JTextField field_imaginary = new JTextField();
temp3 = temp_xcenter * rotation_vals[1] + temp_ycenter * rotation_vals[0] + rotation_center[1];
if(temp3 == 0) {
field_imaginary.setText("" + 0.0);
}
else {
field_imaginary.setText("" + temp3);
}
JTextField field_size = new JTextField();
field_size.setText("" + size);
JTextField field_circle_period = new JTextField();
field_circle_period.setText("" + circle_period);
Object[] message3 = {
" ",
"Set the real and imaginary part of the polar projection center",
"and the size.",
"Real:", field_real,
"Imaginary:", field_imaginary,
"Size:", field_size,
" ",
"Set the circle periods number.",
"Circle Periods:",
field_circle_period,
""};
int res = JOptionPane.showConfirmDialog(scroll_pane, message3, "Polar Projection", JOptionPane.OK_CANCEL_OPTION);
double tempReal, tempImaginary, tempSize, temp_circle_period;
if(res == JOptionPane.OK_OPTION) {
try {
tempReal = Double.parseDouble(field_real.getText()) - rotation_center[0];
tempImaginary = Double.parseDouble(field_imaginary.getText()) - rotation_center[1];
tempSize = Double.parseDouble(field_size.getText());
temp_circle_period = Double.parseDouble(field_circle_period.getText());
if(temp_circle_period <= 0) {
main_panel.repaint();
JOptionPane.showMessageDialog(scroll_pane, "The circle periods must be greater than 0.", "Error!", JOptionPane.ERROR_MESSAGE);
return;
}
size = tempSize;
xCenter = tempReal * rotation_vals[0] + tempImaginary * rotation_vals[1] + rotation_center[0];
yCenter = -tempReal * rotation_vals[1] + tempImaginary * rotation_vals[0] + rotation_center[1];
circle_period = temp_circle_period;
setOptions(false);
progress.setValue(0);
scroll_pane.getHorizontalScrollBar().setValue((int)(scroll_pane.getHorizontalScrollBar().getMaximum() / 2 - scroll_pane.getHorizontalScrollBar().getSize().getWidth() / 2));
scroll_pane.getVerticalScrollBar().setValue((int)(scroll_pane.getVerticalScrollBar().getMaximum() / 2 - scroll_pane.getVerticalScrollBar().getSize().getHeight() / 2));
resetImage();
if(d3) {
Arrays.fill(((DataBufferInt)image.getRaster().getDataBuffer()).getData(), 0, image_size * image_size, Color.BLACK.getRGB());
}
backup_orbit = null;
whole_image_done = false;
if(julia_map) {
createThreadsJuliaMap();
}
else {
createThreads();
}
calculation_time = System.currentTimeMillis();
if(julia_map) {
startThreads(julia_grid_first_dimension);
}
else {
startThreads(n);
}
}
catch(Exception e) {
JOptionPane.showMessageDialog(scroll_pane, "Illegal Argument!", "Error!", JOptionPane.ERROR_MESSAGE);
main_panel.repaint();
return;
}
}
else {
main_panel.repaint();
return;
}
} |
4be5ef29-d7af-4966-9f82-c0f517937492 | 5 | protected Floor decodeFloor(VorbisStream vorbis, BitInputStream source) throws VorbisFormatException, IOException {
//System.out.println("decodeFloor");
if(!source.getBit()) {
//System.out.println("null");
return null;
}
Floor1 clone=(Floor1)clone();
clone.yList=new int[xList.length];
int range=RANGES[multiplier-1];
clone.yList[0]=source.getInt(Util.ilog(range-1));
clone.yList[1]=source.getInt(Util.ilog(range-1));
int offset=2;
for(int i=0; i<partitionClassList.length; i++) {
int cls=partitionClassList[i];
int cdim=classDimensions[cls];
int cbits=classSubclasses[cls];
int csub=(1<<cbits)-1;
int cval=0;
if(cbits>0) {
cval=source.getInt(vorbis.getSetupHeader().getCodeBooks()[classMasterbooks[cls]].getHuffmanRoot());
//cval=vorbis.getSetupHeader().getCodeBooks()[classMasterbooks[cls]].readInt(source);
//System.out.println("cval: "+cval);
}
//System.out.println("0: "+cls+" "+cdim+" "+cbits+" "+csub+" "+cval);
for(int j=0; j<cdim; j++) {
//System.out.println("a: "+cls+" "+cval+" "+csub);
int book=subclassBooks[cls][cval&csub];
cval>>>=cbits;
if(book>=0) {
clone.yList[j+offset]=source.getInt(vorbis.getSetupHeader().getCodeBooks()[book].getHuffmanRoot());
//clone.yList[j+offset]=vorbis.getSetupHeader().getCodeBooks()[book].readInt(source);
//System.out.println("b: "+(j+offset)+" "+book+" "+clone.yList[j+offset]);
//System.out.println("");
}
else {
clone.yList[j+offset]=0;
}
}
offset+=cdim;
}
//System.out.println("");
//for(int i=0; i<clone.xList.length; i++) {
// System.out.println(i+" = "+clone.xList[i]);
//}
//System.out.println("");
//for(int i=0; i<clone.yList.length; i++) {
// System.out.println(i+" = "+clone.yList[i]);
//}
//System.out.println("offset: "+offset);
//System.out.println("yList.length: "+clone.yList.length);
//System.exit(0);
return clone;
} |
758fceec-5e47-41b1-a17e-9a82b74a12ef | 9 | public static String getYoutubeInfo(String s) throws IOException {
String info;
String title = null;
String likes = null;
String dislikes = null;
String user = null;
String veiws = null;
@SuppressWarnings("unused")
String publishdate;
Document doc = Jsoup.connect(s).userAgent("Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17").get();
for (Element e : doc.select("a")) {
if (e.attr("class").equalsIgnoreCase("yt-uix-sessionlink yt-user-videos")) {
user = e.attr("href").split("/user/")[1].split("/")[0];
}
}
for (Element e : doc.select("span")) {
if (e.attr("class").equalsIgnoreCase("watch-view-count")) {
veiws = e.text();
}
if (e.attr("class").equalsIgnoreCase("likes-count")) {
likes = e.text();
}
if (e.attr("class").equalsIgnoreCase("dislikes-count")) {
dislikes = e.text();
}
if (e.attr("class").equalsIgnoreCase("watch-title yt-uix-expander-head") || e.attr("class").equalsIgnoreCase("watch-title long-title yt-uix-expander-head")) {
title = e.text();
}
if (e.attr("class").equalsIgnoreCase("watch-video-date")) {
publishdate = e.text();
}
}
info = title + " - " + user + " Views: " + veiws + " Likes: " + likes + " Dislikes: " + dislikes;
//System.out.println(info);
return info;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.