method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
7e3588a4-5fcb-46cf-ae06-bf1c0ecb9ca2 | 4 | public ArrayList<Administrador> getByDNI(Administrador admin){
PreparedStatement ps;
ArrayList<Administrador> admins = new ArrayList<>();
try {
ps = mycon.prepareStatement("SELECT * FROM Administradores WHERE dni=?");
ps.setString(1, admin.getDNI());
ResultSet rs = ps.executeQuery();
if(rs!=null){
try {
while(rs.next()){
admins.add(
new Administrador(
rs.getString("userName"),
rs.getString("passwd"),
rs.getString("dni")
)
);
}
} catch (SQLException ex) {
Logger.getLogger(Administrador.class.getName()).
log(Level.SEVERE, null, ex);
}
}else{
System.out.println("Total de registros encontrados es: 0");
}
} catch (SQLException ex) {
Logger.getLogger(AdministradorCRUD.class.getName()).log(Level.SEVERE, null, ex);
}
return admins;
} |
c93616b3-6de0-4948-929e-edc1730b54ee | 6 | @Override
public void actionPerformed(ActionEvent e) {
if(e.getID() == ActionEvent.ACTION_PERFORMED) {
GuiButton button = (GuiButton)e.getSource();
if(button == newGame)
Client.instance.setGuiScreen(new GuiSelectServer(this));
else if(button == test)
Client.instance.activateMap(true);
else if(button == options)
Client.instance.setGuiScreen(new GuiOptions(this));
else if(button == credits)
Client.instance.setGuiScreen(new GuiCredits(this));
else if(button == exit)
Client.instance.stop();
}
} |
cbd7f88e-2032-450f-8dda-2894b2f1a4f2 | 4 | public static void main(String[] args) {
Random r = new Random();
ArrayList<Integer> ArrayA = new ArrayList<Integer>();
ArrayList<Integer> ArrayB = new ArrayList<Integer>();
ArrayList<Integer> ArrayC = new ArrayList<Integer>();
ArrayA.add(r.nextInt(10));
ArrayA.add(r.nextInt(10));
ArrayA.add(r.nextInt(10));
ArrayA.add(r.nextInt(10));
ArrayA.add(r.nextInt(10));
ArrayA.add(r.nextInt(10));
ArrayA.add(r.nextInt(10));
ArrayB.add(r.nextInt(10));
ArrayB.add(r.nextInt(10));
ArrayB.add(r.nextInt(10));
ArrayB.add(r.nextInt(10));
ArrayB.add(r.nextInt(10));
ArrayB.add(r.nextInt(10));
System.out.println("ArrayA :" + ArrayA.toString());
System.out.println("ArrayB :" + ArrayB.toString());
for (int i = 0; i < ArrayA.size(); i++) {
for (int j = 0; j < ArrayB.size(); j++) {
if (!ArrayC.contains(ArrayA.get(i))) {
ArrayC.add(ArrayA.get(i));
}
if (!ArrayC.contains(ArrayB.get(j))) {
ArrayC.add(ArrayB.get(j));
}
}
}
System.out.println("ArrayC :" + ArrayC.toString());
} |
8f2d182d-a3c8-4f7a-b2e5-7ab6c63e78f1 | 8 | public void getSimpleRandomGraph(mxAnalysisGraph aGraph, int numNodes, int numEdges, boolean allowSelfLoops,
boolean allowMultipleEdges, boolean forceConnected)
{
mxGraph graph = aGraph.getGraph();
Object parent = graph.getDefaultParent();
Object[] vertices = new Object[numNodes];
for (int i = 0; i < numNodes; i++)
{
vertices[i] = graph.insertVertex(parent, null, new Integer(i).toString(), 0, 0, 25, 25);
}
for (int i = 0; i < numEdges; i++)
{
boolean goodPair = true;
Object startVertex;
Object endVertex;
do
{
goodPair = true;
startVertex = vertices[(int) Math.round(Math.random() * (vertices.length - 1))];
endVertex = vertices[(int) Math.round(Math.random() * (vertices.length - 1))];
if (!allowSelfLoops && startVertex.equals(endVertex))
{
goodPair = false;
}
else if (!allowMultipleEdges && mxGraphStructure.areConnected(aGraph, startVertex, endVertex))
{
goodPair = false;
}
}
while (!goodPair);
graph.insertEdge(parent, null, getNewEdgeValue(aGraph), startVertex, endVertex);
}
if (forceConnected)
{
mxGraphStructure.makeConnected(aGraph);
}
}; |
52738fe1-819b-4667-a75a-636c44b77e9d | 0 | public static void Balconey() {
currentRoomName = "Balconey";
currentRoom = 7;
RoomDescription = "The wafer thin doors are almost crushed in your hands as you open them and enter the balconey." +
"You are immediately faced with the dark figure you saw earlier; only this time, he is slung over the " +
"balconey with a knife in his hand and blood pouring out from his neck. You are at a dead end.";
} |
04d20a97-024d-46c1-a096-9f1b1ac5f5fe | 1 | private String findCaller(int depth) {
if (depth < 0) {
throw new IllegalArgumentException();
}
tracer.fillInStackTrace();
return tracer.getStackTrace()[depth+1].toString();
} |
315d88b1-a546-4533-927e-a17515dbd730 | 2 | public static void main(String[] args) {
// INSERT INTO `bible`.`books`
// (`ID`, `TESTAMENT`, `TITLE`, `TITLE_CN`, `TITLE_CN_SHORT`)
// VALUES
// ('1', 'OT', 'Genesis', '創世紀', '創');
StringBuilder sb = new StringBuilder();
for (int k = 0; k < 39; k++) {
sb.append("INSERT INTO `bible`.`books` ");
sb.append("(`ID`, `TESTAMENT`, `TITLE`, `TITLE_CN`, `TITLE_CN_SHORT`) ");
sb.append(" VALUES (");
sb.append("'").append((1 + k)).append("',");
sb.append("'OT',");
sb.append("'").append(OLD_TESTAMENT[k]).append("',");
sb.append("'").append(OLD_TESTAMENT_CHINESE[k]).append("',");
sb.append("'").append(OLD_TESTAMENT_CHINESE_SHORT[k]).append("');");
sb.append("\n");
}
System.out.println(sb.toString());
System.out.println("nt CNT="+NEW_TESTAMENT_CHINESE.length);
//
//
//
sb = new StringBuilder();
for (int k = 0; k < 27; k++) {
sb.append("INSERT INTO `bible`.`books` ");
sb.append("(`ID`, `TESTAMENT`, `TITLE`, `TITLE_CN`, `TITLE_CN_SHORT`) ");
sb.append(" VALUES (");
sb.append("'").append((39+1 + k)).append("',");
sb.append("'OT',");
sb.append("'").append(NEW_TESTAMENT[k]).append("',");
sb.append("'").append(NEW_TESTAMENT_CHINESE[k]).append("',");
sb.append("'").append(NEW_TESTAMENT_CHINESE_SHORT[k]).append("');");
sb.append("\n");
}
System.out.println(sb.toString());
} |
37d8f596-444e-4dfe-9a05-13ad3b5f980e | 4 | public FieldVisitor visitField(final int access, final String name,
final String desc, final String signature, final Object value) {
if (computeSVUID) {
if ("serialVersionUID".equals(name)) {
// since the class already has SVUID, we won't be computing it.
computeSVUID = false;
hasSVUID = true;
}
/*
* Remember field for SVUID computation For field modifiers, only
* the ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC,
* ACC_FINAL, ACC_VOLATILE, and ACC_TRANSIENT flags are used when
* computing serialVersionUID values.
*/
if ((access & Opcodes.ACC_PRIVATE) == 0
|| (access & (Opcodes.ACC_STATIC | Opcodes.ACC_TRANSIENT)) == 0) {
int mods = access
& (Opcodes.ACC_PUBLIC | Opcodes.ACC_PRIVATE
| Opcodes.ACC_PROTECTED | Opcodes.ACC_STATIC
| Opcodes.ACC_FINAL | Opcodes.ACC_VOLATILE | Opcodes.ACC_TRANSIENT);
svuidFields.add(new Item(name, mods, desc));
}
}
return super.visitField(access, name, desc, signature, value);
} |
15805ef8-460a-4bda-acb4-1ba90531a89e | 8 | public int maxP(int[] A){
int length = A.length;
if(length == 1)
return A[0];
if(A== null || A.length ==0 )
return 0;
int max = A[0];
int n = 0;
int total = 1;
int[] pre = new int[length];
int[] aft = new int[length];
for(int i = 0; i < length; i++){
if(A[i] < 0)
n++;
total *= A[i];
}
pre[0] = 1;
aft[length-1] = 1;
for (int i = length-2; i >=0; i--){
aft[i] = aft[i+1] * A[i+1];
pre[length - i -1] = pre[length-i - 2]* A[length-i-2];
}
if(n % 2 == 0)
return total;
else{
for (int i = 0; i < A.length; i++){
max = Math.max(max,Math.max(aft[i],pre[i]));
}
return max;
}
} |
266f67ee-dc2b-4350-a6c8-e0be1c424e47 | 0 | public void chooseM()
{
m = LemmaMath.fetchRandInt(myRange[0], myRange[1]);
} |
8a9af1c7-764c-4702-83cb-2c52a90b9fa3 | 5 | private static CustomButton doIndividualTickerButtonForPanel(
ArrayList<String> bundle, final String ticker,
final String buttonData, final JFrame closeMe, int type) {
boolean filterResults = meetsFilter(ticker);
if (!filterResults)
return null;
final CustomButton a = new CustomButton((ticker));
a.setPreferredSize(new Dimension(60, 20));
final int tickerLocation = Database.dbSet.indexOf(ticker);
double marketCap = Database.DB_ARRAY.lastEntry().getValue()[tickerLocation][38];
addButtonDetails(a, marketCap, tickerLocation, buttonData);
if (filterResults) {
bundle.add(ticker);
if (type == EARNINGS_REPORT) {
colorButtonByPercentChangeAfterEarningsReport(a, buttonData, a
.getText().split(" ")[0]);
} else if (type == NON_EARNINGS_REPORT) {
colorButtonByOverallChange(a, ticker);
}
} else {
a.setBackground(Color.DARK_GRAY);
}
a.setHorizontalAlignment(SwingConstants.LEFT);
a.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// negative time for most recent listed first
EarningsTest.programSettings.myHistory.put(
-System.currentTimeMillis(), ticker);
MemoryManager.saveSettings();
final JFrame jf = new JFrame(a.getText());
jf.setSize(1300, 650);
jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jf.setExtendedState(jf.getExtendedState()
| JFrame.MAXIMIZED_BOTH);
jf.setVisible(true);
// closeMe.dispose();
if (EarningsTest.singleton.showFFT.isSelected()) {
// FFT fft = new
// FFT(Database.spawnTimeSeriesForFFT(ticker));
FFT fft = new FFT(Database.spawnAveragesArrayFromPricePair(
ticker, EarningsTest.singleton.daysChoice
.getSelectedIndex()));
fft.showFrequencyGraph();
}
ProfileCanvas pc = new ProfileCanvas((buttonData),
tickerLocation, jf.getWidth(), jf.getHeight());
// /////////////
addTickerMangerPanel(jf, ticker, tickerLocation);
// ////////////MEMORYLEAKFIX
final ComponentListener refForRemoval = JComponentFactory
.doWindowRescaleListener(pc);
jf.addComponentListener(refForRemoval);
jf.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e) {
jf.removeComponentListener(refForRemoval);
}
});
jf.add(JComponentFactory.makeJScrollPane(pc));
}
private void addTickerMangerPanel(JFrame jf, String ticker,
int tickerLocation) {
String[] tradeOptions = { "buy", "sell" };
JComboBox<String> buySell = new JComboBox<String>(tradeOptions);
Integer[] rateOptions = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
JComboBox<Integer> myRating = new JComboBox<Integer>(
rateOptions);
CustomButton saveTicker = new CustomButton("trade this stock");
addSaveTickerListener(saveTicker, ticker, buySell, myRating);
JPanel topPanel = JComponentFactory
.makePanel(JComponentFactory.HORIZONTAL);
topPanel.add(saveTicker);
topPanel.add(myRating);
topPanel.add(buySell);
jf.add(topPanel, BorderLayout.NORTH);
}
private void addSaveTickerListener(CustomButton saveTicker,
final String ticker, final JComboBox<String> tradeOpns,
final JComboBox<Integer> rating) {
saveTicker.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
EarningsTest.singleton.programSettings.myTrades.put(
System.currentTimeMillis(),
new Trade((String) tradeOpns.getSelectedItem(),
ticker, ((Integer) rating
.getSelectedItem()).intValue()));
}
});
}
});
return a;
} |
df3b5298-d20b-40df-9b65-d6afea747011 | 8 | public boolean hasNeighbor(int piece, boolean withOpponents) {
boolean condition = false;
for (int dh = UP; dh <= DOWN; dh++) {
for (int dv = LEFT; dv <= RIGHT; dv++) {
if (dh == 0 && dv == 0)
continue;
int neighbor = searchNeighbor(piece, dh, dv);
if (neighbor != -1) {
condition = condition || (!withOpponents || (withOpponents && distance(piece, neighbor) >= 1));
}
}
}
return condition;
} |
eef211d5-17b1-48fe-9e3f-bc6c3b5c9a53 | 7 | public void connect(TreeLinkNode root) {
if(root == null)
return;
if(root.left == null && root.right == null){
root.next = null;
return;
}
TreeLinkNode tempRoot = root;
tempRoot.next = null;
while(tempRoot != null){
TreeLinkNode startPoint = tempRoot;
while(startPoint != null){
if(startPoint.left == null )
return;
startPoint.left.next = startPoint.right;
if(startPoint.next != null){
startPoint.right.next = startPoint.next.left;
}else {
startPoint.right.next = null;
}
startPoint = startPoint.next;
}
tempRoot = tempRoot.left;
}
} |
6252212b-0d36-40ec-9770-8e42df57de88 | 1 | public void printTrees(QuadTree tree)
{
// Include parent tree
// System.out.println(tree);
// for (Point2D p : tree.getEdges()) {
// System.out.println(p.getX() + ", " + p.getY());
//}
// Child trees
for (QuadTree t : tree)
{
System.out.println(t);
//for (Point2D p : t.getEdges()) {
//System.out.println(p.getX() + ", " + p.getY());
//}
t.printTrees(t);
}
} |
995b36ed-ae9f-479a-b772-4fe9207547af | 9 | private static ArrayList<String> loadFile()
{
ArrayList<String> texts = new ArrayList<String>();
File aFile = null;
BufferedReader aBufferedReader = null;
FileReader aFileReader = null;
JFileChooser aFileChooser = new JFileChooser();
int selected = aFileChooser.showOpenDialog(null);
if(selected == JFileChooser.APPROVE_OPTION)
{
aFile = aFileChooser.getSelectedFile();
}
else if(selected == JFileChooser.CANCEL_OPTION)
{
System.out.println("キャンセルされました");
}
else if(selected == JFileChooser.ERROR_OPTION)
{
System.out.println("エラーまたは取り消しがありました");
}
try
{
aFileReader = new FileReader(aFile);
aBufferedReader = new BufferedReader(aFileReader);
for(;;)
{
String aString = aBufferedReader.readLine();
if(aString != null)
{
texts.add(aString);
}else
{
break;
}
}
}catch(FileNotFoundException error)
{
System.err.println("ファイルの指定されていないもしくは見つかりませんでした");
}
catch(NullPointerException error)
{
System.err.println("ファイルの指定されていないもしくは見つかりませんでした");
}
catch(IOException error)
{
System.err.println("予期せぬエラーが発生しました");
}
finally
{
try
{
aBufferedReader.close();
aFileReader.close();
}
catch(IOException error)
{
error.printStackTrace();
}
}
return texts;
} |
b49793b7-cc62-4e7f-8f7a-7c208297f1f7 | 2 | public void newFrame() {
int i = JOptionPane.showOptionDialog(this,
"What kind of page would you like to add?",
"New Page",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
new String[]{"Blank Page", "Page Copy", "Cancel"},
"Blank Page");
switch (i) {
case JOptionPane.NO_OPTION:
centerPanel.remove(layeredPanelList.getSelected());
animationPane.updateAnimation(layeredPanelList, layeredPanelList.getIntSelectedPanel()+1);
//Code to add previous image as background of new page
BufferedImage bi = layeredPanel.paneToBufferedImg();
layeredPanel = new LayeredPanel();
layeredPanel.setBackground(bi);
layeredPanel.addMouseListener(myListener);
layeredPanel.addMouseMotionListener(myListener);
this.setCurrentCanvasListener(layeredPanel);
layeredPanel.setPreferredSize(new Dimension(width - 450, height - 300));
layeredPanelList.add(layeredPanel);
animationPane.updateAnimation(layeredPanelList, layeredPanelList.getIntSelectedPanel() + 1);
refreshDrawPanel(layeredPanelList.getSelected());
toolPanel.resetState();
break;
case JOptionPane.YES_OPTION:
centerPanel.remove(layeredPanelList.getSelected());
animationPane.updateAnimation(layeredPanelList, layeredPanelList.getIntSelectedPanel()+1);
layeredPanel = new LayeredPanel();
layeredPanel.addMouseListener(myListener);
layeredPanel.addMouseMotionListener(myListener);
this.setCurrentCanvasListener(layeredPanel);
layeredPanel.setPreferredSize(new Dimension(width - 450, height - 300));
layeredPanelList.add(layeredPanel);
animationPane.updateAnimation(layeredPanelList, layeredPanelList.getIntSelectedPanel() + 1);
refreshDrawPanel(layeredPanelList.getSelected());
toolPanel.resetState();
default :
break;
}
layeredPanelList.getSelected().clearRootPane();
} |
26546f58-1470-4d34-b439-3554e837f176 | 9 | public void guardarImagen(String rutaArchivo) {
FileWriter fw = null;
PrintWriter pw;
try {
fw = new FileWriter(rutaArchivo);
pw = new PrintWriter(fw);
String comentario = "# Imagen guardada desde programa AxpherPicture\n";
comentario += "# Autor: Juan Sebastian Rios Sabogal\n";
comentario += "# Email: sebaxtianrios@gmail.com\n";
comentario += "# Fecha: " + new Date() + "\n";
comentario += "# Version: 0.1\n";
comentario += "# \n";
//escribe los atributos de la imagen
pw.write(getFormato()+"\n");
pw.write(comentario);
pw.write(getM()+" "+getN()+"\n");
pw.write(getNivelIntensidad()+"\n");
//escribe el contenido de la matriz o matrices en el archivo segun el formato
System.out.println("Imagen::Inicia escritura ...");
//si el formato de imagen es PGM
if(getFormato().equals("P2")){
for(int i = 0; i < getN(); i++) {
for(int j = 0; j < getM(); j++) {
pw.write(getMatrizGris()[i][j]+" ");
}
pw.write("\n");
}
}
//si el formato de imagen es PPM
if(getFormato().equals("P3")) {
for(int i = 0; i < getN(); i++) {
for(int j = 0; j < getM(); j++) {
pw.write(getMatrizR()[i][j]+" ");
pw.write(getMatrizG()[i][j]+" ");
pw.write(getMatrizB()[i][j]+" ");
}
pw.write("\n");
}
}
System.out.println("Imagen::Termina escritura");
} catch (IOException ex) {
System.err.println("Imagen::Error: Durante la escritura del archivo de imagen");
} finally {
//cierra la lectura del archivo ocurra o no una excepcion
if(fw != null) {
try {
fw.close();
} catch (IOException ex) {
System.err.println("Imagen::Error: No fue posible cerrar el archivo de imagen");
}
}
}
} |
bbafdbc4-06a9-4b9e-ad19-216ba453b5cd | 3 | private void doubleClickedNode(Object obj)
{
if (obj instanceof File)
{
final File f = (File) obj;
FileType ft = FileType.typeForFile(f);
//Do first action
for (final FileAction act : Actions.actions)
if (act.canDoOn(ft))
{
act.doOn(f);
break;
}
}
} |
cd7940bc-8f0a-40c4-8ec5-61c027c8e361 | 4 | @Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(null == image) {
return;
}
BMPImage.BMPColor[][] bitmap = image.getBitMap();
int height = image.getHeight();
int width = image.getWidth();
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int i = 1; i <= height; i++) {
for(int j = 1; j <= width; j++) {
Color color = new Color(bitmap[i][j].red, bitmap[i][j].green, bitmap[i][j].blue);
bufferedImage.setRGB(j-1, i-1, color.getRGB());
}
}
float k = (float)(width)/height;
if(k >= 1) {
g.drawImage(bufferedImage, 0, 0, DrawPanel.subPanelWidth, (int) (DrawPanel.subPanelHeight / k), null);
}
else {
g.drawImage(bufferedImage, 0, 0, (int) (DrawPanel.subPanelWidth * k), DrawPanel.subPanelHeight, null);
}
} |
df06caeb-ffd0-4f3e-afd1-322f7051cc60 | 0 | @Test
public void containsReturnsFalseWhenElementNotInArray() {
a.insert(new Vertex(493));
assertFalse(a.contains(v));
} |
0db072fb-0398-4de4-a858-cbd90a96f798 | 2 | @Override
public int compareTo(Object ob){
Event e = (Event) ob;
if(this.time < e.getTime()){
return -1;
}
if(this.time > e.getTime()){
return 1;
}
return 0;
} |
7d83bbf1-c32b-444a-90a2-8f977ad161d5 | 6 | private static void solve_nu_svc(svm_problem prob, svm_parameter param,
double[] alpha, Solver.SolutionInfo si)
{
int i;
int l = prob.l;
double nu = param.nu;
byte[] y = new byte[l];
for(i=0;i<l;i++)
if(prob.y[i]>0)
y[i] = +1;
else
y[i] = -1;
double sum_pos = nu*l/2;
double sum_neg = nu*l/2;
for(i=0;i<l;i++)
if(y[i] == +1)
{
alpha[i] = Math.min(1.0,sum_pos);
sum_pos -= alpha[i];
}
else
{
alpha[i] = Math.min(1.0,sum_neg);
sum_neg -= alpha[i];
}
double[] zeros = new double[l];
for(i=0;i<l;i++)
zeros[i] = 0;
Solver_NU s = new Solver_NU();
s.Solve(l, new SVC_Q(prob,param,y), zeros, y,
alpha, 1.0, 1.0, param.eps, si, param.shrinking);
double r = si.r;
svm.info("C = "+1/r+"\n");
for(i=0;i<l;i++)
alpha[i] *= y[i]/r;
si.rho /= r;
si.obj /= (r*r);
si.upper_bound_p = 1/r;
si.upper_bound_n = 1/r;
} |
5a02aa99-b21b-498b-936e-fb65877a0a8d | 3 | @Override
// Draw certain pictures based on # of lives remaining
public void draw(Graphics g) {
if (Lives >= 3) {
g.drawImage(img1, pos_x, pos_y, width, height, null);
} else if (Lives == 2) {
g.drawImage(img2, pos_x, pos_y, width, height, null);
} else if (Lives == 1) {
g.drawImage(img3, pos_x, pos_y, width, height, null);
}
} |
3f20a4cb-24fe-4cd6-8152-ab46903cce30 | 5 | public void persistir() {
FileOutputStream fos = null;
ObjectOutputStream stream = null;
try {
fos = new FileOutputStream("arquivo.bin");
stream = new ObjectOutputStream(fos);
stream.writeObject(persistencia);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} |
9ae1cff5-020e-4195-b202-23b7510464ea | 1 | public int[] getItemLastModifier(int itemSlot, BagLocation bag) throws IOException {
GWCAPacket receivedGwcaPacket = sendAndReceivePacket(GWCAOperation.GET_ITEM_LAST_MODIFIER, itemSlot, bag != null ? bag.getValue() : ZERO);
return receivedGwcaPacket.getParamsAsIntArray();
} |
26009188-7a2d-4d2d-8c30-aa22a8e0b119 | 0 | public boolean isPropertyInherited() {return propInherited;} |
c6f16d77-254e-4635-985c-42093ab2ef43 | 3 | public void addUserInterruptListener(ActionListener al){
if (listeners==null ||(listeners!=null && listeners.isEmpty()) ) listeners = new Vector<ActionListener>();
listeners.add(al);
} |
c71b6ffa-2bdd-45f3-aab2-ba893d8c0d4d | 6 | public static Object getProperty(Object obj, String propertyName)
{
if (obj == null)
return null;
try
{
BeanInfo info = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
for (int i = 0; i < descriptors.length; i++)
{
if (descriptors[i].getName().equals(propertyName))
{
Method getter = descriptors[i].getReadMethod();
if (getter == null)
return null;
try {
return getter.invoke(obj);
} catch (Exception ex) {
System.out.println(descriptors[i].getName());
return null;
}
}
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
} |
1554afe9-5b0b-4141-b3b3-6a761d4c5af2 | 8 | public Object[][][] readLine() {
try {
//Excelのワークブックを読み込みます。
POIFSFileSystem filein = new POIFSFileSystem(new FileInputStream(targetFile));
HSSFWorkbook wb = new HSSFWorkbook(filein);
Object[][][] sheetArray = new Object[wb.getNumberOfSheets()][][];
// シートごとのループ
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
//シートを読み込みます。
HSSFSheet sheet = wb.getSheetAt(i);
Object[][] rowArray = new Object[sheet.getLastRowNum() + 1][];
// 行ごとのループ
if (sheet.getLastRowNum() == 0)
continue; // シートに何も入っていない時は、最大行数が0として帰ってくる。
for (int j = 0; j < sheet.getLastRowNum() + 1; j++) {
HSSFRow row = sheet.getRow(j);
if (row == null)
continue;
Object[] cellArray = new Object[row.getLastCellNum()];
// 列に対するループ
for (int k = 0; k < row.getLastCellNum(); k++) {
HSSFCell cell = row.getCell(k);
if (cell == null)
continue;
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
cellArray[k] = cell.getRichStringCellValue().getString();
}
rowArray[j] = cellArray;
}
sheetArray[i] = rowArray;
}
return sheetArray;
} catch (Exception e) {
e.printStackTrace();
System.out.println("処理が失敗しました");
}
return null;
} |
80cdd5c6-4dd2-4442-bdb1-1a1a9e972b85 | 1 | public String searchByName(final String name) throws IOException {
if (searchingFile(name,"name") == null) {
return null;
}
return searchingFile(name,"name").toString();
} |
90000d7b-3194-49b1-ab54-59eb202ebd22 | 0 | @Override
public SQLPermissionRcon getRcon() throws DataLoadFailedException {
checkCache(PermissionType.RCON, null);
return (SQLPermissionRcon) cache.get(PermissionType.RCON).get(null);
} |
37e68b76-6106-4dcf-a5d9-b24a70499775 | 0 | public void setPcaUsuario(String pcaUsuario) {
this.pcaUsuario = pcaUsuario;
} |
6aaf4bdb-7c70-4bc8-9985-7baeb02a7bc5 | 5 | public static Collection<? extends Bean> scanForBeansFromMethods(Class baseType) {
Set<Bean> beansCollection = new HashSet<Bean>();
Method[] methods=baseType.getDeclaredMethods();
for (Method method : methods) {
org.frameworkdi.poc.annotations.Bean bean = method.getAnnotation(org.frameworkdi.poc.annotations.Bean.class);
if(bean == null) continue;
Inject injectedBean = method.getAnnotation(Inject.class);
if(injectedBean==null) continue;
String beanName = getBeanName(bean,method.getReturnType());
Set<String> injectedBeansName = getInjectedBeansName(injectedBean, method.getParameterTypes());
Bean beanObj = new Bean(
beanName,
method.getReturnType(),
bean.scope(),
injectedBeansName,
new HashSet<Bean>()
);
beansCollection.add(beanObj);
}
if(!baseType.getSuperclass().equals(Object.class)){
beansCollection.addAll(scanForBeansFromMethods(baseType.getSuperclass()));
}
return beansCollection;
} |
2b2f13ca-8bbc-4bca-90a8-261c28fcb316 | 0 | @Override public int getConnTimeout() {
return connTimeout;
} |
1cc04380-36a1-4c07-9251-023583aa277f | 7 | public Controller(final JComponent c){
final GameComponent gc = (GameComponent) c;
ArrayList<Player> players = GameComponent.getPlayers();
im = gc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
am = gc.getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false), "space-pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, false), "d-pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0 ,true), "d-released");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, false), "a-pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, true), "a-released");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_E, 0, false), "e-pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_Q, 0, false), "q-pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, false), "1-pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_2, 0 ,false), "2-pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_3, 0 ,false), "3-pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_4, 0 ,false), "4-pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_5, 0 ,false), "5-pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_6, 0 ,false), "6-pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_7, 0 ,false), "7-pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_8, 0 ,false), "8-pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_9, 0 ,false), "9-pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_0, 0 ,false), "0-pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0, true), "F12-pressed");
for (Player p: players){
final Player player = p;
am.put("space-pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if(player.isGrounded()) {
player.jump();
}
}
});
am.put("d-pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
//player.setFacingRight(true);//temporary
if(player.isGrounded() && !player.isWalking()) {
player.setIsWalking(true);
player.setSpeed(Math.abs(player.getSpeed()));
}
}
});
am.put("d-released", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
player.setIsWalking(false);
}
});
am.put("a-pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if(player.isGrounded() && !player.isWalking()) {
player.setIsWalking(true);
player.setSpeed(-Math.abs(player.getSpeed()));
}
}
});
am.put("a-released", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
player.setIsWalking(false);
}
});
am.put("e-pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
player.pickupItem();
}
});
am.put("q-pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
player.getArms().toss();
}
});
for(int i = 0; i < 10; i++) {
final int q = i;
am.put(i + "-pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
player.changeSelectedItem(q);
}
});
}
am.put("F12-pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
player.toggleDebug();
}
});
class MouseControls extends MouseAdapter{
@Override
public void mouseClicked(MouseEvent e) {
player.getArms().act();
}
@Override
public void mouseMoved(MouseEvent e){
player.setMouseLocation(e.getPoint());
}
@Override
public void mouseDragged(MouseEvent e) {
player.setMouseLocation(e.getPoint());
}
@Override
public void mouseWheelMoved(MouseWheelEvent e){
}
}
MouseControls mc = new MouseControls();
gc.addMouseListener(mc);
gc.addMouseMotionListener(mc);
gc.addMouseWheelListener(mc);
}
} |
da5b4a7e-45d0-403e-bfc5-94801d5cb3bc | 2 | public final static void encode(Image image, OutputStream os) throws IOException {
CRC32 crc = new CRC32();
int width = image.width;
int height = image.height;
write(os, null, PNGHelper.ID);
write(os, crc, PNGHelper.IHDR);
write(os, crc, width);
write(os, crc, height);
write(os, crc, PNGHelper.HEAD);
writeCRC(os, crc);
ByteArrayOutputStream compressed = new ByteArrayOutputStream(defaultInitDataSize);
BufferedOutputStream cbos = new BufferedOutputStream(
new DeflaterOutputStream(compressed, new Deflater(9)), defaultBufferSize);
int pixel;
for (int y = 0; y < height; y++) {
cbos.write(0);
for (int x=0;x<width;x++) {
pixel = image.getPixel(x,y);
cbos.write((byte)((pixel >> 16) & 0xFF));//R
cbos.write((byte)((pixel >> 8) & 0xFF));//G
cbos.write((byte)(pixel & 0xFF));//B
cbos.write((byte)((pixel >> 24) & 0xFF));//A
}
}
cbos.close();
write(os, null, compressed.size());
write(os, crc, PNGHelper.IDAT);
write(os, crc, compressed.toByteArray());
writeCRC(os, crc);
write(os, null, 0);
write(os, crc, PNGHelper.IEND);
writeCRC(os, crc);
os.close();
} |
8fea724f-7c76-4eda-9ed5-5747994c86b3 | 6 | public void combineElements(int key1, int key2) {
Element element1 = elements.get(key1);
Element element2 = elements.get(key2);
if (element1 == null) {
throw new IllegalArgumentException(
"Unable to find element with key: " + key1);
}
if (element2 == null) {
throw new IllegalArgumentException(
"Unable to find element with key: " + key2);
}
if (element1.isInSet1() != element2.isInSet1()) {
throw new IllegalArgumentException(
"Cannot combine elements from different sets");
}
UndoableEdit edit = new CombineEdit(element1, element2);
element1.setText(element1.getText() + element2.getText());
// Uklanja se element2 i sve njegove veze
for (Integer destination : element2.getConnections()) {
elements.get(destination).removeConnection(key2);
}
if (element2.isInSet1()) {
keys1.remove(Integer.valueOf(key2));
} else {
keys2.remove(Integer.valueOf(key2));
}
elements.remove(key2);
if (element1.isInSet1()) {
firePropertyChange(ELEMENTS_COMBINED_IN_SET1, key2, key1);
} else {
firePropertyChange(ELEMENTS_COMBINED_IN_SET2, key2, key1);
}
postEdit(edit);
} |
2f9d38ef-9018-44a2-8abb-d25a2d9f0057 | 8 | public ArrayList <boid> getArrayNeightEdge(boid osobnik){
ArrayList <boid> temp=new ArrayList <>();
temp.ensureCapacity(400);
int dX=osobnik.getBucketX()+2;
int dY=osobnik.getBucketY()+2;
int tx=0,ty=0;
temp.addAll(bucketList.get(dX-2).get(dY-2).koszyk);
for (int i=dX-3;i<dX;i++){
if (i<0) {tx=x-1;}
else if (i>=x) {tx=0;}
else {tx=i;}
for (int j=dY-3;j<dY;j++){
if (i==dX-2 && j==dY-2){continue;}
if (j<0) {ty=y-1;}
else if (j>=y) {ty=0;}
else {ty=j;}
temp.addAll(bucketList.get(tx).get(ty).koszyk);
}
}
return temp;
} |
15f83d1d-2b6f-442d-867e-5ee1769a7b61 | 3 | private void showLoadDialog() {
try {
if (matchFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
if (matchFileChooser.getSelectedFile().isFile()) {
setMatch(MatchLoader.loadFromSave(matchFileChooser.getSelectedFile().getPath()));
displayMatch();
} else {
throw new FileNotFoundException("The selected file doesn't exist.");
}
}
} catch (FileNotFoundException exception) {
exception.printStackTrace();
JOptionPane.showMessageDialog(this, "Error: Couldn't find the selected file.");
}
} |
6b975ad9-639a-4e9d-91e2-2ad318a915da | 1 | private void runSSLTasks() {
Runnable task = null;
while ((task = mEngine.getDelegatedTask()) != null) {
task.run();
}
} |
89673c8c-17ec-4f0b-9cd7-1f72f8788cc3 | 7 | public void deleteTag()
{
if (this.myApplicationsAppMyTagsList.getSelectedValue()!=null && this.myApplicationsTree.getSelectionPath()!=null)
{
String appId = ((DefaultMutableTreeNode)this.myApplicationsTree.getLastSelectedPathComponent()).toString();
String tagName = ((TagListItem)this.myApplicationsAppMyTagsList.getSelectedValue()).getValue();
String tagType = ((TagListItem)this.myApplicationsAppMyTagsList.getSelectedValue()).getType();
try
{
boolean valid = false;
if(tagType.equalsIgnoreCase("public")){
valid = this.model.deletePublicTag(tagName, tagType, appId);
}else if(tagType.equalsIgnoreCase("private")){
valid = this.model.deletePrivateTag(tagName, tagType, appId);
}else if(tagType.equalsIgnoreCase("communities")){
valid = this.model.deleteCommunityTag(tagName, tagType, appId, ((TagListItem)this.myApplicationsAppMyTagsList.getSelectedValue()).getCommunityId());
}
if (valid)
{
//If everything was correct, reload the tags
this.loadTags(appId);
}else{
JOptionPane.showMessageDialog(this.mainWindow, "It was not possible to delete the tag",
"Deleting a tag", JOptionPane.ERROR_MESSAGE);
}
} catch (RemoteException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this.mainWindow, "It was not possible to connect with the back-end",
"Deleting a tag", JOptionPane.ERROR_MESSAGE);
}
}
} |
3091ee68-5258-4211-b8f3-56c2d9dcce05 | 9 | private static PDFDecrypter createStandardDecrypter(
PDFObject encryptDict,
PDFObject documentId,
PDFPassword password,
Integer keyLength,
boolean encryptMetadata,
StandardDecrypter.EncryptionAlgorithm encryptionAlgorithm)
throws
PDFAuthenticationFailureException,
IOException,
EncryptionUnsupportedByPlatformException,
EncryptionUnsupportedByProductException {
if (keyLength == null) {
keyLength = DEFAULT_KEY_LENGTH;
}
// R describes the revision of the security handler
final PDFObject rObj = encryptDict.getDictRef("R");
if (rObj == null) {
throw new PDFParseException(
"No R entry present in Encrypt dictionary");
}
final int revision = rObj.getIntValue();
if (revision < 2 || revision > 4) {
throw new EncryptionUnsupportedByPlatformException(
"Unsupported Standard security handler revision; R=" +
revision);
}
// O describes validation details for the owner key
final PDFObject oObj = encryptDict.getDictRef("O");
if (oObj == null) {
throw new PDFParseException(
"No O entry present in Encrypt dictionary");
}
final byte[] o = oObj.getStream();
if (o.length != 32) {
throw new PDFParseException("Expected owner key O " +
"value of 32 bytes; found " + o.length);
}
// U describes validation details for the user key
final PDFObject uObj = encryptDict.getDictRef("U");
if (uObj == null) {
throw new PDFParseException(
"No U entry present in Encrypt dictionary");
}
final byte[] u = uObj.getStream();
if (u.length != 32) {
throw new PDFParseException(
"Expected user key U value of 32 bytes; found " + o.length);
}
// P describes the permissions regarding document usage
final PDFObject pObj = encryptDict.getDictRef("P");
if (pObj == null) {
throw new PDFParseException(
"Required P entry in Encrypt dictionary not found");
}
return new StandardDecrypter(
encryptionAlgorithm, documentId, keyLength,
revision, o, u, pObj.getIntValue(), encryptMetadata, password);
} |
3eef064b-a124-4d60-8c62-c23d9eab64d6 | 9 | protected void _realSendMessage()
{
if(null == _m_scSocket)
return ;
if(!_m_scSocket.isConnected())
{
ALBasicSendingClientManager.getInstance().addSendSocket(this);
return ;
}
boolean needAddToSendList = false;
_lockBuf();
while(!_m_lSendBufferList.isEmpty())
{
//Socket 允许写入操作时
ByteBuffer buf = _m_lSendBufferList.getFirst();
if(buf.remaining() <= 0)
{
ALServerLog.Error("try to send a null buffer");
ALServerLog.Error("Wrong buffer:");
for(int i = 0; i < buf.limit(); i++)
{
ALServerLog.Error(buf.get(i) + " ");
}
}
try {
_m_scSocket.write(buf);
//判断写入后对应数据的读取指针位置
if(buf.remaining() <= 0)
_m_lSendBufferList.pop();
else
break;
}
catch (IOException e)
{
ALServerLog.Error("Client Socket send message error! user[" + _m_sUserName + "]");
e.printStackTrace();
break;
}
}
//当需要发送队列不为空时,继续添加发送节点
if(!_m_lSendBufferList.isEmpty())
needAddToSendList = true;
_unlockBuf();
if(needAddToSendList)
ALBasicSendingClientManager.getInstance().addSendSocket(this);
} |
62ccd733-0026-4e39-a8d7-d010ee9e2406 | 0 | public static void main(String[] args) {
System.out.println(HeaderType.valueOf("id").toString());
} |
a55342ba-21ba-4c6d-8109-85b8379d74ee | 7 | public static PairedAlignment getAlignment(String s1, List<IndividualEdit> edits)
throws Exception
{
final StringBuffer top = new StringBuffer();
final StringBuffer bottom = new StringBuffer();
int index=0;
for( IndividualEdit ie : edits)
{
if( ie.getPostion() > index && index < s1.length() )
{
String s = s1.substring(index, Math.min(ie.getPostion(),s1.length()));
top.append(s);
bottom.append(s);
}
if(ie.getEditType().equals(IndividualEdit.EDIT_TYPE.SUBSTITUITION))
{
top.append(s1.charAt(ie.getPostion()));
bottom.append(ie.getBase());
index = ie.getPostion()+1;
}
else if( ie.getEditType().equals(IndividualEdit.EDIT_TYPE.DELETION))
{
top.append(s1.charAt(ie.getPostion()));
bottom.append("-");
index = ie.getPostion()+1;
}
else if ( ie.getEditType().equals(IndividualEdit.EDIT_TYPE.INSERTION))
{
bottom.append( ie.getBase());
top.append("-");
index = ie.getPostion();
}
else throw new Exception("Illegal type " + ie.getEditType());
}
if( index < s1.length())
{
String s= s1.substring(index, s1.length());
top.append(s);
bottom.append(s);
}
return new PairedAlignment()
{
@Override
public String getSecondSequence()
{
return bottom.toString();
}
@Override
public String getFirstSequence()
{
return top.toString();
}
@Override
public float getAlignmentScore()
{
return Float.NaN;
}
};
} |
9fbdb479-4965-44df-892f-953cb32f2d42 | 0 | public void testDate2String() {
Calendar calendar = Calendar.getInstance();
calendar.set(2012, Calendar.SEPTEMBER, 22, 9, 18, 1);
String date = DateUtils.date2String(calendar.getTime());
assertEquals("2012-09-22 09:18:01", date);
date = DateUtils.date2String(calendar.getTime(), "yyyy-MM-dd");
assertEquals("2012-09-22", date);
} |
819ce6d1-63e6-4291-a009-b4644bf919d6 | 6 | protected boolean shouldPaint(final int horizIteration, final int verticalIteration) {
if (horizIteration < 0) {
throw new IllegalArgumentException(String.format(
"Passed horizIteration must be greater equal than 0! %d given.",
horizIteration));
}
if (verticalIteration < 0) {
throw new IllegalArgumentException(String.format(
"Passed verticalIteration must be greater equal than 0! %d given.",
verticalIteration));
}
if (horizIteration % 2 == 1 && verticalIteration % 2 == 1) {
return true;
}
if (horizIteration % 2 == 0 && verticalIteration % 2 == 0) {
return true;
}
return false;
} |
d6ec93ee-925b-4c79-813c-7077a4227eee | 9 | public static void main(String[] args) {
BigInteger secwet = new BigInteger("1234");
System.out.println("in: " + secwet.toString(2));
System.out.println();
int bitlen = secwet.bitLength();
bitlen += 3;
int k = 3, k2 = 3;
SecretSend s = new SecretSend(secwet, k, bitlen);
SecretReceive r = new SecretReceive(k);
while(true) {
for(int i = 0; i < Math.pow(2, k); i++) {
int y = s.y();
r.notY(y);
}
if(k2 == bitlen)
break;
System.out.println("next round: " + k2);
System.out.print("receive: ");
for(int i = 0; i < r.arr.length; i++) {
if(r.arr[i] == null)
System.out.print("NULL, ");
else
System.out.print(r.arr[i].toString(2) + ", ");
}
System.out.println();
System.out.print("send: ");
for(int i = 0; i < s.arr.length; i++) {
if(s.arr[i] == null)
System.out.print("NULL, ");
else {
if(s.cur == i)
System.out.print("[" + s.arr[i].toString(2) + "], ");
else
System.out.print(s.arr[i].toString(2) + ", ");
}
}
System.out.println();
s.nextRound();
r.nextRound();
k2 += 1;
}
System.out.println("giving " + (int) (Math.pow(2, k)-1) + " additional bits...");
for(int i = 0; i < Math.pow(2, k)-1; i++) {
int y = s.yOverride();
r.notY(y);
}
System.out.println();
System.out.println("done! last element left: " + r.solve().toString(2));
} |
2ba1911d-20c4-4eb8-b1ab-2986b661c0dc | 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(ModifyAssociationView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ModifyAssociationView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ModifyAssociationView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ModifyAssociationView.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() {
}
});
} |
8365dddb-7a0c-4545-bd55-f9ef5b4b156c | 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(New_Etudiant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(New_Etudiant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(New_Etudiant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(New_Etudiant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
New_Etudiant dialog = new New_Etudiant(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
} |
75cf558f-3b16-483d-bbcb-546f4de50cba | 5 | @Override
public List<Action> cleanup() {
List<Action> ret = super.cleanup();
// move arrows and kill hunters / wumpii
List<Actor> toKill = new ArrayList<Actor>();
for(Actor arrow : Groups.ofType(Arrow.class, model.actors)) {
MoveAction move = new MoveAction(model, ((Arrow)arrow).nextLocation(), arrow);
ret.add(move);
move.apply();
for(Actor actor : actorsAt(model.locations.get(arrow))) {
if(actor instanceof Hunter || actor instanceof Wumpus) {
toKill.add(actor);
}
}
move.undo();
}
for(Actor dead : toKill) { ret.add(new DestroyAction(this, dead)); }
return ret;
} |
23302ff1-c143-485f-ad00-0d3aafb0a43e | 4 | public static float getFloat() {
float x = 0.0F;
while (true) {
String str = readRealString();
if (str == null) {
errorMessage("Floating point number not found.",
"Real number in the range " + (-Float.MAX_VALUE) + " to " + Float.MAX_VALUE);
}
else {
try {
x = Float.parseFloat(str);
}
catch (NumberFormatException e) {
errorMessage("Illegal floating point input, " + str + ".",
"Real number in the range " + (-Float.MAX_VALUE) + " to " + Float.MAX_VALUE);
continue;
}
if (Float.isInfinite(x)) {
errorMessage("Floating point input outside of legal range, " + str + ".",
"Real number in the range " + (-Float.MAX_VALUE) + " to " + Float.MAX_VALUE);
continue;
}
break;
}
}
inputErrorCount = 0;
return x;
} |
6650d8de-dc70-4e80-9d67-88668ead1d84 | 1 | static FrequencyTable readFrequencies(BitInputStream in) throws IOException {
int[] freqs = new int[3];
for (int i = 0; i < 2; i++)
freqs[i] = readInt(in, 32);
freqs[2] = 1; // EOF symbol
return new SimpleFrequencyTable(freqs);
} |
839dabc0-904d-407f-b4a6-9231a66fc10c | 7 | public final JPoclASTParser.expr0_return expr0() throws RecognitionException {
JPoclASTParser.expr0_return retval = new JPoclASTParser.expr0_return();
retval.start = input.LT(1);
TypeTree root_0 = null;
Token set79=null;
JPoclASTParser.expr1_return expr178 =null;
JPoclASTParser.expr1_return expr180 =null;
TypeTree set79_tree=null;
try {
// C:\\Users\\pc\\Desktop\\IPL\\ew\\JPocl\\JPoclAST.g:102:8: ( expr1 ( ( '+' | '-' ) ^ expr1 )* )
// C:\\Users\\pc\\Desktop\\IPL\\ew\\JPocl\\JPoclAST.g:102:10: expr1 ( ( '+' | '-' ) ^ expr1 )*
{
root_0 = (TypeTree)adaptor.nil();
pushFollow(FOLLOW_expr1_in_expr0806);
expr178=expr1();
state._fsp--;
adaptor.addChild(root_0, expr178.getTree());
// C:\\Users\\pc\\Desktop\\IPL\\ew\\JPocl\\JPoclAST.g:102:16: ( ( '+' | '-' ) ^ expr1 )*
loop16:
do {
int alt16=2;
int LA16_0 = input.LA(1);
if ( (LA16_0==27||LA16_0==29) ) {
alt16=1;
}
switch (alt16) {
case 1 :
// C:\\Users\\pc\\Desktop\\IPL\\ew\\JPocl\\JPoclAST.g:102:17: ( '+' | '-' ) ^ expr1
{
set79=(Token)input.LT(1);
set79=(Token)input.LT(1);
if ( input.LA(1)==27||input.LA(1)==29 ) {
input.consume();
root_0 = (TypeTree)adaptor.becomeRoot(
(TypeTree)adaptor.create(set79)
, root_0);
state.errorRecovery=false;
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
throw mse;
}
pushFollow(FOLLOW_expr1_in_expr0818);
expr180=expr1();
state._fsp--;
adaptor.addChild(root_0, expr180.getTree());
}
break;
default :
break loop16;
}
} while (true);
}
retval.stop = input.LT(-1);
retval.tree = (TypeTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
}
finally {
// do for sure before leaving
}
return retval;
} |
e26b3480-7330-482f-a0e5-91189f0cd8c9 | 5 | @Override
public boolean register(Player player) {
if (_started == false && player.getName() != "" && _list.size() <= 4) {
_list.add(player);
new GUI();
return true;
}
if (_started == true || player.getName() == "") {
return false;
}
return false;
} |
efbda657-e7cd-4af3-b49e-710354fc5268 | 4 | public static int addConnectionThread(Thread con)
{
boolean added = false;
int num = 0;
for(int k = 0;k<=5;k++)
{
if(MainThread.uploadConnectionThreads[k] == null && added == false)
{
MainThread.uploadConnectionThreads[k] = con;
added = true;
}
}
if(added = false)
{
return 99;
}
return num;
} |
059cf155-8a51-443d-8eb2-0e39e27d62e7 | 9 | @Override
public void processKeyEvent(KeyEvent keyEvent) {
final int VK_LEFT = 0x25;
final int VK_RIGHT = 0x27;
final int VK_UP = 0x26;
final int VK_DOWN = 0x28;
final int VK_JUMP = 0x42;
final int VK_W = 0x57;
final int VK_S = 0x53;
final int VK_A = 0x41;
final int VK_D = 0x44;
final int VK_PAUSE = 0x50; // press p for pause
final int VK_HINTS = 0x38; // press 8 for hint map
int k = keyEvent.getKeyCode();
if (k > 0) {
k = k == VK_W ? VK_UP : k == VK_D ? VK_RIGHT : k == VK_A ? VK_LEFT
: k == VK_S ? VK_DOWN : k;
a[(k >= VK_LEFT && k <= VK_DOWN) || k == VK_HINTS
|| k == VK_PAUSE ? k : VK_JUMP] = keyEvent.getID() != 402;
}
} |
a5aab3eb-c32b-4f1c-996e-e8626769d87e | 4 | private void processEvent(BaseEvent event) {
// Retrieve all eventlisteners that are subscribed to this eventtype.
ArrayList<IEventListener> listeners = listenerMap.get(event.getEventType().getID());
if(listeners == null) {
return;
}
for(IEventListener ie : listeners) {
// handleEvent returns true if the eventlistener wants to "swallow" the event.
if(ie.handleEvent(event)) {
Logger.log("EventType: " + event.getEventType().getName() +
" was swallowed by: " + ie.getName()
);
break;
}
}
// Wildcard listeners get notified of everything that happens.
ArrayList<IEventListener> wildcards = listenerMap.get(0);
for(IEventListener ie : wildcards) {
ie.handleEvent(event);
}
} |
8bc5cd6b-ddaa-45e3-b879-063b562f41f5 | 7 | public void Solve() {
HashSet<Integer> numbers = new HashSet<Integer>();
for (int a = 1; a < 100; a++) {
for (int b = a; b < 10000; b++) {
int c = a * b;
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.addAll(GetDigits(a));
temp.addAll(GetDigits(b));
temp.addAll(GetDigits(c));
if (temp.size() == 9) {
boolean areAllThere = true;
for (int i = 1; i < 10 && areAllThere; i++) {
areAllThere = temp.contains(i);
}
if (areAllThere) {
System.out.println("a=" + a + ", b=" + b + ", a * b = c =" + c);
numbers.add(c);
}
}
}
}
long result = 0;
for (Iterator<Integer> it = numbers.iterator(); it.hasNext();) {
result += it.next();
}
System.out.println("Result=" + result);
} |
863c1337-e640-4a30-bff0-f4e50eeb5481 | 2 | public String toString() {
String rep = "";
for (int i = 0; i < this.board.length; i++) {
for (int j = 0; j < this.board[i].length; j++) {
rep += MoveHandler.convertIntToPieceString(this.board[i][j], true) + " ";
}
rep += "\n";
}
return rep;
} |
3c695bf7-d7d6-47c3-88a6-7c76ca3aadfb | 7 | static final public int one_line() throws ParseException {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case MINUS:
case CONSTANT:
case 12:
sum();
jj_consume_token(11);
{if (true) return 0;}
break;
case 11:
jj_consume_token(11);
{if (true) return 1;}
break;
default:
jj_la1[0] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
throw new Error("Missing return statement in function");
} |
a3be959d-dc11-435f-b2cb-fecc86c8b57a | 5 | public void berechneRestzeit(Date end) {
Date now = new Date(); //current date
long diff = end.getTime() - now.getTime(); //milliseconds
long days = diff/(1000*60*60*24);
long hours = (diff-days*1000*60*60*24)/(1000*60*60);
long minutes = (diff-days*1000*60*60*24-hours*1000*60*60)/(1000*60);
String rest = "";
if(days < 0 || hours < 0 || minutes < 0){
rest = "0m";
}
else{
if(days == 0){
if(hours == 0)
rest = minutes + "m";
else
rest = hours + "h" + minutes + "m";
}else{
rest = days + "d" + hours + "h" + minutes + "m";
}
}
setRestzeit(rest);
} |
db5f860f-c2f3-448e-aeed-16eb63694263 | 9 | public static boolean join(Player player, String arena, BowSpleef plugin)
{
if (player.hasPermission("bs.join"))
{
if (BowSpleef.arenaConfig.contains("arenas." + arena))
{
if (BowSpleef.arenaConfig.getBoolean("arenas." + arena + ".enabled"))
{
if (!BowSpleef.arenaConfig.getBoolean("arenas." + arena + ".inGame"))
{
if (!BowSpleef.invConfig.contains(player.getName()))
{
List<String> players = BowSpleef.arenaConfig.getStringList("arenas." + arena + ".players");
int max = BowSpleef.arenaConfig.getInt("arenas." + arena + ".max-players");
if (players.size() == max)
{
Methods.pm("That arena is already full!", player);
}
if (players.size() >= Math.round(max * .66))
{
// Start the Arena
BowSpleefCountdownEvent event = new BowSpleefCountdownEvent(arena);
Bukkit.getServer().getPluginManager().callEvent(event);
new Countdown(event.getArena()).runTaskTimer(plugin, 0L, 20L);
BowSpleef.arenaConfig.set("arenas." + arena + ".inGame", true);
plugin.saveConfig();
}
// Storage for Return GM
int gm = player.getGameMode().getValue();
BowSpleef.invConfig.set(player.getName() + ".return.gamemode", gm);
// Storage for Returning to Pos
Location returnPos = player.getLocation();
BowSpleef.invConfig.set(player.getName() + ".return.x", returnPos.getBlockX());
BowSpleef.invConfig.set(player.getName() + ".return.y", returnPos.getBlockY());
BowSpleef.invConfig.set(player.getName() + ".return.z", returnPos.getBlockZ());
BowSpleef.invConfig.set(player.getName() + ".return.world", returnPos.getWorld().getName());
Inventory storage = InventoryUtil.getArmorInventory(player.getInventory());
Inventory GlobalInv = InventoryUtil.getContentInventory(player.getInventory());
BowSpleef.invConfig.set(player.getName() + ".inventory", InventoryUtil.toBase64(GlobalInv));
BowSpleef.invConfig.set(player.getName() + ".armor", InventoryUtil.toBase64(storage));
// Inventory Storage
String inv = InventoryUtil.toBase64(player.getInventory());
Inventory armorInv = InventoryUtil.getArmorInventory(player.getInventory());
String armor = InventoryUtil.toBase64(armorInv);
BowSpleef.invConfig.set(player.getName() + ".armor", armor);
BowSpleef.invConfig.set(player.getName() + ".inventory", inv);
BowSpleef.invConfig.set(player.getName() + ".arena", arena);
// Clearing Inventory
player.getInventory().clear();
player.getInventory().setHelmet(null);
player.getInventory().setChestplate(null);
player.getInventory().setLeggings(null);
player.getInventory().setBoots(null);
// Teleporting to the Lobby
World world = Bukkit.getServer().getWorld(BowSpleef.arenaConfig.getString("arenas." + arena + ".world"));
int x = BowSpleef.arenaConfig.getInt("arenas." + arena + ".lobby.x"), y = BowSpleef.arenaConfig.getInt("arenas." + arena + ".lobby.y"), z = BowSpleef.arenaConfig.getInt("arenas." + arena + ".lobby.z");
Location lobby = new Location(world, x, y, z);
player.teleport(lobby);
// Setting them to Adventure Time
player.setGameMode(GameMode.ADVENTURE);
// Event
BowSpleefJoinEvent event = new BowSpleefJoinEvent(player, arena);
Bukkit.getServer().getPluginManager().callEvent(event);
players.add(player.getName());
BowSpleef.arenaConfig.set("arenas." + arena + ".players", players);
if (players.size() == Math.round((BowSpleef.arenaConfig.getInt("arenas." + arena + ".max-players") * 2) / 3))
{
BowSpleefJoinEvent eventS = new BowSpleefJoinEvent(player, arena);
Bukkit.getServer().getPluginManager().callEvent(eventS);
}
for (int p = 0; p < players.size(); p++)
{
Methods.pm(player.getName() + " joined the arena!" + " " + players.size() + "/" + max, Bukkit.getPlayer(players.get(p)));
}
plugin.saveConfig();
return true;
}
pm("You are already in an arena!", player);
return true;
}
pm("That arena is in game!", player);
return true;
}
pm("That arena is Disabled", player);
return true;
}
pm("That Arena doesn't Exist!", player);
return true;
}
pm("You do not have the required permissions!", player);
return true;
} |
943c55a7-dc0f-4a6d-9478-7eafd1cc60f3 | 7 | public PartieDeRisk(int nombreDeJoueurs)
{
this.plateau = new Plateau();
this.nombreDeJoueurs = nombreDeJoueurs;
this.joueursDeLaPartie = new Joueur[nombreDeJoueurs];
int[] total = new int[6];
switch (nombreDeJoueurs)
{
case 2:
total[0] = 21;
total[1] = 21;
this.nbRenfortPremierTour = 40;
break;
case 3:
total[0] = 14;
total[1] = 14;
total[2] = 14;
this.nbRenfortPremierTour = 35;
break;
case 4:
total[0] = 10;
total[1] = 10;
total[2] = 11;
total[3] = 11;
this.nbRenfortPremierTour = 30;
break;
case 5:
total[0] = 8;
total[1] = 8;
total[2] = 8;
total[3] = 9;
total[4] = 9;
this.nbRenfortPremierTour = 25;
break;
case 6:
total[0] = 7;
total[1] = 7;
total[2] = 7;
total[3] = 7;
total[4] = 7;
total[5] = 7;
this.nbRenfortPremierTour = 20;
break;
default:
System.out
.println("Le nombre de joueur doit être compris entre 2 et 6.");
this.nbRenfortPremierTour = 0;
}
for(int numeroDuJoueur = 0; numeroDuJoueur<this.nombreDeJoueurs; numeroDuJoueur++)
{
joueursDeLaPartie[numeroDuJoueur] = new Joueur(Couleur.values()[numeroDuJoueur], numeroDuJoueur,plateau.obtenirRegion(total[numeroDuJoueur]));
Region[] RegionDuJoueur= joueursDeLaPartie[numeroDuJoueur].obtenirRegionDuJoueur();
if(RegionDuJoueur.length==42){
System.out.println("Felicitation ! le joueur"+joueursDeLaPartie[numeroDuJoueur].obtenirNomJoueur()+"a gagné !") ;
}
}
} |
82dd5191-a79a-4bae-984b-a579e313ee46 | 4 | void addShapelessRecipe(ItemStack var1, Object ... var2) {
ArrayList var3 = new ArrayList();
Object[] var4 = var2;
int var5 = var2.length;
for(int var6 = 0; var6 < var5; ++var6) {
Object var7 = var4[var6];
if(var7 instanceof ItemStack) {
var3.add(((ItemStack)var7).copy());
} else if(var7 instanceof Item) {
var3.add(new ItemStack((Item)var7));
} else {
if(!(var7 instanceof Block)) {
throw new RuntimeException("Invalid shapeless recipy!");
}
var3.add(new ItemStack((Block)var7));
}
}
this.recipes.add(new ShapelessRecipes(var1, var3));
} |
01673487-8ec5-4c32-97cc-7a68a7a8b42b | 6 | public List<Interval> merge(List<Interval> intervals) {
int size = intervals.size();
if(size <= 1) return intervals;
Collections.sort(intervals, new Comparator<Interval>(){
@Override
public int compare(Interval A, Interval B) {
if(A.start < B.start) return -1;
if(A.start > B.start) return 1;
return 0;
}
});
List<Interval> result = new ArrayList<Interval>();
Interval element = intervals.get(0);
for(int i=1; i < size; i++){
Interval temp = intervals.get(i);
//handle special case
if(element.end < temp.start){
result.add(element);
element = new Interval(temp.start, temp.end);
}if(element.end < temp.end){
element.end = temp.end;
}
}
result.add(element);
return result;
} |
a46f5a1a-7287-40dc-8fb5-87b4878beddd | 8 | static int checkStyle(Shell parent, int style) {
int mask = SWT.PRIMARY_MODAL | SWT.APPLICATION_MODAL | SWT.SYSTEM_MODAL;
if ((style & SWT.SHEET) != 0) {
style &= ~SWT.SHEET;
if ((style & mask) == 0) {
style |= parent == null ? SWT.APPLICATION_MODAL
: SWT.PRIMARY_MODAL;
}
}
if ((style & mask) == 0) {
style |= SWT.APPLICATION_MODAL;
}
style &= ~SWT.MIRRORED;
if ((style & (SWT.LEFT_TO_RIGHT | SWT.RIGHT_TO_LEFT)) == 0) {
if (parent != null) {
if ((parent.style & SWT.LEFT_TO_RIGHT) != 0)
style |= SWT.LEFT_TO_RIGHT;
if ((parent.style & SWT.RIGHT_TO_LEFT) != 0)
style |= SWT.RIGHT_TO_LEFT;
}
}
return Widget.checkBits(style, SWT.LEFT_TO_RIGHT, SWT.RIGHT_TO_LEFT, 0,
0, 0, 0);
} |
874bdaca-1148-4ad3-9824-b2e77021b6df | 7 | private static Binomialnode merge(Binomial heap1, Binomial heap2) {
//Jos toisen juuri on tyhjä, palautetaan suoraan toinen
if (heap1.root == null) {
return heap2.root;
} else if (heap2.root == null) {
return heap1.root;
}
//Kumpikaan juurilista ei siis ole tyhjä. Käydään molemmat läpi käyttäen aina pienimmän arvon omaavaa solmua.
Binomialnode root;
Binomialnode last;
Binomialnode next1 = heap1.root,
next2 = heap2.root;
if (heap1.root.value <= heap2.root.value) {
root = heap1.root;
next1 = next1.sibling;
} else {
root = heap2.root;
next2 = next2.sibling;
}
last = root;
//Käy molemmat juurilistat läpi kunnes toinen loppuu.
while (next1 != null && next2 != null) {
if (next1.value <= next2.value) {
last.sibling = next1;
next1 = next1.sibling;
} else {
last.sibling = next2;
next2 = next2.sibling;
}
last = last.sibling;
}
//Nyt toinen juurilista on loppunut. Jatketaan jäljellä olevasta juurilistasta loput listaan.
if (next1 != null) {
last.sibling = next1;
} else {
last.sibling = next2;
}
return root;
} |
fd8dd0e5-abc1-4954-98b6-6e6de098c4d0 | 0 | public BinaryLogicalOperator<Boolean> getOperator() {
return binaryLogicalOperator;
} |
73c3ff83-88b2-454d-8ba7-94e3ce7fada6 | 2 | protected int byteArrayToInt(byte[] bytes) {
int result = 0;
int l = bytes.length - 1;
for (int i = 0; i < bytes.length; i++) {
if (i == l) result += bytes[i] << i * 8;
else result += (bytes[i] & 0xFF) << i * 8;
}
return result;
} |
c704a7b9-faf8-418e-bf64-ad4033e2d8a0 | 3 | @Override
public double[] get2DData(int px, int pz, int sx, int sz)
{
double[] da = a.get2DData(px, pz, sx, sz);
double[] db;
if(a == b)
db = da;
else
db = b.get2DData(px, pz, sx, sz);
int s = sx*sz;
for(int i = 0; i < s; i++)
da[i] = da[i] > db[i] ? da[i] : db[i];
return da;
} |
e4a9842e-6662-401f-bbc0-b4ade63e55f3 | 8 | protected static Ptg calcDGet( Ptg[] operands )
{
if( operands.length != 3 )
{
return new PtgErr( PtgErr.ERROR_NULL );
}
DB db = getDb( operands[0] );
Criteria crit = getCriteria( operands[2] );
if( (db == null) || (crit == null) )
{
return new PtgErr( PtgErr.ERROR_NUM );
}
int fNum = db.findCol( operands[1].getString().trim() );
if( fNum == -1 )
{
return new PtgErr( PtgErr.ERROR_NUM );
}
String val = "";
int count = 0;
// this is the colname to match
String colname = operands[1].getValue().toString();
for( int i = 0; i < db.getNRows(); i++ )
{ // loop thru all db rows
// check if current row passes criteria requirements
if( crit.passes( colname, db.getRow( i ), db ) )
{
// passes; now do action
val = db.getCell( i, fNum ).getValue().toString();
count++;
}
}
if( count == 0 )
{
return new PtgErr( PtgErr.ERROR_VALUE ); // no recs match
}
if( count > 1 )
{
return new PtgErr( PtgErr.ERROR_NUM ); // if more than one record matches criteria
}
return new PtgStr( val );
} |
33b7d664-f1da-47da-9ac6-2fa54e38ee25 | 6 | public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // LEFT_RHINO_ID
return LEFT_RHINO_ID;
case 2: // LEFT_TITAN_ID
return LEFT_TITAN_ID;
case 3: // RIGHT_RHINO_ID
return RIGHT_RHINO_ID;
case 4: // RIGHT_TITAN_ID
return RIGHT_TITAN_ID;
case 5: // LABEL
return LABEL;
case 6: // PROPERTIES
return PROPERTIES;
default:
return null;
}
} |
e59967ff-5639-4a32-83dc-7caf5a5e3e1a | 0 | public static void runFileDataBaseEditor(){
frames.runFileDataBaseEditor();
frames.getFileDataBaseEditor().setVisible(true);
} |
72775451-0533-470c-a65d-2a804e3726f7 | 4 | private static Move ForwardLeftForBlack(int r, int c, Board board){
Move forwardLeft = null;
assert(board.cell[r][c] == CellEntry.black || board.cell[r][c] == CellEntry.blackKing);
if( r>=1 && c<Board.cols-1 &&
board.cell[r-1][c+1] == CellEntry.empty
)
{
forwardLeft = new Move(r,c,r-1, c+1);
}
return forwardLeft;
} |
f0e44f0d-280a-4cca-a831-90fbc3a7a7d1 | 7 | public Section(int sectionId, String name, Subject subject, Schedule schedule, Teacher teacher)
throws ScheduleConflictException {
if (sectionId < 0) {
throw new IllegalArgumentException("Section id must not be negative.");
}
if (name == null) {
throw new IllegalArgumentException("Section name must not be null.");
}
if (subject == null) {
throw new IllegalArgumentException("Subject must not be null.");
}
if (schedule == null) {
throw new IllegalArgumentException("Schedule must not be null.");
}
if (teacher == null) {
throw new IllegalArgumentException("Teacher must not be null.");
}
this.teacher = teacher;
this.sectionId = sectionId;
this.name = name;
this.subject = subject;
this.schedule = schedule;
this.classCards = new HashSet<ClassCard>();
if (teacher.hasScheduledClass(schedule)) {
boolean scheduledClassIsSameSection = teacher.hasSection(this);
if (!scheduledClassIsSameSection) {
throw new ScheduleConflictException("Schedule conflict for a teacher when adding the section.");
}
}
teacher.addSection(this);
} |
43438847-6950-42fe-b0db-479ad8a7dff9 | 7 | @EventHandler(priority=EventPriority.LOWEST, ignoreCancelled=true)
public void onPlayerPortal(PlayerPortalEvent event1)
{
if(debug) this.getLogger().info("PlayerPortalEvent cast");
UnitedPortalEvent ev=new UnitedPortalEvent(event1);
if(!chevronFinder(ev))
{
if(gateHandler(ev))
{
if(debug) this.getLogger().info("PlayerPortalEvent cast - gate handler");
ChevronWorld b=AddressBook.readAddress(event1.getTo().getWorld().getName());
event1.getPlayer().sendMessage(ConfigHandler.lng.get("gate.transfer")+(b.getName().equals("NONE")? b.getWorld().getName():b.getName()));
}
}
else
{
if(debug) this.getLogger().info("PlayerPortalEvent cast - chevron finded");
ChevronWorld b=AddressBook.readAddress(event1.getTo().getWorld().getName());
event1.getPlayer().sendMessage(ConfigHandler.lng.get("gate.transfer")+(b.getName().equals("NONE")? b.getWorld().getName():b.getName()));
}
} |
39fe42bf-392d-4ffb-8779-dd3d8d0431c9 | 1 | private static int myRecursiveMethod(int aValue) {
aValue--;
System.out.println(aValue);
if(aValue == 0) {
return 0;
}
return myRecursiveMethod(aValue);
} |
9a6cbbca-12e5-42af-b608-6ae497329f05 | 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(VistaLogIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(VistaLogIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(VistaLogIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(VistaLogIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new VistaLogIn().setVisible(true);
}
});
} |
16a4fba2-87b4-4cbc-a190-91d665340fa2 | 1 | public void PerformIPTest()
{
if(!responseServer.running) {
gameList.clear();
UpdateGameList();
}
responseServer.startServerIPTest();
} |
e131d3d5-ed72-4252-ad20-1445e1596bc7 | 0 | public boolean isSatisfied() {
return Satisfied;
} |
a08f10a8-cf47-4938-b87e-195d52a72a69 | 0 | public void setUp() {
Scanner scanner = new Scanner(System.in);
setAquarium(scanner);
setVictims(scanner);
setStepToVictim(scanner);
setPredators(scanner);
setStepToPredator(scanner);
setHurdles(scanner);
setLengthLifeInAquarium(scanner);
} |
ac0f0b8a-b42e-438a-852e-0b4a4b1eeaf4 | 0 | public int getCityID(){
return targetCityID;
} |
40e7cacd-d841-46b9-bf0e-a06196d9b58c | 0 | public JCheckBoxMenuItem getAcceptByHaltingCheckBox() {
return turingAcceptByHaltingCheckBox;
} |
9021eba0-478f-4331-8e83-c303ea994277 | 2 | private User findGameHostByID(String gameHostID) {
for (int i = 0; i < availableGames.size(); i++) {
if (availableGames.get(i).getID().equals(gameHostID)) {
return availableGames.get(i);
}
}
return null;
} |
aa00c9f3-0f73-41e4-911c-c659ddde83a2 | 4 | public void setInterpolationMethod(int interpolationMethod) {
switch(interpolationMethod) {
case INTERPOLATE_REGRESSION:
calculateBestFitLine();
case INTERPOLATE_LEFT:
case INTERPOLATE_RIGHT:
case INTERPOLATE_LINEAR:
this.interpolationMethod = interpolationMethod;
break;
default:
this.interpolationMethod = INTERPOLATE_LINEAR;
}
} |
e71e7ef7-cf9e-46c8-843c-060ca41cf630 | 7 | private String startSetToString() {
StringBuffer FString = new StringBuffer();
boolean didPrint;
if (m_starting == null) {
return getStartSet();
}
for (int i = 0; i < m_starting.length; i++) {
didPrint = false;
if ((m_hasClass == false) ||
(m_hasClass == true && i != m_classIndex)) {
FString.append((m_starting[i] + 1));
didPrint = true;
}
if (i == (m_starting.length - 1)) {
FString.append("");
}
else {
if (didPrint) {
FString.append(",");
}
}
}
return FString.toString();
} |
ecc49631-63ee-493e-a4ce-7a8d005a6314 | 6 | private void FindObjectInRow (ABObject target, List<ABObject> objects, List<ABObject> directList)
{
for (int i = 0; i < objects.size(); i++)
{
if (directList.size() <= 3)
{
ABObject x = objects.get(i);
if (x.getCenterX() >= target.getMaxX() && x.getCenterX() <= target.getMaxX() + 10)
{
if (x.getCenterY() >= target.getMinY()-10 && x.getCenterY() <= target.getMaxY()+10)
{
directList.add(x);
}
}
}
else
break;
}
} |
00267f11-f1dc-4f26-aa6f-71524fb61200 | 3 | public static boolean isValidTime(String time)
{
String[] times = time.split(":");
for (int i = 0; i < times.length - 1; i++)
if (!isInteger(times[i]))
return false;
if (!isDouble(times[times.length - 1]))
return false;
return true;
} |
bd9e3bec-84c9-4797-ba30-d4d8d49983c3 | 8 | public boolean stateEquals(Object o) {
if (o == this) return true;
if (o == null || !(o instanceof MersenneTwister))
return false;
MersenneTwister other = (MersenneTwister) o;
if (mti != other.mti) return false;
for (int x = 0; x < mag01.length; x++)
if (mag01[x] != other.mag01[x]) return false;
for (int x = 0; x < mt.length; x++)
if (mt[x] != other.mt[x]) return false;
return true;
} |
6bb99425-d477-48e3-97db-cbeb6f41b742 | 5 | private static void method499(char arg0[]) {
boolean flag = true;
for (int chars = 0; chars < arg0.length; chars++) {
char c = arg0[chars];
if (Censor.isLetter(c)) {
if (flag) {
if (Censor.isLowerCaseLetter(c)) {
flag = false;
}
} else if (Censor.isUpperCaseLetter(c)) {
arg0[chars] = (char) (c + 97 - 65);
}
} else {
flag = true;
}
}
} |
f3562e8a-152a-4066-bda3-bee844e2b800 | 4 | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FloatPair floatPair = (FloatPair) o;
return(floatPair.first == first && floatPair.second == second);
} |
a9f073dd-812b-4cc3-b535-6dd9368e0a82 | 5 | public JmeControlsDemoScreenController(final String ... mapping) {
if (mapping == null || mapping.length == 0 || mapping.length % 2 != 0) {
logger.warning("expecting pairs of values that map menuButton IDs to dialog IDs");
} else {
for (int i=0; i<mapping.length/2; i++) {
String menuButtonId = mapping[i*2+0];
String dialogId = mapping[i*2+1];
buttonToDialogMap.put(menuButtonId, dialogId);
buttonIdList.add(menuButtonId);
if (i == 0) {
currentMenuButtonId = menuButtonId;
}
}
}
} |
ecb89b92-eb83-427c-8396-31aa97eec7bf | 7 | public int[][] setMatrixZeros(int[][] m){
int nRow = m.length;
int nColumn = m[0].length;
//find all rows and columns should be set to zero
boolean[] isZeroRow = new boolean[nRow];
boolean[] isZeroColumn = new boolean[nColumn];
for(int i=0;i<nRow;i++){
for(int j=0;j<nColumn;j++){
if(m[i][j]==0){
isZeroRow[i] = true;
isZeroColumn[j] = true;
}
}
}
//set zeros
for(int i=0;i<nRow;i++){
for(int j=0;j<nColumn;j++){
if(isZeroRow[i] == true || isZeroColumn[j] == true){
m[i][j]=0;
}
}
}
return m;
} |
3692842a-85bc-4372-8f0b-cb296f82ab8d | 1 | public Object getElement(int index) {
if (indexOK(index)) {
return array[index];
}
return null;
} |
d52d7f99-457f-40a5-bbf6-b361e7c120f5 | 2 | private void getFileNameImage(String line) {
StringTokenizer tokens = new StringTokenizer(line);
if (tokens.countTokens() == 2) {
tokens.nextToken(); // skip command label
loadSingleImage(GameController.IMAGES_DIR + tokens.nextToken(), "", 1.0f, (short) -1, (short) -1, (short) -1);
} else if (tokens.countTokens() == 7) {
tokens.nextToken(); // skip command label
String name = tokens.nextToken();
String img = tokens.nextToken();
float transperancy = Float.valueOf(tokens.nextToken());
short red = Short.valueOf(tokens.nextToken());
short green = Short.valueOf(tokens.nextToken());
short blue = Short.valueOf(tokens.nextToken());
loadSingleImage(GameController.IMAGES_DIR + img, name, transperancy, red, green, blue);
} else {
EIError.debugMsg("Wrong no. of arguments for " + line, EIError.ErrorLevel.Error);
}
} |
081d7858-e48a-480c-97e4-8b6edc11d848 | 7 | public void generateUsers(int nb) {
String line;
int end = currentLine + nb;
int i = 0;
InputStream is = null;
BufferedReader br = null;
try {
is = getClass().getClassLoader().getResourceAsStream("data/data.csv");
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
if (i < currentLine) {
i++;
} else if (i >= currentLine) {
if (i >= end) {
currentLine = i;
break;
} else {
i++;
String[] user = line.split(",");
creeUtilisateur(user[2], user[1], user[0]);
}
}
}
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
} |
16658e71-226e-400a-aae5-fc7eac13eeb0 | 8 | public void train(Vector labelset, Matrix dataset) throws TrainingException {
if (labelset.size() != dataset.columnSize()) {
throw new CardinalityException(labelset.size(), dataset.columnSize());
}
boolean converged = false;
int iteration = 0;
while (!converged) {
if (iteration > 1000) {
throw new TrainingException("Too many iterations needed to find hyperplane.");
}
converged = true;
int columnCount = dataset.columnSize();
for (int i = 0; i < columnCount; i++) {
Vector dataPoint = dataset.viewColumn(i);
log.debug("Training point: {}", dataPoint);
synchronized (this.model) {
boolean prediction = model.classify(dataPoint);
double label = labelset.get(i);
if (label <= 0 && prediction || label > 0 && !prediction) {
log.debug("updating");
converged = false;
update(label, dataPoint, this.model);
}
}
}
iteration++;
}
} |
13055f1c-26f8-4c31-8503-d197cd6161c3 | 4 | @Override
public void apply(Graphics2D g) {
g.setColor(new Color(color));
g.setStroke(new BasicStroke(strokeSize, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
int minX = Math.min(x, width);
int minY = Math.min(y, height);
int maxX = Math.max(x, width);
int maxY = Math.max(y, height);
int width = maxX - minX;
int height = maxY - minY;
switch (String.valueOf(type)) {
case "RECT":
if (fill) {
g.fillRect(minX, minY, width, height);
} else {
g.drawRect(minX, minY, width, height);
}
break;
case "OVAL":
if (fill) {
g.fillOval(minX, minY, width, height);
} else {
g.drawOval(minX, minY, width, height);
}
break;
}
} |
8d6606df-8158-41e7-8c7e-6355bf305346 | 7 | public synchronized void run() {
long lastMinute = System.currentTimeMillis();
long lastTime = System.nanoTime();
double nsPerTick = 1000000000 / 60.0;
int frames = 0;
long lastTimer = System.currentTimeMillis();
double delta = 0;
while (running) {
try {
if (System.currentTimeMillis() > lastMinute + 1000) {
lastMinute = System.currentTimeMillis();
minutes++;
if (minutes > 60) {
minutes = 0;
hours++;
if (hours > 24) {
hours = 0;
}
}
}
long now = System.nanoTime();
delta += (now - lastTime) / nsPerTick;
lastTime = now;
while (delta >= 1) {
tick();
delta--;
}
frames++;
render();
if (System.currentTimeMillis() - lastTimer >= 1000) {
lastTimer += 1000;
Game.fps = frames;
frames = 0;
}
} catch (Exception e) {
e.printStackTrace();
display.sendCrashReportToScreen(e);
running = false;
}
}
Display.stop();
display = null;
new Launcher().start();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.