method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
92fcbb4a-b352-4245-9a56-a93470b0944b
| 8
|
public static void main(String[] args) throws Exception {
int choice = -1;
while (choice < 4) {
System.out.println("Please Enter your choice\n");
System.out
.println("1. Create New Array \n2. Search Element \n3. Delete Element \n4. Exit\n");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
choice = Integer.parseInt(reader.readLine());
switch (choice) {
case 1:
System.out.println("Enter Array Size\n");
size = Integer.parseInt(reader.readLine());
array = new int[size];
System.out.println("Enter Elements\n");
for (int count = 0; count < size; count++) {
array[count] = Integer.parseInt(reader.readLine());
}
break;
case 2:
System.out.println("Enter Element to search : \n");
int pos = searchElement(Integer.parseInt(reader.readLine()));
if (pos < 0) {
System.out.println("Element not present !");
break;
}
System.out.println("Element position in the array : " + (pos + 1));
break;
case 3:
System.out.println("Enter Element to delete : \n");
if (deleteElement(Integer.parseInt(reader.readLine())) == null) {
System.out.println("Element not present !");
break;
}
size--;
System.out.println("Updated Array");
for (int count = 0; count < size; count++) {
System.out.println(array[count]);
}
break;
}
}
}
|
8bb493de-59ef-4ff6-9699-96b37e800514
| 2
|
private void init() {
try {
// Setup Parser
factory = SAXParserFactory.newInstance();
factory.setValidating(true);
reader = factory.newSAXParser().getXMLReader();
reader.setErrorHandler(new SimpleSAXErrorHandler());
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
|
5a51a714-bc8c-49ca-a78f-217c3ec0401b
| 6
|
private static double readNum(String[] tokens,int[] st,int end,boolean allowNeg,int lnum,String line)
throws IOException{
if(st[0]==end) throwMe("syntax error",lnum,line);
String s=tokens[st[0]++];
boolean neg=s.equals("-");
if(neg){
if(!allowNeg) throwMe("envelope durations must be positive",lnum,line);
if(st[0]==end) throwMe("syntax error",lnum,line);
s=tokens[st[0]++];
}
if(!isDecimal(s.charAt(0))) throwMe("syntax error",lnum,line);
return Double.parseDouble(s)*(neg? -1:1);
}
|
adcbda5f-d9a8-4b87-a5e7-fb2928d3e865
| 2
|
private void addFirst(Item item) {
if (item == null)
throw new NullPointerException();
if (isEmpty()) {
first = new Node<Item>();
last = new Node<Item>();
first.item = item;
last = first;
} else {
Node<Item> node = new Node<Item>();
node.item = item;
node.next = first;
first.prev = node;
node.prev = null;
first = node;
}
size++;
}
|
2395b020-623a-4aed-997c-5ae1eebb3b5a
| 7
|
public void setParameterDefs(ArrayList<Attribute> paramDefs) throws Exception {
if (paramDefs.size() != m_parameters.size()) {
throw new Exception("[DefineFunction] number of parameter definitions does not match "
+ "number of parameters!");
}
// check these defs against the optypes of the parameters
for (int i = 0; i < m_parameters.size(); i++) {
if (m_parameters.get(i).getOptype() == FieldMetaInfo.Optype.CONTINUOUS) {
if (!paramDefs.get(i).isNumeric()) {
throw new Exception("[DefineFunction] parameter "
+ m_parameters.get(i).getFieldName() + " is continuous, but corresponding "
+ "supplied parameter def " + paramDefs.get(i).name() + " is not!");
}
} else {
if (!paramDefs.get(i).isNominal() && !paramDefs.get(i).isString()) {
throw new Exception("[DefineFunction] parameter "
+ m_parameters.get(i).getFieldName() + " is categorical/ordinal, but corresponding "
+ "supplied parameter def " + paramDefs.get(i).name() + " is not!");
}
}
}
// now we need to rename these argument definitions to match the names of
// the actual parameters
ArrayList<Attribute> newParamDefs = new ArrayList<Attribute>();
for (int i = 0; i < paramDefs.size(); i++) {
Attribute a = paramDefs.get(i);
newParamDefs.add(a.copy(m_parameters.get(i).getFieldName()));
}
m_parameterDefs = newParamDefs;
// update the Expression
m_expression.setFieldDefs(m_parameterDefs);
}
|
2e87e924-199e-4a67-8bfc-3165c70f8fa3
| 3
|
public static void main(String args[]){
String[][] dateExamples = new String [][]{{"24-04-2013", "27-04-2013"},{"24-10-2014","27-10-2014"},{"29-03-2014","31-03-2014"},{"01-04-2014","31-03-2014"}} ;
for (String[] testData : dateExamples) {
int num = DateTimeComparisonSampler.numberOfDaysWrongJava7(testData[0], testData[1]);
System.out.println(new StringBuilder().append("Number of days between ")
.append(testData[0]).append(" and ")
.append(testData[1]).append(" are: ")
.append(num).toString());
}
for (String[] testData : dateExamples) {
int num = DateTimeComparisonSampler.numberOfDaysBetterJava7(testData[0], testData[1]);
System.out.println(new StringBuilder().append("Number of days between ")
.append(testData[0]).append(" and ")
.append(testData[1]).append(" are: ")
.append(num).toString());
}
for (String[] testData : dateExamples) {
long num = DateTimeComparisonSampler.numberOfDaysJava8Style(testData[0], testData[1]);
System.out.println(new StringBuilder().append("Number of days between ")
.append(testData[0]).append(" and ")
.append(testData[1]).append(" are: ")
.append(num).toString());
}
}
|
a5d7f08c-51f0-4879-b418-31d5eee61715
| 9
|
@Override
public String putString(Rider R)
{
switch(rideBasis)
{
case Rideable.RIDEABLE_AIR:
case Rideable.RIDEABLE_LAND:
case Rideable.RIDEABLE_WAGON:
case Rideable.RIDEABLE_WATER:
case Rideable.RIDEABLE_SLEEP:
case Rideable.RIDEABLE_ENTERIN:
return "in";
case Rideable.RIDEABLE_SIT:
case Rideable.RIDEABLE_TABLE:
case Rideable.RIDEABLE_LADDER:
return "on";
}
return "in";
}
|
ffed1931-2740-43ae-86a3-4e13bd9fab30
| 8
|
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, DataAccessException, Exception {
response.setContentType("text/html;charset=UTF-8");
// app initialization parameters
String email = this.getServletContext().getInitParameter("email");
request.setAttribute("email", email);
// create session
String backgroundColor =
this.getServletContext().getInitParameter("backgroundColor");
HttpSession session = request.getSession();
session.setAttribute("backgroundColor", backgroundColor);
// servlet initialization parameter
String driverClassName = this.getServletConfig().getInitParameter("driverClassName");
String url = this.getServletConfig().getInitParameter("url");
String userName = this.getServletConfig().getInitParameter("userName");
String password = this.getServletConfig().getInitParameter("password");
DBConnector dbConnector = new DBConnector(driverClassName, url, userName, password);
try {
String action = request.getParameter("action");
List<MenuItem> updatedMenuItems = null;
MenuService ms = new MenuService(dbConnector);
// delete functionality handled within this section
if (action.equals("Delete Item")) {
ms.deleteMenuItem(request.getParameterValues("menuItem"));
updatedMenuItems = ms.getAllMenuItems();
request.setAttribute("menuItems", updatedMenuItems);
RequestDispatcher view = request.getRequestDispatcher(RESULT_PAGE);
view.forward(request, response);
// insert & update functionality handled here
} else if (action.equals("Add/Edit Item")) {
String[] idValues = request.getParameterValues("menuItem");
if (idValues == null) {
MenuItem menuItem = new MenuItem();
request.setAttribute("menuItem", menuItem);
} else {
MenuItem menuItem = ms.getMenuItemById(idValues[0]);
// System.out.println("\nRetrieved menu item by itemId: "
// + menuItem.getItemName() + "(" + menuItem.getItemId()
// + ") ... " + menuItem.getItemPrice());
request.setAttribute("menuItem", menuItem);
}
// forward to the update page
RequestDispatcher view = request.getRequestDispatcher(UPDATE_PAGE);
view.forward(request, response);
} else if (action.equals("Submit Update")) {
String itemId = request.getParameter("itemId");
System.out.println(itemId);
String itemName = request.getParameter("itemName");
System.out.println(itemName);
String itemPrice = request.getParameter("itemPrice");
System.out.println(itemPrice);
// need to convert itemId into a Long object
Long objItemId = (itemId == null || itemId.length() == 0L) ? null : new Long(itemId);
MenuItem menuItem = new MenuItem(objItemId, itemName, Double.valueOf(itemPrice));
try {
ms.saveMenuItem(menuItem);
updatedMenuItems = ms.getAllMenuItems();
} catch (DataAccessException e) {
System.out.println(e.getLocalizedMessage());
}
request.setAttribute("menuItems", updatedMenuItems);
RequestDispatcher view = request.getRequestDispatcher(RESULT_PAGE);
view.forward(request, response);
}
} catch (DataAccessException e) {
System.out.println(e.getLocalizedMessage());
}
}
|
bb2a8c24-eb1b-4b60-84d8-2230d27dd551
| 2
|
public int getY(Board board, int x) {
for (int y=0; y<6; y++) {
if (board.get_state(x, y) == 0) {
return y;
}
}
return -1; //return -1 if column is full
}
|
8e9b4431-e5b9-4445-9a90-802715a7626b
| 8
|
final public void BraExp() throws ParseException {/*@bgen(jjtree) BraExp */
SimpleNode jjtn000 = (SimpleNode)SimpleNode.jjtCreate(this, JJTBRAEXP);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
try {
jj_consume_token(LEFTB);
Expression();
jj_consume_token(RIGHTB);
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{if (true) throw (RuntimeException)jjte000;}
}
if (jjte000 instanceof ParseException) {
{if (true) throw (ParseException)jjte000;}
}
{if (true) throw (Error)jjte000;}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
}
}
}
|
a56c7dfd-39fd-41ee-91e6-60051ba00866
| 9
|
public GraphPanel(int width, int height) {
this.setPreferredSize(new Dimension(width, height));
requestFocus();
requestFocusInWindow();
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
ctrl = e.isControlDown();
}
@Override
public void keyReleased(KeyEvent e) {
ctrl = e.isControlDown();
}
});
addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
if (!App.INST.isSelectionMode()) {
Graphics2D g = (Graphics2D) GraphPanel.this.getGraphics();
if (elm != null) {
g.setXORMode(elm.getXORColor());
elm.myPaint(g, true);
}
if (elm instanceof Polyline) {
Polyline pl = (Polyline) elm;
pl.addPos(e.getX(), e.getY());
} else if (e.getPoint().distance(ref.getX(), ref.getY()) > 5) {
elm = AbstractElementFactory.INST.createElement(ref, fix(e.getPoint()));
}
if (elm != null) {
g.setXORMode(elm.getXORColor());
elm.myPaint(g, true);
}
}
}
});
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
ref = e.getPoint();
requestFocusInWindow();
}
@Override
public void mouseReleased(MouseEvent e) {
try {
if (App.INST.isSelectionMode()) {
App.INST.setSelected(DAO.INST.find(e.getPoint()));
} else if (elm instanceof Polyline) {
Polyline pl = (Polyline) elm;
pl.addPos(e.getX(), e.getY());
DAO.INST.create(elm);
} else {
if (!ref.equals(e.getPoint())) {
DAO.INST.create(AbstractElementFactory.INST.createElement(ref, fix(e.getPoint())));
}
}
elm = null;
App.INST.notifyObservers();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
App.INST.addObserver(this);
}
|
8afe8768-9e04-4c76-876a-4b567d0995f8
| 6
|
public final void method65(int i, int[] is, int i_8_, int i_9_, int i_10_,
byte i_11_, int i_12_) {
if (Class108.aClass304_1662 != ((Class310_Sub2) this).aClass304_3896
|| ((Class310_Sub2) this).aClass68_3895 != Class68.aClass68_1183)
throw new RuntimeException();
if (i_11_ != 112)
((Class310_Sub2) this).aBoolean6334 = false;
PixelBuffer pixelbuffer
= (((DirectxToolkit) ((Class310_Sub2) this).aClass378_3893)
.aPixelBuffer9803);
int i_13_ = anIDirect3DTexture6332.LockRect(0, i, i_9_, i_8_, i_10_,
16, pixelbuffer);
if (ue.a(i_13_, false)) {
int i_14_ = pixelbuffer.getRowPitch();
if (i_14_ != 4 * i_8_) {
for (int i_15_ = 0; i_15_ < i_10_; i_15_++)
pixelbuffer.b(is, i_12_ - -(i_8_ * i_15_), i_15_ * i_14_,
i_8_);
} else
pixelbuffer.b(is, i_12_, 0, is.length);
anIDirect3DTexture6332.UnlockRect(0);
}
}
|
34e5e085-430c-454d-817c-a9e32c4c1d51
| 9
|
public void updateStatus(){
if(jobState == JobState.MAP_RUNNING || jobState == JobState.REDUCE_RUNNING){
int numTaskComplete = 0;
Map<Integer,Task> runningTasks = null;
if (jobState == JobState.MAP_RUNNING){
runningTasks = this.mapTasks;
} else if(jobState == JobState.REDUCE_RUNNING){
runningTasks = this.reduceTasks;
}
for(int taskId:runningTasks.keySet()){
Task task = runningTasks.get(taskId);
if(task.getState() == TaskState.SUCCESS){
numTaskComplete += 1;
}
}
if(jobState == JobState.MAP_RUNNING){
this.numFinishedMapTask = numTaskComplete;
if(numFinishedMapTask == numTotalMapTask){
setJobState(JobState.MAP_FINISHED);
}
} else {
this.numFinishedReduceTask = numTaskComplete;
if(numFinishedReduceTask == numTotalReduceTask){
setJobState(JobState.SUCCESS);
}
}
this.message = "Job Id " + this.getJob().getId() +
" completed map tasks: " + this.numFinishedMapTask + "/" + this.numTotalMapTask +
" completed reduce tasks: " + this.numFinishedReduceTask + "/" + this.numTotalReduceTask;
System.out.println(message);
}
}
|
127ac241-7cc3-4c38-85cb-3851e6efec4e
| 0
|
public static PastPane getPastPaneNoScroll(Configuration configuration) {
return new PastPane(configuration);
}
|
e270d096-73c1-46f4-9c15-f97609622bb2
| 5
|
private void doLog(String msg){
if(toConsole) {
System.out.append(msg);
System.out.flush();
}
if(toFile) {
try {
fw.append(msg);
fw.flush();
} catch(IOException e) {
e.printStackTrace();
log.log(Level.SEVERE, "IOException while writing to LogFile!"); //<_may cause loop!?
}
}
if(toStream) {
try {
outStream.write(msg.getBytes());
} catch(IOException e) {
e.printStackTrace();
log.log(Level.SEVERE, "IOException while writing to LogStream!"); //<_may cause loop!?
}
}
}
|
fe3b1c8f-4655-4d2e-8202-09288c834aea
| 8
|
@Override
public void tActionEvent(TActionEvent event)
{
Object source = event.getSource();
if (source == newSimButton)
{
mainMenu.setX(0);
newSimMenu.setX(640);
simWidth = (int) simWidthSlider.getValue(0);
}
else if (source == resumeSimButton)
{
if (Hub.simWindow != null && Hub.simWindow.sim != null && Hub.simWindow.sim.simWidth >= 800)
{
changeRenderableObject(Hub.simWindow);
reset();
}
}
else if (source == startSimButton)
{
Hub.simWindow = new SimulationWindow();
Hub.simWindow.sim = new Simulation(simWidth);
changeRenderableObject(Hub.simWindow);
reset();
}
else if (source == editorButton)
{
if (Hub.simWindow == null)
{
Hub.simWindow = new SimulationWindow();
Hub.simWindow.sim = new Simulation(1);
changeRenderableObject(Hub.simWindow);
}
changeRenderableObject(Hub.editor);
reset();
}
}
|
db256b0a-8c2f-4ae6-abc6-5b4d03f8b8a1
| 1
|
public void randomRoom(Rectangle bounds) {
Point bstart = bounds.start;
Point bend = bounds.end;
int max_x = (int) (bend.x - bstart.x - min_size.x + 1);
int max_y = (int) (bend.y - bstart.y - min_size.y + 1);
int x = Rand.randRange(1, max_x);
int y = Rand.randRange(1, max_y);
Point start = Point.add(bstart, new Point(x, y));
int width = Rand.randRange((int) min_size.x, (int) (bend.x - start.x));
int height = Rand.randRange((int) min_size.y, (int) (bend.y - start.y));
Point end = Point.add(start, new Point(width, height));
if (height > bend.y - start.y) {
Log.print("WTF");
}
rectangle(start, end, Tile.FLOOR_STONE);
}
|
cd48f9f4-a09f-493a-8305-601cd6811f1b
| 3
|
public void processFile() {
LOG.info("processFile ... " + file);
// final Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
// LOG.info("Locale : " + locale.getDisplayName());
if (file != null) {
try {
final InputStream is = file.getInputStream();
selectedItem.getDocument().setName(file.getSubmittedFileName());
final String result = excelProcessor.processExcel(is);
selectedItem.getDocument().setHtmlData(result);
is.close();
} catch (IOException ex) {
Logger.getLogger(PresentationListPage.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(PresentationListPage.class.getName()).log(Level.SEVERE, null, ex);
}
}
setFile(null);
}
|
0c169f5f-0f55-456f-8fbf-4de27f3a6b34
| 1
|
public void printImplements(final PrintWriter out, int indent) {
// There are multiple roots to the implements graph.
indent += 2;
final Iterator roots = this.implementsGraph.roots().iterator();
while (roots.hasNext()) {
final TypeNode iNode = (TypeNode) roots.next();
indent(out, indent);
out.println(iNode.type);
printImplementors(iNode.type, out, true, indent + 2);
}
}
|
95616fb6-2714-4f54-9a75-633b7c610fea
| 2
|
@Override
public void printAnswer(Object answer) {
if (!(answer instanceof int[])) return;
int[] choices = (int[]) answer;
for (int i=0; i<choices.length; i++){
System.out.println(i+"). "+choices[i]);
}
}
|
aef62de6-a19f-494f-93b3-c2e7c98cdb9f
| 2
|
private void btnRestartSyncActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRestartSyncActionPerformed
// Make sure we ended current synch process
// If not, ask user what to do with current synch process
if (this.syncState != SyncState.COMPLETE) {
if (JOptionPane.showConfirmDialog(this, "Synchronization with server isn't done.\nAre you sure to restart current synch process?", "Synchronization isn't complete yet", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE)
== JOptionPane.CANCEL_OPTION) {
return;
}
}
// Restart
startFileSync();
}//GEN-LAST:event_btnRestartSyncActionPerformed
|
52bc9164-1e97-4d22-8663-1564850dd9c9
| 8
|
private static Map<String, DPermission> groupPagesByPermissions(String source) {
//convert input to array
List<DPermission> list = new ArrayList<DPermission>();
String[] array = source.split("\n");
for (String s : array) {
String[] perArray = s.split(",");
DPermission permission = new DPermission();
permission.setName(perArray[0]);
if (!perArray[1].isEmpty()) {
permission.dependencies = Arrays.asList(perArray[1].split("; "));
} else {
permission.setDependencies(null);
}
if (!perArray[2].isEmpty()) {
permission.pages = new ArrayList<String>(Arrays.asList(perArray[2].split("; ")));
} else {
permission.setPages(null);
}
list.add(permission);
}
//group pages by permission
Map<String, DPermission> map = new HashMap<String, DPermission>();
for (DPermission p : list) {
DPermission mapP = map.get(p.getName());
if (mapP == null) {
map.put(p.getName(), p);
} else {
if (mapP != p) { //skip if the same permission
//replace with non-empty dependency
if (mapP.getDependencies() == null && p.getDependencies() != null) {
mapP.setDependencies(p.getDependencies());
}
//group pages
mapP.pages.add(p.getPages().get(0));
}
}
}
return map;
}
|
16a41074-f363-4010-93d2-04232ef1d1f6
| 5
|
public static String getDirectory(){
String relativeWdPath,workingDirectory;
String inputFileName;
//Folder workingDirectory;
//Because userHome is a public static field, it can be used without having initialized any instance of Folder:
//This because the static variables have their own memory space and are initialized by their own;
System.out.println(Folder.userHome);
//Also the static method can be called without any instantiation of a Folder object.
String ynf="No";
do{
System.out.println("Input the relative path of the working directory");
relativeWdPath=TextIO.getlnWord();
workingDirectory=Folder.folderRequest(relativeWdPath);
new ListFiles(workingDirectory);
System.out.println("Do you want to change directory ? [write 'Y' or the name of the file you want to read or write]");
ynf=TextIO.getlnWord();
}while(ynf.equalsIgnoreCase("Yes") || ynf.equalsIgnoreCase("Y") || ynf.equalsIgnoreCase("Ye"));
inputFileName=workingDirectory;
File test=new File(inputFileName);
while((!test.exists()) || (!test.isDirectory())){
System.out.println("Enter the correct directory name with full relative path");
inputFileName=TextIO.getlnWord();
test=new File(inputFileName);
}
return inputFileName;
}
|
c0d21e55-c4ee-4193-924d-dff0951146fb
| 7
|
private void moveNewZipFiles(String zipPath) {
File[] list = listFilesOrError(new File(zipPath));
for (final File dFile : list) {
if (dFile.isDirectory() && this.pluginExists(dFile.getName())) {
// Current dir
final File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName());
// List of existing files in the new dir
final File[] dList = listFilesOrError(dFile);
// List of existing files in the current dir
final File[] oList = listFilesOrError(oFile);
for (File cFile : dList) {
// Loop through all the files in the new dir
boolean found = false;
for (final File xFile : oList) {
// Loop through all the contents in the current dir to see if it exists
if (xFile.getName().equals(cFile.getName())) {
found = true;
break;
}
}
if (!found) {
// Move the new file into the current dir
File output = new File(oFile, cFile.getName());
this.fileIOOrError(output, cFile.renameTo(output), true);
} else {
// This file already exists, so we don't need it anymore.
this.fileIOOrError(cFile, cFile.delete(), false);
}
}
}
this.fileIOOrError(dFile, dFile.delete(), false);
}
File zip = new File(zipPath);
this.fileIOOrError(zip, zip.delete(), false);
}
|
517174fb-b69f-45d2-8e3f-a26fcf360011
| 7
|
public Component getListComponentForDataSection(TaskObserver taskObserver, String dataSectionName, List list, Iterator indexIterator) throws InterruptedException
{
if ( (GameVersion.MM6 == outdoorDataMap.getGameVersion())
&& (dataSectionName == DATA_SECTION_TERRAIN_NORMAL_DATA) ) return getNonApplicablePanel(taskObserver);
if (dataSectionName == DATA_SECTION_GENERAL) { return getGeneralPanel(taskObserver); }
else if (dataSectionName == DATA_SECTION_TILESET) { return getTilesetPanel(taskObserver); }
else if (dataSectionName == DATA_SECTION_TEXT_MAPS) { return getTextMapsPanel(taskObserver); }
else if (dataSectionName == DATA_SECTION_PIXEL_MAPS) { return getPixelMapsPanel(taskObserver); }
else if (dataSectionName == DATA_SECTION_UNKNOWN_MAPPED_DATA) { return getUnknownMappedDataPanel(taskObserver); }
else return super.getListComponent(dataSectionName, taskObserver, list, indexIterator);
}
|
71926390-2005-4cfb-b9fa-a4b3cf5731ac
| 7
|
public void sumMatrix()
{
// Sums the matrix and places the result in the Division Factor text box
float sum = 0;
int size = Integer.parseInt(windowSizes[jComboBox1.getSelectedIndex()].substring(0,1));
int start_position = 0;
switch(size)
{
case 3 : start_position = 2; break;
case 5 : start_position = 1; break;
case 7 : start_position = 0; break;
}
for(int r = start_position; r < start_position + size; r++)
for(int c = start_position; c < start_position + size; c++)
{
try
{
float value = Float.parseFloat(textArray[r][c].getText());
sum += value;
}
catch(Exception e3)
{
textArray[r][c].requestFocus();
textArray[r][c].selectAll();
JIPTAlert.error(this, "Value must be a real number", "Invalid Matrix Value","OK");
return;
}
}
String division_string = null;
Float fl = new Float(sum);
if(fl.intValue() == fl.floatValue())
division_string = "" + fl.intValue();
else
division_string = "" + fl.floatValue();
divisionTextField.setText(division_string);
}
|
6cae8b21-bbc1-481d-a602-49953d65364f
| 6
|
private boolean canTrim() {
if(!(s.endsWith(")")&&s.startsWith("("))) {
return false;
}
int grade=1;
for(int i=1;i<s.length()-1;i++) {
if(s.charAt(i)==')') {
grade--;
}
else if(s.charAt(i)=='(') {
grade++;
}
if(grade==0) {
return false;
}
}
return true;
}
|
332e8035-4853-47da-b011-eb0891f80c75
| 8
|
public void preiseAnpassen()
{
int unterschiedMehl = this.mengeMehlEnde - this.mengeMehlAnfang;
int unterschiedKorn = this.mengeKornEnde - this.mengeKornAnfang;
// wenn der Mehlendbestand sich um min. 50% des Anfangsbestandes erhöht
// hat wird das Mehl ggf. billiger
if ( unterschiedMehl >= ( (int) ( this.mengeMehlAnfang / 2 ) )
&& ( this.preisMehl > 1 ) )
{
this.preisMehl = (int) ( this.preisMehl / 2 );
}
// wenn der Mehlendbestand kleiner als der Mehlanfangsbestand ist wird das
// Mehl ggf. teurer
// dafür muss sich der Mehlbestand um die hälfte des Anfangsbestandes
// verringert haben
else if ( ( unterschiedMehl < 0 )
&& ( ( unterschiedMehl * -1 ) >= ( (int) ( this.mengeMehlAnfang / 2 ) ) ) )
{
this.preisMehl += (int) ( this.preisMehl / 2 );
}
// wenn der Kornbestand sich um min. 50% des Anfangsbestandes erhöht hat
// wird das Korn ggf. billiger
if ( unterschiedKorn >= ( (int) ( this.mengeKornAnfang / 2 ) )
&& ( this.preisKorn > 1 ) )
{
this.preisKorn = (int) ( this.preisKorn / 2 );
}
// wenn der Kornendbestand kleiner als der Kornanfangsbestand ist wird das
// Korn ggf. teurer
// dafür muss sich der Kornbestand um die hälfte des Anfangsbestandes
// verringert haben
else if ( ( unterschiedKorn < 0 )
&& ( ( unterschiedKorn * -1 ) >= ( (int) ( this.mengeKornAnfang / 2 ) ) ) )
{
this.preisKorn += (int) ( this.preisKorn / 2 );
}
}
|
172d40d4-bb75-44c9-907e-cb4ccbc41622
| 5
|
public void run()
{
//WHILE loop for game commands
while (AL_ManagerCommands.size() > 0)
{
//Checking which command to pick
// ::: ::: ::: ::: :::
/* DESTROY
*
* Format: [COMMAND #], object ID
* */
if (AL_ManagerCommands.get(0)[0] == REMOVE)
{
DestroyByID(AL_ManagerCommands.get(0)[1]);
}
/* SET NEW SCENE
*
* Format: [COMMAND #], Scene #
* */
if (AL_ManagerCommands.get(0)[0] == NEW_SCENE)
{
SetNewScene(AL_ManagerCommands.get(0)[1]);
}
/* ADD_GO
*
* Format: [COMMAND #], object ID (of game object in ToAdd arraylist)
* */
if (AL_ManagerCommands.get(0)[0] == ADD_GO)
{
AddNewGameObject(AL_ManagerCommands.get(0)[1]);
}
/* ADD_TEXT
*
* Format: [COMMAND #], object ID (of text object in ToAdd arraylist)
* */
if (AL_ManagerCommands.get(0)[0] == ADD_TEXT)
{
AddNewTextObject(AL_ManagerCommands.get(0)[1]);
}
// ::: ::: ::: ::: :::
//Removing the command
AL_ManagerCommands.remove(0);
}
UpdateArrayOfInUseIDs();
}
|
30b24d77-af77-4c3f-b180-391a93d8065c
| 5
|
public static String getFolder() {
os = OS.getOS();
String path = "";
switch (os) {
case LINUX:
path = System.getProperty("user.home", ".") + File.separator + ".minecraft" + File.separator;
break;
case WINDOWS:
String appdata = System.getenv("APPDATA");
if (appdata == null) {
appdata = System.getenv("APPDATA");
}
path = appdata + File.separator + ".minecraft" + File.separator;
break;
case MAC:
path = System.getProperty("user.home", ".") + File.separator + "Library/Application Support/minecraft" + File.separator;
break;
case OTHER:
break;
default:
path = System.getProperty("user.home", ".") + File.separator + "minecraft" + File.separator;
break;
}
return path;
}
|
b7cf7fba-8a97-48ba-b05c-f4ac7353d86e
| 8
|
public int getAttributes() {
int perms = 0;
if (archive)
perms |= net.decasdev.dokan.FileAttribute.FILE_ATTRIBUTE_ARCHIVE;
if (compressed)
perms |= net.decasdev.dokan.FileAttribute.FILE_ATTRIBUTE_COMPRESSED;
if (encrypted)
perms |= net.decasdev.dokan.FileAttribute.FILE_ATTRIBUTE_ENCRYPTED;
if (hidden)
perms |= net.decasdev.dokan.FileAttribute.FILE_ATTRIBUTE_HIDDEN;
if (notContentIndexed)
perms |= net.decasdev.dokan.FileAttribute.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
if (offline)
perms |= net.decasdev.dokan.FileAttribute.FILE_ATTRIBUTE_OFFLINE;
if (readonly)
perms |= net.decasdev.dokan.FileAttribute.FILE_ATTRIBUTE_READONLY;
if (temporary)
perms |= net.decasdev.dokan.FileAttribute.FILE_ATTRIBUTE_TEMPORARY;
return perms;
}
|
6b2889dc-17f7-4a27-aa5a-58361a99192d
| 5
|
public void closeTag(LangProfile profile) {
if (profile != null && tag_ == target_ && buf_.length() > threshold_) {
NGram gram = new NGram();
for(int i=0; i<buf_.length(); ++i) {
gram.addChar(buf_.charAt(i));
for(int n=1; n<=NGram.N_GRAM; ++n) {
profile.add(gram.get(n));
}
}
++count_;
}
clear();
}
|
c7170785-7577-49b3-911c-0dd2a60c0d0c
| 5
|
private void addMenuItemForFileToMenu(DocumentInfo docInfo) {
RecentFilesListItem menuItem = null;
// switch on nameform to create a menu item
String path = PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_PATH);
switch (currentDisplayNameForm) {
case FULL_PATHNAME:
default:
menuItem = new RecentFilesListItem(path, docInfo);
break;
case TRUNC_PATHNAME:
menuItem = new RecentFilesListItem(StanStringTools.getTruncatedPathName(path, TRUNC_STRING), docInfo);
break;
case JUST_FILENAME:
menuItem = new RecentFilesListItem(StanStringTools.getFileNameFromPathName(path), docInfo);
break;
}
// tell the menu item to listen to its menu
menuItem.addActionListener(this);
// switch out on menu's item orientation
switch (currentDisplayDirection) {
case TOP_TO_BOTTOM:
default:
// append the menu item to the menu
add(menuItem);
break;
case BOTTOM_TO_TOP:
// prepend the menu item to the menu
insert(menuItem,0);
break;
}
// Since we've got at least one item in our menu we should be enabled.
setEnabled(true);
}
|
32bba022-cd2c-40ee-945f-7ee0f9f8acd8
| 9
|
public DrawableTree getCurrentTree() {
DrawableTree tree = null;
if (currentLine == null)
return null;
try {
int index = currentLine.indexOf("(");
int parenDepth = 1;
int lastIndex = 0;
StringBuilder treeStrBuilder = new StringBuilder();
treeStrBuilder.append("(");
//If the tree spans multiple lines, parenDepth won't be zero here
while(currentLine != null && parenDepth>0) {
for(int i = index+1; i<currentLine.length(); i++) {
if (currentLine.charAt(i)=='(')
parenDepth++;
if (currentLine.charAt(i)==')')
parenDepth--;
if (parenDepth==0) {
lastIndex = i;
break;
}
}
treeStrBuilder.append(currentLine.substring(index+1, lastIndex+1));
currentLine = buf.readLine();
}
//TODO can this happen later?
tree = new SquareTree(treeStrBuilder.toString());
if (translationTable != null) {
translate(tree);
}
}
catch (IOException ex) {
}
return tree;
}
|
8ad2ffb7-219c-4c60-aa65-a5017ddb037e
| 5
|
public SimulationWorkerResult(double[] wins, double[] ties, double[] loses)
{
if (wins == null || ties == null || loses == null) {
throw new NullPointerException();
} else if (wins.length != ties.length || ties.length != loses.length) {
throw new IllegalArgumentException();
}
this.wins = wins;
this.loses = loses;
this.ties = ties;
}
|
696b7059-adb5-4f41-98f2-43243f417943
| 9
|
public Serializable call(Class<?> iface, Serializable param,
long receivedTime) throws IOException {
try {
Invocation call = (Invocation) param; //调用参数 Invocationd对象包含方法名称 形式参数列表和实际参数列表
if (verbose)
log("Call: " + call);
//从实例缓存中按照接口寻找实例对象
Object instance = INSTANCE_CACHE.get(iface);
if (instance == null)
throw new IOException("interface `" + iface + "` not inscribe.");
//通过Class对象获取Method对象
Method method = iface.getMethod(call.getMethodName(),
call.getParameterClasses());
//取消Java语言访问权限检查
method.setAccessible(true);
long startTime = System.currentTimeMillis();
//调用Method对象的invoke方法
Object value = method.invoke(instance, call.getParameters());
int processingTime = (int) (System.currentTimeMillis() - startTime);
int qTime = (int) (startTime - receivedTime);
if (LOG.isDebugEnabled()) {
LOG.debug("Served: " + call.getMethodName()
+ " queueTime= " + qTime + " procesingTime= "
+ processingTime);
}
if (verbose)
log("Return: " + value);
call.setResult(value); //向Invocation对象设置结果
return call;
} catch (InvocationTargetException e) {
Throwable target = e.getTargetException();
if (target instanceof IOException) {
throw (IOException) target;
} else {
IOException ioe = new IOException(target.toString());
ioe.setStackTrace(target.getStackTrace());
throw ioe;
}
} catch (Throwable e) {
if (!(e instanceof IOException)) {
LOG.error("Unexpected throwable object ", e);
}
IOException ioe = new IOException(e.toString());
ioe.setStackTrace(e.getStackTrace());
throw ioe;
}
}
|
7279bbf5-f4ef-414a-8485-1df81701c955
| 9
|
@Override
public void handle(String dataDir, String arg) throws Exception
{
if(inputDataDir == null || inputDataDir.length() == 0)
{
inputDataDir = dataDir;
}
File queryFile = new File(arg);
if(queryFile.exists())
{
if(queryFile.isDirectory())
{
System.out.println("Going into directory: " + queryFile.getName());
for(File file : queryFile.listFiles())
{
handle(dataDir, file.getAbsolutePath());
}
}
else if(queryFile.canRead())
{
System.out.println("Reading query in: " + queryFile.getName());
arg = new Scanner(queryFile).useDelimiter("\\Z").next();
handle(dataDir, arg);
}
else
{
throw new IllegalArgumentException("Unable to read file: '" + arg + "' for query");
}
return;
}
org.openrdf.repository.Repository repo = new SailRepository(new NativeStore(new File(dataDir), indexes));
repo.initialize();
RepositoryConnection con = repo.getConnection();
RepositoryConnection inputCon;
org.openrdf.repository.Repository inputRepo = null;
if(inputDataDir == dataDir)
{
inputCon = con;
}
else
{
inputRepo = new SailRepository(new NativeStore(new File(inputDataDir), indexes));
inputRepo.initialize();
inputCon = inputRepo.getConnection();
}
try
{
long start = System.nanoTime();
GraphQuery graphQuery = inputCon.prepareGraphQuery(QueryLanguage.SPARQL, arg);
graphQuery.evaluate(new ChunkCommitter(con,commit,chunkSize));
System.out.println("Query processed in time: " + (System.nanoTime()-start)/1000000 + " ms");
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if(inputRepo != null)
{
inputCon.close();
inputRepo.shutDown();
}
con.close();
repo.shutDown();
}
}
|
520b8513-0c97-4e8c-9ad6-260610504d53
| 8
|
@Override
public boolean execute(MOB mob, List<String> commands, int metaFlags)
throws java.io.IOException
{
String parm = (commands.size() > 1) ? CMParms.combine(commands,1) : "";
if((!mob.isAttributeSet(MOB.Attrib.AUTOLOOT) && (parm.length()==0))||(parm.equalsIgnoreCase("ON")))
{
mob.setAttribute(MOB.Attrib.AUTOLOOT,true);
mob.tell(L("Autolooting has been turned on."));
}
else
if((mob.isAttributeSet(MOB.Attrib.AUTOLOOT) && (parm.length()==0))||(parm.equalsIgnoreCase("OFF")))
{
mob.setAttribute(MOB.Attrib.AUTOLOOT,false);
mob.tell(L("Autolooting has been turned off."));
}
else
if(parm.length() > 0)
{
mob.tell(L("Illegal @x1 argument: '@x2'. Try ON or OFF, or nothing to toggle.",getAccessWords()[0],parm));
}
return false;
}
|
c4d41126-7c89-4a8e-aa8a-a8fc38ce1ed5
| 8
|
private void generateClassifierForNode(Instances data, Range classes,
Random rand, Classifier classifier, Hashtable table)
throws Exception {
// Get the indices
int[] indices = classes.getSelection();
// Randomize the order of the indices
for (int j = indices.length - 1; j > 0; j--) {
int randPos = rand.nextInt(j + 1);
int temp = indices[randPos];
indices[randPos] = indices[j];
indices[j] = temp;
}
// Pick the classes for the current split
int first = indices.length / 2;
int second = indices.length - first;
int[] firstInds = new int[first];
int[] secondInds = new int[second];
System.arraycopy(indices, 0, firstInds, 0, first);
System.arraycopy(indices, first, secondInds, 0, second);
// Sort the indices (important for hash key)!
int[] sortedFirst = Utils.sort(firstInds);
int[] sortedSecond = Utils.sort(secondInds);
int[] firstCopy = new int[first];
int[] secondCopy = new int[second];
for (int i = 0; i < sortedFirst.length; i++) {
firstCopy[i] = firstInds[sortedFirst[i]];
}
firstInds = firstCopy;
for (int i = 0; i < sortedSecond.length; i++) {
secondCopy[i] = secondInds[sortedSecond[i]];
}
secondInds = secondCopy;
// Unify indices to improve hashing
if (firstInds[0] > secondInds[0]) {
int[] help = secondInds;
secondInds = firstInds;
firstInds = help;
int help2 = second;
second = first;
first = help2;
}
m_Range = new Range(Range.indicesToRangeList(firstInds));
m_Range.setUpper(data.numClasses() - 1);
Range secondRange = new Range(Range.indicesToRangeList(secondInds));
secondRange.setUpper(data.numClasses() - 1);
// Change the class labels and build the classifier
MakeIndicator filter = new MakeIndicator();
filter.setAttributeIndex("" + (data.classIndex() + 1));
filter.setValueIndices(m_Range.getRanges());
filter.setNumeric(false);
filter.setInputFormat(data);
m_FilteredClassifier = new FilteredClassifier();
if (data.numInstances() > 0) {
m_FilteredClassifier.setClassifier(Classifier.makeCopies(classifier, 1)[0]);
} else {
m_FilteredClassifier.setClassifier(new weka.classifiers.rules.ZeroR());
}
m_FilteredClassifier.setFilter(filter);
// Save reference to hash table at current node
m_classifiers=table;
if (!m_classifiers.containsKey( getString(firstInds) + "|" + getString(secondInds))) {
m_FilteredClassifier.buildClassifier(data);
m_classifiers.put(getString(firstInds) + "|" + getString(secondInds), m_FilteredClassifier);
} else {
m_FilteredClassifier=(FilteredClassifier)m_classifiers.get(getString(firstInds) + "|" +
getString(secondInds));
}
// Create two successors if necessary
m_FirstSuccessor = new ClassBalancedND();
if (first == 1) {
m_FirstSuccessor.m_Range = m_Range;
} else {
RemoveWithValues rwv = new RemoveWithValues();
rwv.setInvertSelection(true);
rwv.setNominalIndices(m_Range.getRanges());
rwv.setAttributeIndex("" + (data.classIndex() + 1));
rwv.setInputFormat(data);
Instances firstSubset = Filter.useFilter(data, rwv);
m_FirstSuccessor.generateClassifierForNode(firstSubset, m_Range,
rand, classifier, m_classifiers);
}
m_SecondSuccessor = new ClassBalancedND();
if (second == 1) {
m_SecondSuccessor.m_Range = secondRange;
} else {
RemoveWithValues rwv = new RemoveWithValues();
rwv.setInvertSelection(true);
rwv.setNominalIndices(secondRange.getRanges());
rwv.setAttributeIndex("" + (data.classIndex() + 1));
rwv.setInputFormat(data);
Instances secondSubset = Filter.useFilter(data, rwv);
m_SecondSuccessor = new ClassBalancedND();
m_SecondSuccessor.generateClassifierForNode(secondSubset, secondRange,
rand, classifier, m_classifiers);
}
}
|
51f059a3-07cb-465d-9985-613497d3af22
| 8
|
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
cost = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i=0; i<n; i++){
cost[i] = Integer.parseInt(st.nextToken());
}
int m = Integer.parseInt(br.readLine());
d = new int[n+1];
reversedD = new int[n+1];
int[] x = new int[m];
int[] y = new int[m];
for(int i=0; i<m; i++){
st = new StringTokenizer(br.readLine());
x[i] = Integer.parseInt(st.nextToken())-1;
y[i] = Integer.parseInt(st.nextToken())-1;
d[x[i]]++;
reversedD[y[i]]++;
}
for(int i=0; i<n; i++){
d[i+1]+=d[i];
reversedD[i+1]+=reversedD[i];
}
edges = new int[m];
reversedEdges = new int[m];
for(int i=0; i<m; i++){
edges[d[x[i]]-1] = y[i];
reversedEdges[reversedD[y[i]]-1] = x[i];
d[x[i]]--;
reversedD[y[i]]--;
}
visited = new boolean[n];
order = new ArrayList<Integer>();
Arrays.fill(visited, false);
for(int i=0; i<n; i++){
if(!visited[i]) label(i);
}
Arrays.fill(visited, false);
long minCount=1;
long minCost=0;
for(int i=n-1; i>=0; i--){
if(!visited[order.get(i)]){
curMin = Integer.MAX_VALUE;
nMin = 1;
calculate(order.get(i));
minCost+=curMin;
minCount = (minCount*nMin)%1000000007;
}
}
System.out.println(minCost+" "+minCount);
}
|
d0b59980-650b-46b7-97a8-08411abadf46
| 8
|
public static void main(String[] args) throws Exception {
String env = null;
if (args != null && args.length > 0) {
env = args[0];
}
if (! "dev".equals(env))
if (! "prod".equals(env)) {
System.out.println("Usage: $0 (dev|prod)\n");
System.exit(1);
}
// Topology config
Config conf = new Config();
// Load parameters and add them to the Config
Map configMap = YamlLoader.loadYamlFromResource("config_" + env + ".yml");
conf.putAll(configMap);
log.info(JSONValue.toJSONString((conf)));
// Set topology loglevel to DEBUG
conf.put(Config.TOPOLOGY_DEBUG, JsonPath.read(conf, "$.deck36_storm.debug"));
// Create Topology builder
TopologyBuilder builder = new TopologyBuilder();
// if there are not special reasons, start with parallelism hint of 1
// and multiple tasks. By that, you can scale dynamically later on.
int parallelism_hint = JsonPath.read(conf, "$.deck36_storm.default_parallelism_hint");
int num_tasks = JsonPath.read(conf, "$.deck36_storm.default_num_tasks");
// Create Stream from RabbitMQ messages
// bind new queue with name of the topology
// to the main plan9 exchange (from properties config)
// consuming only POINTS-related events by using the routing key 'points.#'
String badgeName = StatusLevelTopology.class.getSimpleName();
String rabbitQueueName = badgeName; // use topology class name as name for the queue
String rabbitExchangeName = JsonPath.read(conf, "$.deck36_storm.StatusLevelBolt.rabbitmq.exchange");
String rabbitRoutingKey = JsonPath.read(conf, "$.deck36_storm.StatusLevelBolt.rabbitmq.routing_key");
// Get JSON deserialization scheme
Scheme rabbitScheme = new SimpleJSONScheme();
// Setup a Declarator to configure exchange/queue/routing key
RabbitMQDeclarator rabbitDeclarator = new RabbitMQDeclarator(rabbitExchangeName, rabbitQueueName, rabbitRoutingKey);
// Create Configuration for the Spout
ConnectionConfig connectionConfig =
new ConnectionConfig(
(String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.host"),
(Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.port"),
(String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.user"),
(String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.pass"),
(String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.vhost"),
(Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.heartbeat"));
ConsumerConfig spoutConfig = new ConsumerConfigBuilder().connection(connectionConfig)
.queue(rabbitQueueName)
.prefetch((Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.prefetch"))
.requeueOnFail()
.build();
// add global parameters to topology config - the RabbitMQSpout will read them from there
conf.putAll(spoutConfig.asMap());
// For production, set the spout pending value to the same value as the RabbitMQ pre-fetch
// see: https://github.com/ppat/storm-rabbitmq/blob/master/README.md
if ("prod".equals(env)) {
conf.put(Config.TOPOLOGY_MAX_SPOUT_PENDING, (Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.prefetch"));
}
// Add RabbitMQ spout to topology
builder.setSpout("incoming",
new RabbitMQSpout(rabbitScheme, rabbitDeclarator),
parallelism_hint)
.setNumTasks((Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.spout_tasks"));
// construct command to invoke the external bolt implementation
ArrayList<String> command = new ArrayList(15);
// Add main execution program (php, hhvm, zend, ..) and parameters
command.add((String) JsonPath.read(conf, "$.deck36_storm.php.executor"));
command.addAll((List<String>) JsonPath.read(conf, "$.deck36_storm.php.executor_params"));
// Add main command to be executed (app/console, the phar file, etc.) and global context parameters (environment etc.)
command.add((String) JsonPath.read(conf, "$.deck36_storm.php.main"));
command.addAll((List<String>) JsonPath.read(conf, "$.deck36_storm.php.main_params"));
// Add main route to be invoked and its parameters
command.add((String) JsonPath.read(conf, "$.deck36_storm.StatusLevelBolt.main"));
List boltParams = (List<String>) JsonPath.read(conf, "$.deck36_storm.StatusLevelBolt.params");
if (boltParams != null)
command.addAll(boltParams);
// Log the final command
log.info("Command to start bolt for StatusLevel badges: " + Arrays.toString(command.toArray()));
// Add constructed external bolt command to topology using MultilangAdapterBolt
builder.setBolt("badge",
new MultilangAdapterBolt(command, "badge"),
1)
.setNumTasks(1)
.shuffleGrouping("incoming");
builder.setBolt("rabbitmq_router",
new Plan9RabbitMQRouterBolt(
(String) JsonPath.read(conf, "$.deck36_storm.StatusLevelBolt.rabbitmq.target_exchange"),
"StatusLevel" // RabbitMQ routing key
),
parallelism_hint)
.setNumTasks(num_tasks)
.shuffleGrouping("badge");
builder.setBolt("rabbitmq_producer",
new Plan9RabbitMQPushBolt(),
parallelism_hint)
.setNumTasks(num_tasks)
.shuffleGrouping("rabbitmq_router");
if ("dev".equals(env)) {
LocalCluster cluster = new LocalCluster();
cluster.submitTopology(badgeName + System.currentTimeMillis(), conf, builder.createTopology());
Thread.sleep(2000000);
}
if ("prod".equals(env)) {
StormSubmitter.submitTopology(badgeName + "-" + System.currentTimeMillis(), conf, builder.createTopology());
}
}
|
f3c47c1c-7f7e-42a5-a262-9d49ce1a3717
| 6
|
public static double findNetworkDistance(NeuralNetwork one,NeuralNetwork two){
ArrayList<Node> oneNodes=Node.sort(one.getAllNodes());
ArrayList<Node> twoNodes=Node.sort(two.getAllNodes());
double distance=0.0;
int i=0;
int f=0;
int oneIn=oneNodes.get(i).getInnovationNum();
int twoIn=twoNodes.get(i).getInnovationNum();
while(i!=oneNodes.size()-1&&f!=twoNodes.size()-1){
if(oneIn==twoIn){
distance+=findNodeDistance(oneNodes.get(i),twoNodes.get(f));
oneIn=oneNodes.get(++i).getInnovationNum();
twoIn=twoNodes.get(++f).getInnovationNum();
}else if(oneIn>twoIn){
distance+=1.0;
twoIn=twoNodes.get(++f).getInnovationNum();
}else{
distance+=1.0;
oneIn=oneNodes.get(++i).getInnovationNum();
}
}
while(i!=oneNodes.size()){
distance+=1.0;
i++;
}
while(f!=twoNodes.size()){
distance+=1.0;
f++;
}
return distance;
}
|
42cdf4fd-a63a-4d2c-a8a8-d242f991c84d
| 2
|
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
if(this.jTextField1.getText().isEmpty()){
Error np = new Error(this,true);
np.ready("Debe ingresar su nombre de usuario");
np.setVisible(true);
}
else{
if(this.jPasswordField1.getText().isEmpty()){
Error np = new Error(this,true);
np.ready("Debe ingresar su contraseña");
np.setVisible(true);
}
else{
Administrador.Menu adm = new Administrador.Menu();
adm.setVisible(true);
}
}
}//GEN-LAST:event_jButton2ActionPerformed
|
fba912e4-3249-4491-9b94-33ce1cec30cc
| 1
|
private void compute_new_v_old()
{
// p is fully initialized from x1
//float[] p = _p;
// pp is fully initialized from p
//float[] pp = _pp;
//float[] new_v = _new_v;
float[] new_v = new float[32]; // new V[0-15] and V[33-48] of Figure 3-A.2 in ISO DIS 11172-3
float[] p = new float[16];
float[] pp = new float[16];
for (int i=31; i>=0; i--)
{
new_v[i] = 0.0f;
}
// float[] new_v = new float[32]; // new V[0-15] and V[33-48] of Figure 3-A.2 in ISO DIS 11172-3
// float[] p = new float[16];
// float[] pp = new float[16];
float[] x1 = samples;
p[0] = x1[0] + x1[31];
p[1] = x1[1] + x1[30];
p[2] = x1[2] + x1[29];
p[3] = x1[3] + x1[28];
p[4] = x1[4] + x1[27];
p[5] = x1[5] + x1[26];
p[6] = x1[6] + x1[25];
p[7] = x1[7] + x1[24];
p[8] = x1[8] + x1[23];
p[9] = x1[9] + x1[22];
p[10] = x1[10] + x1[21];
p[11] = x1[11] + x1[20];
p[12] = x1[12] + x1[19];
p[13] = x1[13] + x1[18];
p[14] = x1[14] + x1[17];
p[15] = x1[15] + x1[16];
pp[0] = p[0] + p[15];
pp[1] = p[1] + p[14];
pp[2] = p[2] + p[13];
pp[3] = p[3] + p[12];
pp[4] = p[4] + p[11];
pp[5] = p[5] + p[10];
pp[6] = p[6] + p[9];
pp[7] = p[7] + p[8];
pp[8] = (p[0] - p[15]) * cos1_32;
pp[9] = (p[1] - p[14]) * cos3_32;
pp[10] = (p[2] - p[13]) * cos5_32;
pp[11] = (p[3] - p[12]) * cos7_32;
pp[12] = (p[4] - p[11]) * cos9_32;
pp[13] = (p[5] - p[10]) * cos11_32;
pp[14] = (p[6] - p[9]) * cos13_32;
pp[15] = (p[7] - p[8]) * cos15_32;
p[0] = pp[0] + pp[7];
p[1] = pp[1] + pp[6];
p[2] = pp[2] + pp[5];
p[3] = pp[3] + pp[4];
p[4] = (pp[0] - pp[7]) * cos1_16;
p[5] = (pp[1] - pp[6]) * cos3_16;
p[6] = (pp[2] - pp[5]) * cos5_16;
p[7] = (pp[3] - pp[4]) * cos7_16;
p[8] = pp[8] + pp[15];
p[9] = pp[9] + pp[14];
p[10] = pp[10] + pp[13];
p[11] = pp[11] + pp[12];
p[12] = (pp[8] - pp[15]) * cos1_16;
p[13] = (pp[9] - pp[14]) * cos3_16;
p[14] = (pp[10] - pp[13]) * cos5_16;
p[15] = (pp[11] - pp[12]) * cos7_16;
pp[0] = p[0] + p[3];
pp[1] = p[1] + p[2];
pp[2] = (p[0] - p[3]) * cos1_8;
pp[3] = (p[1] - p[2]) * cos3_8;
pp[4] = p[4] + p[7];
pp[5] = p[5] + p[6];
pp[6] = (p[4] - p[7]) * cos1_8;
pp[7] = (p[5] - p[6]) * cos3_8;
pp[8] = p[8] + p[11];
pp[9] = p[9] + p[10];
pp[10] = (p[8] - p[11]) * cos1_8;
pp[11] = (p[9] - p[10]) * cos3_8;
pp[12] = p[12] + p[15];
pp[13] = p[13] + p[14];
pp[14] = (p[12] - p[15]) * cos1_8;
pp[15] = (p[13] - p[14]) * cos3_8;
p[0] = pp[0] + pp[1];
p[1] = (pp[0] - pp[1]) * cos1_4;
p[2] = pp[2] + pp[3];
p[3] = (pp[2] - pp[3]) * cos1_4;
p[4] = pp[4] + pp[5];
p[5] = (pp[4] - pp[5]) * cos1_4;
p[6] = pp[6] + pp[7];
p[7] = (pp[6] - pp[7]) * cos1_4;
p[8] = pp[8] + pp[9];
p[9] = (pp[8] - pp[9]) * cos1_4;
p[10] = pp[10] + pp[11];
p[11] = (pp[10] - pp[11]) * cos1_4;
p[12] = pp[12] + pp[13];
p[13] = (pp[12] - pp[13]) * cos1_4;
p[14] = pp[14] + pp[15];
p[15] = (pp[14] - pp[15]) * cos1_4;
// this is pretty insane coding
float tmp1;
new_v[36-17] = -(new_v[4] = (new_v[12] = p[7]) + p[5]) - p[6];
new_v[44-17] = -p[6] - p[7] - p[4];
new_v[6] = (new_v[10] = (new_v[14] = p[15]) + p[11]) + p[13];
new_v[34-17] = -(new_v[2] = p[15] + p[13] + p[9]) - p[14];
new_v[38-17] = (tmp1 = -p[14] - p[15] - p[10] - p[11]) - p[13];
new_v[46-17] = -p[14] - p[15] - p[12] - p[8];
new_v[42-17] = tmp1 - p[12];
new_v[48-17] = -p[0];
new_v[0] = p[1];
new_v[40-17] = -(new_v[8] = p[3]) - p[2];
p[0] = (x1[0] - x1[31]) * cos1_64;
p[1] = (x1[1] - x1[30]) * cos3_64;
p[2] = (x1[2] - x1[29]) * cos5_64;
p[3] = (x1[3] - x1[28]) * cos7_64;
p[4] = (x1[4] - x1[27]) * cos9_64;
p[5] = (x1[5] - x1[26]) * cos11_64;
p[6] = (x1[6] - x1[25]) * cos13_64;
p[7] = (x1[7] - x1[24]) * cos15_64;
p[8] = (x1[8] - x1[23]) * cos17_64;
p[9] = (x1[9] - x1[22]) * cos19_64;
p[10] = (x1[10] - x1[21]) * cos21_64;
p[11] = (x1[11] - x1[20]) * cos23_64;
p[12] = (x1[12] - x1[19]) * cos25_64;
p[13] = (x1[13] - x1[18]) * cos27_64;
p[14] = (x1[14] - x1[17]) * cos29_64;
p[15] = (x1[15] - x1[16]) * cos31_64;
pp[0] = p[0] + p[15];
pp[1] = p[1] + p[14];
pp[2] = p[2] + p[13];
pp[3] = p[3] + p[12];
pp[4] = p[4] + p[11];
pp[5] = p[5] + p[10];
pp[6] = p[6] + p[9];
pp[7] = p[7] + p[8];
pp[8] = (p[0] - p[15]) * cos1_32;
pp[9] = (p[1] - p[14]) * cos3_32;
pp[10] = (p[2] - p[13]) * cos5_32;
pp[11] = (p[3] - p[12]) * cos7_32;
pp[12] = (p[4] - p[11]) * cos9_32;
pp[13] = (p[5] - p[10]) * cos11_32;
pp[14] = (p[6] - p[9]) * cos13_32;
pp[15] = (p[7] - p[8]) * cos15_32;
p[0] = pp[0] + pp[7];
p[1] = pp[1] + pp[6];
p[2] = pp[2] + pp[5];
p[3] = pp[3] + pp[4];
p[4] = (pp[0] - pp[7]) * cos1_16;
p[5] = (pp[1] - pp[6]) * cos3_16;
p[6] = (pp[2] - pp[5]) * cos5_16;
p[7] = (pp[3] - pp[4]) * cos7_16;
p[8] = pp[8] + pp[15];
p[9] = pp[9] + pp[14];
p[10] = pp[10] + pp[13];
p[11] = pp[11] + pp[12];
p[12] = (pp[8] - pp[15]) * cos1_16;
p[13] = (pp[9] - pp[14]) * cos3_16;
p[14] = (pp[10] - pp[13]) * cos5_16;
p[15] = (pp[11] - pp[12]) * cos7_16;
pp[0] = p[0] + p[3];
pp[1] = p[1] + p[2];
pp[2] = (p[0] - p[3]) * cos1_8;
pp[3] = (p[1] - p[2]) * cos3_8;
pp[4] = p[4] + p[7];
pp[5] = p[5] + p[6];
pp[6] = (p[4] - p[7]) * cos1_8;
pp[7] = (p[5] - p[6]) * cos3_8;
pp[8] = p[8] + p[11];
pp[9] = p[9] + p[10];
pp[10] = (p[8] - p[11]) * cos1_8;
pp[11] = (p[9] - p[10]) * cos3_8;
pp[12] = p[12] + p[15];
pp[13] = p[13] + p[14];
pp[14] = (p[12] - p[15]) * cos1_8;
pp[15] = (p[13] - p[14]) * cos3_8;
p[0] = pp[0] + pp[1];
p[1] = (pp[0] - pp[1]) * cos1_4;
p[2] = pp[2] + pp[3];
p[3] = (pp[2] - pp[3]) * cos1_4;
p[4] = pp[4] + pp[5];
p[5] = (pp[4] - pp[5]) * cos1_4;
p[6] = pp[6] + pp[7];
p[7] = (pp[6] - pp[7]) * cos1_4;
p[8] = pp[8] + pp[9];
p[9] = (pp[8] - pp[9]) * cos1_4;
p[10] = pp[10] + pp[11];
p[11] = (pp[10] - pp[11]) * cos1_4;
p[12] = pp[12] + pp[13];
p[13] = (pp[12] - pp[13]) * cos1_4;
p[14] = pp[14] + pp[15];
p[15] = (pp[14] - pp[15]) * cos1_4;
// manually doing something that a compiler should handle sucks
// coding like this is hard to read
float tmp2;
new_v[5] = (new_v[11] = (new_v[13] = (new_v[15] = p[15]) + p[7]) + p[11])
+ p[5] + p[13];
new_v[7] = (new_v[9] = p[15] + p[11] + p[3]) + p[13];
new_v[33-17] = -(new_v[1] = (tmp1 = p[13] + p[15] + p[9]) + p[1]) - p[14];
new_v[35-17] = -(new_v[3] = tmp1 + p[5] + p[7]) - p[6] - p[14];
new_v[39-17] = (tmp1 = -p[10] - p[11] - p[14] - p[15])
- p[13] - p[2] - p[3];
new_v[37-17] = tmp1 - p[13] - p[5] - p[6] - p[7];
new_v[41-17] = tmp1 - p[12] - p[2] - p[3];
new_v[43-17] = tmp1 - p[12] - (tmp2 = p[4] + p[6] + p[7]);
new_v[47-17] = (tmp1 = -p[8] - p[12] - p[14] - p[15]) - p[0];
new_v[45-17] = tmp1 - tmp2;
// insert V[0-15] (== new_v[0-15]) into actual v:
x1 = new_v;
// float[] x2 = actual_v + actual_write_pos;
float[] dest = actual_v;
dest[0 + actual_write_pos] = x1[0];
dest[16 + actual_write_pos] = x1[1];
dest[32 + actual_write_pos] = x1[2];
dest[48 + actual_write_pos] = x1[3];
dest[64 + actual_write_pos] = x1[4];
dest[80 + actual_write_pos] = x1[5];
dest[96 + actual_write_pos] = x1[6];
dest[112 + actual_write_pos] = x1[7];
dest[128 + actual_write_pos] = x1[8];
dest[144 + actual_write_pos] = x1[9];
dest[160 + actual_write_pos] = x1[10];
dest[176 + actual_write_pos] = x1[11];
dest[192 + actual_write_pos] = x1[12];
dest[208 + actual_write_pos] = x1[13];
dest[224 + actual_write_pos] = x1[14];
dest[240 + actual_write_pos] = x1[15];
// V[16] is always 0.0:
dest[256 + actual_write_pos] = 0.0f;
// insert V[17-31] (== -new_v[15-1]) into actual v:
dest[272 + actual_write_pos] = -x1[15];
dest[288 + actual_write_pos] = -x1[14];
dest[304 + actual_write_pos] = -x1[13];
dest[320 + actual_write_pos] = -x1[12];
dest[336 + actual_write_pos] = -x1[11];
dest[352 + actual_write_pos] = -x1[10];
dest[368 + actual_write_pos] = -x1[9];
dest[384 + actual_write_pos] = -x1[8];
dest[400 + actual_write_pos] = -x1[7];
dest[416 + actual_write_pos] = -x1[6];
dest[432 + actual_write_pos] = -x1[5];
dest[448 + actual_write_pos] = -x1[4];
dest[464 + actual_write_pos] = -x1[3];
dest[480 + actual_write_pos] = -x1[2];
dest[496 + actual_write_pos] = -x1[1];
// insert V[32] (== -new_v[0]) into other v:
}
|
896b686e-7bfc-4b70-a951-c3ad45f18ad0
| 0
|
public String toString() {
return id + ": " + "i4 = " + i4 + ", INT_5 = " + INT_5;
}
|
16cd9b99-a661-49fd-850c-51442117854a
| 3
|
public void buttonClicked(String actionCommand) {
if (MANAGE.equals(actionCommand)) {
showAccountManager(accounts, accountTypes);
} else if (DETAILS.equals(actionCommand)) {
AccountDetails.getAccountDetails(lijst.getSelectedValue(), journals, journalInputGUI);
} else if (ADD.equals(actionCommand)) {
new NewAccountGUI(accounts, accountTypes).setVisible(true);
}
}
|
959f76e3-691d-4a7f-9eaf-2fd6aadf46ce
| 9
|
public FoodFileBean getFileName(int idx) throws Exception{
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
FoodFileBean fileBean = null;
String sql = "";
String filename = "";
String fileTmp = "";
try{
conn = getConnection();
sql = "select * from foodfile where idx=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, idx);
rs = pstmt.executeQuery();
fileBean = new FoodFileBean();
if(rs.next()){
fileBean.setFileid(rs.getInt("fileid"));
fileTmp = rs.getString("filename");
StringTokenizer st = new StringTokenizer(fileTmp,"\\");
while(st.hasMoreElements()){
filename=st.nextToken();
}
fileBean.setFilename(filename);
fileBean.setRealpath("upload/"+filename);
}else{
fileBean.setFilename("파일없음");
fileBean.setRealpath("파일없음");
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(rs!=null)try{rs.close();}catch(SQLException ex){}
if(pstmt!=null)try{pstmt.close();}catch(SQLException ex){}
if(conn!=null)try{conn.close();}catch(SQLException ex){}
}
return fileBean;
}
|
5d8d4372-3057-4221-a83f-7fd619a67dcc
| 6
|
private static boolean isHexString(String str) {
if (str == null
|| !(str.startsWith("0x") || str.startsWith("0X"))
|| str.length() <= 2) return false;
for (int i = 2; i < str.length(); i++) {
if ("0123456789ABCDEFabcdef".indexOf(str.substring(i, i+1)) < 0) {
return false;
}
}
return true;
}
|
e504679d-045b-49b0-83a7-0f09d6b6eb4f
| 7
|
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Game other = (Game) o;
if (getQuestionsCount() != other.getQuestionsCount() || !getName().equals(other.getName())) {
return false;
}
for (int i = 0; i < questions.size(); i++) {
Question origQuestion = questions.get(i);
Question otherQuestion = other.questions.get(i);
if (!origQuestion.equals(otherQuestion)) {
return false;
}
}
return true;
}
|
7c0433f8-ae89-4105-a8d4-414d7710c2e3
| 5
|
private boolean mouseOverBottomArrow(int mx, int my) {
if (!isVisible) return false;
if (mx < positionX || mx > positionX + width) return false;
if (my < positionY || my > positionY + height) return false;
return (my >= positionY + height - 16);
}
|
106a6c0f-5c58-438d-853f-2184c1d78302
| 5
|
public double pow(double x, int n) {
if (n == 0)
return 1;
if (n == 1)
return x;
if (n == -1) {
if (x != 0) {
return 1 / x;
} else {
return Integer.MAX_VALUE;
}
}
// n>=2 || n<=-2;
double square = x * x;
if (n > 0) {
int powerForSquare = n / 2;
int restPower = n % 2;
return pow(square, powerForSquare) * pow(x, restPower);
} else {
int tmpN = -n;
int powerForSquare = tmpN / 2;
int restPower = tmpN % 2;
return 1 / (pow(square, powerForSquare) * pow(x, restPower));
}
}
|
281211d3-7e09-4d34-b466-01f7e35c5ffc
| 3
|
public void testXML2JSON(){
String generatedJson = "{\"response\":{\"ip_addresses\":{\"ip_address\":\"66.249.17.251\",\"domain_names\":[\"DMAINTOOLS.COM\",\"DOAMINTOOLS.COM\"],\"domain_count\":52}}}";
String originalJson = "{\"response\":{\"ip_addresses\":{\"ip_address\":\"66.249.17.251\",\"domain_count\":52,\"domain_names\":[\"DMAINTOOLS.COM\",\"DOAMINTOOLS.COM\"]}}}";
ObjectMapper objectMapper = new ObjectMapper();
JsonNode generatedJsonNode = null;
JsonNode originalJsonNode = null;
try {
generatedJsonNode = (JsonNode) objectMapper.readTree(generatedJson);
originalJsonNode = (JsonNode) objectMapper.readTree(originalJson);
if(!generatedJsonNode.equals(originalJsonNode)) fail();
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
|
cfeb970a-b4fd-4353-b3ee-eb45836f5ed6
| 4
|
@Override
public int mover() {
Partida.Pantalla pantalla = Partida.getPantalla();
//cambiamos el estado del disparo si saliera del panel del Juego
if(x < -width)
return -1;
if(x > pantalla.getX()*2 + pantalla.getWidth())
return -1;//sale por la derecha
if(y < -height)
return -1; //sale por arriba
if(y > pantalla.getY()*2 + pantalla.getHeigth())
return -1;//sale por abajo
y += yv;
x += xv;
return salud;
}
|
46aa9ff4-d527-4b14-88da-1cd5377fafc8
| 4
|
public void test_add_RP_int_intarray_int() {
int[] values = new int[] {10, 20, 30, 40};
int[] expected = new int[] {10, 20, 30, 40};
BaseDateTimeField field = new MockStandardBaseDateTimeField();
int[] result = field.add(new TimeOfDay(), 2, values, 0);
assertEquals(true, Arrays.equals(expected, result));
values = new int[] {10, 20, 30, 40};
expected = new int[] {10, 20, 31, 40};
result = field.add(new TimeOfDay(), 2, values, 1);
assertEquals(true, Arrays.equals(expected, result));
values = new int[] {10, 20, 30, 40};
expected = new int[] {10, 21, 0, 40};
result = field.add(new TimeOfDay(), 2, values, 30);
assertEquals(true, Arrays.equals(expected, result));
values = new int[] {23, 59, 30, 40};
try {
field.add(new TimeOfDay(), 2, values, 30);
fail();
} catch (IllegalArgumentException ex) {}
values = new int[] {10, 20, 30, 40};
expected = new int[] {10, 20, 29, 40};
result = field.add(new TimeOfDay(), 2, values, -1);
assertEquals(true, Arrays.equals(expected, result));
values = new int[] {10, 20, 30, 40};
expected = new int[] {10, 19, 59, 40};
result = field.add(new TimeOfDay(), 2, values, -31);
assertEquals(true, Arrays.equals(expected, result));
values = new int[] {0, 0, 30, 40};
try {
field.add(new TimeOfDay(), 2, values, -31);
fail();
} catch (IllegalArgumentException ex) {}
values = new int[] {0, 0};
try {
field.add(new MockPartial(), 0, values, 1000);
fail();
} catch (IllegalArgumentException ex) {}
values = new int[] {1, 0};
try {
field.add(new MockPartial(), 0, values, -1000);
fail();
} catch (IllegalArgumentException ex) {}
}
|
92667c7c-bb12-4ca2-bb41-6c675361131d
| 3
|
public Boolean http_status_filter(String url){
HttpResponse response;
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget=new HttpGet(url);
httpget.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
response = httpclient.execute(httpget);
StatusLine status=response.getStatusLine();
System.out.print(status.getStatusCode());
if(status.getStatusCode()==200){
return true;
}else{
return false;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
mTimeOutList.add(url);//timeout urls are saved
m_list.add(url);//timeout urls are saved in already used url
System.out.println("TimeOut url :"+url);
return false;
}
}
|
6c843052-8dc6-47dd-8734-b28498c50910
| 5
|
private boolean shouldIgnorePacket(DatagramPacket packet) {
boolean result = false;
InetAddress from = packet.getAddress();
if (from != null)
{
if (from.isLinkLocalAddress() && (!_BoundAddress.isLinkLocalAddress()))
{
// Ignore linklocal packets on regular interfaces, unless this is
// also a linklocal interface. This is to avoid duplicates. This is
// a terrible hack caused by the lack of an API to get the address
// of the interface on which the packet was received.
result = true;
}
if (from.isLoopbackAddress() && (!_BoundAddress.isLoopbackAddress()))
{
// Ignore loopback packets on a regular interface unless this is
// also a loopback interface.
result = true;
}
}
return result;
}
|
3f7e5eeb-38b7-4059-ba71-ed80a21e9117
| 9
|
public BookBuilderSpec<P> paperColors(Map<PaperBuilderSpec<?>, ColorBuilderSpec<?>> paperColors) {
verifyMutable();
if (this.paperColors == null) {
this.paperColors = new HashMap<PaperBuilderSpec<?>, ColorBuilderSpec<?>>();
}
if (paperColors != null) {
for (Map.Entry<PaperBuilderSpec<?>, ColorBuilderSpec<?>> e : paperColors.entrySet()) {
CollectionUtils.putItem(this.paperColors, e.getKey(), e.getValue());
}
}
return this;
}
|
98b4cbbb-91ad-4887-9437-743d566aefc8
| 5
|
public String apply(String s) {
if (s == null) {
if (matchesNull()) {
if (!replace.contains("$1")) {
return replace;
}
}
return null;
}
Matcher m = pattern.matcher(s);
StringBuffer sb = new StringBuffer();
while (m.find()) {
if (m.start() < m.end()) {
m.appendReplacement(sb, replace);
}
}
return sb.toString();
}
|
d4c6064e-92c4-4b92-8f36-16914856e7ee
| 4
|
public void setOpponentSkin(int character) {
String s;
s = character == 0 ? "/Characters/TestChar.png"
: "/Characters/TestChar2.png";
// load sprites
try {
final BufferedImage spritesheet = ImageIO.read(getClass()
.getResourceAsStream(s));
sprites = new ArrayList<BufferedImage[]>();
for (int i = 0; i < numFrames.length; i++) {
final BufferedImage[] bi = new BufferedImage[numFrames[i]];
for (int j = 0; j < numFrames[i]; j++) {
bi[j] = spritesheet.getSubimage(j * width, i * height,
width, height);
}
sprites.add(bi);
}
} catch (final Exception e) {
e.printStackTrace();
}
animation = new Animation();
currentAction = IDLE;
animation.setFrames(sprites.get(IDLE));
animation.setDelay(100);
}
|
450a8b48-4d9d-4579-99f2-2b4d3e2e066b
| 5
|
@Override
public boolean equals(Object other) {
if (other instanceof BackpackData) {
return ((BackpackData) other).isRegistered() == this.isRegistered()
&& ((BackpackData) other).getType().equals(this.getType())
&& ((BackpackData) other).getOwner().equals(this.getOwner())
&& ((BackpackData) other).getId() == this.getId()
&& ((BackpackData) other).hasFallbackCheckKey() == this.hasFallbackCheckKey();
}
return false;
}
|
25734d39-e534-4ac9-9f38-fcaf3fef8f1a
| 9
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TextAnalyzer other = (TextAnalyzer) obj;
if (averageSentenceCharLength != other.averageSentenceCharLength)
return false;
if (averageSentenceWordLength != other.averageSentenceWordLength)
return false;
if (averageWordLength != other.averageWordLength)
return false;
if (totalCharCount != other.totalCharCount)
return false;
if (totalSentenceCount != other.totalSentenceCount)
return false;
if (totalWordCount != other.totalWordCount)
return false;
return true;
}
|
983e708f-b6ca-43b9-a825-48777a2b75f3
| 3
|
@Override
public List<ByteBuffer> transfer(List<ByteBuffer> elements)
{
List<ByteBuffer> denied = new ArrayList<ByteBuffer>();
// Calculate how much memory is transfered to this factory, and build
// a list of the buffers denied for caching.
for (ByteBuffer b : elements)
{
// If the buffer can be cached, increment the amount of cache memory
if (b.capacity() + usedMemory.get() <= maxMemory.get() && onCache(b)) {
usedMemory.addAndGet(b.capacity());
}
// Else the buffer wasn't the right type, size, or the max amount of
// memory has been reached.
else {
denied.add(b);
}
}
return denied;
}
|
4b0b8dd5-d5cf-4d48-ac62-b95079a8b63f
| 7
|
@Override
public int hashCode()
{
int result = _name.hashCode();
result = 31 * result + (_hidden ? 1 : 0);
result = 31 * result + (_systemHidden ? 1 : 0);
result = 31 * result + _resultType.hashCode();
result = 31 * result + (_value != null ? _value.hashCode() : 0);
result = 31 * result + (_startNanos != null ? _startNanos.hashCode() : 0);
result = 31 * result + (_pendingNanos != null ? _pendingNanos.hashCode() : 0);
result = 31 * result + (_endNanos != null ? _endNanos.hashCode() : 0);
result = 31 * result + (_attributes != null ? _attributes.hashCode() : 0);
return result;
}
|
90b85d59-1d64-4f80-9fb8-f0633d74b5ad
| 8
|
private void ParseHtml(StringBuffer buffer, ITag root)
throws HtmlParseException {
int startIndex = 0;
// Iterate as long as there are children
while (true) {
int startTagStartIndex = 0;
int startTagEndIndex = 0;
int endTagStartIndex = 0;
int endTagEndIndex = 0;
// Find the beginning of the next start tag ------------------------
startTagStartIndex = buffer.indexOf(START_TAG_START, startIndex);
// This is the base case.
if (startTagStartIndex < 0) {
AddTextElement(buffer.substring(startIndex), root);
return;
}
// Find the end of the next start tag ------------------------------
startTagEndIndex = buffer.indexOf(TAG_END, startTagStartIndex);
if (startTagEndIndex < 0) {
throw new HtmlParseException("No '>' found for opening tag.");
}
String startTag = buffer.substring(startTagStartIndex + 1,
startTagEndIndex);
String tagname = startTag.replaceAll("\\s+$", "");
// Find the beginning of the corresponding end tag -----------------
endTagStartIndex = buffer.indexOf(END_TAG_START + startTag.trim(),
startTagEndIndex);
if (endTagStartIndex < 0) {
throw new HtmlParseException("No '</' found for closing tag.");
}
// Find the corresponding end tag ----------------------------------
endTagEndIndex = buffer.indexOf(TAG_END, endTagStartIndex);
if (endTagEndIndex < 0) {
throw new HtmlParseException("No '>' found for closing tag.");
}
String endTag = buffer.substring(endTagStartIndex + 1,
endTagEndIndex);
// See if there is a string before this tag.
if (startIndex != startTagStartIndex) {
String str = buffer.substring(startIndex, startTagStartIndex);
AddTextElement(str, root);
}
// Create the tag
ITag tag = (ITag) factory.Create(startTag, endTag);
if (tag == null) {
throw new HtmlParseException("Invalid HTML tag: '" + tagname
+ "'");
}
try {
root.Add(tag);
} catch (NotImplementedException e) {
e.printStackTrace();
}
// Make the recursive parsing call to parse below the tag
String tagstring = buffer.substring(startTagEndIndex + 1,
endTagStartIndex);
StringBuffer subbuffer = new StringBuffer(tagstring);
ParseHtml(subbuffer, tag);
// Set up the starting index for the iteration
startIndex = endTagEndIndex + 1;
}
}
|
4afe15c3-519a-4e6d-89d8-b6e0f59c625c
| 4
|
public static void main(String args[]) throws Exception, CannotProduceDateParser, ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
String xmlPath = "monitor.xml";
if (args.length > 0) xmlPath = args[0];
xmlPath = new File(xmlPath).getAbsolutePath();
com.actimind.diagnostic.xml.Monitor m = JAXB.unmarshal(xmlPath, com.actimind.diagnostic.xml.Monitor.class);
String dbName = null;
for (com.actimind.diagnostic.xml.Monitor.Use use: m.getUse()) {
if (use.getDb() != null) {
dbName = use.getDb();
Class.forName(use.getConnector());
}
}
if (dbName == null) throw new RuntimeException("Database info shall be provided in 'use' tag in monitor.xml, attributes 'db' and 'connector'");
new Monitor(xmlPath, dbName);
}
|
f5e29e5f-9c12-4f69-a6e7-3655c1ad4e26
| 8
|
public int maximumGap(int[] nums) {
if (nums.length < 2) {
return 0;
}
int max = 0;
int min = Integer.MAX_VALUE;
for (int n : nums) {
max = Math.max(max, n);
min = Math.min(min, n);
}
int len = (max - min) / nums.length + 1;
int size = (max - min) / len + 1;
int buckets[][] = new int[size][2];
for (int n : nums) {
int i = (n - min) / len;
if (buckets[i][0] == 0 && buckets[i][1] == 0) {
buckets[i][0] = n;
buckets[i][1] = n;
} else {
buckets[i][0] = Math.min(buckets[i][0], n);
buckets[i][1] = Math.max(buckets[i][1], n);
}
}
int result = 0;
int pre = 0;
for (int i = 1; i < buckets.length; i++) {
if (buckets[i][0] == 0 && buckets[i][1] == 0) {
continue;
} else {
result = Math.max(result, buckets[i][0] - buckets[pre][1]);
pre = i;
}
}
return result;
}
|
a9b6c7c8-d843-4594-a478-974abd80a6f8
| 1
|
public String getSuperclass() {
if (cachedSuperclass == null)
cachedSuperclass = constPool.getClassInfo(superClass);
return cachedSuperclass;
}
|
a66257a2-543c-4a29-90c2-87cd0b5cdc5c
| 8
|
private Dimension layoutSize(Container target, boolean preferred)
{
synchronized (target.getTreeLock())
{
// Each row must fit with the width allocated to the containter.
// When the container width = 0, the preferred width of the container
// has not yet been calculated so lets ask for the maximum.
int targetWidth = target.getSize().width;
if (targetWidth == 0)
targetWidth = Integer.MAX_VALUE;
int hgap = getHgap();
int vgap = getVgap();
Insets insets = target.getInsets();
int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2);
int maxWidth = targetWidth - horizontalInsetsAndGap;
// Fit components into the allowed width
Dimension dim = new Dimension(0, 0);
int rowWidth = 0;
int rowHeight = 0;
int nmembers = target.getComponentCount();
for (int i = 0; i < nmembers; i++)
{
Component m = target.getComponent(i);
if (m.isVisible())
{
Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize();
// Can't add the component to current row. Start a new row.
if (rowWidth + d.width > maxWidth)
{
addRow(dim, rowWidth, rowHeight);
rowWidth = 0;
rowHeight = 0;
}
// Add a horizontal gap for all components after the first
if (rowWidth != 0)
{
rowWidth += hgap;
}
rowWidth += d.width;
rowHeight = Math.max(rowHeight, d.height);
}
}
addRow(dim, rowWidth, rowHeight);
dim.width += horizontalInsetsAndGap;
dim.height += insets.top + insets.bottom + vgap * 2;
// When using a scroll pane or the DecoratedLookAndFeel we need to
// make sure the preferred size is less than the size of the
// target containter so shrinking the container size works
// correctly. Removing the horizontal gap is an easy way to do this.
Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target);
if (scrollPane != null && target.isValid())
{
dim.width -= (hgap + 1);
}
return dim;
}
}
|
9008c16a-a02d-4abf-abef-e4d6fed95f93
| 6
|
public static String numberToString(Number number) throws JSONException {
if (number == null) {
throw new JSONException("Null pointer");
}
testValidity(number);
// Shave off trailing zeros and decimal point, if possible.
String string = number.toString();
if (string.indexOf('.') > 0 && string.indexOf('e') < 0
&& string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
}
|
c376f167-61c3-482c-8d2c-78929e8a9353
| 1
|
public void test_append_nullPrinter() {
try {
DateTimeFormatterBuilder bld2 = new DateTimeFormatterBuilder();
bld2.append((DateTimePrinter) null);
fail();
} catch (IllegalArgumentException ex) {
// expected
}
}
|
b2bcbc42-7657-4ae1-aa82-de6e0eefd57f
| 8
|
public void render()
{
try
{
buffer = createImage(720, 720);
Graphics g = buffer.getGraphics();
Graphics i = image.getGraphics();
g.drawImage(board.getImage(), 0, 0, 720, 720, this);
i.drawImage(board.getImage(), 0, 0, 720, 720, this);
g.setColor(Color.BLACK);
g.drawRect(x - 25, y - 25, 50, 50);
for (Square[] a : squares)
{
for (Square s : a)
{
if (s.piece != null) // makes sure the space is open, if so it draws the piece
{
s.piece.draw(g);
s.piece.draw(i);
}
}
}
// If both black and white pass in the same turn the game ends
if ((whitePass && blackPass) || numOfEmptySquares() == 0)
{
dispose();
}
// This was our test to see whether the groups and territories were working
// for (GroupAi h : groups)
// {
// h.numOfLiberties();
// Color random = new Color((int) (Math.random() * 256), (int) (Math.random() * 256),
// (int) (Math.random() * 256));
// for (Piece p : h.pieces)
// {
// g.setColor(random);
// g.fillOval(p.where.x + 28, p.where.y + 28, 24, 24);
// }
// for (Square s : h.liberties)
// {
// g.setColor(random);
// g.fillOval(s.x + 28, s.y + 28, 24, 24);
// }
// }
// processTerritories();
// for (TerritoryAi t : territories)
// {
// if (t.team() == 0)
// g.setColor(Color.green);
//
// if (t.team() == 1)
// g.setColor(Color.black);
// if (t.team() == 2)
// g.setColor(Color.white);
// for (Square s : t.squares)
// {
// g.fillRect(s.x + 28, s.y + 28, 24, 24);
// }
//
// }
if (!current)
{
evaluate(10);
current = true;
}
getGraphics().drawImage(buffer, 0, 0, 720, 720, this); // so there is no updating
// flashes
}
catch (Exception e)
{
}
}
|
32c11db4-1f15-4c54-a676-f5fa6ea25813
| 7
|
public static void main(String[] args) {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=AdventureWorks;integratedSecurity=true;";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
// Create and execute an SQL statement that returns a
// set of data and then display it.
String SQL = "SELECT * FROM Production.Product;";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
displayRow("PRODUCTS", rs);
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
|
ec96f261-e350-43cc-95b5-e205d2780bf6
| 1
|
public void setLeaves(final List leaves) {
if (SSAPRE.DEBUG) {
System.out.println("setting leaves of " + this + " to "
+ leaves);
}
this.leaves = new ArrayList(leaves);
}
|
6e167b64-0474-4cc6-b5f4-a11e0a5329d8
| 6
|
public static void print(int[][] table, CustomLogic logic) {
int padding = String.valueOf(table[table.length - 1][table[0].length - 1]).length();
String strFmt = " %" + padding + "s |";
String dgtFmt = " %" + padding + "s |";
String sep = "+";
for (int i = 0; i < padding + 2; i++) sep = "-" + sep;
StringBuilder str = new StringBuilder();
str.append(String.format(strFmt, 'X'));
for (int i = 1; i <= table.length; i++) {
str.append(String.format(dgtFmt, i));
}
str.append('\n');
for (int i = 0; i <= table.length; i++) {
str.append(sep);
}
for (int i = 0; i < table[0].length; i++) {
str.append('\n');
str.append(String.format(dgtFmt, i + 1));
for (int j = 0; j < table.length; j++) {
if (logic.call(table[j][i])) {
str.append(String.format(dgtFmt, table[j][i]));
} else {
str.append(String.format(strFmt, ' '));
}
}
}
System.out.println(str.toString());
}
|
bf189608-252d-4af0-a9f8-1e70bf439833
| 2
|
public boolean quitChecker(String input)
{
boolean okToQuit = false;
if(input != null && input.equals("bye"))
{
okToQuit = true;
}
return okToQuit;
}
|
b2b92858-5fbe-45cd-92f1-76d42e33b516
| 7
|
private String DDCRET_String(int retcode)
{
switch ( retcode )
{
case DDC_SUCCESS: return "DDC_SUCCESS";
case DDC_FAILURE: return "DDC_FAILURE";
case DDC_OUT_OF_MEMORY: return "DDC_OUT_OF_MEMORY";
case DDC_FILE_ERROR: return "DDC_FILE_ERROR";
case DDC_INVALID_CALL: return "DDC_INVALID_CALL";
case DDC_USER_ABORT: return "DDC_USER_ABORT";
case DDC_INVALID_FILE: return "DDC_INVALID_FILE";
}
return "Unknown Error";
}
|
8eb9743b-59d8-4665-b6b1-4e98643759b5
| 1
|
@Override
public void show() {
// Lazy Instantiation
if (!initialized) {
initialize();
initialized = true;
}
OutlinerDocument doc = (OutlinerDocument) Outliner.documents.getMostRecentDocumentTouched();
documentTitleValue.setText(doc.getTitle());
int lineCount = doc.tree.getLineCount();
lineCountValue.setText("" + lineCount);
int charCount = doc.tree.getCharCount();
charCountValue.setText("" + charCount);
super.show();
}
|
634a30e0-d980-4045-bb47-6d68d700cd59
| 2
|
public void enable() throws IOException {
// This has to be synchronized or it can collide with the check in the task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set it.
if (isOptOut()) {
configuration.set("opt-out", false);
configuration.save(configurationFile);
}
// Enable Task, if it is not running
if (task == null) {
start();
}
}
}
|
7b211836-176b-4b52-940b-a6a79039fc87
| 0
|
public void close() throws IOException {
//init();
isInited = true;
internalIn.close();
}
|
0cb01bdf-14d3-4493-ad75-92acb028ae9b
| 5
|
@RequestMapping(value = "del", method = RequestMethod.POST)
@ResponseBody
public Map del(@RequestParam int[] id) {
Map<String, Object> map = new HashMap<>();
List<String> l1 = new ArrayList<>();
List<String> l2 = new ArrayList<>();
List<String> l3 = new ArrayList<>();
for (int i = 0; i < id.length; i++) {
Option option = optionService.getById(id[i]);
if (option != null) {
if (false) {
l1.add(option.getOptionName());
optionService.delete(option);
} else {
l3.add(option.getOptionName());
}
} else {
l2.add(id[i] + "");
}
}
String s1 = Tools.toArrayString(l1);
String s2 = Tools.toArrayString(l2);
String s3 = Tools.toArrayString(l3);
map.put("success", true);
map.put("msg", "选项:" + s1 + ",删除成功!"
+ (s2.isEmpty() ? "" : ("\n选项:" + s2 + ",信息不存在,请刷新后重试。"))
+ (s3.isEmpty() ? "" : ("\n选项:" + s3 + ",存在子项,请清空子项后重试。")));
return map;
}
|
191ed027-014f-4226-a752-051bf725902d
| 6
|
@Override
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
DatabaseManager manager=DatabaseManager.getManager();
try {
MultipurposeRoom room = manager.getMultipurposeRoomDao().queryForId(
Integer.parseInt(request.getParameter(ID)));
if(room==null){
ServletResult.sendResult(response, ServletResult.NOT_FOUND);
return;
}
String name=request.getParameter(MultipurposeRoom.NAME);
String location=request.getParameter(MultipurposeRoom.LOCATION);
if(!MyServlet.isEmpty(name)){
room.setName(name);
}
if(!MyServlet.isEmpty(location)){
room.setLocation(location);
}
ServletResult.sendResult(response,
manager.getMultipurposeRoomDao().update(room)==1 ?
ServletResult.SUCCESS
: ServletResult.ERROR);
} catch (NumberFormatException e) {
e.printStackTrace();
ServletResult.sendResult(response, ServletResult.BAD_NUMBER_FORMAT);
} catch (SQLException e) {
e.printStackTrace();
ServletResult.sendResult(response, ServletResult.ERROR);
}
}
|
071f57b3-3f61-477e-bc5c-420088ee6531
| 7
|
public ByteBuffer formatCommand(String format, Object... args) throws IOException
{
Preconditions.checkNotNull(format);
for (Object arg : args)
{
Preconditions.checkNotNull(arg);
}
int argidx = 0;
ByteBuffer result = BufferUtils.EMPTY;
String[] chunks = format.split("[ ]+");
byte[] preamble = String.format("*%d\r\n", chunks.length).getBytes(CHARSET);
result = BufferUtils.makeRoom(result, preamble.length).put(preamble);
ByteBuffer temp = ByteBuffer.allocate(PADDING);
temp.position(PADDING);
for (String chunk : chunks)
{
byte[] chunkBuff = chunk.getBytes(CHARSET);
temp = BufferUtils.makeRoom(temp, PADDING + 2 + chunkBuff.length);
for (int i = 0; i < chunkBuff.length; i++)
{
byte c = chunkBuff[i];
if (c == C_PERCENT && i+1 < chunkBuff.length)
{
byte c2 = chunkBuff[i+1];
if (c2 == C_s)
{
Preconditions.checkState(argidx < args.length, "Not enough parameters given");
byte[] arg = args[argidx].toString().getBytes(CHARSET);
temp = BufferUtils.makeRoom(temp, arg.length);
temp.put(arg);
argidx++;
}
else if (c2 == C_b)
{
Preconditions.checkState(argidx < args.length, "Not enough parameters given");
Object arg = args[argidx];
byte[] argBuff = serialize(arg);
temp = BufferUtils.makeRoom(temp, argBuff.length);
temp.put(argBuff);
argidx++;
}
else
{
temp = BufferUtils.makeRoom(temp, 2);
temp.put(c);
temp.put(c2);
}
i++;
}
else
{
temp = BufferUtils.makeRoom(temp, 1);
temp.put(c);
}
}
temp = BufferUtils.makeRoom(temp, 2);
byte[] tempPreamble = String.format("$%d\r\n", temp.position() - PADDING).getBytes(CHARSET);
temp.put(CRLF).flip().position(PADDING - tempPreamble.length).mark();
temp.put(tempPreamble).reset();
result = BufferUtils.makeRoom(result, temp.remaining()).put(temp);
temp.clear().position(PADDING);
}
result.flip();
return result;
}
|
70883750-e08d-42ee-b16a-cb78e8575383
| 9
|
void setProperty(String propertyName, Object value, BitSet bs) {
if ("color" == propertyName) {
isActive = true;
short colix = Graphics3D.getColix(value);
if (bsColixSet == null)
bsColixSet = new BitSet();
byte pid = JmolConstants.pidOf(value);
for (int i = atomCount; --i >= 0; )
if (bs.get(i))
setColixAndPalette(colix, pid, i);
return;
}
if ("translucency" == propertyName) {
isActive = true;
boolean isTranslucent = ("translucent" == value);
for (int i = atomCount; --i >= 0; )
if (bs.get(i)) {
if (colixes == null) {
colixes = new short[atomCount];
paletteIDs = new byte[atomCount];
}
colixes[i] = Graphics3D.getColixTranslucent(colixes[i], isTranslucent);
if (isTranslucent)
bsColixSet.set(i);
}
return;
}
}
|
e80fa460-8a2f-40d8-ab1a-9865cb71afdb
| 8
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Project_eXceed))
return false;
Project_eXceed other = (Project_eXceed) obj;
if (id != other.id)
return false;
if (project_Name == null) {
if (other.project_Name != null)
return false;
} else if (!project_Name.equals(other.project_Name))
return false;
if (score != other.score)
return false;
return true;
}
|
62a11026-dfff-420d-9339-ab2a36ccc6ff
| 8
|
@Override
public void caseADeclAvalieDefinicaoComando(ADeclAvalieDefinicaoComando node)
{
inADeclAvalieDefinicaoComando(node);
if(node.getAvalie() != null)
{
node.getAvalie().apply(this);
}
if(node.getLPar() != null)
{
node.getLPar().apply(this);
}
if(node.getExp() != null)
{
node.getExp().apply(this);
}
if(node.getRPar() != null)
{
node.getRPar().apply(this);
}
if(node.getMultiploCaso() != null)
{
node.getMultiploCaso().apply(this);
}
if(node.getOpcionalSenaoCaso() != null)
{
node.getOpcionalSenaoCaso().apply(this);
}
if(node.getFimAvalie() != null)
{
node.getFimAvalie().apply(this);
}
if(node.getPontoVirgula() != null)
{
node.getPontoVirgula().apply(this);
}
outADeclAvalieDefinicaoComando(node);
}
|
54d182a9-01b4-4785-9ba0-55f45b941fb3
| 4
|
@Override
public int compareTo(SASRunner compareTarget)
{
if (this.priorityLevel != null || compareTarget.getPriority() != null)
{
if (this.priorityLevel > ((SASRunner)compareTarget).getPriority())
{
return -1;
}
else if (this.priorityLevel < ((SASRunner)compareTarget).getPriority())
{
return 1;
}
}
return 0;
}
|
021dad13-0255-496e-94c8-ccc67adcf42d
| 9
|
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final int dirCode=CMLib.directions().getDirectionCode(CMParms.combine(commands,0));
if(dirCode<0)
{
mob.tell(L("Climb where?"));
return false;
}
if((mob.location().getRoomInDir(dirCode)==null)
||(mob.location().getExitInDir(dirCode)==null))
{
mob.tell(L("You can't climb that way."));
return false;
}
if(CMLib.flags().isSitting(mob)||CMLib.flags().isSleeping(mob))
{
mob.tell(L("You need to stand up first!"));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
boolean success=proficiencyCheck(mob,0,auto);
final CMMsg msg=CMClass.getMsg(mob,null,this,CMMsg.MSG_NOISYMOVEMENT,null);
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
success=proficiencyCheck(mob,0,auto);
if(mob.fetchEffect(ID())==null)
{
mob.addEffect(this);
mob.recoverPhyStats();
}
CMLib.tracking().walk(mob,dirCode,false,false);
mob.delEffect(this);
mob.recoverPhyStats();
if(!success)
mob.location().executeMsg(mob,CMClass.getMsg(mob,mob.location(),CMMsg.MASK_MOVE|CMMsg.TYP_GENERAL,null));
}
return success;
}
|
3a015f5a-cd02-41d1-b258-8be7cd4a743f
| 6
|
@Override
protected void lock() {
while (true) {
if (!calcLocker.isWriteLocked() && calcLocker.writeLock().tryLock())
if (calcLocker.getWriteHoldCount() != 1)
calcLocker.writeLock().unlock();
else if (hasAdjustment() == PRO_ADJ_PAR
&& ((BoolProperty) ((AbstractProperty) parentProperty)).calcLocker.isWriteLocked())
calcLocker.writeLock().unlock();
else
return;
}
}
|
5e4e3130-589f-4b71-9a9b-2ed17a0824ef
| 9
|
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final BinaryNode other = (BinaryNode) obj;
if (left == null) {
if (other.left != null) {
return false;
}
} else if (!left.equals(other.left)) {
return false;
}
if (right == null) {
if (other.right != null) {
return false;
}
} else if (!right.equals(other.right)) {
return false;
}
return true;
}
|
2848415e-b4cd-44a5-a448-04a807a1f358
| 7
|
public static BufferedImage buildCostume(Object[] form) {
int width = ((Number)form[0]).intValue();
int height = ((Number)form[1]).intValue();
int depth = ((Number)form[2]).intValue();
int[] bitmap;
try {
bitmap = decodePixels((byte[]) form[4]);
} catch (IOException e) {
System.err.println("Failed to build image.");
return null;
}
MemoryImageSource localMemoryImageSource = null;
Object[] colors;
ColorModel colorMap;
if (depth <= 8)
{
if (form.length == 6) {
colors = (Object[]) form[5];
colorMap = customColorMap(depth, Arrays.asList(colors).toArray(new Color[0]));
}
else {
colorMap = squeakColorMap(depth);
}
localMemoryImageSource = new MemoryImageSource(width, height, colorMap, rasterToByteRaster(bitmap, width, height, depth), 0, width);
} else if (depth == 16) {
localMemoryImageSource = new MemoryImageSource(width, height, raster16to32(bitmap, width, height), 0, width);
} else if (depth == 32) {
localMemoryImageSource = new MemoryImageSource(width, height, rasterAddAlphaTo32(bitmap), 0, width);
}
if (localMemoryImageSource != null) {
int[] pixels = new int[width * height];
PixelGrabber grabber = new PixelGrabber(localMemoryImageSource, 0, 0, width, height, pixels, 0, width);
try {
grabber.grabPixels();
}
catch (InterruptedException localInterruptedException) {
System.out.println("???");
}
BufferedImage localBufferedImage = new BufferedImage(width, height, 2);
localBufferedImage.getRaster().setDataElements(0, 0, width, height, pixels);
return localBufferedImage;
}
System.err.println("Unknown image depth: " + depth);
return null;
}
|
552ee653-9443-4ecb-8c4d-a05414252185
| 4
|
public int plusDILookback( int optInTimePeriod )
{
if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) )
optInTimePeriod = 14;
else if( ((int)optInTimePeriod < 1) || ((int)optInTimePeriod > 100000) )
return -1;
if( optInTimePeriod > 1 )
return optInTimePeriod + (this.unstablePeriod[FuncUnstId.PlusDI.ordinal()]) ;
else
return 1;
}
|
fff39479-ce1d-4d26-b054-7fe1d3722da6
| 1
|
@SuppressWarnings("unchecked")
public Transition usingId(Id id) {
if (this.id != null) {
throw new IllegalStateException("Id already assigned!");
}
this.id = id;
return this;
}
|
1df3fdf0-7c3d-4009-8145-32d775ff4691
| 7
|
public synchronized void preDraw(Graphics2D g) {
if (!updated) {
dw = dh = 0;
lines.clear();
for (Information info : list) {
dw = Math.max(dw, (double) info.wrap(g, maxWidth, lines));
// Mala medzera medzi spavami
dh -= g.getFontMetrics().getAscent();
dh += g.getFontMetrics().getAscent() * 0.25;
}
dw += dr;
dh += lines.size() * g.getFontMetrics().getAscent() - g.getFontMetrics().getAscent()
* 0.25 + g.getFontMetrics().getDescent();
updated = true;
}
dx = (position == BubblePosition.NE || position == BubblePosition.SE) ? x : x - dw;
dy = (position == BubblePosition.SW || position == BubblePosition.SE) ? y : y - dh;
if (locked) {
dx = (dx - graph.canvas.offX) / graph.canvas.zoom;
dy = (dy - graph.canvas.offY) / graph.canvas.zoom;
g.translate((x - graph.canvas.offX) / graph.canvas.zoom, (y - graph.canvas.offY)
/ graph.canvas.zoom);
g.scale(1.0 / Math.sqrt(graph.canvas.zoom), 1.0 / Math.sqrt(graph.canvas.zoom));
g.translate(-(x - graph.canvas.offX) / graph.canvas.zoom, -(y - graph.canvas.offY)
/ graph.canvas.zoom);
} else {
g.translate(x, y);
g.scale(1.0 / Math.sqrt(graph.canvas.zoom), 1.0 / Math.sqrt(graph.canvas.zoom));
g.translate(-x, -y);
}
}
|
01ebb6f0-acd5-4afa-89a7-886fbe177a9e
| 7
|
@Override
public LinkedList<Tuple<Sentence_tree, Tuple<String, String>>> interesting_subtree(Hashtable<String,Boolean> voc, Hashtable<String, Boolean> subvoc){
LinkedList<Sentence_tree> keyword_list = bfs_name(voc);
LinkedList<Tuple<Sentence_tree, Tuple<String, String>>> interest = new LinkedList<Tuple<Sentence_tree, Tuple<String, String>>>();
Hashtable<String,Boolean> already_done = new Hashtable<String,Boolean>();
if(!keyword_list.isEmpty()){
for(int i = 0; i < keyword_list.size(); i++){
for(int j = 0; j < keyword_list.size(); j++){
if(i != j && !already_done.containsKey(keyword_list.get(i).get_root()+" "+keyword_list.get(j).get_root())){
already_done.put(keyword_list.get(i).get_root()+" "+keyword_list.get(j).get_root(), true);
Sentence_tree interesting_tree1 = keyword_list.get(i);
Sentence_tree interesting_tree2 = keyword_list.get(j);
if(subvoc.containsKey(interesting_tree1.get_root()) || subvoc.containsKey(interesting_tree2.get_root())){
Sentence_tree sub_tree = interesting_tree1.find_common_node(interesting_tree2).copy();
interest.add(new Tuple<Sentence_tree,Tuple<String,String>>(sub_tree, new Tuple<String,String>(interesting_tree1.root.name, interesting_tree2.root.name)));
}
}
}
}
}
return interest;
}
|
c785f0a8-a9bb-4d23-80bf-957506ca060a
| 0
|
public String compileDetail(){
myCompiler.compileSource(pass_code);
return SUCCESS;
}
|
28b09d94-25c7-45fa-8af7-97d6ab00db38
| 6
|
@SuppressWarnings("unchecked")
@Override
public void drop(DropTargetDropEvent event) {
Transferable tr = event.getTransferable();
if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
event.acceptDrop(DnDConstants.ACTION_COPY);
final List<File> files;
try {
files = new LinkedList<File>((List<File>) tr.getTransferData(DataFlavor.javaFileListFlavor));
event.dropComplete(true);
// asks info about files is a separate thread, so drop can conclude.
new SwingWorker<Void, Void> () {
@Override
protected Void doInBackground() throws Exception {
for (File f : files) {
DialogData dialogData = new DialogData();
dialogData.data.addAttribute(EMediumAttribute.PATH, f.getAbsolutePath());
new EMediumPropertiesUI(frame, dialogData, false, true);
if (dialogData.didUserAccept()) {
boolean resultAdd = uiDelegate.addEMediumLibrary((String) dialogData.data.getAttribute(EMediumAttribute.MEDIUM_TYPE), dialogData.data);
if (!resultAdd)
JOptionPane.showMessageDialog(frame, "Duplicated document!",
"Add document error", JOptionPane.ERROR_MESSAGE);
}
}
return null;
}
}.execute();
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
event.rejectDrop();
}
} else
event.rejectDrop();
}
|
564ce7aa-a6d5-4f9d-9f95-c225412a1cc2
| 8
|
public int maximalSquare(char[][] matrix) {
if (matrix.length == 0) {
return 0;
}
int height = matrix.length;
int width = matrix[0].length;
int dp[][] = new int[height][width];
for (int i = 0; i < height; i++) {
dp[i][0] = Character.getNumericValue(matrix[i][0]);
}
for (int i = 0; i < width; i++) {
dp[0][i] = Character.getNumericValue(matrix[0][i]);
}
for (int i = 1; i < height; i++) {
for (int j = 1; j < width; j++) {
if (matrix[i][j] == '1') {
dp[i][j] = Math.min(
Math.min(dp[i - 1][j], dp[i - 1][j - 1]),
dp[i][j - 1]) + 1;
} else {
dp[i][j] = 0;
}
}
}
int max = 0;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
max = Math.max(max, dp[i][j]);
}
}
return max * max;
}
|
32d24c60-22e7-4cea-a6fb-c10a4ef81f23
| 3
|
private void resize() {
size = getSkinnable().getWidth() < getSkinnable().getHeight() ? getSkinnable().getWidth() : getSkinnable().getHeight();
if (size > 0) {
for (Region led : leds) {
led.setPrefSize(size, size);
}
}
}
|
abd3768e-b177-457c-b607-42c53e1bc42e
| 2
|
public boolean checkCollision(int r, int c)
{
if (row == r && column == c)
{
alive = false;
return true;
}
return false;
}
|
1daf75ad-81df-443a-86b8-100122930095
| 7
|
@Override
public void execute(FileSystem fs, String[] parts) {
if (parts.length > 2) {
throw new IllegalArgumentException("too much arguments, use only file name");
}
String name = parts[1];
boolean nonexistent = true;
Locker.lock(Thread.currentThread().getId());
Descriptor[] list = fs.getCurrentDirList();
for (Descriptor d : list) {
if (d.getName().trim().equals(name)) {
if (d.isDirectory()) throw new IllegalArgumentException("can't be directory");
try {
Block b = fs.readBlock(d.getFirstBlock());
do {
System.out.print(new String(b.getData()).trim());
b = b.nextBlock();
} while (b != null);
System.out.println();
}
catch (IOException e) {
System.err.println("Error during reading file!");
}
nonexistent = false;
break;
}
}
Locker.unlock(Thread.currentThread().getId());
if (nonexistent) System.out.println("No such file!");
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.