or4cl3ai/Aiden_t5
Text Generation
•
Updated
•
846
•
14
text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public int getNowYear() {
return Integer.parseInt(sysNowTime[5]);
} | 0 |
public static void main(String[] args) {
if (args.length >= 2 && args[0].endsWith("output:xml")) {
File in = new File(args[1]);
if (!in.exists()) {
printUsage();
System.exit(1);
}
File out;
if (args.length >= 3) {
out = new File(args[2]);
} else {
String filename = in.getName().replaceAll(".fsg", ".xml");
if (filename.equals(in.getName())) {
filename += ".xml";
}
out = new File(filename);
}
try {
FSGConverter fsgc = FSGConverter.getFSGConverter();
fsgc.convertToXML(in, out);
} catch (IOException e) {
System.out.println("An error occured while converting the file.");
e.printStackTrace();
System.exit(1);
}
} else {
printUsage();
System.exit(1);
}
} | 6 |
public void updateItem(HttpServletRequest arequest) throws Exception
{
for (int idx = this.getCount()-1; idx >= 0; idx--)
{
CNonadItem myitem = (CNonadItem) this.getItem(idx);
String datid = "Ndate" + myitem.nonadmid;
String serid = "NonSeries" + myitem.nonadmid;
String reaid = "NonReason" + myitem.nonadmid;
String nyrsid = "Nyrs" + myitem.nonadmid;
String nmosid = "Nmos" + myitem.nonadmid;
String nwksid = "Nwks" + myitem.nonadmid;
String ndaysid = "Ndys" + myitem.nonadmid;
String datstr = CParser.truncStr(arequest.getParameter(datid), CAppConsts.MaxLenDate);
if (datstr == null || datstr.length() == 0)
{
this.delItem(idx);
continue;
}
String serstr = arequest.getParameter(serid);
String reastr = arequest.getParameter(reaid);
myitem.setNonadmDate(datstr);
myitem.seriescd = serstr;
myitem.reasoncd = reastr;
myitem.nageyears = getIntVal(arequest.getParameter(nyrsid));
myitem.nagemonths = getIntVal(arequest.getParameter(nmosid));
myitem.nageweeks = getIntVal(arequest.getParameter(nwksid));
myitem.nagedays = getIntVal(arequest.getParameter(ndaysid));
}
// int nslot = Math.max(CAppConsts.NewSlotNonAdmin, CAppConsts.NumSlotNonAdmin - getCount());
int nslot = (this.getCount()==0)?2:1;
for (int idx = 0; idx < nslot; idx++)
{
CNonadItem myitem = new CNonadItem();
String myid = "New" + Integer.toString(idx);
String datid = "Ndate" + myid;
String serid = "NonSeries" + myid;
String reaid = "NonReason" + myid;
String nyrsid = "Nyrs" + myid;
String nmosid = "Nmos" + myid;
String nwksid = "Nwks" + myid;
String ndaysid = "Ndys" + myid;
String datstr = CParser.truncStr(arequest.getParameter(datid), CAppConsts.MaxLenDate);
if (datstr == null || datstr.length() == 0) continue; //no data here
String serstr = arequest.getParameter(serid);
String reastr = arequest.getParameter(reaid);
myitem.nonadmid = this.makeNewId("nad", 6);
myitem.setNonadmDate(datstr);
myitem.seriescd = serstr;
myitem.reasoncd = reastr;
myitem.nageyears = getIntVal(arequest.getParameter(nyrsid));
myitem.nagemonths = getIntVal(arequest.getParameter(nmosid));
myitem.nageweeks = getIntVal(arequest.getParameter(nwksid));
myitem.nagedays = getIntVal(arequest.getParameter(ndaysid));
this.addItem(myitem.nonadmid, myitem);
}
} | 7 |
public List<Player> getPlayersInRegion() {
List<Player> rangeList = new ArrayList<Player>();
for (Player p : FFA.getServer().getOnlinePlayers()) {
Location loc = p.getLocation();
Vector vec = new Vector(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
if (this.contains(p.getWorld(), vec)) {
rangeList.add(p);
}
}
return rangeList;
} | 2 |
@Override
public List<Framedata> translateFrame( ByteBuffer buffer ) throws InvalidDataException {
buffer.mark();
List<Framedata> frames = super.translateRegularFrame( buffer );
if( frames == null ) {
buffer.reset();
frames = readyframes;
readingState = true;
if( currentFrame == null )
currentFrame = ByteBuffer.allocate( 2 );
else {
throw new InvalidFrameException();
}
if( buffer.remaining() > currentFrame.remaining() ) {
throw new InvalidFrameException();
} else {
currentFrame.put( buffer );
}
if( !currentFrame.hasRemaining() ) {
if( Arrays.equals( currentFrame.array(), closehandshake ) ) {
frames.add( new CloseFrameBuilder( CloseFrame.NORMAL ) );
return frames;
}
else{
throw new InvalidFrameException();
}
} else {
readyframes = new LinkedList<Framedata>();
return frames;
}
} else {
return frames;
}
} | 5 |
public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
if (!f.hasTag(FUNCTION_TAG)) {
return super.execIdCall(f, cx, scope, thisObj, args);
}
int id = f.methodId();
switch (id) {
case Id_constructor:
return jsConstructor(cx, scope, args);
case Id_toString: {
BaseFunction realf = realFunction(thisObj, f);
int indent = ScriptRuntime.toInt32(args, 0);
return realf.decompile(indent, 0);
}
case Id_toSource: {
BaseFunction realf = realFunction(thisObj, f);
int indent = 0;
int flags = Decompiler.TO_SOURCE_FLAG;
if (args.length != 0) {
indent = ScriptRuntime.toInt32(args[0]);
if (indent >= 0) {
flags = 0;
} else {
indent = 0;
}
}
return realf.decompile(indent, flags);
}
case Id_apply:
case Id_call:
return ScriptRuntime.applyOrCall(id == Id_apply,
cx, scope, thisObj, args);
}
throw new IllegalArgumentException(String.valueOf(id));
} | 8 |
public void showPage(int page) {
if (!hasPage(page))
page = 1;
int start = elementsPerPage * (page - 1);
System.out.println("====[" + title + " Page " + page + "/" + pages + titleContainer + "]====");
if (subtitle != null && !subtitle.isEmpty())
System.out.println(subtitle);
for (int i = start; i < start + elementsPerPage; i++) {
if (i + 1 > elements.size())
break;
System.out.println(elements.get(i));
}
} | 5 |
public int largestRectangleArea(int[] height) {
Stack<Integer> stk = new Stack<Integer>();
int index = 0;
int result = 0;
while (index<height.length) {
if (stk.isEmpty()||height[stk.peek()]<=height[index]) {
stk.push(index);
index++;
}
else {
int t = stk.pop();
result = Math.max(result, height[t]*(stk.isEmpty()?index:index-stk.peek()-1));
}
}
while (!stk.isEmpty()) {
int t = stk.pop();
result = Math.max(result, height[t]*(stk.isEmpty()?height.length:height.length-stk.peek()-1));
}
return result;
} | 6 |
private String getHeaderCaseInsensitive(String name) {
Validate.notNull(name, "Header name must not be null");
// quick evals for common case of title case, lower case, then scan for mixed
String value = headers.get(name);
if (value == null)
value = headers.get(name.toLowerCase());
if (value == null) {
Map.Entry<String, String> entry = scanHeaders(name);
if (entry != null)
value = entry.getValue();
}
return value;
} | 3 |
public static void startupPropositions() {
{ Object old$Module$000 = Stella.$MODULE$.get();
Object old$Context$000 = Stella.$CONTEXT$.get();
try {
Native.setSpecial(Stella.$MODULE$, Stella.getStellaModule("/LOGIC", Stella.$STARTUP_TIME_PHASE$ > 1));
Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get())));
if (Stella.currentStartupTimePhaseP(2)) {
_StartupPropositions.helpStartupPropositions1();
_StartupPropositions.helpStartupPropositions2();
_StartupPropositions.helpStartupPropositions3();
_StartupPropositions.helpStartupPropositions4();
}
if (Stella.currentStartupTimePhaseP(4)) {
_StartupPropositions.helpStartupPropositions5();
}
if (Stella.currentStartupTimePhaseP(5)) {
_StartupPropositions.helpStartupPropositions6();
}
if (Stella.currentStartupTimePhaseP(6)) {
Stella.finalizeClasses();
}
if (Stella.currentStartupTimePhaseP(7)) {
_StartupPropositions.helpStartupPropositions7();
_StartupPropositions.helpStartupPropositions8();
_StartupPropositions.helpStartupPropositions9();
_StartupPropositions.helpStartupPropositions10();
_StartupPropositions.helpStartupPropositions11();
_StartupPropositions.helpStartupPropositions12();
}
if (Stella.currentStartupTimePhaseP(8)) {
Stella.finalizeSlots();
Stella.cleanupUnfinalizedClasses();
}
if (Stella.currentStartupTimePhaseP(9)) {
Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("LOGIC")))));
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT ZERO-VARIABLES-VECTOR VARIABLES-VECTOR (NEW VARIABLES-VECTOR :ARRAY-SIZE 0) :DOCUMENTATION \"Save space by structure-sharing zero-length variable vectors.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *PARTIAL-SUPPORT-COUNTER* INTEGER 0)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *OPERATOR-NAME-TO-SURROGATE-TABLE* (PROPERTY-LIST OF KEYWORD SURROGATE) (NEW PROPERTY-LIST :THE-PLIST (BQUOTE (:AND /PL-KERNEL-KB/@AND :OR /PL-KERNEL-KB/@OR :NOT /PL-KERNEL-KB/@NOT :FORALL /PL-KERNEL-KB/@FORALL :EXISTS /PL-KERNEL-KB/@EXISTS :EQUIVALENT /PL-KERNEL-KB/@EQUIVALENT :FAIL /PL-KERNEL-KB/@FAIL :COLLECT-INTO /PL-KERNEL-KB/@COLLECT-INTO :IMPLIES /PL-KERNEL-KB/@SUBSET-OF))) :DOCUMENTATION \"Maps names of KIF operators to relational surrogates.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *LOGIC-MODULE* MODULE (GET-STELLA-MODULE \"LOGIC\" TRUE) :PUBLIC? TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *PL-KERNEL-MODULE* MODULE (GET-STELLA-MODULE \"PL-KERNEL\" TRUE) :PUBLIC? TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *NOW-TIMESTAMP* TIMESTAMP 0 :DOCUMENTATION \"The NOW time stamp is incremented whenever a series\nof one or more updates is followed by a query.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *LAST-KB-ACTION* KEYWORD :UPDATE-PROPOSITION :DOCUMENTATION \"Records whether the last KB access was a query or\nan update. Used to determine when to increment the NOW time stamp\ncounter.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL BOTTOM LOGIC-OBJECT NULL :PUBLIC? TRUE :DOCUMENTATION \"The undefined individual. Denotes the non-existence of\nan individual in whatever slot it occupies.\")");
Logic.BOTTOM = Logic.createSkolem(null, Logic.SYM_LOGIC_BOTTOM);
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *EVALUATIONMODE* KEYWORD :EXTENSIONAL-ASSERTION :DOCUMENTATION \"Indicates the context for evaluating a proposition. One\nof :DESCRIPTION, :INTENSIONAL-ASSERTION, or :EXTENSIONAL-ASSERTION.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *CLIPPINGENABLED?* BOOLEAN TRUE :DOCUMENTATION \"When enabled, slot-value assertions can be retracted\nby later conflicting assertions.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *NATURALDEDUCTIONMODE?* BOOLEAN TRUE :DOCUMENTATION \"When enabled, blocks normalizations that significantly\nchange the behavior of inference rules.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *CONTEXT-DEPENDENT-SEARCH-MODE?* BOOLEAN FALSE :DOCUMENTATION \"Signals that we are performing search across multiple\ncontexts. Used to disable retraction from collections, since that increases\nthe overhead of the context mechanism.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *COMPUTEDQUERY?* BOOLEAN FALSE :DOCUMENTATION \"Used to signal 'ground-value-of' that it can\ncall 'bound-to' safely.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *SKOLEM-ID-COUNTER* INTEGER 0)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *VARIABLEIDCOUNTER* INTEGER 0)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *FREESKOLEMS* CONS NULL :DOCUMENTATION \"Cons-list of top-level existentially-quantified skolems.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT TRUE-TRUTH-VALUE TRUTH-VALUE (NEW TRUTH-VALUE :POLARITY :TRUE :STRENGTH :STRICT :POSITIVE-SCORE 1.0) :DOCUMENTATION \"Value representing TRUE.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT FALSE-TRUTH-VALUE TRUTH-VALUE (NEW TRUTH-VALUE :POLARITY :FALSE :STRENGTH :STRICT :POSITIVE-SCORE -1.0) :DOCUMENTATION \"Value representing FALSE.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT DEFAULT-TRUE-TRUTH-VALUE TRUTH-VALUE (NEW TRUTH-VALUE :POLARITY :TRUE :STRENGTH :DEFAULT :POSITIVE-SCORE 0.8) :DOCUMENTATION \"Value representing DEFAULT-TRUE.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT DEFAULT-FALSE-TRUTH-VALUE TRUTH-VALUE (NEW TRUTH-VALUE :POLARITY :FALSE :STRENGTH :DEFAULT :POSITIVE-SCORE -0.8) :DOCUMENTATION \"Value representing DEFAULT-FALSE.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT UNKNOWN-TRUTH-VALUE TRUTH-VALUE (NEW TRUTH-VALUE :POLARITY :UNKNOWN) :DOCUMENTATION \"Value representing UNKNOWN. Needed for those cases\nwhere we need a non-NULL truth value to represents UNKNOWN.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT INCONSISTENT-TRUTH-VALUE TRUTH-VALUE (NEW TRUTH-VALUE :POLARITY :INCONSISTENT :STRENGTH :STRICT) :DOCUMENTATION \"Value representing a contradiction.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *SUPPRESSUNTYPEDTYPEERROR?* BOOLEAN FALSE :DOCUMENTATION \"Used by 'safe-logical-type' to ask for a type\nwithout signalling an error if none exists.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *EQUIVALENCE-COLLECTIONS?* BOOLEAN TRUE :DOCUMENTATION \"Experiment with equality reasoning on collections.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT TRUE-PROPOSITION PROPOSITION (NEW PROPOSITION :KIND :CONSTANT :OPERATOR @TRUE :ARGUMENTS (NEW ARGUMENTS-VECTOR :ARRAY-SIZE 0) :TRUTH-VALUE TRUE-TRUTH-VALUE :HOME-CONTEXT *PL-KERNEL-MODULE*))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT FALSE-PROPOSITION PROPOSITION (NEW PROPOSITION :KIND :CONSTANT :OPERATOR @FALSE :ARGUMENTS (NEW ARGUMENTS-VECTOR :ARRAY-SIZE 0) :TRUTH-VALUE FALSE-TRUTH-VALUE :HOME-CONTEXT *PL-KERNEL-MODULE*))");
Logic.SGT_STELLA_TRUE.surrogateValue = Logic.TRUE_PROPOSITION;
Logic.SGT_STELLA_FALSE.surrogateValue = Logic.FALSE_PROPOSITION;
Proposition.findDuplicateProposition(Logic.TRUE_PROPOSITION);
Proposition.findDuplicateProposition(Logic.FALSE_PROPOSITION);
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT ANONYMOUS-VARIABLE-NAME SYMBOL (QUOTE ?) :DOCUMENTATION \"Variables with name 'ANONYMOUS-VARIABLE-NAME' are considered\nanonymous, and are not assumed to be identical to any other variable also named\n'ANONYMOUS-VARIABLE-NAME'.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *MISSING-KEY-VALUE-LIST* KEY-VALUE-LIST (NEW KEY-VALUE-LIST) :DOCUMENTATION \"Represents a key-value list that should never be used.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *AUTOMATICINSTANCETABLE* (KEY-VALUE-LIST OF SYMBOL LOGIC-OBJECT) *MISSING-KEY-VALUE-LIST* :DOCUMENTATION \"Used by 'evaluate-automatic-instance' to\nrecord current bindings of automatic instance symbols.\")");
HookList.addHook(Stella.$REDEFINE_RELATION_HOOKS$, Logic.SYM_LOGIC_TRANSFER_LOGIC_INFORMATION_FROM_RELATION_HOOK);
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *DEFAULTCREATIONTYPE* SURROGATE NULL)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *STRUCTURED-OBJECTS-INDEX* (KEY-VALUE-MAP OF INTEGER-WRAPPER (LIST OF CONTEXT-SENSITIVE-OBJECT)) (NEW KEY-VALUE-MAP) :DOCUMENTATION \"Contains a table of propositions and descriptions, indexed by a\nstructure hash code which might be shared by different objects.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *DONT-CHECK-FOR-DUPLICATE-PROPOSITIONS?* BOOLEAN FALSE :DOCUMENTATION \"If TRUE never check for the existence of duplicate\npropositions when building a new proposition.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *VISITEDUNFASTENEDDEFININGPROPOSITIONS* LIST NULL :DOCUMENTATION \"Used by 'recursively-fasten-down-propositions'.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *AUTO-COERCE-PROPOSITIONAL-ARGUMENTS?* BOOLEAN FALSE :DOCUMENTATION \"If TRUE, automatically coerce propositional arguments of a\nproposition, even if the corresponding argument type of the hosting relation\ndoesn't indicate that.\" :PUBLIC? TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *TYPE-CHECK-POLICY* KEYWORD :AUTOMATICALLY-FIX-TYPE-VIOLATIONS :DOCUMENTATION \"Three policies are implemented:\n :AUTOMATICALLY-FIX-TYPE-VIOLATIONS asserts missing types to fix type\n violations (default),\n :REPORT-TYPE-VIOLATIONS complains about missing or incorrect types,\n :SIGNAL-TYPE-VIOLATIONS throws exception for missing or incorrect types, and\n :IGNORE-TYPE-VIOLATIONS which disables all type checking.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *TYPECHECKMODE* KEYWORD :POST-TYPE-VIOLATIONS :DOCUMENTATION \"Controls the behavior of the type-checking\nroutines in the event that a type-check fails. Options are:\n :POST-TYPE-VIOLATIONS push offending proposition onto queue,\n :REPORT-TYPE-VIOLATIONS print occasions of failed type checks,\n :SIGNAL-TYPE-VIOLATIONS throw exception for failed type checks,\n :AUTOMATICALLY-FIX-TYPE-VIOLATIONS assert missing types on propositions, and\n :IGNORE-TYPE-VIOLATIONS don't perform any type checking at all.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *CHECK-TYPES-AGENDA* (VECTOR-SEQUENCE OF CHECK-TYPES-RECORD) (NEW VECTOR-SEQUENCE :ARRAY-SIZE 4) :DOCUMENTATION \"List of propositions that have failed a type check,\nbut might pass once finalization is complete.\")");
Symbol.registerNativeName(Logic.SYM_STELLA_ASSERT, Logic.KWD_CPP, Logic.KWD_FUNCTION);
HookList.addHook(Stella.$DEFINE_MODULE_HOOKS$, Logic.SYM_LOGIC_INTRODUCE_MODULE);
HookList.addHook(Stella.$CLEAR_MODULE_HOOKS$, Logic.SYM_LOGIC_CLEAR_LOGIC_MODULE_HOOK);
HookList.addHook(Stella.$DESTROY_CONTEXT_HOOKS$, Logic.SYM_LOGIC_DESTROY_LOGIC_CONTEXT_HOOK);
}
} finally {
Stella.$CONTEXT$.set(old$Context$000);
Stella.$MODULE$.set(old$Module$000);
}
}
} | 7 |
public void GenerateTiles(){
for(int l=0;l<WrittenBlockID.length;l++){
for(int h=0;h<WrittenBlockID[l].length;h++){
for(int w=0;w<WrittenBlockID[l][h].length;w++){
if(l==0){
WrittenBlockID[l][h][w]=1;
}else{
if(h==0){
WrittenBlockID[l][h][w]=2;
}else if(h==WrittenWorldH-1){
WrittenBlockID[l][h][w]=2;
}else if(w==0){
WrittenBlockID[l][h][w]=2;
}else if(w==WrittenWorldW-1){
WrittenBlockID[l][h][w]=2;
}else{
WrittenBlockID[l][h][w]=0;
}
}
}
}
}
} | 8 |
private void displayReview() {
ArrayList<Task> tasks = calendar.getTasks();
for (Task t : tasks) {
if (TaskService.isTaskToday(t)) {
System.out.println(t.toString());
}
}
} | 2 |
public ArrayList moves(Point point)
{
ArrayList a = new ArrayList();
Iterator it = point.neighbors().iterator();
while(true)
{
if (!it.hasNext())
break;
Point point1 = (Point) it.next();
if (isInBounds(point1) && isOpen(point1) && !isVisited(point1))
a.add(point1);
}
return a;
} | 5 |
public void setEmail(String email) {
this.email = email;
} | 0 |
private static void writeTextFile(Path path){
BufferedWriter bufferWriter=null;
try{
//apertura del stream. StandardOpenOption.CREATE->si el fichero no existe se crea
bufferWriter=Files.newBufferedWriter(path,
java.nio.charset.StandardCharsets.UTF_8, java.nio.file.StandardOpenOption.CREATE);
for (int i=0;i<Data.COD.length;i++){
bufferWriter.write(Data.COD[i]+";"+Data.DESC[i]+";"+Data.STOCK[i]+";"+Data.PRICE[i]);
bufferWriter.newLine();
}
System.out.println("Escritura fichero "+path.getFileName().toString()+ " finalizada");
readTextFile(path);
} catch (IOException ex) {
System.err.println("I/O Error: "+ex);
}finally{
//Se cierra el stream y se liberan los recursos de sistema asociados a él.
if (bufferWriter!=null)
try {
bufferWriter.close();
} catch (IOException ex) {
System.err.println("I/O Error: "+ex);
}
}
} | 4 |
private String assembleAuthority(
String host,
int port,
String userInfo,
String authority
) {
if (authority != null) {
return authority;
}
StringBuffer buf = new StringBuffer();
// UserInfo
if (userInfo != null) {
buf.append(userInfo);
buf.append(USERINFO_DELIM);
}
// Host. Note if the host is null then this URL will be malformed
if (host != null) {
buf.append(host);
}
// Port
if (port > 0) {
buf.append(PORT_DELIM);
buf.append(port);
}
return buf.toString();
} | 4 |
public int yCoordToRowNumber(int y) {
Insets insets = getInsets();
if (y < insets.top)
return -1;
double rowHeight = (double)(getHeight()-insets.top-insets.bottom) / rows;
int row = (int)( (y-insets.top) / rowHeight);
if (row >= rows)
return rows;
else
return row;
} | 2 |
public TSValue abstractRelationalComparison(final TSValue right)
{
TSNumber ny = right.toNumber();
// if nx is NaN return undefined
if (Double.isNaN(this.getInternal())){
return TSUndefined.value;
}
// if ny is NaN return undefined
else if (Double.isNaN(ny.getInternal()))
{
return TSUndefined.value;
}
// if nx and ny are equal, return false
// ( also covers +0 == -0 and -0 == +0 )
else if (this.getInternal() == ny.getInternal())
{
return TSBoolean.booleanFalse;
}
// if nx is +infinity return false
else if (this.getInternal() == Double.POSITIVE_INFINITY)
{
return TSBoolean.booleanFalse;
}
// if ny is +infinity return true
else if (ny.getInternal() == Double.POSITIVE_INFINITY)
{
return TSBoolean.booleanTrue;
}
// if ny is -infinity return false
else if (ny.getInternal() == Double.NEGATIVE_INFINITY)
{
return TSBoolean.booleanFalse;
}
// if nx is -infinity return true
else if (this.getInternal() == Double.NEGATIVE_INFINITY)
{
return TSBoolean.booleanTrue;
}
// else if nx < ny return true
else if (this.getInternal() < ny.getInternal())
{
return TSBoolean.booleanTrue;
}
// else return false
else
{
return TSBoolean.booleanFalse;
}
} | 8 |
private static int parseInt(String s) {
if (s.startsWith("0x")) {
return Integer.parseInt(s.substring(2), 16);
}
else {
return Integer.parseInt(s);
}
} | 1 |
public static void render(Entity e, Graphics2D g) {
Color oldColor = g.getColor();
Font oldFont = g.getFont();
if (e instanceof Asteroid) {
renderAsteroid((Asteroid) e, g);
} else if (e instanceof Ship) {
renderShip((Ship) e, g);
} else if (e instanceof Bullet) {
renderBullet((Bullet) e, g);
} else if (e instanceof Alien) {
renderAlien((Alien) e, g);
} else if (e instanceof Powerup) {
renderPowerup((Powerup) e, g);
} else if (e instanceof Particle) {
renderParticle((Particle) e, g);
}
g.setFont(oldFont);
g.setColor(oldColor);
} | 6 |
private void activateRow()
{
// Make sure the file exists (and that something is selected)
if(MainFrame.getInstance().selectedFile != null
&& MainFrame.getInstance().selectedFile.toFile().exists())
{
// Go into directories
if(MainFrame.getInstance().selectedFile.toFile().isDirectory())
{
logger.debug("Activated on folder: "
+ MainFrame.getInstance().selectedFile.toString());
// Set the new directory
MainFrame.getInstance().currentDirectory = MainFrame.getInstance().currentDirectory.resolve(MainFrame.getInstance().selectedFile.getFileName());
// And recreate the table
MainFrame.getInstance().redrawTable(MainFrame.getInstance().currentDirectory);
// Disable options that require a selected file
MainFrame.getInstance().menubar.copyToOption.setEnabled(false);
MainFrame.getInstance().menubar.revisionsOption.setEnabled(false);
MainFrame.getInstance().toolbar.upButton.setEnabled(true);
}
// Display revision window for files
else
{
logger.debug("Activated on file: "
+ MainFrame.getInstance().selectedFile.toString());
RevisionDialog revisionWindow = new RevisionDialog(
FileOp.convertPath(MainFrame.getInstance().selectedFile));
revisionWindow.setLocationRelativeTo(MainFrame.getInstance());
revisionWindow.setModalityType(ModalityType.APPLICATION_MODAL);
revisionWindow.setVisible(true);
}
}
else if(MainFrame.getInstance().selectedFile != null)
{
Errors.nonfatalError("The selected file no longer exists.");
}
} | 4 |
public boolean resetPasswordWithToken(Token t, User u, Map<String,String> parameters)
{
if (!parameters.containsKey("password") || !parameters.containsKey("reset_token"))
{
GoCoin.log(new Exception("Invalid parameters for resetPasswordWithToken!"));
return false;
}
//TODO: pull out map keys as constants
String path = "/users/"+u.getId()+"/reset_password/"+parameters.get("reset_token");
//get a new http client and set the options
//NOTE: since its a post request, the parameters get converted into JSON
HTTPClient client = GoCoin.getHTTPClient();
client.setRequestOption(HTTPClient.KEY_OPTION_PATH,path);
client.setRequestOption(HTTPClient.KEY_OPTION_METHOD,HTTPClient.METHOD_PUT);
client.addAuthorizationHeader(t);
//create the json map
Map<String,String> body = new LinkedHashMap<String,String>();
body.put("password",parameters.get("password"));
body.put("password_confirmation",parameters.get("password"));
//set the body
client.setRequestBody(GoCoin.toJSON(body));
try
{
//make the PUT request
client.doPUT(client.createURL(HTTPClient.URL_TYPE_API));
//check the response
GoCoin.checkResponse(client);
//return true if we got a 204
return true;
}
catch (Exception e)
{
GoCoin.log(e);
return false;
}
} | 3 |
public boolean hasChild(String child_key) {
String[] split = child_key.split("[.]", 2);
// This should never occur but just in case
if (split.length == 0) {
return false;
} else if (split.length == 1) { // child key was a single name
return children.containsKey(child_key);
} else if ((split.length > 1) && (split[0] == key)) { // Child key was qualified with this nodes name
return hasChild(split[1]);
} else if ((split.length > 1) && children.containsKey(split[0])) { // Child key is a child of a child
// If the root key is not a group then the key is invalid
if (!children.get(split[0]).isGroup()) {
return false;
}
try {
ParameterGroup child = (ParameterGroup) children.get(split[0]);
return child.hasChild(split[1]);
} catch (Exception e) {
return false;
}
}
return false;
} | 8 |
public final double nextDouble()
{
if(mti >= 624)
{
int i2;
for(i2 = 0; i2 < 227; i2++)
{
int i = mt[i2] & 0x80000000 | mt[i2 + 1] & 0x7fffffff;
mt[i2] = mt[i2 + 397] ^ i >>> 1 ^ mag01[i & 1];
}
for(; i2 < 623; i2++)
{
int j = mt[i2] & 0x80000000 | mt[i2 + 1] & 0x7fffffff;
mt[i2] = mt[i2 + -227] ^ j >>> 1 ^ mag01[j & 1];
}
int k = mt[623] & 0x80000000 | mt[0] & 0x7fffffff;
mt[623] = mt[396] ^ k >>> 1 ^ mag01[k & 1];
mti = 0;
}
int l = mt[mti++];
l ^= l >>> 11;
l ^= l << 7 & 0x9d2c5680;
l ^= l << 15 & 0xefc60000;
l ^= l >>> 18;
if(mti >= 624)
{
int j2;
for(j2 = 0; j2 < 227; j2++)
{
int i1 = mt[j2] & 0x80000000 | mt[j2 + 1] & 0x7fffffff;
mt[j2] = mt[j2 + 397] ^ i1 >>> 1 ^ mag01[i1 & 1];
}
for(; j2 < 623; j2++)
{
int j1 = mt[j2] & 0x80000000 | mt[j2 + 1] & 0x7fffffff;
mt[j2] = mt[j2 + -227] ^ j1 >>> 1 ^ mag01[j1 & 1];
}
int k1 = mt[623] & 0x80000000 | mt[0] & 0x7fffffff;
mt[623] = mt[396] ^ k1 >>> 1 ^ mag01[k1 & 1];
mti = 0;
}
int l1 = mt[mti++];
l1 ^= l1 >>> 11;
l1 ^= l1 << 7 & 0x9d2c5680;
l1 ^= l1 << 15 & 0xefc60000;
l1 ^= l1 >>> 18;
return (double)(((long)(l >>> 6) << 27) + (long)(l1 >>> 5)) / 9007199254740992D;
} | 6 |
public void launch(int threads){
service = Executors.newFixedThreadPool(threads);
for (int i = 0; i < tblData.size(); i++) {
String url = tblData.get(i)[0];
Runnable worker = new WebWorker(url, i, frame);
if (!Thread.interrupted()) {
service.submit(worker);
} else {
break;
}
}
service.shutdown();
} | 2 |
public void put(String key, Object value) {
// если корня нет - вставить в корень
if (root == null) {
Node newNode = new Node(key, value);
root = newNode;
} else {
boolean inserted = false;
Node currentNode = root;
while (!inserted) {
int compare = key.compareTo(currentNode.getKey());
// если совпадает
if (compare == 0) {
// заменить значение
currentNode.setValue(value);
// выйти из метода
inserted = true;
} else if (compare < 0) {
// если меньше
// перейти к левому элементу
if (currentNode.getLeftChild() == null) {
Node newNode = new Node(key, value);
currentNode.setLeftChild(newNode);
inserted = true;
} else {
currentNode = currentNode.getLeftChild();
}
} else if (compare > 0) {
// если больше
// перейти к правому элементу
if (currentNode.getRightChild() == null) {
Node newNode = new Node(key, value);
currentNode.setRightChild(newNode);
inserted = true;
} else {
currentNode = currentNode.getRightChild();
}
}
}
}
} | 7 |
private int hash(PageId pageNo) {
return (pageNo.pid % HTSIZE);
} // end hash() | 0 |
public int threeSumClosest(int[] num, int target) {
Arrays.sort(num);
int mx =num[0]+num[1]+num[2];
int sum =0;
int length = num.length;
for (int i = 0; i < length-2; i++) {
int j = i + 1;
int k = length - 1;
while (j < k) {
sum = num[i] +num[j] + num[k];
if (Math.abs(target - mx) > Math.abs(target - sum)) {
mx = sum;
if (mx == target) return mx;
}
if (sum > target)
k-- ;
else
j++;
}
}
return mx;
} | 5 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Prescale other = (Prescale) obj;
if (moduloDivide == null) {
if (other.moduloDivide != null)
return false;
}
else if (!moduloDivide.equals(other.moduloDivide))
return false;
if (multiplier == null) {
if (other.multiplier != null)
return false;
}
else if (!multiplier.equals(other.multiplier))
return false;
return true;
} | 9 |
private void grow() {
Bucket[] oldBuckets = buckets;
int newCap = buckets.length * 2 + 1;
threshold = (int) (loadFactor * newCap);
buckets = new Bucket[newCap];
for (int i = 0; i < oldBuckets.length; i++) {
Bucket nextBucket;
for (Bucket b = oldBuckets[i]; b != null; b = nextBucket) {
if (i != Math.abs(b.hash % oldBuckets.length))
throw new RuntimeException("" + i + ", hash: " + b.hash
+ ", oldlength: " + oldBuckets.length);
int newSlot = Math.abs(b.hash % newCap);
nextBucket = b.next;
b.next = buckets[newSlot];
buckets[newSlot] = b;
}
}
} | 3 |
public World getCurrentWorld() {
return currentWorld;
} | 0 |
private void noloteFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_noloteFieldKeyTyped
// TODO add your handling code here:
if (!Character.isLetterOrDigit(evt.getKeyChar()) && !Character.isISOControl(evt.getKeyChar()) && evt.getKeyChar() !='-' && evt.getKeyChar() != '.')
{
Toolkit.getDefaultToolkit().beep();
evt.consume();
}
if(noloteField.getText().length() == 45)
{
Toolkit.getDefaultToolkit().beep();
evt.consume();
JOptionPane.showMessageDialog(this, "Numero de lote demadiado largo.", "ADVERTENCIA", WIDTH);
}
}//GEN-LAST:event_noloteFieldKeyTyped | 5 |
public static void inputFleet(Player p){
String nameBoat = "";
for(int i=0; i<GameConfiguration.gameConfiguration_NBSHIP; i++){
boolean add = false;
while(!add) {
Ship s = null;
System.out.println(Game.display(p.myGrid.displayOwnGrid()));
switch(i) {
case 0:
nameBoat = "Get ready to place your Destroyer (Size 2)";
break;
case 1:
nameBoat = "Get ready to place your Submarine (Size 3)";
break;
case 2:
nameBoat = "Get ready to place your Battleship (Size 4)";
break;
}
System.out.println(nameBoat);
String msg = "Please enter the couple of coordinate of ship (like 'A1'): "; //+ count
String msgOrient = "Please enter the orientation of the ship (H or V)";
int coord [] = PlayerInput.readCoordinate(msg);
char orient = PlayerInput.readOrientation(msgOrient);
switch(i) {
case 0:
s = new Destroyer(coord[0],coord[1],orient);
break;
case 1:
s = new Submarine(coord[0],coord[1],orient);
break;
case 2:
s = new Battleship(coord[0],coord[1],orient);
break;
}
add = p.addShip(s);
if(!add) {
System.out.println("/!\\You can't add this ship at the defined position.\n");
Scanner sc = new Scanner(System.in);
sc.nextLine();
}
}
}
} | 9 |
public void optionsChangedListener() {
volume = Application.get().getOptions().soundVolume();
musicVolume = Application.get().getOptions().musicVolume();
for(IntBuffer source : sources) {
AL10.alSourcef(source.get(0), AL10.AL_GAIN, volume);
}
if(currentMusic != null) {
AL10.alSourcef(currentMusic.get(0), AL10.AL_GAIN, musicVolume);
}
} | 2 |
public static void main(String arguments[]){
try{
if(arguments != null && arguments.length > 0 && "--help".equalsIgnoreCase(arguments[0])){
log.info(ArgsParser.help);
return;
}
Args args = new ArgsParser().parse(arguments);
printArgs(args);
AutoCode autoCode = new AutoCode();
autoCode.run(args);
}catch(InvalidParameterException e){
log.error(e);
log.error("-------------------------------help-----------------------------\n"+ArgsParser.help);
}
catch(Exception e){
log.error(e);
}
} | 5 |
final public Sort[] CobSortsDecl(Module module) throws ParseException {
Sort[] sorts;
Vector vec = new Vector();
Sort sort;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case SORT:
jj_consume_token(SORT);
break;
case SORTS:
jj_consume_token(SORTS);
break;
default:
jj_la1[181] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
label_65:
while (true) {
sort = SortReference(module);
vec.addElement(sort);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case INTEGER_LITERAL:
case IDENTIFIER:
;
break;
default:
jj_la1[182] = jj_gen;
break label_65;
}
}
jj_consume_token(DOT);
sorts = new Sort[vec.size()];
vec.copyInto(sorts);
{if (true) return sorts;}
throw new Error("Missing return statement in function");
} | 8 |
TetrisPiece()
{
int type = (int) (NumBrickTypes * Math.random() ); //rand() % globals.NumBrickTypes;
int pose = (int) (NumPoses * Math.random() );//rand() % globals.NumPoses;
brickType = type;
brickPose = pose;
width = bricks[type][pose].w;
height = bricks[type][pose].h;
xposition = COLS/2 - 1;
yposition = ROWS - STAGING_ROWS;
int counter = 0;
for( int i = 0; i < width; i++)
for( int j = 0; j < height; j++)
{
String tempRow = bricks[type][pose].grid[j];
if( tempRow.charAt(i) == 'X' )
{
xvalues[counter] = xposition + i;
yvalues[counter] = yposition + j;
counter++;
}
}
assignColor();
} | 3 |
public FileChangeEvent(Environment environment, File oldFile) {
super(environment);
this.oldFile = oldFile;
} | 0 |
@Override
//public int getDistribution(double standardDeviation)
public int getDistribution()
{
//*********************
//mean = this.mean();
//*********************
//keeps track of packets created
int PacketCounter = 0;
int[] a =new int[inputbuffersize];
int val;
//for (int i=0;i<EDarray.length;i++)
while (PacketCounter < NumberOfPackets)
{
val = (int) Math.round((-mean) * Math.log(rand.nextDouble()));
if (val >=0 && val<=inputbuffersize-1)
{
//EDarray[i]=val;
//add each value to the distribution array
EDarray.add(val);
a[val] +=1;
//count packet
PacketCounter += 1;
}
// System.out.print(EDarray[i]+ " ");
}
//for(Object x:EDarray)
//{
// System.out.print((int)x+" ");
//}
//System.out.println("\n-----------");
//***************
int total = 0;
//***************
for(int x:a)
//for(Object x:EDarray)
{
//System.out.print(x+" ");
q.add(x);
//***************
total += x;
//***************
}
//***************
//System.out.println("\n<Total>: "+total);
//***************
//System.out.println("<E N D>\n");
/*
List lst = Arrays.asList(a);
q.addAll(lst);
*/
//clear array distribution
EDarray.clear();
return -1;
} | 4 |
@Override
public void keyPressed(KeyEvent paramKeyEvent) {
int id = paramKeyEvent.getKeyCode();
if (id == KeyEvent.VK_Q) {
currenth = "blackmage";
}
else if (id == KeyEvent.VK_W) {
currenth = "ninja";
}
else if (id == KeyEvent.VK_E) {
currenth = "warrior";
}
else if (id == KeyEvent.VK_R) {
currenth = "dragoon";
}
else if (id == KeyEvent.VK_T) {
currenth = "whitemage";
}
} | 5 |
public Server() {
ExecutorService executor = null;
ServerSocket serverSocket = null;
try {
/**
* Создание сокета сервера для заданного порта
* */
serverSocket = new ServerSocket(PORT);
System.out.println("Waiting");
/**
* Создание пула с числом потоков, равному AMOUNT_OF_THREADS
* */
executor = Executors.newFixedThreadPool(MAX_AMOUNT_OF_THREADS);
while (true) {
/**
* Выполнение метода, который обеспечивает подключение сервера к
* клиенту
* */
Socket s = serverSocket.accept();
/**
* Запуск нового потока
* */
executor.execute(new Thread(s));
}
} catch (IOException e) {
System.err.println("Can't use " + PORT);
e.printStackTrace();
} finally {
/**
* Выход по завершению всех потоков
* */
if (executor != null) {
executor.shutdown();
}
}
} | 3 |
private List<Itemset> aprioriGen(List<Itemset> seed, int k) {
List<Itemset> candidateList;
// Populate candidate large itemsets by either a sql query
// or hand-written main-memory join algorithm
if (usesql) {
DBAccess db = new DBAccess();
//this returns a new candidate list
candidateList = db.populateLargeItemSet(seed, k);
}
else {
// do the join in the memory, it returns a new candidate list
candidateList = populateLargeItemSet(seed, k);
}
/*
* Optimize by evaluating subsets of each candidate of size k-1. If any candidate's subsets
* are not contained in the seed, delete that candidate
*/
List<Itemset> removeList = new ArrayList<Itemset>();
for (Itemset is : candidateList)
{
boolean remove = false;
List<Itemset> subsets = populateSubsets(is, k);
for (Itemset subsetIs : subsets) {
boolean isFound = false;
for (Itemset seedIs : seed) {
if (seedIs.containsSameItems(subsetIs)) {
isFound = true;
break;
}
}
if (!isFound) {
remove = true;
break;
}
}
if (remove)
removeList.add(is);
}
candidateList.removeAll(removeList);
return candidateList;
} | 7 |
protected TextIDPair readNextDocText(BufferedReader docIn) throws IOException{
String line = docIn.readLine();
// find the beginning of the document
while( line != null &&
!line.startsWith(".I") ){
line = docIn.readLine();
}
if( line == null ){
return null;
}else{
// figure out what the docID is
String[] parts = line.split("\\s+");
if( parts.length != 2 ){
throw new RuntimeException("CranfieldReader::Problems finding docID: " + line);
}
int docID = Integer.parseInt(parts[1]);
line = docIn.readLine();
// find the beginning of the text
while( line != null &&
!line.startsWith(".W") ){
line = docIn.readLine();
}
if( line == null ){
return null;
}else{
StringBuffer buffer = new StringBuffer();
line = docIn.readLine();
// grab all the text between <DOC> and </DOC>
while( line != null &&
!line.equals("<END_DOC>") ){
buffer.append(" " + line);
line = docIn.readLine();
}
return new TextIDPair(buffer.toString(), docID);
}
}
} | 9 |
public CharSeqHelper(CharSequence... charSequences)
{
s = new StringBuilder();
for(CharSequence c : charSequences)
{
s.append(c);
}
} | 1 |
public static void main(String[] args) throws Exception {
//Verify arguments
if (args.length != 5) {
usage();
}
DatagramSocket mailbox = null;
String serverHost = null;
int serverPort = 0;
String clientHost = null;
int clientPort = 0;
String name = null;
try {
//Create the socket
name = args[0];
clientHost = args[1];
clientPort = Integer.parseInt(args[2]);
serverHost = args[3];
serverPort = Integer.parseInt(args[4]);
mailbox = new DatagramSocket
(new InetSocketAddress (clientHost, clientPort));
}
catch (Exception e) {
usage();
}
//Create the objects and set the appropriate listeners
final ModelProxy proxy = new ModelProxy(mailbox,
new InetSocketAddress (serverHost, serverPort));
FifteenView view = new FifteenView(name);
view.setViewListener(proxy);
proxy.setModelListener(view);
//Handle timeouts
Runtime.getRuntime().addShutdownHook (new Thread() {
public void run() {
proxy.quit();
}
});
} | 2 |
public synchronized void bake() {
if (events != null) return; // don't re-bake when still valid
List<RegisteredListener> entries = new ArrayList<RegisteredListener>();
for (Entry<Priority, ArrayList<RegisteredListener>> entry : muffinbag.entrySet()) {
entries.addAll(entry.getValue());
}
events = entries.toArray(new RegisteredListener[entries.size()]);
} | 2 |
public JDBCConnect() {
String driver = "com.mysql.jdbc.Driver";
String artlcle_url = "jdbc:mysql://localhost:3306/zhangyu_sca";
String user = "root";
String password = "root";
try {
Class.forName(driver);
Connection article_conn = DriverManager.getConnection(artlcle_url, user, password);
if (article_conn.isClosed()) {
System.out.println("False connect database");
}
article_ste = article_conn.createStatement();
tags_ste = article_conn.createStatement();
content_ste = article_conn.createStatement();
article_url = article_conn.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
} | 2 |
private void CheckViolentSpeech(String message, String sender, String channel)
{
for(String word: m_ViolentWords)
{
if(message.toLowerCase().contains(word))
{
sendMessage(channel, "Nana, sowas sagt man aber nicht, " + sender);
break;
}
}
} | 2 |
public boolean exist2Rec(char[][] board, String word, int pos, int i, int j){
if(pos == word.length()) return true;
if(isValidIdx(i, j) && !visited[i][j] && pos < word.length() && board[i][j] == word.charAt(pos)){
visited[i][j] = true;
if(exist2Rec(board, word, pos+1, i-1, j)) return true;
if(exist2Rec(board, word, pos+1, i+1, j)) return true;
if(exist2Rec(board, word, pos+1, i, j-1)) return true;
if(exist2Rec(board, word, pos+1, i, j+1)) return true;
visited[i][j] = false;
}
return false;
} | 9 |
static protected void FillBuff() throws java.io.IOException
{
if (maxNextCharInd == available)
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = maxNextCharInd = 0;
available = tokenBegin;
}
else if (tokenBegin < 0)
bufpos = maxNextCharInd = 0;
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
int i;
try {
if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
--bufpos;
backup(0);
if (tokenBegin == -1)
tokenBegin = bufpos;
throw e;
}
} | 9 |
public Pair getCrossoverPoints(int delta){
Pair pair = new Pair();
int len = this.bins.size();
if(len == 0)
return null;
pair.x = randRange(0, len - 1);
if(pair.x == (len - 1 )){
pair.y = len;
} else {
pair.y = randRange(pair.x, pair.x + delta);
}
return pair;
} | 2 |
public void InsertaInicio (int ElemInser)
{
if (VaciaLista())
{
PrimerNodo = new NodosProcesos (ElemInser);
PrimerNodo.siguiente = PrimerNodo;
}
else
{
NodosProcesos Nuevo = new NodosProcesos(ElemInser);
NodosProcesos Aux = PrimerNodo;
while (Aux.siguiente !=PrimerNodo)
Aux = Aux.siguiente;
Aux.siguiente = Nuevo;
Nuevo.siguiente = PrimerNodo;
PrimerNodo = Nuevo;
}
} | 2 |
public Causa ingresoTestigoPorTeclado(){
@SuppressWarnings("resource")
Scanner scanner = new Scanner (System.in);
String texto;
int expediente;
Long dni;
Causa causa = new Causa();
try {
System.out.println("Agregar Testigo a Causa");
System.out.println("-----------------------");
while (true) {
try {
System.out.print("Ingrese Numero de Expediente: ");
expediente = scanner.nextInt();
causa = this.getCausaByNumero(expediente);
if (causa == null) {
System.out.println("No existe ninguna Causa con Expediente " + expediente + ".Intente nuevamente");
} else {
break;
}
} catch (RangeException e) {
System.out.println(e.getMessage());
}
}
System.out.println("Datos de la Causa");
System.out.println("-----------------");
System.out.println(causa);
scanner = new Scanner (System.in);
while (true) {
try {
System.out.print("Ingrese el DNI del Testigo a agregar a la Causa o presione [ENTER] para continuar: ");
texto = scanner.nextLine();
if (texto.length()>0) {
dni=Long.parseLong(texto);
if (dni>0)
causa.addTestigo(dni);
}
break;
} catch (NumberFormatException e) {
System.out.println("El DNI del Testigo debe ser numerico");
} catch (ExcepcionValidacion e) {
System.out.println(e.getMessage());
}
}
return causa;
} catch (Exception e) {
System.out.printf("ERROR EN EL SISTEMA: %s",e);
return null;
}
} | 9 |
public static TextBuffer listToJava(List<Exprent> lst, int indent, BytecodeMappingTracer tracer) {
if (lst == null || lst.isEmpty()) {
return new TextBuffer();
}
TextBuffer buf = new TextBuffer();
for (Exprent expr : lst) {
TextBuffer content = expr.toJava(indent, tracer);
if (content.length() > 0) {
if (expr.type != Exprent.EXPRENT_VAR || !((VarExprent)expr).isClassDef()) {
buf.appendIndent(indent);
}
buf.append(content);
if (expr.type == Exprent.EXPRENT_MONITOR && ((MonitorExprent)expr).getMonType() == MonitorExprent.MONITOR_ENTER) {
buf.append("{}"); // empty synchronized block
}
if (endsWithSemicolon(expr)) {
buf.append(";");
}
buf.appendLineSeparator();
tracer.incrementCurrentSourceLine();
}
}
return buf;
} | 9 |
@GET
@Path("/{repoName}/prime")
@Produces(MediaType.TEXT_PLAIN)
public String primeRepositoryCache(
@PathParam("repoName") String repoName,
@Context HttpServletRequest request) {
try {
dao.primeCache(getBaseUrl(request), repoName);
}
catch (Exception e) {
logger.log(Level.SEVERE, "Failed to prime repo cache: {0}", e.getMessage());
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
return "Repo cache for " + repoName + " primed!";
} | 1 |
@Override
public void displayLog(String[] presentStatusLog) {
for (String s : presentStatusLog) {
logModel.addElement(s);
}
} | 1 |
public boolean validBlackMovement(double x1, double y1, double x2, double y2, Square newSquare)
{
boolean move = false;
if( ((x2 == x1) && (y2 == y1 - PAWN_MOVEMENT_RESTRICTION)) && newSquare.getPiece().getPieceType() == "-")
{
move = true;
super.setHasMoved(true);
}
else if( ((x2 == x1 && (y1 == BLACK_PAWN_Y_STARTING_SPOT)) && (y2 == y1 - STARTING_PAWN_MOVEMENT_RESTRICTION) && !(super.hasMoved)
&& newSquare.getPiece().getPieceType() == "-"))
{
move = true;
super.setHasMoved(true);
}
return move;
} | 8 |
@Override
public void mouseDragged(MouseEvent e)
{
if (graphComponent.isEnabled() && isEnabled() && !e.isConsumed()
&& first != null)
{
mxRectangle dirty = current;
current = new mxRectangle(first.x, first.y, 0, 0);
current.add(new mxRectangle(e.getX(), e.getY(), 0, 0));
if (dirty != null)
{
dirty.add(current);
}
else
{
dirty = current;
}
Rectangle tmp = dirty.getRectangle();
int b = (int) Math.ceil(lineWidth);
graphComponent.getGraphControl().repaint(tmp.x - b, tmp.y - b,
tmp.width + 2 * b, tmp.height + 2 * b);
e.consume();
}
} | 5 |
protected void onUpdateTetris( int keyCode ) {
long time = System.currentTimeMillis();
if ( keyCode != 0 ) {
int dir = Block.DOWN;
switch ( keyCode ) {
case KeyEvent.VK_LEFT:
dir = Block.LEFT;
break;
case KeyEvent.VK_RIGHT:
dir = Block.RIGHT;
break;
case KeyEvent.VK_DOWN:
dir = Block.DOWN;
break;
case KeyEvent.VK_SPACE:
dir = Block.TURN;
break;
}
execTetris( dir );
} else {
if ( time - _tetrisStart > BLOCK_MOVE_TIME ) {
execTetris( Block.DOWN );
_tetrisStart = time;
}
}
} | 6 |
protected double[] makeDistribution() throws Exception {
double total = 0;
double[] distribution = new double[m_TrainBags.numClasses()];
boolean debug = false;
total = (double)m_TrainBags.numClasses() / Math.max(1, m_TrainBags.numInstances());
for(int i = 0; i < m_TrainBags.numClasses(); i++){
distribution[i] = 1.0 / Math.max(1, m_TrainBags.numInstances());
if(debug) System.out.println("distribution[" + i + "]: " + distribution[i]);
}
if(debug)System.out.println("total: " + total);
for(int i = 0; i < m_TrainBags.numClasses(); i++){
distribution[i] += m_References[i];
distribution[i] += m_Citers[i];
}
total = 0;
//total
for(int i = 0; i < m_TrainBags.numClasses(); i++){
total += distribution[i];
if(debug)System.out.println("distribution[" + i + "]: " + distribution[i]);
}
for(int i = 0; i < m_TrainBags.numClasses(); i++){
distribution[i] = distribution[i] / total;
if(debug)System.out.println("distribution[" + i + "]: " + distribution[i]);
}
return distribution;
} | 8 |
private QueueInterface<T> checkPostfix(QueueInterface<T> postfix) throws DAIllegalArgumentException, DAIndexOutOfBoundsException, BadPostfixException
{
if(postfix.getSize() < 3 && (postfix.getSize()%2) == 1)//makes sure the size of infix is greater than 3 and is an odd number
{
throw new BadPostfixException();
}
QueueInterface<T> newPostfix = new DynamicArray<T>();
if(((String)postfix.getFront()).matches(OPERATOR))//first element can't be an operator
{
throw new BadPostfixException();
}
newPostfix.addLast(postfix.removeFront());
newPostfix.addLast(postfix.removeFront());
while(postfix.getSize() != 0)
{
if(postfix.getSize() == 1)
{
if(((String)postfix.getFront()).matches(OPERAND)) //second element can't be an operator
{
throw new BadPostfixException();
}
}
if(!(((String)postfix.getFront()).matches(OPERAND) || ((String)postfix.getFront()).matches(OPERATOR)))
{
throw new BadPostfixException();
}
newPostfix.addLast(postfix.removeFront());
}
return newPostfix;
} | 8 |
public boolean checkPasswd(String id, String passwd) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConnection();
pstmt = conn
.prepareStatement("select password from member where id=?");
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if (rs.next()) {
if (passwd.equals(rs.getString(1))) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return false;
} | 9 |
private void initializeArrayField(JimpleBody new_body, SootField f, String type, Local local2, Value prev_val) {
if( type!= null && type.equals("int")){
Stmt assStmt = Jimple.v().newAssignStmt( prev_val,
Jimple.v().newInstanceFieldRef(local2, f.makeRef()));
SootMethod m = Scene.v().getMethod("<java.util.Arrays: void fill(int[],int)>");
List l = new ArrayList();
l.add(prev_val);
l.add(IntConstant.v(0));
Stmt insertStmt = Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr( m.makeRef(),l));
new_body.getUnits().addLast(assStmt);
new_body.getUnits().addLast(insertStmt);
}
if( type!= null && type.equals("float")){
Stmt assStmt = Jimple.v().newAssignStmt( prev_val,
Jimple.v().newInstanceFieldRef(local2, f.makeRef()));
SootMethod m = Scene.v().getMethod("<java.util.Arrays: void fill(float[],float)>");
List l = new ArrayList();
l.add(prev_val);
l.add(FloatConstant.v(0));
Stmt insertStmt = Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr( m.makeRef(),l));
new_body.getUnits().addLast(assStmt);
new_body.getUnits().addLast(insertStmt);
}
field_to_be_ini.remove(f);
} | 4 |
public void print_classifier() {
int c, f, i, j;
for (c = 0; c < classes; c++) {
System.out.println(data.classlist[c]+":");
for (f = 0; f < features; f++) {
System.out.print(" "+f+"{");
for (i = 0; i < iterations; i++) {
System.out.print(i+"[");
for (j = 0; j < classifiers[c][f][i].value.length; j++) {
System.out.print(classifiers[c][f][i].interval[j]+"-"+classifiers[c][f][i].interval[j+1]+":"+classifiers[c][f][i].value[j]+", ");
}
System.out.print("] ");
}
System.out.println("}");
}
}
} | 4 |
public void addPointObject(SVGCircleElement graphic) throws XPathExpressionException, DOMException {
String osmNamespace = xpath.getNamespaceContext().getNamespaceURI("osm");
SVGOMTextElement text = (SVGOMTextElement) xpath.evaluate("//svg:g[@id='map']/svg:text[(@k='species' or contains(@class, 'caption-core') or contains(@class, 'caption')) and @osm:id='"+graphic.getAttributeNS(osmNamespace, "id")+"']", doc, XPathConstants.NODE);
LabeledPointGene gene = new LabeledPointGene(graphic, text);
if (gene.isFeasiblePositionAvailable(avoids)) {
baseGenome.add(gene);
} else {
gene.discard();
}
} | 1 |
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == submit) {
// Window work
game.getControlPanel().setSubmitted(true);
HumanPlayer humanPlayer = (HumanPlayer) game.getPlayers().get(0);
humanPlayer.setHumanMustFinish(false);
setVisible(false);
game.getBoard().unhighlightTargets();
String selectedPerson = (String) peoplePossibilities.getSelectedItem();
String selectedRoom = (String) roomsPossibilities.getSelectedItem();
String selectedWeapon = (String) weaponsPossibilities.getSelectedItem();
// Process the accusation
boolean winner = game.checkAccusation(new Solution(selectedPerson, selectedWeapon, selectedRoom));
if (winner) {
JOptionPane.showMessageDialog(game,"You win!", "Accusation", JOptionPane.INFORMATION_MESSAGE);
// Logic to stop game progression
}
else {
JOptionPane.showMessageDialog(game,"Sorry, that is not correct", "Accusation", JOptionPane.INFORMATION_MESSAGE);
}
}
else if (e.getSource() == cancel) {
setVisible(false);
}
} | 3 |
private float calculateTBonds() {
int n = model.tBonds.size();
if (n <= 0)
return 0;
TBond tBond;
float energy = 0;
synchronized (model.tBonds) {
for (int i = 0; i < n; i++) {
tBond = model.tBonds.get(i);
atom1 = tBond.getAtom1();
atom2 = tBond.getAtom2();
atom3 = tBond.getAtom3();
atom4 = tBond.getAtom4();
if (!atom1.isMovable() && !atom2.isMovable() && !atom3.isMovable() && !atom4.isMovable())
continue;
angle = tBond.getAngle();
strength = tBond.getStrength();
rxij = atom1.rx - atom2.rx;
ryij = atom1.ry - atom2.ry;
rzij = atom1.rz - atom2.rz;
vector1.set(rxij, ryij, rzij);
rxlk = atom4.rx - atom3.rx;
rylk = atom4.ry - atom3.ry;
rzlk = atom4.rz - atom3.rz;
vector2.set(rxlk, rylk, rzlk);
rijsq = rxij * rxij + ryij * ryij + rzij * rzij;
rlksq = rxlk * rxlk + rylk * rylk + rzlk * rzlk;
rij = (float) Math.sqrt(rijsq);
rlk = (float) Math.sqrt(rlksq);
sr2 = rxij * rxlk + ryij * rylk + rzij * rzlk;
theta = vector1.angle(vector2);
sintheta = (float) Math.sin(theta);
if (Math.abs(sintheta) < MIN_SINTHETA) {// zero or 180 degree disaster
sintheta = sintheta > 0 ? MIN_SINTHETA : -MIN_SINTHETA;
}
sr12 = (float) Math.sin(tBond.getPeriodicity() * theta - tBond.getAngle());
sr6 = 0.5f * tBond.getPeriodicity() * strength * sr12 / (rij * rlk * sintheta);
rijsq = 1.0f / rijsq;
rlksq = 1.0f / rlksq;
fxi = sr6 * (rxlk - sr2 * rxij * rijsq);
fyi = sr6 * (rylk - sr2 * ryij * rijsq);
fzi = sr6 * (rzlk - sr2 * rzij * rijsq);
fxl = sr6 * (rxij - sr2 * rxlk * rlksq);
fyl = sr6 * (ryij - sr2 * rylk * rlksq);
fzl = sr6 * (rzij - sr2 * rzlk * rlksq);
inverseMass1 = GF_CONVERSION_CONSTANT / atom1.mass;
inverseMass2 = GF_CONVERSION_CONSTANT / atom2.mass;
inverseMass3 = GF_CONVERSION_CONSTANT / atom3.mass;
inverseMass4 = GF_CONVERSION_CONSTANT / atom4.mass;
atom1.fx += fxi * inverseMass1;
atom1.fy += fyi * inverseMass1;
atom1.fz += fzi * inverseMass1;
atom4.fx += fxl * inverseMass4;
atom4.fy += fyl * inverseMass4;
atom4.fz += fzl * inverseMass4;
atom2.fx -= fxi * inverseMass2;
atom2.fy -= fyi * inverseMass2;
atom2.fz -= fzi * inverseMass2;
atom3.fx -= fxl * inverseMass3;
atom3.fy -= fyl * inverseMass3;
atom3.fz -= fzl * inverseMass3;
// note that we use 1-cos(...) instead of 1+cos(...) as used on the following page:
// http://en.wikipedia.org/wiki/AMBER
// This reduced the equilibrium energy to zero, as in the case of radial and angular bonds
energy += strength * (1.0f - Math.cos(tBond.getPeriodicity() * theta - tBond.getAngle()));
}
}
return 0.5f * energy;
} | 8 |
public Frame3() {
try{
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL,USER, PASS);
statement = conn.createStatement();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
setTitle("KutaRaya, 19 - 31");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(350, 50, 739, 630);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setIcon(new ImageIcon(Frame3.class.getResource("/gambar/Frame 3.jpg")));
lblNewLabel.setBounds(10,58,500, 500);
contentPane.add(lblNewLabel);
comboBox = new JComboBox();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (comboBox.getSelectedItem().equals("")){
textField.setText("");
textField_1.setText("");
textField_2.setText("");
textField_3.setText("");
textField_4.setText("");
textField_5.setText("");
isSelected = false;
}
else{
isSelected = true;
String noRumah = (String) comboBox.getSelectedItem();
rumah = new Rumah(noRumah);
String sql = "SELECT * FROM `tabel_rumah` WHERE noRumah='"+rumah.getNoRumah()+"';";
try {
ResultSet rs = statement.executeQuery(sql);
if (!rs.isBeforeFirst()){
System.out.println("Tabel Kosong");
}
while(rs.next()){
rumah.setIDRumah(rs.getInt("idRumah"));
rumah.setTipe(rs.getString("tipeRumah"));
rumah.setLT(rs.getInt("LT"));
rumah.LTAwal = rs.getInt("LTAwal");
rumah.setLB(rs.getInt("LB"));
rumah.setHargaAwal(rs.getInt("HargaAwal"));
rumah.setHargaNett(rs.getInt("HargaNett"));
rumah.setIsBought(rs.getBoolean("isBought"));
rumah.setIsEdited(rs.getBoolean("isEdited"));
rumah.setIsLocked(rs.getBoolean("isLocked"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
textField.setText(rumah.getTipe());
textField_1.setText(rumah.getNoRumah());
textField_3.setText(rumah.getStrLT());
textField_2.setText(rumah.getStrLB());
textField_4.setText(rumah.getStrHN());
textField_5.setText(rumah.getStrIsBought(rumah.getIsBought()));
}
}
});
comboBox.setFont(new Font("Tahoma", Font.PLAIN, 12));
comboBox.setModel(new DefaultComboBoxModel(new String[] {"","KR-19", "KR-20", "KR-21", "KR-22", "KR-23", "KR-24", "KR-25", "KR-26", "KR-27", "KR-28", "KR-29", "KR-30", "KR-31"}));
comboBox.setBounds(653, 89, 63, 20);
contentPane.add(comboBox);
JLabel labelKeterangan = new JLabel("KutaRaya, 19 - 31");
labelKeterangan.setHorizontalAlignment(SwingConstants.CENTER);
labelKeterangan.setFont(new Font("Monospaced", Font.BOLD, 20));
labelKeterangan.setBounds(90, 12, 346, 41);
contentPane.add(labelKeterangan);
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBorder(new LineBorder(new Color(0, 0, 0)));
panel.setBounds(536, 141, 179, 158);
contentPane.add(panel);
JLabel label = new JLabel("Kavling");
label.setBounds(10, 11, 46, 14);
panel.add(label);
JLabel label_1 = new JLabel("No Rumah");
label_1.setBounds(10, 33, 55, 14);
panel.add(label_1);
JLabel label_2 = new JLabel("LB");
label_2.setBounds(10, 80, 55, 14);
panel.add(label_2);
JLabel label_3 = new JLabel("LT");
label_3.setBounds(10, 58, 46, 14);
panel.add(label_3);
JLabel label_4 = new JLabel("Harga");
label_4.setBounds(10, 105, 55, 14);
panel.add(label_4);
JLabel label_5 = new JLabel("Status");
label_5.setBounds(10, 130, 55, 14);
panel.add(label_5);
textField = new JTextField();
textField.setText((String) null);
textField.setColumns(10);
textField.setBounds(71, 8, 98, 20);
panel.add(textField);
textField_1 = new JTextField();
textField_1.setText((String) null);
textField_1.setColumns(10);
textField_1.setBounds(71, 30, 98, 20);
panel.add(textField_1);
textField_2 = new JTextField();
textField_2.setText((String) null);
textField_2.setColumns(10);
textField_2.setBounds(71, 77, 98, 20);
panel.add(textField_2);
textField_3 = new JTextField();
textField_3.setText((String) null);
textField_3.setColumns(10);
textField_3.setBounds(71, 55, 98, 20);
panel.add(textField_3);
textField_4 = new JTextField();
textField_4.setText((String) null);
textField_4.setColumns(10);
textField_4.setBounds(71, 105, 98, 20);
panel.add(textField_4);
textField_5 = new JTextField();
textField_5.setColumns(10);
textField_5.setBounds(71, 127, 98, 20);
panel.add(textField_5);
JLabel lblPilihanRumah = new JLabel("Pilihan Rumah :");
lblPilihanRumah.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblPilihanRumah.setBounds(535, 93, 90, 14);
contentPane.add(lblPilihanRumah);
JButton btnNewButton = new JButton("Kembali ke Peta Awal");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
PetaAwal frame = new PetaAwal();
frame.setVisible(true);
}
});
btnNewButton.setBounds(541, 361, 176, 30);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("Masuk ke Menu Rumah");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (isSelected){
MainRumah.noRumahDariPeta = rumah.getNoRumah();
setVisible(false);
MainRumah frameMain = new MainRumah();
frameMain.setVisible(true);
}
else if (!isSelected){
JOptionPane.showMessageDialog(null, "Rumah belum dipilih, silahkan pilih terlebih dahulu");
}
}
});
btnNewButton_1.setBounds(542, 322, 173, 30);
contentPane.add(btnNewButton_1);
} | 8 |
public Boolean parse(final boolean current) {
for (String s : TOGGLE_VALUES) {
if (string.equalsIgnoreCase(s)) {
return !current;
}
}
for (String s : POSITIVE_VALUES) {
if (string.equalsIgnoreCase(s)) {
return true;
}
}
for (String s : NEGATIVE_VALUES) {
if (string.equalsIgnoreCase(s)) {
return false;
}
}
return null;
} | 6 |
private long readNumber ( int side, int l, boolean FF )
{
long r = 0, b = 1;
int q=0;
byte[] g = new byte[l];
try { fcdx.read(g); }
catch (IOException e) { e.printStackTrace(); }
if(side>0 && l>1) b<<=((l-1)<<3);
for(int i=0;i<l;i++)
{
q = g[i]; if(q<0) q+=0x100;
if(q!=0xff) FF=false;
r|= b*q;
if(side>0) b>>=8; else b<<=8;
}
return (FF ? -1 : r );
} | 8 |
@Override
public String execute(SessionRequestContent request) throws ServletLogicException {
String page = ConfigurationManager.getProperty("path.page.directions");
String prevPage = (String) request.getSessionAttribute(JSP_PAGE);
resaveParamsShowDirections(request);
formDirectionList(request);
if (page == null ? prevPage != null : ! page.equals(prevPage)) {
request.setSessionAttribute(JSP_PAGE, page);
cleanSessionShowDirections(request);
}
return page;
} | 2 |
public ArrayList<Move> whiteUrgentMoves(ArrayList<Move> allWhiteMoves) {
ArrayList<Move> rez = new ArrayList<Move>();
// if black king isn't near any pieces, it can't eat them
if (this.piecesNearPosition(this.piecePosition[28]).size() == 0) { return rez; }
for (Move currMove : allWhiteMoves) {
int from = Utils.getStartingPositionFromMoveNumber(currMove.moveNumber);
int to = Utils.getTargetPositionFromMoveNumber(currMove.moveNumber);
int movedPiece = Utils.getMovedPieceFromMoveNumber(currMove.moveNumber);
if (movedPiece == 4) {
for (int piecesAroundBlackKing : this.piecesNearPosition(this.piecePosition[28])) {
if (!ChessboardUtils.arePositionsAdjacent(from, this.piecePosition[piecesAroundBlackKing])
&& ChessboardUtils.arePositionsAdjacent(to, this.piecePosition[piecesAroundBlackKing])) {
rez.add(currMove);
}
}
}
else if (!ChessboardUtils.arePositionsAdjacent(from, this.piecePosition[4]) && ChessboardUtils.arePositionsAdjacent(from, this.piecePosition[28])
&& !ChessboardUtils.arePositionsAdjacent(to, this.piecePosition[28])) {
rez.add(currMove);
}
}
return rez;
} | 9 |
public Info() {
setTitle("Info");
//this.setLocationRelativeTo(null);
this.setIconImage(new ImageUtil().getLogo());
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setBounds(100, 100, 575, 409);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
JLabel lblImage = new JLabel(new ImageUtil().getImgIcon("icon.png"));
JLabel lblVersion = new JLabel(("Version: ")+GrooveJaar.version);
lblVersion.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
JEditorPane dtrpnrnthirdpartySoftwareInvolved = new JEditorPane();
dtrpnrnthirdpartySoftwareInvolved.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
dtrpnrnthirdpartySoftwareInvolved.setOpaque(false);
dtrpnrnthirdpartySoftwareInvolved.setBackground(SystemColor.control);
dtrpnrnthirdpartySoftwareInvolved.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent arg0) {
if (HyperlinkEvent.EventType.ACTIVATED.equals(arg0.getEventType())) {
try {
GrooveJaar.openURL(arg0.getURL().toString());
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
});
dtrpnrnthirdpartySoftwareInvolved.setEditable(false);
dtrpnrnthirdpartySoftwareInvolved.setContentType("text/html");
dtrpnrnthirdpartySoftwareInvolved.setText("<html>\r\n<font size=\"4\" face=\"Tahoma\" >\r\n<center>\r\nThird-party software involved (and obviously thanks to all):<br />\r\n<a href='http://code.google.com/p/jgroove/'><b>jgroove</b></a><br />\r\n<a href='http://code.google.com/p/google-gson/'><b>gson</b></a><br />\r\n<a href='http://www.jthink.net/jaudiotagger/'><b>Jaudiotagger</b></a><br />\r\n<a href='http://www.miglayout.com/'><b>MigLayout</b></a><br />\r\n<a href='http://sourceforge.net/projects/jacomp3player/'><b>jaco-mp3-player</b></a><br />\r\nExtra thanks goes to all the people that share his kwnolodge (a lot of code is taken from them).\r\n</center>\r\n</font>\r\n</html>");
GroupLayout gl_contentPanel = new GroupLayout(contentPanel);
gl_contentPanel.setHorizontalGroup(
gl_contentPanel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPanel.createSequentialGroup()
.addGap(206)
.addComponent(lblImage, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(478))
.addGroup(gl_contentPanel.createSequentialGroup()
.addContainerGap()
.addComponent(dtrpnrnthirdpartySoftwareInvolved, GroupLayout.PREFERRED_SIZE, 509, GroupLayout.PREFERRED_SIZE)
.addContainerGap(165, Short.MAX_VALUE))
.addGroup(gl_contentPanel.createSequentialGroup()
.addGap(171)
.addComponent(lblVersion, GroupLayout.PREFERRED_SIZE, 223, GroupLayout.PREFERRED_SIZE)
.addContainerGap(155, Short.MAX_VALUE))
);
gl_contentPanel.setVerticalGroup(
gl_contentPanel.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_contentPanel.createSequentialGroup()
.addContainerGap()
.addComponent(lblImage, GroupLayout.PREFERRED_SIZE, 164, GroupLayout.PREFERRED_SIZE)
.addGap(11)
.addComponent(lblVersion)
.addGap(11)
.addComponent(dtrpnrnthirdpartySoftwareInvolved, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE))
);
contentPanel.setLayout(gl_contentPanel);
} | 3 |
public static void main(String[] args) {
int t;
int SIZE = 5;
int[] inputArray = new int[SIZE];
//-----------Take user input---------------//
Scanner element = new Scanner(System.in);
System.out.println("Enter Element : ");
for (int i = 0; i < SIZE; i++) {
inputArray[i] = element.nextInt();
}
//-----------Shift places---------------//
t = inputArray[0];
for (int j = 0; j < SIZE; j++) {
if(j == SIZE -1){
inputArray[j] = t;
}else{
inputArray[j] = inputArray[j+1];
}
}
//-----------Display outputs---------------//
for (int j = 0; j < SIZE; j++) {
System.out.println(inputArray[j]);
}
} | 4 |
private static int getOlympianNumber(String pathToFile) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(
pathToFile));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
System.out.println("file not found");
}
String line = null;
int i = 0;
try {
line = reader.readLine();
while ((line = reader.readLine()) != null) {
i++;
}
} catch (IOException e) {
System.out.println("File can not be read");
}
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return i;
} | 4 |
public void obfuscateProject() {
if (variablePanel.getVariableListSize() == 0) {
MessageDialog.displayMessageDialog(this, "INFORMATION_DIALOG", "NO_VAR_TO_OBF");
return;
}
if (!destinationDirectory.equals("")) {
setActionButtonsEnabled(false);
tabbedPanel.setSelectedComponent(variablePanel);
ThreadInterface threadInterface = new ThreadInterface(2);
threadInterface.setMethod(0, obfuscator, "obfuscateProject", (Class<Object>[])null, (Object[])null);
threadInterface.setMethod(1, this, "displayDestinationFolder", (Class<Object>[])null, (Object[])null);
threadInterface.runMethods("obfuscate Thread");
} else {
tabbedPanel.setSelectedComponent(projectPanel);
MessageDialog.displayMessageDialog(this, "INFORMATION_DIALOG", "CHOOSE_DES_DIR");
fillPanelFields(false);
}
} | 2 |
public void exec(){
try {
ArrayList<String> erg = util.networkCommand("ps -e | wc -l");
count = Integer.parseInt(erg.get(0));
System.out.println(count);
} catch (Exception e) {
System.out.println(e.getMessage());
}
} | 1 |
public void move() {
Random generator = new Random();
int num1 = generator.nextInt(4);
if (num1 == 0) {
x -= 5;
y -= 5;
} else if (num1 == 1) {
x -= 5;
y += 5;
} else if (num1 == 2) {
x += 5;
y -= 5;
} else {
x += 5;
y += 5;
}
if (x >= 525) {
x = 525;
} else if (x <= 0) {
x = 0;
}
if (y >= 525) {
y = 525;
} else if (y <= 0) {
y = 0;
}
rec.setLocation(x, y);
} | 7 |
public int etsiVasenX(){
int vasX = 9;
for (Palikka palikka : palikat) {
if (palikka.getX() < vasX){
vasX = palikka.getX();
}
}
return vasX;
} | 2 |
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
if (!new RequiredValidator().isValid(value, context)) {
return true;
}
Date dateValue = (Date) value;
if (!util.isValid(annotation, dateValue, context)) {
if (annotation.message().isEmpty()) {
buildConstraintViolation(context, annotation.value());
}
return false;
}
if (!util.isValidMin(annotation, dateValue, context)) {
if (annotation.message().isEmpty()) {
buildConstraintViolation(context, annotation.min());
}
return false;
}
if (!util.isValidMax(annotation, dateValue, context)) {
if (annotation.message().isEmpty()) {
buildConstraintViolation(context, annotation.max());
}
return false;
}
return true;
} | 7 |
public List<Step> getSteps() {
return steps;
} | 0 |
private void addWordTop(String word, int occur) {
if (occur > 255) occur = 255;
char firstChar = word.charAt(0);
int index = indexOf(roots, firstChar);
if (index == -1) {
CharNode newNode = new CharNode();
newNode.data = firstChar;
newNode.freq = occur;
index = roots.size();
roots.add(newNode);
} else {
roots.get(index).freq += occur;
}
if (word.length() > 1) {
addWordRec(roots.get(index), word, 1, occur);
} else {
roots.get(index).terminal = true;
}
} | 3 |
public void manage() {
super.manage();
List<Evenement> events = new ArrayList<Evenement>();
List<Incendie> incendies = this.donnees.getIncendies();
List<Robot> robots = this.donnees.getRobots();
long dateSimulation = this.simul.getDateSimulation();
int indiceIncendie = 0;
while(indiceIncendie < incendies.size()){
Incendie incendie = incendies.get(indiceIncendie);
if(incendie.getNRobot() == -1){ /* est-ce que l'incendie a déjà un robot d'assoccié */
int j, isEnd = 0;
for(j =0; j< robots.size(); j++){ /* On parcourt les robots jusqu'à en trouver un dispo et qui n'est associé à aucun incendie */
Robot robot = robots.get(j);
if(robot.getDateDisponible() <= this.simul.getDateSimulation() && robot.getNIncendie() == -1){
robot.setNIncendie(indiceIncendie);
isEnd = 1;
break;
}
}
if (isEnd == 0) { /* Si aucun robot n'a été trouvé */
indiceIncendie++;
continue;
}
incendie.setNRobot(j); /* Si l'incendie n'a pas encore attribué à un robot */
}
events.add(new EvenementDeplacerPCC(1, incendie.getNRobot(), incendie.getCase(), this.donnees));
events.add(new EvenementAgir(2, incendie.getNRobot(), this.donnees));
indiceIncendie++;
}
for (int k = 0; k < events.size(); k++) {
if (events.get(k).getDate() > this.simul.dateSimulation - 1 && this.simul.dateSimulation >= events.get(k).getDate()){
this.simul.ajouteEvenement(events.get(k));
}
}
} | 9 |
public final void waitForTasks() {
synchronized (this.taskPool) {
while ((this.runningTasks > 0) || !this.taskPool.isEmpty()) {
try {
this.taskPool.wait();
} catch (final InterruptedException e) {
this.master.interrupt();
}
}
}
} | 3 |
@Override
public void actionPerformed(ActionEvent e) {
// If the new game button was pushed, reinitialize everything and repaint
if (e.getSource() == newGame){
fPanel.proj = new Projectile(90,400);
fPanel.targetLeft.setHit(false);
fPanel.targetMid.setHit(false);
fPanel.targetRight.setHit(false);
aPanel.getAngle().setText("");
aPanel.getPower().setText("");
fPanel.endGame = false;
fPanel.message = false;
fPanel.repaint();
}
// If the launch button was pushed, check if it's the end of the game
// and launch the projectile given the values in the appropriate text
// fields if the game is still going.
else if (e.getSource() == launch){
if (fPanel.endGame == false){
if(fPanel.newProj) {
fPanel.newProj = false;
fPanel.proj = new Projectile(90,400);
}
fPanel.repaint();
}
calcLaunch();
}
// If the checkbox was hit, toggle the showTrajectory variable
else if (e.getSource() == trajectory) {
fPanel.sling.setShowTrajectory();
}
// If none of the above was hit, then it must've been the exit button.
else {
System.exit(0);
}
} | 5 |
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
TCPAddress other = (TCPAddress) obj;
if (inetAddress == null) {
if (other.inetAddress != null) {
return false;
}
} else if (!inetAddress.equals(other.inetAddress)) {
return false;
}
if (port != other.port) {
return false;
}
return true;
} | 7 |
public Map<String, Integer> getGenreCounts() throws Exception {
Connection connect = null;
Statement statement = null;
ResultSet resultSet = null;
// Each element of the collection genreMap contains the name of a genre and its count
Map<String, Integer> genreMap = new HashMap<String, Integer>();
try {
// First connect to the database
connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/librarysystem?user=admin&password=123456");
statement = connect.createStatement();
createCheckOutView();
resultSet = statement.executeQuery("SELECT HG.name, COUNT(*) "
+ "FROM NoReturnCheckOut NRC, HasSearchGenre HG "
+ "WHERE NRC.isbn = HG.isbn "
+ "GROUP BY HG.name "
+ "ORDER BY COUNT(*) desc");
// Add genres and their counts into collection genreMap one at a time
while(resultSet.next()){
genreMap.put(resultSet.getString(1), resultSet.getInt(2));
}
statement.executeUpdate("DROP VIEW NoReturnCheckOut");
} catch (Exception e) {
System.out.println(e.getMessage());
throw e;
}
finally
{
try {
if(connect != null){
connect.close();
}
if(statement != null){
statement.close();
}
if(resultSet != null){
resultSet.close();
}
} catch (Exception e) {
}
}
return genreMap;
} | 6 |
public void visitIfCmpStmt(final IfCmpStmt stmt) {
stmt.left().visit(this); // search the left branch
if (!found) { // if nothing has been found
exchangeFactor++; // increase the exchange factor,
if (stmt.left().type().isWide()) {
exchangeFactor++; // twice to get
}
// around wides
if (exchangeFactor < 3) {
stmt.right().visit(this); // search the right branch.
}
}
} | 3 |
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String outputJson = "";
PrintWriter out = response.getWriter();
try {
String method = request.getParameter("method").toLowerCase(
Locale.ENGLISH);
switch (CommandType.convertFormString(method)) {
// Get orders by user.
case GetUserOrders: {
int userId = Integer.parseInt(request.getParameter("uid")
.toString().trim());
outputJson = doGetUserOrders(userId);
break;
}
// Get orders for user in event
case GetEventUserOrders: {
int userId = Integer.parseInt(request.getParameter("uid")
.toString().trim());
int eventId = Integer.parseInt(request.getParameter("eid")
.toString().trim());
outputJson = doGetUserOrders(userId, eventId);
break;
}
// Get event orders
case GetEventOrders: {
int eventId = Integer.parseInt(request.getParameter("eid")
.toString().trim());
outputJson = doGetEventOrders(eventId);
break;
}
default: {
break;
}
}
} catch (Exception ex) {
AppLogger.error(ex);
CommonObjectWrapper jsonResult = handlerException(ex.toString());
outputJson = Gson.toJson(jsonResult);
}
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
out.print(outputJson);
} | 4 |
public void setTooltipZeroText(String zeroTip)
throws IllegalStateException
{
if ((ttip_text == null) && (zeroTip != null))
throw new IllegalStateException("Must call setTooltipText first");
boolean isZero = (intValue == 0);
ttip_text_zero = zeroTip; // Remember new zeroTip text
// TODO simplify, docu
if ((zeroTip == null) && (ttip_text != null))
{
// No more zeroTip text.
if (isZero)
{
if (hasWarnLow && isWarnLow)
ttip.setTip(ttip_text_warnLow); // Revert to low-level tooltip text
else
ttip.setTip(ttip_text); // Revert to non-warning tooltip text
}
}
else if ((zeroTip != null) && isZero)
{
// New zeroTip text. We may have been at low-level or standard tooltip text.
ttip.setTip(zeroTip);
}
} | 9 |
public TestArray7x7(){
arr7x7 = new Array7x7();
colLeftPanel = new JPanel();
colRightPanel = new JPanel();
arrayPanel = new JPanel();
commandPanel = new JPanel();
moveLeftButton = new JButton("moveLeft");
moveRightButton = new JButton("moveRight");
colLeft = new JTextField[7];
colRight = new JTextField[7];
visualArray = new JTextField[49];
frame = new JFrame("Testning");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
colLeftPanel.setLayout(new GridLayout(7, 1));
colRightPanel.setLayout(new GridLayout(7, 1));
arrayPanel.setLayout(new GridLayout(7, 7));
frame.add(colLeftPanel, BorderLayout.WEST);
frame.add(colRightPanel, BorderLayout.EAST);
frame.add(arrayPanel, BorderLayout.CENTER);
frame.add(commandPanel, BorderLayout.SOUTH);
// fylla colLeftPanel
for (int i = 0; i < 7; i++) {
colLeft[i] = new JTextField();
colLeft[i].setBackground(Color.RED);
colLeftPanel.add(colLeft[i]);
}
// fylla colRightPanel
for (int i = 0; i < 7; i++) {
colRight[i] = new JTextField();
colRight[i].setBackground(Color.RED);
colRightPanel.add(colRight[i]);
}
// fylla arrayPanel
int counter = 0;
for(int i = 0; i < 7; i++){
for(int k = 0; k < 7; k++){
visualArray[counter] = new JTextField();
arrayPanel.add(visualArray[counter]);
visualArray[counter].setText("" + arr7x7.getElement(i, k));
counter++;
}
}
commandPanel.add(moveRightButton);
commandPanel.add(moveLeftButton);
moveLeftButton.addActionListener(this);
moveRightButton.addActionListener(this);
colLeftPanel.setPreferredSize(new Dimension(70, 70));
colRightPanel.setPreferredSize(new Dimension(70, 70));
arrayPanel.setPreferredSize(new Dimension(200, 200));
frame.pack();
frame.setVisible(true);
} | 4 |
public void svgPath(double x, double y, UPath path, double deltaShadow) {
manageShadow(deltaShadow);
ensureVisible(x, y);
final StringBuilder sb = new StringBuilder();
for (USegment seg : path) {
final USegmentType type = seg.getSegmentType();
final double coord[] = seg.getCoord();
if (type == USegmentType.SEG_MOVETO) {
sb.append("M" + format(coord[0] + x) + "," + format(coord[1] + y) + " ");
ensureVisible(coord[0] + x + 2 * deltaShadow, coord[1] + y + 2 * deltaShadow);
} else if (type == USegmentType.SEG_LINETO) {
sb.append("L" + format(coord[0] + x) + "," + format(coord[1] + y) + " ");
ensureVisible(coord[0] + x + 2 * deltaShadow, coord[1] + y + 2 * deltaShadow);
} else if (type == USegmentType.SEG_QUADTO) {
sb.append("Q" + format(coord[0] + x) + "," + format(coord[1] + y) + " " + format(coord[2] + x) + ","
+ format(coord[3] + y) + " ");
ensureVisible(coord[0] + x + 2 * deltaShadow, coord[1] + y + 2 * deltaShadow);
ensureVisible(coord[2] + x + 2 * deltaShadow, coord[3] + y + 2 * deltaShadow);
} else if (type == USegmentType.SEG_CUBICTO) {
sb.append("C" + format(coord[0] + x) + "," + format(coord[1] + y) + " " + format(coord[2] + x) + ","
+ format(coord[3] + y) + " " + format(coord[4] + x) + "," + format(coord[5] + y) + " ");
ensureVisible(coord[0] + x + 2 * deltaShadow, coord[1] + y + 2 * deltaShadow);
ensureVisible(coord[2] + x + 2 * deltaShadow, coord[3] + y + 2 * deltaShadow);
ensureVisible(coord[4] + x + 2 * deltaShadow, coord[5] + y + 2 * deltaShadow);
} else if (type == USegmentType.SEG_ARCTO) {
sb.append("A" + format(coord[0]) + "," + format(coord[1]) + " " + format(coord[2]) + ","
+ format(coord[3]) + " " + format(coord[4]) + "," + format(coord[5] + x) + ","
+ format(coord[6] + y) + " ");
} else if (type == USegmentType.SEG_CLOSE) {
// Nothing
} else {
Log.println("unknown " + seg);
}
}
if (hidden == false) {
final Element elt = (Element) document.createElement("path");
elt.setAttribute("d", sb.toString());
elt.setAttribute("style", getStyle());
elt.setAttribute("fill", fill);
if (deltaShadow > 0) {
elt.setAttribute("filter", "url(#f1)");
}
getG().appendChild(elt);
}
} | 9 |
public static void handle(String[] tokens, Client client) {
if(tokens[1].equals("-")) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
/* Do Nothing */
}
client.send(PacketCreator.pong());
}
} | 2 |
@SuppressWarnings("deprecation")
@EventHandler(priority=EventPriority.LOWEST)
public void onItemDrop(final PlayerDropItemEvent event) {
if(opposite.containsKey(event.getPlayer().getName())) {
event.setCancelled(true);
Bukkit.getScheduler().runTaskLater(instance, new Runnable() {
public void run() {
event.getPlayer().updateInventory();
}
}, 1);
event.getPlayer().updateInventory();
}
} | 1 |
public void run()
{
try {
s = new ServerSocket(port);
synchronized (this) {
notifyAll();
}
while (!quit) {
try {
r = s.accept();
final BufferedReader in =
new BufferedReader(new InputStreamReader(r.getInputStream()));
String str = in.readLine();
for (; str != null; str = in.readLine())
System.out.println(str);
in.close();
}
finally {
if (r != null)
r.close();
}
}
}
catch (final IOException e) {}
finally {
try {
if (s != null)
s.close();
}
catch (final IOException e) {}
synchronized (this) {
if (quit)
notifyAll();
}
}
System.out.println("Receiver - quit");
} | 7 |
public static void startupUnitSupport() {
{ Object old$Module$000 = Stella.$MODULE$.get();
Object old$Context$000 = Stella.$CONTEXT$.get();
try {
Native.setSpecial(Stella.$MODULE$, Stella.getStellaModule("/UNIT-SUPPORT", Stella.$STARTUP_TIME_PHASE$ > 1));
Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get())));
if (Stella.currentStartupTimePhaseP(2)) {
Units.SGT_UNIT_SUPPORT_DIM_NUMBER_LOGIC_WRAPPER = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("DIM-NUMBER-LOGIC-WRAPPER", null, 1)));
Units.SYM_STELLA_WRAPPER_VALUE = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("WRAPPER-VALUE", Stella.getStellaModule("/STELLA", true), 0)));
Units.SGT_UNIT_KB_UNITS = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("UNITS", Stella.getStellaModule("/UNIT-KB", true), 1)));
Units.SGT_TIMEPOINT_SUPPORT_DATE_TIME_LOGIC_WRAPPER = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("DATE-TIME-LOGIC-WRAPPER", Stella.getStellaModule("/TIMEPOINT-SUPPORT", true), 1)));
Units.SGT_STELLA_CALENDAR_DATE = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("CALENDAR-DATE", Stella.getStellaModule("/STELLA", true), 1)));
Units.SGT_STELLA_TIME_DURATION = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("TIME-DURATION", Stella.getStellaModule("/STELLA", true), 1)));
Units.SGT_LOGIC_PATTERN_VARIABLE = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("PATTERN-VARIABLE", Stella.getStellaModule("/LOGIC", true), 1)));
Units.SGT_LOGIC_SKOLEM = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("SKOLEM", Stella.getStellaModule("/LOGIC", true), 1)));
Units.SGT_STELLA_CS_VALUE = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("CS-VALUE", Stella.getStellaModule("/STELLA", true), 1)));
Units.KWD_FINAL_SUCCESS = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("FINAL-SUCCESS", null, 2)));
Units.KWD_TERMINAL_FAILURE = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("TERMINAL-FAILURE", null, 2)));
Units.KWD_FAILURE = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("FAILURE", null, 2)));
Units.SYM_STELLA_ITERATOR = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("ITERATOR", Stella.getStellaModule("/STELLA", true), 0)));
Units.KWD_CONTINUING_SUCCESS = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("CONTINUING-SUCCESS", null, 2)));
Units.SGT_STELLA_INTEGER_WRAPPER = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("INTEGER-WRAPPER", Stella.getStellaModule("/STELLA", true), 1)));
Units.SGT_UNIT_KB_NUMERATOR_MEASURES = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("NUMERATOR-MEASURES", Stella.getStellaModule("/UNIT-KB", true), 1)));
Units.SGT_UNIT_KB_DENOMINATOR_MEASURES = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("DENOMINATOR-MEASURES", Stella.getStellaModule("/UNIT-KB", true), 1)));
Units.SGT_LOGIC_LOGIC_OBJECT = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("LOGIC-OBJECT", Stella.getStellaModule("/LOGIC", true), 1)));
Units.SGT_STELLA_NUMBER_WRAPPER = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("NUMBER-WRAPPER", Stella.getStellaModule("/STELLA", true), 1)));
Units.SYM_UNIT_SUPPORT_STARTUP_UNIT_SUPPORT = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("STARTUP-UNIT-SUPPORT", null, 0)));
}
if (Stella.currentStartupTimePhaseP(4)) {
Units.$DIM_NUMBER_HASH_TABLE$ = StellaHashTable.newStellaHashTable();
Units.$MEASURE_INSTANCE_TABLE$ = HashTable.newHashTable();
Units.$INSTANCE_MEASURE_TABLE$ = HashTable.newHashTable();
}
if (Stella.currentStartupTimePhaseP(5)) {
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("DIM-NUMBER-LOGIC-WRAPPER", "(DEFCLASS DIM-NUMBER-LOGIC-WRAPPER (QUANTITY-LOGIC-WRAPPER) :PUBLIC-SLOTS ((WRAPPER-VALUE :TYPE DIM-NUMBER :REQUIRED? TRUE)) :PRINT-FORM (IF *PRINTREADABLY?* (PRINT-NATIVE-STREAM STREAM (WRAPPER-VALUE SELF)) (PRINT-NATIVE-STREAM STREAM \"|uw|\" (WRAPPER-VALUE SELF))))");
renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper", "newDimNumberLogicWrapper", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.utilities.DimNumber")});
renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper", "accessDimNumberLogicWrapperSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE});
}
}
if (Stella.currentStartupTimePhaseP(6)) {
Stella.finalizeClasses();
}
if (Stella.currentStartupTimePhaseP(7)) {
Stella.defineMethodObject("(DEFMETHOD (GENERATE-SPECIALIZED-TERM OBJECT) ((SELF DIM-NUMBER-LOGIC-WRAPPER)))", Native.find_java_method("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper", "generateSpecializedTerm", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (HASH-CODE INTEGER) ((SELF DIM-NUMBER-LOGIC-WRAPPER)))", Native.find_java_method("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper", "hashCode_", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (OBJECT-EQL? BOOLEAN) ((SELF DIM-NUMBER-LOGIC-WRAPPER) (X OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper", "objectEqlP", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), ((java.lang.reflect.Method)(null)));
Stella.defineFunctionObject("WRAP-DIM-NUMBER", "(DEFUN (WRAP-DIM-NUMBER DIM-NUMBER-LOGIC-WRAPPER) ((VALUE DIM-NUMBER)) :PUBLIC? TRUE :DOCUMENTATION \"Return an interned LOGIC-WRAPPER for `value'. This assures us\nthat all logic-wrapped DIM-NUMBERs are the same object.\")", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "wrapDimNumber", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.utilities.DimNumber")}), null);
Stella.defineMethodObject("(DEFMETHOD (GET-UNIT STRING) ((SELF DIM-NUMBER-LOGIC-WRAPPER)))", Native.find_java_method("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper", "getUnit", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (GET-BASE-UNIT STRING) ((SELF DIM-NUMBER-LOGIC-WRAPPER)))", Native.find_java_method("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper", "getBaseUnit", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (GET-MAGNITUDE FLOAT) ((SELF DIM-NUMBER-LOGIC-WRAPPER) (UNITS STRING)))", Native.find_java_method("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper", "getMagnitude", new java.lang.Class [] {Native.find_java_class("java.lang.String")}), ((java.lang.reflect.Method)(null)));
Stella.defineFunctionObject("HELP-GET-DIM-NUMBER", "(DEFUN (HELP-GET-DIM-NUMBER DIM-NUMBER-LOGIC-WRAPPER) ((ITEM OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "helpGetDimNumber", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("HELP-GET-UNIT-VALUE", "(DEFUN (HELP-GET-UNIT-VALUE DIM-NUMBER-LOGIC-WRAPPER) ((MAGNITUDE OBJECT) (UNITS OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "helpGetUnitValue", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("UNITS-EVALUATOR", "(DEFUN UNITS-EVALUATOR ((SELF PROPOSITION)))", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "unitsEvaluator", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.Proposition")}), null);
Stella.defineFunctionObject("UNITS-SPECIALIST", "(DEFUN (UNITS-SPECIALIST KEYWORD) ((FRAME CONTROL-FRAME) (LASTMOVE KEYWORD)))", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "unitsSpecialist", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.stella.Keyword")}), null);
Stella.defineFunctionObject("U-PLUS-CONSTRAINT", "(DEFUN (U-PLUS-CONSTRAINT OBJECT) ((MISSING-ARGUMENT INTEGER-WRAPPER) (X1 DIM-NUMBER-LOGIC-WRAPPER) (X2 DIM-NUMBER-LOGIC-WRAPPER) (X3 DIM-NUMBER-LOGIC-WRAPPER)))", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "uPlusConstraint", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.IntegerWrapper"), Native.find_java_class("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper"), Native.find_java_class("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper"), Native.find_java_class("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper")}), null);
Stella.defineFunctionObject("U-MINUS-CONSTRAINT", "(DEFUN (U-MINUS-CONSTRAINT OBJECT) ((MISSING-ARGUMENT INTEGER-WRAPPER) (X1 DIM-NUMBER-LOGIC-WRAPPER) (X2 DIM-NUMBER-LOGIC-WRAPPER) (X3 DIM-NUMBER-LOGIC-WRAPPER)))", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "uMinusConstraint", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.IntegerWrapper"), Native.find_java_class("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper"), Native.find_java_class("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper"), Native.find_java_class("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper")}), null);
Stella.defineFunctionObject("U-TIMES-CONSTRAINT", "(DEFUN (U-TIMES-CONSTRAINT OBJECT) ((MISSING-ARGUMENT INTEGER-WRAPPER) (X1 DIM-NUMBER-LOGIC-WRAPPER) (X2 DIM-NUMBER-LOGIC-WRAPPER) (X3 DIM-NUMBER-LOGIC-WRAPPER)))", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "uTimesConstraint", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.IntegerWrapper"), Native.find_java_class("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper"), Native.find_java_class("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper"), Native.find_java_class("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper")}), null);
Stella.defineFunctionObject("U-DIVIDE-CONSTRAINT", "(DEFUN (U-DIVIDE-CONSTRAINT OBJECT) ((MISSING-ARGUMENT INTEGER-WRAPPER) (X1 DIM-NUMBER-LOGIC-WRAPPER) (X2 DIM-NUMBER-LOGIC-WRAPPER) (X3 DIM-NUMBER-LOGIC-WRAPPER)))", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "uDivideConstraint", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.IntegerWrapper"), Native.find_java_class("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper"), Native.find_java_class("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper"), Native.find_java_class("edu.isi.powerloom.extensions.units.DimNumberLogicWrapper")}), null);
Stella.defineFunctionObject("U-ABS-SPECIALIST", "(DEFUN (U-ABS-SPECIALIST KEYWORD) ((FRAME CONTROL-FRAME) (LASTMOVE KEYWORD)))", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "uAbsSpecialist", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.stella.Keyword")}), null);
Stella.defineFunctionObject("U-SIGNUM-SPECIALIST", "(DEFUN (U-SIGNUM-SPECIALIST KEYWORD) ((FRAME CONTROL-FRAME) (LASTMOVE KEYWORD)))", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "uSignumSpecialist", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.stella.Keyword")}), null);
Stella.defineFunctionObject("MINIMUM-OF-UNITS-SPECIALIST", "(DEFUN (MINIMUM-OF-UNITS-SPECIALIST KEYWORD) ((FRAME CONTROL-FRAME) (LASTMOVE KEYWORD)))", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "minimumOfUnitsSpecialist", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.stella.Keyword")}), null);
Stella.defineFunctionObject("MAXIMUM-OF-UNITS-SPECIALIST", "(DEFUN (MAXIMUM-OF-UNITS-SPECIALIST KEYWORD) ((FRAME CONTROL-FRAME) (LASTMOVE KEYWORD)))", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "maximumOfUnitsSpecialist", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.stella.Keyword")}), null);
Stella.defineFunctionObject("SUM-OF-UNITS-SPECIALIST", "(DEFUN (SUM-OF-UNITS-SPECIALIST KEYWORD) ((FRAME CONTROL-FRAME) (LASTMOVE KEYWORD)))", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "sumOfUnitsSpecialist", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.stella.Keyword")}), null);
Stella.defineFunctionObject("U-VALUE-MEASURE-SPECIALIST", "(DEFUN (U-VALUE-MEASURE-SPECIALIST KEYWORD) ((FRAME CONTROL-FRAME) (LASTMOVE KEYWORD)))", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "uValueMeasureSpecialist", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.stella.Keyword")}), null);
Stella.defineFunctionObject("ARGUMENT-MATCHES-LIST-HELPER?", "(DEFUN (ARGUMENT-MATCHES-LIST-HELPER? BOOLEAN) ((ARGUMENT OBJECT) (THE-LIST LIST)))", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "argumentMatchesListHelperP", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.List")}), null);
Stella.defineFunctionObject("INTEGER-TO-MEASURES-HELPER", "(DEFUN (INTEGER-TO-MEASURES-HELPER KEYWORD) ((FRAME CONTROL-FRAME) (LASTMOVE KEYWORD) (CODE INTEGER)))", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "integerToMeasuresHelper", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.stella.Keyword"), java.lang.Integer.TYPE}), null);
Stella.defineFunctionObject("U-BASE-MEASURES-SPECIALIST", "(DEFUN (U-BASE-MEASURES-SPECIALIST KEYWORD) ((FRAME CONTROL-FRAME) (LASTMOVE KEYWORD)))", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "uBaseMeasuresSpecialist", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.stella.Keyword")}), null);
Stella.defineFunctionObject("GET-OBJECT-PID", "(DEFUN (GET-OBJECT-PID RATIO) ((OBJ OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "getObjectPid", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null);
Stella.defineFunctionObject("COMENSURATE-UNITS-SPECIALIST", "(DEFUN (COMENSURATE-UNITS-SPECIALIST KEYWORD) ((FRAME CONTROL-FRAME) (LASTMOVE KEYWORD)))", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "comensurateUnitsSpecialist", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.stella.Keyword")}), null);
Stella.defineFunctionObject("INITIALIZE-MEASURE-CONCEPTS", "(DEFUN INITIALIZE-MEASURE-CONCEPTS ())", Native.find_java_method("edu.isi.powerloom.extensions.units.Units", "initializeMeasureConcepts", new java.lang.Class [] {}), null);
Stella.defineFunctionObject("STARTUP-UNIT-SUPPORT", "(DEFUN STARTUP-UNIT-SUPPORT () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.extensions.units._StartupUnitSupport", "startupUnitSupport", new java.lang.Class [] {}), null);
{ MethodSlot function = Symbol.lookupFunction(Units.SYM_UNIT_SUPPORT_STARTUP_UNIT_SUPPORT);
KeyValueList.setDynamicSlotValue(function.dynamicSlots, edu.isi.powerloom.extensions.Extensions.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("_StartupUnitSupport"), Stella.NULL_STRING_WRAPPER);
}
}
if (Stella.currentStartupTimePhaseP(8)) {
Stella.finalizeSlots();
Stella.cleanupUnfinalizedClasses();
}
if (Stella.currentStartupTimePhaseP(9)) {
Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("UNIT-SUPPORT")))));
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *DIM-NUMBER-HASH-TABLE* (STELLA-HASH-TABLE OF DIM-NUMBER DIM-NUMBER-LOGIC-WRAPPER) (NEW STELLA-HASH-TABLE) :DOCUMENTATION \"Table for interning dim number logic wrappers\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *MEASURE-INSTANCE-TABLE* (HASH-TABLE OF MEASURE LOGIC-OBJECT) (NEW HASH-TABLE) :DOCUMENTATION \"Mapping table from measure objects to their PowerLoom representation.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *INSTANCE-MEASURE-TABLE* (HASH-TABLE OF LOGIC-OBJECT MEASURE) (NEW HASH-TABLE) :DOCUMENTATION \"Mapping table from PowerLoom representations of measures to measure objects\")");
}
} finally {
Stella.$CONTEXT$.set(old$Context$000);
Stella.$MODULE$.set(old$Module$000);
}
}
} | 7 |
public void repondre(HttpServletRequest requete, HttpServletResponse reponse, String action)
throws ServletException, IOException {
Utilisateur u = UtilisateurService.utilisateur(requete);
Role roleUtilisateur = u != null ? u.getRole() : Role.Visiteur;
if (roleUtilisateur.getValeur() < roleRequis().getValeur())
throw new AccesRefuseException("Accès refusé, l'utilisateur n'a pas les droits requis");
repondreExtension(requete, reponse, action, u);
} | 2 |
private void removeListener() throws NoSuchMethodException,
SecurityException, IllegalArgumentException, IllegalAccessException {
Class<?> guiType = getGui().getClass();
Class<?> type = guiType;
while (type != null && !type.equals(Object.class)) {
for (Field field : type.getDeclaredFields()) {
if (JComponent.class.isAssignableFrom(field.getType())) {
field.setAccessible(true);
JComponent component = (JComponent) field.get(gui);
if (component instanceof JButton) {
((JButton) component)
.removeActionListener(actionListener);
} else if (component instanceof JTextField) {
((JTextField) component).getDocument()
.removeDocumentListener(actionListener);
}
}
}
type = type.getSuperclass();
}
active = false;
} | 8 |
public static void main(String[] args) throws IOException {
ArrayList<Img<Color>> els = new ArrayList<Img<Color>>();
Random r = new Random(/*2413*/);
String[] FONTS = { "Times", "Georgia", "Optima", "Times New Roman" };
for (int i = 0; i < 200; i++) {
TreePredict.Img<Color> timg = TreePredict.getImg("a", new Config.FontType(FONTS[i % FONTS.length], false), Color.RED, r);
float[] fftdata = fft(timg.data, new float[timg.data.length], true);
els.add(new Img<Color>(fftdata, Color.RED));
}
for (int i = 0; i < 200; i++) {
TreePredict.Img<Color> timg = TreePredict.getImg("e", new Config.FontType(FONTS[i % FONTS.length], false), Color.BLUE, r);
float[] fftdata = fft(timg.data, new float[timg.data.length], true);
els.add(new Img<Color>(fftdata, Color.BLUE));
}
SVNode tree = createSVTree(els, els, 5, 2, null);
int failures = 0;
int tries = 0;
for (File f : new File("/Users/zar/Desktop/DesktopContents/ltestdata3/a/").listFiles()) {
if (!f.getName().endsWith(".png")) { continue; }
float[] data = TreePredict.getImg(ImageIO.read(f), Color.RED).data;
float[] fftdata = fft(data, new float[data.length], true);
Color tag = tree.classify(new Img(fftdata, Color.RED));
if (!tag.equals(Color.RED)) { failures++; }
tries++;
}
for (File f : new File("/Users/zar/Desktop/DesktopContents/ltestdata3/e/").listFiles()) {
if (!f.getName().endsWith(".png")) { continue; }
float[] data = TreePredict.getImg(ImageIO.read(f), Color.BLUE).data;
float[] fftdata = fft(data, new float[data.length], true);
Color tag = tree.classify(new Img(fftdata, Color.BLUE));
if (!tag.equals(Color.BLUE)) { failures++; }
tries++;
}
System.out.println(failures + "/" + tries);
System.out.println((tries - failures) * 100.0 / tries);
/*// Find SV Tree
for (int i = 1; i < 8; i += 2) {
BufferedImage img = new BufferedImage(IMG_SZ, IMG_SZ, BufferedImage.TYPE_INT_RGB);
Graphics2D g = img.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, IMG_SZ, IMG_SZ);
SVNode tree = createSVTree(els, els, i, 2, null);
// Draw support vector by checking each pixel of the display.
drawVector(tree, g, 0);
// Draw classes.
int score = 0;
for (Img<Color> e : els) {
Color c = tree.classify(e);
if (c == e.tag) { score++; }
g.setColor(c);
g.drawRect((int) (IMG_SZ / 2 * (e.data[0] + 1)) - 2, (int) (IMG_SZ / 2 * (e.data[1] + 1)) - 2, 5, 5);
}
// Draw points with correct classes.
for (Img<Color> e : els) {
g.setColor(e.tag);
g.fillRect((int) (IMG_SZ / 2 * (e.data[0] + 1)) - 1, (int) (IMG_SZ / 2 * (e.data[1] + 1)) - 1, 4, 4);
}
g.setColor(Color.BLACK);
g.drawString(score + "/" + els.size(), 10, 20);
ImageIO.write(img, "png", new File("/Users/zar/Desktop/" + i + ".png"));
}*/
} | 8 |
public void visitAttribute(final Attribute attr) {
super.visitAttribute(attr);
if (fv != null) {
fv.visitAttribute(attr);
}
} | 1 |