text stringlengths 14 410k | label int32 0 9 |
|---|---|
synchronized void sendPacket(Packet packet) throws IOException {
if (open) {
out.writeInt(packet.id);
packetTypes.get(packet.id).write(packet, out);
}
} | 1 |
@Test
public void testIntegrative() throws FileNotFoundException {
final JUnitCore core = new JUnitCore();
core.addListener(new TestLinkXmlRunListener());
core.addListener(new TestLinkLoggingRunListener(LoggerFactory.getLogger("MYTESTLINK"), URI.create("http://testlink.sourceforge.net/demo/")));
core.run(SUTTestLinkRunListener.class);
assertTrue("Did not find logfile", new File("target/testlink.xml").exists());
} | 0 |
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String action = request.getParameter("act");
if(action != null) {
try {
RequestContext context = new RequestContext(request);
if(context.isLogged()) {
int projId = Utilities.chooseParam(request, "projid", 0);
int workId = Utilities.chooseParam(request, "id", 0);
long salary = Utilities.chooseParam(request, "sal", 0L);
switch(action) {
case "hire":
hireWorker(workId, projId, salary, response, context);
break;
case "changesal":
changeSalary(workId, salary, response, context);
break;
case "changeproj":
changeProject(workId, projId, response, context);
break;
case "fire":
fireWorker(workId, response, context);
break;
case "steal":
jobOffer(workId, projId, salary, response, context);
break;
default:
response.sendRedirect("home.jsp");
}
} else {
response.sendRedirect("login.jsp");
}
} catch(SQLException e) {
log.error("SQLException caught in Worker servlet.", e);
response.sendRedirect("error.jsp?err=dberr");
}
} else {
response.sendRedirect("home.jsp");
}
} | 8 |
public void incFrequency() {
docFrequency++;
} | 0 |
public static void printDescriptionsAsKifRule(Description head, Description tail, Proposition rule, boolean reversepolarityP) {
{ OutputStream stream = ((OutputStream)(Logic.$PRINTLOGICALFORMSTREAM$.get()));
boolean forwardarrowP = ((BooleanWrapper)(KeyValueList.dynamicSlotValue(rule.dynamicSlots, Logic.SYM_LOGIC_FORWARD_ONLYp, Stella.FALSE_WRAPPER))).wrapperValue &&
(!reversepolarityP);
boolean reverseargumentsP = forwardarrowP ||
reversepolarityP;
int currentindentcounter = ((Integer)(Logic.$INDENTCOUNTER$.get())).intValue();
Surrogate operatorprefix = Proposition.chooseImplicationOperator(rule, forwardarrowP);
int operatorprefixindent = 2 + (operatorprefix.symbolName).length();
boolean mapheadvariablesP = Description.namedDescriptionP(head);
Vector ruleVariables = ((Vector)(KeyValueList.dynamicSlotValue(rule.dynamicSlots, Logic.SYM_LOGIC_IO_VARIABLES, null)));
KeyValueMap headvariablemapping = null;
KeyValueMap tailvariablemapping = null;
if (head.deletedP() ||
tail.deletedP()) {
stream.nativeStream.print("(=> <DeLeTeD ArGuMeNt(S)>)");
return;
}
if (reverseargumentsP) {
{ Description temp = head;
head = tail;
tail = temp;
}
mapheadvariablesP = !mapheadvariablesP;
}
if (ruleVariables != null) {
headvariablemapping = ((KeyValueMap)(Logic.createSkolemMappingTable(head.ioVariables, ruleVariables)));
tailvariablemapping = ((KeyValueMap)(Logic.createSkolemMappingTable(tail.ioVariables, ruleVariables)));
}
else if (mapheadvariablesP) {
ruleVariables = tail.ioVariables;
headvariablemapping = ((KeyValueMap)(Logic.createSkolemMappingTable(head.ioVariables, ruleVariables)));
}
else {
ruleVariables = head.ioVariables;
tailvariablemapping = ((KeyValueMap)(Logic.createSkolemMappingTable(tail.ioVariables, ruleVariables)));
}
{ Object old$Indentcounter$000 = Logic.$INDENTCOUNTER$.get();
try {
Native.setIntSpecial(Logic.$INDENTCOUNTER$, currentindentcounter);
stream.nativeStream.print("(" + Logic.stringifiedSurrogate(Logic.SGT_PL_KERNEL_KB_FORALL) + " ");
Logic.printKifQuantifiedVariables(ruleVariables, false);
stream.nativeStream.println();
Logic.increaseIndent(Stella.NULL_INTEGER);
Logic.printIndent(stream, Stella.NULL_INTEGER);
stream.nativeStream.print("(" + Logic.stringifiedSurrogate(operatorprefix) + " ");
Logic.increaseIndent(operatorprefixindent);
{ Object old$Skolemnamemappingtable$000 = Logic.$SKOLEMNAMEMAPPINGTABLE$.get();
try {
Native.setSpecial(Logic.$SKOLEMNAMEMAPPINGTABLE$, headvariablemapping);
Description.printKifDescriptionProposition(head, reversepolarityP);
} finally {
Logic.$SKOLEMNAMEMAPPINGTABLE$.set(old$Skolemnamemappingtable$000);
}
}
stream.nativeStream.println();
Logic.printIndent(stream, Stella.NULL_INTEGER);
{ Object old$Skolemnamemappingtable$001 = Logic.$SKOLEMNAMEMAPPINGTABLE$.get();
try {
Native.setSpecial(Logic.$SKOLEMNAMEMAPPINGTABLE$, tailvariablemapping);
Description.printKifDescriptionProposition(tail, reversepolarityP);
} finally {
Logic.$SKOLEMNAMEMAPPINGTABLE$.set(old$Skolemnamemappingtable$001);
}
}
stream.nativeStream.print("))");
Logic.decreaseIndent(operatorprefixindent);
Logic.decreaseIndent(Stella.NULL_INTEGER);
} finally {
Logic.$INDENTCOUNTER$.set(old$Indentcounter$000);
}
}
}
} | 7 |
@Override
public boolean equals(Object obj) {
if(this == obj)
{
return true;
}
if(obj != null)
{
if(obj instanceof Coordinates)
{
Coordinates otherCoordinates = (Coordinates)obj;
if(otherCoordinates.getX() == this.getX() && otherCoordinates.getY() == this.getY())
{
return true;
}
}
}
return false;
} | 5 |
private void showTeachingPlan() {
content = null;
head = null;
Object fb = logic.showTPHead();
if (fb instanceof Feedback) {
JOptionPane.showMessageDialog(null, ((Feedback) fb).getContent());
} else if (fb instanceof String[]) {
head = (String[]) fb;
fb = logic
.showTPContent(((DeptVO) deptChooser.getSelectedItem()).deptName);
if ((fb instanceof Feedback) && fb != Feedback.LIST_EMPTY) {
JOptionPane.showMessageDialog(null,
((Feedback) fb).getContent());
} else if (fb instanceof String[][]) {
content = (String[][]) fb;
}
}
if (content != null) {
map = new TeachingPlanMap(content);
dtm = new DefaultTableModel(content.length, head.length);
table2 = new CTable(map, dtm);
dtm.setColumnIdentifiers(head);
for (int i = 0; i < content.length; i++) {
for (int j = 0; j < content[i].length; j++) {
if (content[i][j].contains("null-null")) {
content[i][j] = content[i][j].replaceAll("null-null",
"");
}
dtm.setValueAt(content[i][j], i, j);
}
}
table2.setEnabled(false);
js2.setViewportView(table2);
cl.show(cardp, "2");
}
this.repaint();
this.validate();
} | 9 |
@Override
public String[] getHelp() {
return new String[]{
"ttp help",
"Displays help information"
};
} | 0 |
public AnnotationVisitor visitAnnotationDefault() {
text.add(tab2 + "default=");
TraceAnnotationVisitor tav = createTraceAnnotationVisitor();
text.add(tav.getText());
text.add("\n");
if (mv != null) {
tav.av = mv.visitAnnotationDefault();
}
return tav;
} | 1 |
public boolean getBoolean(String columnLabel) {
Object obj = getObject(columnLabel);
if (!(obj instanceof Boolean)) {
throw new RuntimeException("[" + columnLabel + "] is not a boolean, but a "+ (null == obj ? "null" : obj.getClass().getName()) +".");
}
return (boolean) obj;
} | 2 |
@Override
public LauncherAction createActionFromDataElement(Element element) {
if(element == null) return null;
AppletDesc desc = new AppletDesc();
initNameAndId(desc, element);
//Use Browser
if(element.getAttribute("use-browser").equals("true")) {
desc.setUseWebBrowser(true);
}
else {
desc.setUseWebBrowser(false);
}
//Separate VM
if(element.getAttribute("separate-vm").equals("true")) {
desc.setSeperateVM(true);
}
else {
desc.setSeperateVM(false);
}
//Address
String address = element.getAttribute("address");
if(address != null && !address.equals("")) {
try {
desc.setDocumentURL(new URL(address));
} catch(MalformedURLException badURL) {
logger.log(Level.WARNING, badURL.getMessage(), badURL);
}
}
//Custom info
org.w3c.dom.NodeList children = element.getChildNodes();
for(int i=0;i<children.getLength();i++) {
org.w3c.dom.Node n = children.item(i);
if(n.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
org.w3c.dom.Element appletE = (org.w3c.dom.Element)n;
if(appletE.getTagName().equals("applet")==false)
continue;
AppletHTMLParser parser = new AppletHTMLParser();
AppletDesc customDesc = parser.getAppletDesc(appletE, desc.getDocumentURL());
desc.updateInfo(customDesc);
}
}
return new AppletAction(this, desc);
} | 9 |
public State getStateForVariable(String variable) {
return (State) MAP.get(variable);
} | 0 |
public DisplayPane(LSystem lsystem) {
super(new BorderLayout());
this.lsystem = lsystem;
expander = new Expander(lsystem);
// We can't edit the expansion, of course.
expansionDisplay.setEditable(false);
// The user has to be able to change the recursion depth.
JSpinner spinner = new JSpinner(spinnerModel);
spinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
updateDisplay();
}
});
// Now, for the angle at which the damn thing is viewed...
JSpinner s1 = new JSpinner(pitchModel), s2 = new JSpinner(rollModel), s3 = new JSpinner(
yawModel);
ChangeListener c = new ChangeListener() {
public void stateChanged(ChangeEvent e) {
updateDisplay();
// displayAction.setEnabled(true);
}
};
pitchModel.addChangeListener(c);
rollModel.addChangeListener(c);
yawModel.addChangeListener(c);
// Lay out the component.
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(spinner, BorderLayout.EAST);
topPanel.add(expansionDisplay, BorderLayout.CENTER);
topPanel.add(progressBar, BorderLayout.WEST);
add(topPanel, BorderLayout.NORTH);
JPanel bottomPanel = new JPanel();
bottomPanel.add(new JLabel("Pitch"));
bottomPanel.add(s1);
bottomPanel.add(new JLabel("Roll"));
bottomPanel.add(s2);
bottomPanel.add(new JLabel("Yaw"));
bottomPanel.add(s3);
//bottomPanel.setBackground(Color.WHITE);
JScrollPane scroller = new JScrollPane(imageDisplay);
add(scroller, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.SOUTH);
// Finally, set the initial display.
updateDisplay();
} | 0 |
public void setMapData(File file) {
if (!file.exists()) {
throw new IllegalArgumentException("Map data file does not exist.");
}
this.mapData = file;
} | 1 |
private static long getLastCached(String playerName) {
// Already found
if (lastCached.containsKey(playerName))
return lastCached.get(playerName);
// Search for lowercase matches
for (final String loggedName : lastCached.keySet()) {
if (loggedName.equalsIgnoreCase(playerName)) {
playerName = loggedName;
break;
}
}
if (!lastCached.containsKey(playerName))
return -1;
// Grab last changed
return lastCached.get(playerName);
} | 4 |
public void buildTrackForTest()
{
if (!built)
{
// Create
Record r = new Record();
r.setAuthor("fake-author");
r.setCategory(new Category("fake-cat", 12));
r.setCatNo("fake-cat-no");
r.setDate(new Date());
r.setDiscogsNum(12);
r.setFormat(new Format("fake-format", "12"));
r.setLabel(new Label("fake-label"));
r.setNotes("fake-notes");
r.setOwner(1);
r.setPrice(12.65);
r.setReleaseMonth(12);
r.setReleaseType(1);
r.setTitle("fake-tracks-testing");
r.setYear(2000);
try
{
r.save();
Artist g1 = new Artist("DonkeyManTester");
Artist g2 = new Artist("Goat ManTester");
Groop g3 = new Groop("AnimalsTester");
LineUp lu = new LineUp(g3);
lu.addArtist(g1);
lu.addArtist(g2);
Artist p1 = new Artist("Bunny ProducerTester");
Track t1 = new Track(1);
t1.setLengthInSeconds(100);
t1.setTitle("DonkeyTester");
t1.addLineUp(lu);
t1.addPersonnel(p1);
t1.setFormTrackNumber(1);
Track t2 = new Track(2);
t2.setLengthInSeconds(120);
t2.setTitle("HelpTester");
t2.addLineUp(lu);
t2.addPersonnel(p1);
t2.setFormTrackNumber(1);
// This should cause the record to update
r.addTrack(t1);
r.addTrack(t2);
r.save();
Record r2 = GetRecords.create().getRecords("fake-tracks-testing").get(0);
assert (r2.getTracks().iterator().next().getLineUps().size() == 1);
}
catch (SQLException e)
{
System.err.println("Exception");
e.printStackTrace();
assert (false);
}
built = true;
}
} | 2 |
@Override
public boolean onCommand(CommandSender sender, org.bukkit.command.Command cmd, String[] args) {
if(!Commands.isPlayer(sender)) return false;
Player p = (Player) sender;
if(args.length != 1) return false;
if(PlayerChat.plugin.getConfig().getBoolean("CustomChannels.Enabled", true)) {
channel.joinChannel(p, args[0]);
return true;
} else {
Messenger.tell(p, Msg.CUSTOM_CHANNELS_DISABLED);
return true;
}
} | 3 |
private Image getImage(int i){
if (i == 1){
return newgame;
}
if (i == 2){
return loadgame;
}
if (i == 3){
return credits;
}
if (i == 4){
return options;
}
if (i == 5){
return quit;
}
return null;
} | 5 |
public void update() {
for (int particleIndex = 0; particleIndex < particleArray.length; particleIndex++) {
if (particleArray[particleIndex] != null) {
particleArray[particleIndex].update();
}
}
this.removeDeadParticles();
} | 2 |
String run(String input){
String[] array = new Tokenizer().makeToken(input);
double mChance = 0;
double fChance = 0;
for(int i = 0; i < array.length; i++){
if(mProb.keySet().contains(array[i])){
mChance = mChance + (Math.log(mProb.get(array[i])/(mProb.get(array[i]) + fProb.get(array[i])) / Math.log(2)));
} else {
mChance = mChance + (Math.log(k)/(mAmountWords + k * diffWords)) / Math.log(2);
}
if(fProb.keySet().contains(array[i])) {
fChance = fChance + Math.log(fProb.get(array[i])/(mProb.get(array[i]) + fProb.get(array[i]))/Math.log(2));
} else {
fChance = fChance + (Math.log(k)/(fAmountWords + k * diffWords)) / Math.log(2);
}
}
// System.out.println(mChance);
// System.out.println(fChance);
if(mChance > fChance) {
return "MALE";
} else if (fChance > mChance){
return "FEMALE";
} else {
return "TIE";
}
} | 5 |
private String whichBinary(String type)
{
for (int i = 0; i < Expression.binaryTypes.length; i++)
{
if (type.equals (Expression.binaryTypes[i]))
{
if(type.equals("plus")||type.equals("minus")||type.equals("times")
||type.equals("divided by"))
{
return "operator";
}
else if(type.equals("or")||type.equals("and"))
{
return "logic";
}
else
{
//"equals", "greater than", "less than"
return "compare";
}
}
}
return null;
} | 8 |
private void scan() {
for(String location : locations) {
File pluginDir = new File(location);
if (pluginDir.exists() && pluginDir.isDirectory()) {
for (String n : pluginDir.list()) {
if (n.endsWith(".jar")) {
try {
URL url = new File(location + File.separator + n)
.toURI().toURL();
PluginDescriptor plugin = parsePluginManifest(url);
if (plugin != null) {
plugins.add(plugin);
}
} catch (MalformedURLException e) {
// This basically shouldn't happen, since we're
// constructing
// the URL directly from the directory name and the
// name of
// a located file.
}
}
}
}
}
logger.logTimedMessage("Found " + plugins.size() + " plugins", 0,0);
} | 7 |
@Override
public void merge(I merger, I mergee) {
Set<TKey<?, ?>> keys = mergee.getAvailableKeys();
for (TKey key : keys) {
if (filterKeys.contains(key)) {
List<?> qvs = mergee.getQualifiedValues(key);
merger.deleteValues(key);
for (Object ob : qvs) {
QualifiedValue<?> qv = (QualifiedValue<?>) ob;
merger.addValue(key, qv.getValue(), qv.getQualifiers().toArray(new Enum[qv.getQualifiers().size()]));
}
}
}
} | 8 |
public String getTaxes(String s)
{
String taxValue = "17";
return taxValue;
}; | 0 |
public int getMinimum() {
int res = -1;
int min = -1;
for (int i = 0; i < result.length; i++) {
if (result[i] != -1 && visited[i] != 1 && (result[i] < min || min == -1)) {
min = result[i];
res = i;
}
}
return res;
} | 5 |
public LocalDataManager(String dataHome) throws WrongArgumentException
{
File dfile = new File(dataHome);
if( dfile == null || !dfile.exists())
{
dfile.mkdir();
}else if(dfile.exists()&&!dfile.isDirectory()){
throw new WrongArgumentException("dataHome","Can not create Directory"+dataHome);
}
this.dataHome = dataHome;
} | 4 |
public double geometricMean_as_double() {
double gmean = 0.0D;
switch (type) {
case 1:
double[] dd = this.getArray_as_double();
gmean = Stat.geometricMean(dd);
break;
case 12:
BigDecimal[] bd = this.getArray_as_BigDecimal();
gmean = Stat.geometricMean(bd);
bd = null;
break;
case 14:
throw new IllegalArgumentException("Complex cannot be converted to double");
default:
throw new IllegalArgumentException("This type number, " + type + ", should not be possible here!!!!");
}
return gmean;
} | 3 |
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Starting");
String userName = request.getParameter("username");
String password1 = request.getParameter("password1");
String password2 = request.getParameter("password2");
String makeadmin = request.getParameter("makeadmin");
int admin = 0;
try{
if(makeadmin.equals("on"))
admin=1;
else
admin=0;
} catch (Exception e) {
}
System.out.println("Got post data. Starting encryption");
String encryptedpass1 = Encryptor.Encrypt(password1);
String encryptedpass2 = Encryptor.Encrypt(password2);
if(encryptedpass1.equalsIgnoreCase(encryptedpass2))
{
System.out.println("Passwords match");
//**********************
//CONNECTING TO DATABASE
//**********************
Connection conn = null;
conn = ConnectionManager.getConnection();
if (conn == null)
{
}
else
{
//**************************
//END CONNECTING TO DATABASE
//**************************
System.out.println("Connection successful");
java.sql.Statement checkStmt;
try {
checkStmt = conn.createStatement();
ResultSet rs = checkStmt.executeQuery("SELECT * FROM users WHERE username = \"" + userName + "\"");
if(!rs.next())
{
System.out.println("Username is available");
java.sql.Statement submitStmt;
try {
submitStmt = conn.createStatement();
System.out.println("Inserting..");
submitStmt.executeUpdate("INSERT INTO users VALUES ('" + userName + "','" + encryptedpass1 + "','" + String.valueOf(admin) + "')");
System.out.println("Inserted! ..hopefully");
conn.close();
response.sendRedirect("/Mr_Faulty/Faulty/");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
System.out.println("Username taken.");
response.sendRedirect("/Mr_Faulty/Faulty/");
}
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
System.out.println("Passwords don't match.");
System.out.println(encryptedpass1);
System.out.println(encryptedpass2);
response.sendRedirect("/Mr_Faulty/Faulty/Registration/");
}
} | 7 |
public void setDateTo(Date dateTo) {
this.dateTo = dateTo;
} | 0 |
private void addAnimPanel() {
String s = MDView.getInternationalText("Animation");
animPanel = new JPanel(new BorderLayout());
JPanel p = new JPanel(new BorderLayout(5, 5));
p.setBorder(new EmptyBorder(10, 10, 10, 10));
animPanel.add(p, BorderLayout.NORTH);
JPanel child = new JPanel(new SpringLayout());
p.add(child, BorderLayout.NORTH);
// row 1
s = MDView.getInternationalText("NumberOfFrames");
child.add(new JLabel((s != null ? s : "Number of Frames") + ":"));
nFrameLabel = new JLabel("Unknown");
child.add(nFrameLabel);
// row 2
s = MDView.getInternationalText("CurrentFrame");
child.add(new JLabel((s != null ? s : "Current Frame") + ":"));
currentFrameLabel = new JLabel("Unknown");
child.add(currentFrameLabel);
// row 3
s = MDView.getInternationalText("CurrentOffset");
child.add(new JLabel((s != null ? s : "Current Offset") + ":"));
offsetLabel = new JLabel("Unknown");
child.add(offsetLabel);
// row 4
s = MDView.getInternationalText("CurrentDelayTime");
child.add(new JLabel((s != null ? s : "Current Delay") + ":"));
currentDelayLabel = new JLabel("Unknown");
child.add(currentDelayLabel);
// row 5
s = MDView.getInternationalText("LogicalScreen");
child.add(new JLabel((s != null ? s : "Logical Screen") + ":"));
logicalScreenLabel = new JLabel("Unknown");
child.add(logicalScreenLabel);
// row 6
s = MDView.getInternationalText("NumberOfLoops");
child.add(new JLabel((s != null ? s : "Number of Loops") + " (-1: No loop; 0: Loop forever):"));
loopField = new IntegerTextField(1000, -1, 100000, 8);
child.add(loopField);
PropertiesPanel.makeCompactGrid(child, 6, 2, 5, 5, 20, 10);
loopField.addActionListener(okListener);
nFrameLabel.setText(image.getFrames() + "");
currentFrameLabel.setText(image.getCurrentFrame() + "");
currentDelayLabel.setText(image.getDelayTime(image.getCurrentFrame()) + " milliseconds");
offsetLabel.setText("( " + (int) (image.getXFrame() - image.getRx()) + " , "
+ (int) (image.getYFrame() - image.getRy()) + " ) pixels");
logicalScreenLabel.setText(image.getLogicalScreenWidth() + " x " + image.getLogicalScreenHeight() + " pixels");
loopField.setValue(image.getLoopCount());
tabbedPane.addTab(s != null ? s : "Animation", animPanel);
} | 7 |
@Override
public void endElement(String uri,
String localName,
String qname) {
if (qname.equals("parse")) {
indent -= 2;
scopes.pop();
} else if (qname.equals("uncommon_trap")) {
currentTrap = null;
} else if (qname.equals("late_inline")) {
// Populate late inlining info.
// late_inline scopes are specified in reverse order:
// compiled method should be on top of stack.
CallSite caller = late_inline_scope.pop();
Method m = compile.getMethod();
if (m != caller.getMethod()) {
System.out.println(m);
System.out.println(caller.getMethod() + " bci: " + bci);
throw new InternalError("call site and late_inline info don't match");
}
// late_inline contains caller+bci info, convert it
// to bci+callee info used by LogCompilation.
site = compile.getLateInlineCall();
do {
bci = caller.getBci();
// Next inlined call.
caller = late_inline_scope.pop();
CallSite callee = new CallSite(bci, caller.getMethod());
site.add(callee);
site = callee;
} while (!late_inline_scope.empty());
if (caller.getBci() != -999) {
System.out.println(caller.getMethod());
throw new InternalError("broken late_inline info");
}
if (site.getMethod() != caller.getMethod()) {
System.out.println(site.getMethod());
System.out.println(caller.getMethod());
throw new InternalError("call site and late_inline info don't match");
}
// late_inline is followed by parse with scopes.size() == 0,
// 'site' will be pushed to scopes.
late_inline_scope = null;
} else if (qname.equals("task")) {
types.clear();
methods.clear();
site = null;
}
} | 8 |
public static AccessToken getAccessToken(String appid, String appsecret) {
AccessToken accessToken = null;
String requestUrl = access_token_url.replace("APPID", appid).replace(
"APPSECRET", appsecret);
JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
// ɹ
if (null != jsonObject) {
try {
accessToken = new AccessToken();
accessToken.setToken(jsonObject.getString("access_token"));
accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
} catch (Exception e) {
accessToken = null;
// ȡtokenʧ
log.error("ȡtokenʧ errcode:{} errmsg:{}",
jsonObject.getInt("errcode"),
jsonObject.getString("errmsg"));
}
}
return accessToken;
} | 2 |
public String remove(int key) {
Node current, previous;
current = head;
previous = null;
while (current != null && current.getKey() != key) {
previous = current;
current = current.getNext();
}
String output = current.getContent();
if (previous == null) {
head = head.getNext();
size--;
return output;
}
previous.setNext(current.getNext());
size--;
return output;
} | 3 |
public void setHP(int hp)
{
this.hp = hp;
} | 0 |
@Override
public final String readLine() throws IOException {
if (lineBuffer == null) {
lineBuffer = new char[LINE_BUFFER_INCREMENT_SIZE];
}
char[] buf = lineBuffer;
int room = buf.length;
int offset = 0;
int c;
loop: while (true) {
c = read();
switch (c) {
case -1:
case '\n':
break loop;
case '\r':
read();
break loop;
default:
if (--room < 0) {
buf = new char[offset + LINE_BUFFER_INCREMENT_SIZE];
room = buf.length - offset - 1;
System.arraycopy(lineBuffer, 0, buf, 0, offset);
lineBuffer = buf;
}
buf[offset++] = (char) c;
break;
}
}
if ((c == -1) && (offset == 0)) {
return null;
}
return String.copyValueOf(buf, 0, offset);
} | 8 |
public int transform(CtClass tclazz, int pos, CodeIterator iterator,
ConstPool cp) throws BadBytecode
{
int c = iterator.byteAt(pos);
if (c == PUTFIELD || c == PUTSTATIC) {
int index = iterator.u16bitAt(pos + 1);
String typedesc = isField(tclazz.getClassPool(), cp,
fieldClass, fieldname, isPrivate, index);
if (typedesc != null) {
if (c == PUTSTATIC) {
CodeAttribute ca = iterator.get();
iterator.move(pos);
char c0 = typedesc.charAt(0);
if (c0 == 'J' || c0 == 'D') { // long or double
// insertGap() may insert 4 bytes.
pos = iterator.insertGap(3);
iterator.writeByte(ACONST_NULL, pos);
iterator.writeByte(DUP_X2, pos + 1);
iterator.writeByte(POP, pos + 2);
ca.setMaxStack(ca.getMaxStack() + 2);
}
else {
// insertGap() may insert 4 bytes.
pos = iterator.insertGap(2);
iterator.writeByte(ACONST_NULL, pos);
iterator.writeByte(SWAP, pos + 1);
ca.setMaxStack(ca.getMaxStack() + 1);
}
pos = iterator.next();
}
int mi = cp.addClassInfo(methodClassname);
String type = "(Ljava/lang/Object;" + typedesc + ")V";
int methodref = cp.addMethodrefInfo(mi, methodName, type);
iterator.writeByte(INVOKESTATIC, pos);
iterator.write16bit(methodref, pos + 1);
}
}
return pos;
} | 6 |
public ArrayList<Integer> readData(String filename) throws FileNotFoundException {
Scanner scanner = new Scanner(new BufferedInputStream(new FileInputStream(filename)));
ArrayList<Integer> data = new ArrayList<Integer>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.trim().length() == 0)
continue;
String result = line.trim();
int value = Integer.parseInt(result);
data.add(value);
}
scanner.close();
return data;
} | 2 |
public void initialize() throws Exception {
m_RunNumber = getRunLower();
m_DatasetNumber = 0;
m_PropertyNumber = 0;
m_CurrentProperty = -1;
m_CurrentInstances = null;
m_Finished = false;
if (m_UsePropertyIterator && (m_PropertyArray == null)) {
throw new Exception("Null array for property iterator");
}
if (getRunLower() > getRunUpper()) {
throw new Exception("Lower run number is greater than upper run number");
}
if (getDatasets().size() == 0) {
throw new Exception("No datasets have been specified");
}
if (m_ResultProducer == null) {
throw new Exception("No ResultProducer set");
}
if (m_ResultListener == null) {
throw new Exception("No ResultListener set");
}
// if (m_UsePropertyIterator && (m_PropertyArray != null)) {
determineAdditionalResultMeasures();
// }
m_ResultProducer.setResultListener(m_ResultListener);
m_ResultProducer.setAdditionalMeasures(m_AdditionalMeasures);
m_ResultProducer.preProcess();
// constrain the additional measures to be only those allowable
// by the ResultListener
String [] columnConstraints = m_ResultListener.
determineColumnConstraints(m_ResultProducer);
if (columnConstraints != null) {
m_ResultProducer.setAdditionalMeasures(columnConstraints);
}
} | 7 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TMasterProduct other = (TMasterProduct) obj;
if (!Objects.equals(this.pcodeSap, other.pcodeSap)) {
return false;
}
if (!Objects.equals(this.pcodeScylla, other.pcodeScylla)) {
return false;
}
return true;
} | 4 |
public void run(){
try{
sendChannelOpen();
Buffer buf=new Buffer(rmpsize);
Packet packet=new Packet(buf);
Session _session=getSession();
int i=0;
while(isConnected() &&
thread!=null &&
io!=null &&
io.in!=null){
i=io.in.read(buf.buffer,
14,
buf.buffer.length-14
-Session.buffer_margin
);
if(i<=0){
eof();
break;
}
packet.reset();
buf.putByte((byte)Session.SSH_MSG_CHANNEL_DATA);
buf.putInt(recipient);
buf.putInt(i);
buf.skip(i);
synchronized(this){
if(close)
break;
_session.write(packet, this, i);
}
}
}
catch(Exception e){
}
disconnect();
} | 7 |
@Override
public void execute() throws BuildException {
Migrator migrator = new Migrator(url, driver, user, password, scriptsLocation);
log(migrator.printBeforeDiagnostics());
if (action != null) {
if (action.equals(UPGRADE)) {
log(UPGRADE + " action started");
migrator.migrateUp();
log(UPGRADE + " action ended");
} else if (action.equals(UPGRADE_ALL)) {
log(UPGRADE_ALL + " action started");
migrator.migrateUpAll();
log(UPGRADE_ALL + " action ended");
} else if (action.equals(ROLLBACK)) {
log(ROLLBACK + " action started");
migrator.migrateDown();
log(ROLLBACK + " action ended");
} else if (action.equals(INIT)) {
log(INIT + " action started");
migrator.initDb();
log(INIT + " action ended");
} else if (action.equals(STATUS)) {
log(STATUS + " action started");
migrator.printAfterDiagnostics();
log(STATUS + " action ended");
} else {
throw new BuildException("don't kow what " + action
+ " is. Must be one of:" + UPGRADE_ALL + " " + UPGRADE + " "
+ ROLLBACK + " " + INIT + " " + STATUS);
}
log(migrator.printAfterDiagnostics());
} else {
throw new BuildException("action is required");
}
} | 6 |
public Integer getRosterCount (Date d) {
Integer rc = 0;
for (Trip t: getAllTrips(d)) {
rc += t.getRosterCount();
}
return rc;
} | 1 |
public double describe(GameState state, Player player)
{
Map<Player, Integer> largestClusterSize = new HashMap<Player, Integer>();
Set<Country> countedCountries = new HashSet<Country>();
for (Country country : state.getCountries())
{
if (countedCountries.contains(country))
continue;
int clusterSize = Util.countCluster(country, countedCountries);
if (largestClusterSize.containsKey(country.getPlayer()))
{
if(largestClusterSize.get(country.getPlayer()) < clusterSize)
largestClusterSize.put(country.getPlayer(), clusterSize);
}
else
{
largestClusterSize.put(country.getPlayer(), clusterSize);
}
}
if ( !largestClusterSize.containsKey(player) )
return -1;
int playerCount = 0;
while(largestClusterSize.size() < state.getNumberOfPlayers())
largestClusterSize.put(new RandomPlayer("empty"+playerCount++), 0);
int sum = 0;
for(Integer clusterSize : largestClusterSize.values())
{
sum += clusterSize;
}
sum -= largestClusterSize.get(player);
if (sum == 0)
return 1;
//double mean = (double)sum / (largestClusterSize.size() - 1);
double ratio = (double)(largestClusterSize.get(player)) / (double)sum;
// ratio capped at 2. If you have more than twice as large a cluster as all other players combined, you reach max value
if(ratio > 2)
ratio = 2;
return normalize(ratio, 0, 2);
} | 9 |
private void makeHashTable(NonDuplicateArrayList<String> newTransaction,
int[] hashTable,
int iteration,
int[] newHashTable,
NonDuplicateArrayList<String> newnewTransaction){
int[] occurrenceCount = new int[newTransaction.size()];
// for (NonDuplicateArrayList<Integer> subset: getKSubset(newTransaction, iteration + 1)){
for (NonDuplicateArrayList<String> subset: getKSubset(newTransaction, iteration + 1)){
boolean flag = true;
// for (NonDuplicateArrayList<Integer> subsubset: getKSubset(subset, iteration)){
for (NonDuplicateArrayList<String> subsubset: getKSubset(subset, iteration)){
if (hashTable[Math.hash(subsubset, hashTable.length)] < Config.minSupCount){
flag = false;
break;
}
}
if (flag){
newHashTable[Math.hash(subset, newHashTable.length)]++;
// for (Integer i: subset)
for (String i: subset)
occurrenceCount[newTransaction.indexOf(i)]++;
}
}
for (int i = 0; i < newTransaction.size(); i++){
if (occurrenceCount[i] > 0)
newnewTransaction.add(newTransaction.get(i));
}
} | 7 |
public TargetPicker createTargetPicker(String targetPickerId, NamedNodeMap attributes, List<Element> childElements){
currentAttributesMap = attributes;
TargetPickerId id = TargetPickerId.valueOf(targetPickerId);
TargetPicker targetPicker;
switch(id){
case ADJACENT:
targetPicker = new TargetAdjacentEntities(createAnimation(childElements), readTeam("targetTeam"));
break;
case ONE_IN_FRONT:
targetPicker = new TargetOneInFront(createAnimation(childElements), readTeam("targetTeam"));
break;
case IN_RANGE:
targetPicker = new TargetEntitiesInRange(readDouble("range"), createAnimation(childElements), readTeam("targetTeam"), readBoolean("includeActor", false));
break;
case LINE_AHEAD:
targetPicker = new TargetLineAhead(read("distance"), read("skipNFirstSquares"), createAnimation(childElements), readTeam("targetTeam"));
break;
case RECTANGLE_AHEAD:
targetPicker = new TargetRectangleAhead(read("skipNFirstSquares", 0), read("width"), read("length"), createAnimation(childElements), readTeam("targetTeam"));
break;
case SELF:
targetPicker = new TargetSelf();
break;
case FILTER_BELOW_HEALTH:
targetPicker = new FilterBelowHealthThreshold(createSubTargetPicker(childElements), read("healthThresholdPercent"));
break;
default:
throw new IllegalArgumentException();
}
if(read("maxNumTargets", 0) > 0){
return new LimitNumberOfTargets(targetPicker, read("maxNumTargets"));
}
return targetPicker;
} | 8 |
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
String v = value.toString();
String dv = v;
final ImageIcon archIcon = new ImageIcon(getClass().getResource(Constants.ICON_PATH + "arch.gif"));
final ImageIcon dirIcon = new ImageIcon(getClass().getResource(Constants.ICON_PATH + "dir.gif"));
if(value.toString().startsWith("a:"))
{
this.setIcon(archIcon);
dv =v.substring(2);
}
else if(value.toString().startsWith("d:"))
{
this.setIcon(dirIcon);
dv =v.substring(2);
}
else
{
this.setIcon(null);
}
//setBorder(isSelected ? new LineBorder(list.getSelectionForeground()) :new LineBorder(list.getBackground()) );
//setBackground(list.getBackground());
setFont(list.getFont().deriveFont(Font.PLAIN));
setBackground(isSelected ? list.getSelectionBackground() : list.getBackground());
setForeground(isSelected ? list.getSelectionForeground() : list.getForeground());
setText(dv);
return this;
} | 4 |
public void run() {
ServerThread sendToClients = new ServerThread(this);
sendToClients.start();
while (true) {
try {
DatagramPacket recvPacket = new DatagramPacket(recvBuffer, recvBuffer.length);
sock.receive(recvPacket);
String data = new String(recvPacket.getData());
InetAddress ip = recvPacket.getAddress();
int port = recvPacket.getPort();
System.out.println("Received from " + ip + " , port " + port + ": " + data);
String type = Utils.parseType(data);
if (type == null) continue;
if (type.equals("connect")) {
UUID id = Utils.parseId(data);
clients.put(id, new ClientData(ip, port));
continue;
} else if (type.equals("disconnect")) {
UUID id = Utils.parseId(data);
// TODO: Remove objects owned by player
continue;
} else if (type.equals("chat")) {
for(ClientData client : clients.values()) {
InetAddress ip1 = client.getIp();
int port1 = client.getPort();
sendBuffer2 = data.getBytes();
DatagramPacket sendPacket2 = new DatagramPacket(sendBuffer2, sendBuffer2.length, ip, port);
try {
sock.send(sendPacket2);
} catch (IOException e) {
e.printStackTrace();
}
}
continue;
}
// Send ack
UUID id = Utils.parseId(data);
state.put(id, data);
sendBuffer = ("type:ACK " + id + "\n").getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, ip, port);
sock.send(sendPacket);
} catch (Exception e) {
e.printStackTrace();
}
}
} | 8 |
public int calculateFitness(Hypothesis h)
{
if (type == RANDOM)
{
//Just return a random fitness
return (int)(Math.random() * 100);
}
else if (type == TARGET)
{
double sumPerc = 0;
int hIndex = 0;
for (int i = 0; i < targetValues.length; i++)
{
//Convert each block of seven bits to an integer value
String binStr = "";
for (int j = 0; j < 7; j++)
{
binStr += h.bitstring[hIndex] + "";
hIndex++;
}
int cVal = Integer.parseInt(binStr, 2); //2 for binary
if (debug) System.out.println(binStr + " -> " + cVal);
//Calculate how much the hypothesis fitness value
//differs from the target value.
int diff = Math.abs(cVal - targetValues[i]);
double perc = (double)100 - (double)diff / (double)128 * (double)100;
//Add a small random diff to fitness for testing purpose
if (rndFitness)
{
double rndDiff = Math.random() * 10 - 5;
perc += rndDiff;
if (perc < 0) perc = 0;
if (perc >= 100) perc = 100;
}
sumPerc += perc;
if (debug) System.out.println(targetValues[i] + "/" + cVal + ": diff=" + diff + " perc=" + perc);
}
//Return average diff (in percent)
return (int)(sumPerc / (double)targetValues.length);
}
else
{
return 10;
}
} | 9 |
private void checkMessage() {
while (true) {
jTextArea1.append(jTextField1.getText() + control.receiveMessage() + "\n");
}
} | 1 |
public Dimension getPreferredSize() {
int height = 0;
int width = 0;
//
// Use the size set by the application
//
if (isPreferredSizeSet())
return super.getPreferredSize();
//
// Leave room for the component border
//
Border border = getBorder();
if (border != null) {
Insets insets = border.getBorderInsets(this);
width += insets.left + insets.right;
height += insets.top + insets.bottom;
}
//
// Get the label font
//
Font font = getFont();
if (font == null)
font = new Font("Dialog", Font.PLAIN, 8);
else
font = font.deriveFont(Font.PLAIN, font.getSize()-2);
//
// Leave room for the chart title
//
if (chartTitle != null && chartTitle.length() != 0) {
Font titleFont = font.deriveFont(Font.BOLD, font.getSize()+10);
height += getFontMetrics(titleFont).getHeight();
}
//
// Leave room for the chart grid
//
FontMetrics fm = getFontMetrics(font);
int labelHeight = fm.getHeight();
int labelWidth = fm.stringWidth("1234.56");
int gridSize = getGridSize();
width += labelWidth*gridSize + 6*labelHeight;
height += labelWidth*gridSize + 6*labelHeight;
return new Dimension(width, height);
} | 5 |
public static void main(String[] args)
{
try
{
//////////////////////////////////////////
// Step 1: Initialize the GridSim package. It should be called
// before creating any entities. We can't run this example without
// initializing GridSim first. We will get run-time exception
// error.
// number of grid user entities + any Workload entities.
int num_user = 5;
Calendar calendar = Calendar.getInstance();
// a flag that denotes whether to trace GridSim events or not.
boolean trace_flag = false;
// Initialize the GridSim package
System.out.println("Initializing GridSim package");
GridSim.init(num_user, calendar, trace_flag);
//////////////////////////////////////////
// Step 2: Creates one or more GridResource entities
// baud rate and MTU must be big otherwise the simulation
// runs for a very long period.
double baud_rate = 1000000; // 1 Gbits/sec
double propDelay = 10; // propagation delay in millisecond
int mtu = 100000; // max. transmission unit in byte
int rating = 400; // rating of each PE in MIPS
int i = 0;
// more resources can be created by
// setting totalResource to an appropriate value
int totalResource = 3;
ArrayList resList = new ArrayList(totalResource);
String[] resArray = new String[totalResource];
for (i = 0; i < totalResource; i++)
{
String resName = "Res_" + i;
GridResource res = createGridResource(resName, baud_rate,
propDelay, mtu, rating);
// add a resource into a list
resList.add(res);
resArray[i] = resName;
}
//////////////////////////////////////////
// Step 3: Get the list of trace files. The format should be:
// ASCII text, gzip or zip.
// In this example, I use the trace files from:
// http://www.cs.huji.ac.il/labs/parallel/workload/index.html
String[] fileName = {
"l_lanl_o2k.swf.zip", // LANL Origin 2000 Cluster (Nirvana)
"l_sdsc_blue.swf.txt.gz", // SDSC Blue Horizon
};
String dir = "../"; // location of these files
String customFile = "custom_trace.txt"; // custom trace file format
// total number of Workload entities
int numWorkload = fileName.length + 1; // including custom trace
//////////////////////////////////////////
// Step 4: Creates one or more Workload trace entities.
// Each Workload entity can only read one trace file and
// submit its Gridlets to one grid resource entity.
int resID = 0;
Random r = new Random();
ArrayList load = new ArrayList();
for (i = 0; i < fileName.length; i++)
{
resID = r.nextInt(totalResource);
Workload w = new Workload("Load_"+i, baud_rate, propDelay, mtu,
dir + fileName[i], resArray[resID], rating);
// add into a list
load.add(w);
}
// for the custom trace file format
Workload custom = new Workload("Custom", baud_rate, propDelay, mtu,
dir + customFile, resArray[resID], rating);
// add into a list
load.add(custom);
// tells the Workload entity what to look for.
// parameters: maxField, jobNum, submitTime, runTime, numPE
custom.setField(4, 1, 2, 3, 4);
custom.setComment("#"); // set "#" as a comment
//////////////////////////////////////////
// Step 5: Creates one or more grid user entities.
// number of grid user entities
int numUserLeft = num_user - numWorkload;
// number of Gridlets that will be sent to the resource
int totalGridlet = 5;
// create users
ArrayList userList = new ArrayList(numUserLeft);
for (i = 0; i < numUserLeft; i++)
{
// if trace_flag is set to "true", then this experiment will
// create User_i.csv where i = 0 ... (num_user-1)
NetUser user = new NetUser("User_"+i, totalGridlet, baud_rate,
propDelay, mtu, trace_flag);
// add a user into a list
userList.add(user);
}
//////////////////////////////////////////
// Step 6: Builds the network topology among entities.
// In this example, the topology is:
// user(s) --1Gb/s-- r1 --10Gb/s-- r2 --1Gb/s-- GridResource(s)
// |
// workload(s) --1Gb/s-- |
// create the routers.
// If trace_flag is set to "true", then this experiment will create
// the following files (apart from sim_trace and sim_report):
// - router1_report.csv
// - router2_report.csv
Router r1 = new RIPRouter("router1", trace_flag); // router 1
Router r2 = new RIPRouter("router2", trace_flag); // router 2
// connect all user entities with r1 with 1Mb/s connection
// For each host, specify which PacketScheduler entity to use.
NetUser obj = null;
for (i = 0; i < userList.size(); i++)
{
// A First In First Out Scheduler is being used here.
// SCFQScheduler can be used for more fairness
FIFOScheduler userSched = new FIFOScheduler("NetUserSched_"+i);
obj = (NetUser) userList.get(i);
r1.attachHost(obj, userSched);
}
// connect all Workload entities with r1 with 1Mb/s connection
// For each host, specify which PacketScheduler entity to use.
Workload w = null;
for (i = 0; i < load.size(); i++)
{
// A First In First Out Scheduler is being used here.
// SCFQScheduler can be used for more fairness
FIFOScheduler loadSched = new FIFOScheduler("LoadSched_"+i);
w = (Workload) load.get(i);
r1.attachHost(w, loadSched);
}
// connect all resource entities with r2 with 1Mb/s connection
// For each host, specify which PacketScheduler entity to use.
GridResource resObj = null;
for (i = 0; i < resList.size(); i++)
{
FIFOScheduler resSched = new FIFOScheduler("GridResSched_"+i);
resObj = (GridResource) resList.get(i);
r2.attachHost(resObj, resSched);
}
// then connect r1 to r2 with 10 Gbits/s connection
// For each host, specify which PacketScheduler entity to use.
baud_rate = 10000000;
Link link = new SimpleLink("r1_r2_link", baud_rate, propDelay, mtu);
FIFOScheduler r1Sched = new FIFOScheduler("r1_Sched");
FIFOScheduler r2Sched = new FIFOScheduler("r2_Sched");
// attach r2 to r1
r1.attachRouter(r2, link, r1Sched, r2Sched);
//////////////////////////////////////////
// Step 7: Starts the simulation
GridSim.startGridSimulation();
//////////////////////////////////////////
// Final step: Prints the Gridlets when simulation is over
// also prints the routing table
r1.printRoutingTable();
r2.printRoutingTable();
GridletList glList = null;
for (i = 0; i < userList.size(); i++)
{
obj = (NetUser) userList.get(i);
glList = obj.getGridletList();
printGridletList(glList, obj.get_name(), trace_flag);
}
// prints the Gridlets inside a Workload entity
for (i = 0; i < load.size(); i++)
{
w = (Workload) load.get(i);
w.printGridletList(trace_flag);
}
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Unwanted errors happen");
}
} | 9 |
int getPreferredWidth (int columnIndex) {
int width = 0;
GC gc = new GC (parent);
gc.setFont (getFont (columnIndex, false));
width += gc.stringExtent (getText (columnIndex, false)).x + 2 * MARGIN_TEXT;
if (columnIndex == 0) {
if (parent.col0ImageWidth > 0) {
width += parent.col0ImageWidth;
width += CTable.MARGIN_IMAGE;
}
} else {
Image image = getImage (columnIndex, false);
if (image != null) {
width += image.getBounds ().width;
width += CTable.MARGIN_IMAGE;
}
}
if (parent.isListening (SWT.MeasureItem)) {
Event event = new Event ();
event.item = this;
event.gc = gc;
event.index = columnIndex;
event.x = getContentX (columnIndex);
event.y = parent.getItemY (this);
event.width = width;
event.height = parent.itemHeight;
parent.notifyListeners (SWT.MeasureItem, event);
if (parent.itemHeight != event.height) {
parent.customHeightSet = true;
boolean update = parent.setItemHeight (event.height + 2 * parent.getCellPadding ());
if (update) parent.redraw ();
}
width = event.width;
}
gc.dispose ();
if (columnIndex == 0 && (parent.getStyle () & SWT.CHECK) != 0) {
width += parent.checkboxBounds.width;
width += CTable.MARGIN_IMAGE;
}
return width + 2 * parent.getCellPadding ();
} | 8 |
private void inputTextPaneKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_inputTextPaneKeyPressed
// TODO add your handling code here:
String s = (String) sendToCombo.getSelectedItem() ;
if(!s.equals("To All")){
whisper = true;
}
else{
whisper = false;
}
// for test
if(evt.getKeyChar( )== '\n'&& client.getLogState()){
// client.send(parseInputText(inputTextPane.getText()));
// inputText = inputTextPane.getText();
inputText = getInputText(inputTextPane);
refreshInputPane();
System.out.println(inputText);
if(!inputText.equals("") ){
showMessage();
if(!whisper){
client.sendRoomMsg(roomKey,inputText);
}else{
String receiver = (String)sendToCombo.getSelectedItem();
client.sendWhisper(roomKey,receiver,inputText);
}
}
}
}//GEN-LAST:event_inputTextPaneKeyPressed | 5 |
public Main_Frame() {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CE_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CE_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CE_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CE_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
initComponents();
} | 6 |
public static boolean isVariable(char ch) {
return Character.isUpperCase(ch);
} | 0 |
protected void byteLoop(RasterAccessor src,
RasterAccessor dst,
int filterSize) {
int dwidth = dst.getWidth();
int dheight = dst.getHeight();
int dnumBands = dst.getNumBands();
byte dstDataArrays[][] = dst.getByteDataArrays();
int dstBandOffsets[] = dst.getBandOffsets();
int dstPixelStride = dst.getPixelStride();
int dstScanlineStride = dst.getScanlineStride();
byte srcDataArrays[][] = src.getByteDataArrays();
int srcBandOffsets[] = src.getBandOffsets();
int srcPixelStride = src.getPixelStride();
int srcScanlineStride = src.getScanlineStride();
int medianValues[] = new int[filterSize];
int tmpValues[] = new int[filterSize];
int wp = filterSize;
int tmpBuffer[] = new int[filterSize*dwidth];
int tmpBufferSize = filterSize*dwidth;
for (int k = 0; k < dnumBands; k++) {
byte dstData[] = dstDataArrays[k];
byte srcData[] = srcDataArrays[k];
int srcScanlineOffset = srcBandOffsets[k];
int dstScanlineOffset = dstBandOffsets[k];
int revolver = 0;
for (int j = 0; j < filterSize-1; j++) {
int srcPixelOffset = srcScanlineOffset;
for (int i = 0; i < dwidth; i++) {
int imageOffset = srcPixelOffset;
for (int v = 0; v < wp; v++) {
tmpValues[v] = srcData[imageOffset] & 0xff;
imageOffset += srcPixelStride;
}
tmpBuffer[revolver+i] = medianFilter(tmpValues);
srcPixelOffset += srcPixelStride;
}
revolver += dwidth;
srcScanlineOffset += srcScanlineStride;
}
// srcScanlineStride already bumped by
// filterSize-1*scanlineStride
for (int j = 0; j < dheight; j++) {
int srcPixelOffset = srcScanlineOffset;
int dstPixelOffset = dstScanlineOffset;
for (int i = 0; i < dwidth; i++) {
int imageOffset = srcPixelOffset;
for (int v = 0; v < wp; v++) {
tmpValues[v] = srcData[imageOffset] & 0xff;
imageOffset += srcPixelStride;
}
tmpBuffer[revolver + i] = medianFilter(tmpValues);
int a = 0;
for (int b = i; b < tmpBufferSize; b += dwidth) {
medianValues[a++] = tmpBuffer[b];
}
int val = medianFilter(medianValues);
dstData[dstPixelOffset] = (byte)val;
srcPixelOffset += srcPixelStride;
dstPixelOffset += dstPixelStride;
}
revolver += dwidth;
if (revolver == tmpBufferSize) {
revolver = 0;
}
srcScanlineOffset += srcScanlineStride;
dstScanlineOffset += dstScanlineStride;
}
}
} | 9 |
@Override
public String execute(SessionRequestContent request) throws ServletLogicException {
String page = ConfigurationManager.getProperty("path.page.user");
String prevPage = (String) request.getSessionAttribute(JSP_PAGE);
findUser(request);
if(page == null ? prevPage == null : !page.equals(prevPage)){
request.setSessionAttribute(JSP_PAGE, page);
cleanSessionShowUser(request);
}
return page;
} | 2 |
static void getMax(ArrayList<Integer> input, int k, int[] maxNum,ArrayList<Integer> output){
if(k==0){
int sum=0;
for(int v:input){
sum*=10;
sum+=v;
}//calculate the number after several swaps
if(sum>maxNum[0]){
maxNum[0]=sum;
deepCopyList(input,output);
}//update the results
return;
}
for (int i = 0; i < input.size() - 1; i ++) {
for (int j = i + 1; j < input.size(); j ++) {
swapList(input,i, j);//try to swap input[i] with input[j]
getMax(input, k - 1, maxNum,output);//take care of the other k - 1 swaps
swapList(input,i, j);//swap back
}
}
return;
} | 5 |
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false)
public void onJoin(PlayerJoinEvent e)
{
if(!isStaff(e.getPlayer()))
{
if(!e.getPlayer().hasPermission(Permissions.SPEAK))
{
return;
}
}
if(StaffChat.getStaffChat().getToggledStaffMembers().contains(e.getPlayer()))
{
e.getPlayer().sendMessage(StringUtilities.formatInfo("You have the staff chat enabled! All of your chat messages will go to it. Type in /togglestaffchat to disable it"));
}
if(e.getPlayer().hasPermission(Permissions.UPDATE) && StaffChat.getStaffChat().getUpdater().getResult() == Updater.UpdateResult.UPDATE_AVAILABLE)
{
e.getPlayer().sendMessage(StringUtilities.formatInfo("An update is available! get it at http://dev.bukkit.org/bukkit-plugins/staffchatbyroe or do /update to update it automatically"));
}
} | 5 |
public char revert(char c) {
if (c != '0' && c != '1') {
throw new IllegalArgumentException("Argument must be '0' or '1'");
}
return (c == '1') ? '0' : '1';
} | 3 |
public void showWall() {
allPosts = new ArrayList<TimedPosts>();
for (int i = 0; i < this.posts.size(); i++) {
String newPost = this.name + ": " + this.posts.get(i).getPost();
Long time = posts.get(i).getTime();
allPosts.add(new TimedPosts(newPost, time));
}
for (User follower : followers) {
for (TimedPosts post : follower.getPosts()) {
String newPost = follower.getName() + ": " + post.getPost();
Long time = post.getTime();
allPosts.add(new TimedPosts(newPost, time));
}
}
Collections.sort(allPosts, new Comparator<TimedPosts>() {
@Override
public int compare(TimedPosts o1, TimedPosts o2) {
return (int) ((o1.time - o2.time) / 1000000000);
}
});
for (TimedPosts post : allPosts) {
long elapsedTimeInSec = (System.nanoTime() - post.getTime()) / 1000000000;
if (elapsedTimeInSec < 60) {
int elapsedTime = (int) elapsedTimeInSec;
System.out.println(post.getPost() + "(" + elapsedTime
+ " seconds ago)");
} else {
int elapsedTime = (int) (elapsedTimeInSec / 60);
System.out.println(post.getPost() + "(" + elapsedTime
+ " minutes ago)");
}
}
} | 5 |
public ArrayList<Curso> listar(String condicao) throws Exception
{
ArrayList<Curso> listaCurso = new ArrayList<Curso>();
String sql = "SELECT * FROM curso " + condicao;
try
{
PreparedStatement stmt = ConnectionFactory.getConnection().prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
Curso curso = new Curso();
curso.setId(rs.getLong("id"));
curso.setNome(rs.getString("nome"));
listaCurso.add(curso);
}
rs.close();
}
catch (SQLException e)
{
throw e;
}
return listaCurso;
} | 2 |
public WumpusWorld()
{
String option = Config.getOption();
if (option.equalsIgnoreCase("gui"))
{
showGUI();
}
if (option.equalsIgnoreCase("sim"))
{
runSimulator();
}
if (option.equalsIgnoreCase("simdb"))
{
runSimulatorDB();
}
} | 3 |
public synchronized void parse(InputStream is) throws MiniXMLException {
automaton.reset();
try {
oTokenParser = new MiniXMLTokenParser(is);
} catch (IOException e) {
throw new MiniXMLException(MiniXMLException._MXMLE_TP_E_IE);
}
MiniXMLToken oMiniXMLToken;
boolean bEnd = false;
handler.startDocument();
String data;
do {
oMiniXMLToken = oTokenParser.getToken();
switch (oMiniXMLToken.getType()) {
case MiniXMLTokenParser.tError:
bEnd = true;
break;
case MiniXMLTokenParser.tComment:
break;
case MiniXMLTokenParser.tCharData:
data = oMiniXMLToken.getValue().trim();
if (data.length() > 0)
handler.data(automaton.getStateInt(), data);
// System.out.println("{" + oMiniXMLToken.getValue().trim() +
// "}");
break;
case MiniXMLTokenParser.tTagBeg:
getStartElement(oMiniXMLToken.getValue());
break;
case MiniXMLTokenParser.tEndTagBeg:
getEndElement(oMiniXMLToken.getValue());
break;
case MiniXMLTokenParser.tXMLTagBeg:
getXMLElement();
break;
// case MiniXMLTokenParser.tXMLTagEnd:
// System.out.print("?>");
// break;
default:
throw new MiniXMLException(
MiniXMLException._MXMLE_TGE_UKNOWN_TOKEN);
}
} while (!bEnd);
handler.endDocument(automaton.getStateInt());
} | 9 |
private static void initAgents(Simulation controller) {
agents = new Agent[numAgents];
int id = 0;
for(int i = 0; i < numStrategies; i++) {
int a = 0;
while (a < agentsStrat[i]) {
agents[id] = new Agent(controller, id, strategies[i]);
id++;
a++;
}
a = 0;
}
for(int a = 0; a < numAgents; a++) {
int x = 0;
int y = 0;
boolean free = false;
while(!free) {
x = gen.nextInt(xSize);
y = gen.nextInt(ySize);
if ((grid[x][y].getAgent()) == null) {
free = true;
}
}
agents[a].setPosition(x,y);
grid[x][y].setAgent(agents[a]);
}
} | 5 |
@Override
public List<Framedata> translateFrame(ByteBuffer buffer, int available) {
List<Framedata> frames = new LinkedList<Framedata>();
int offset = 0;
Framedata cur;
if (incompleteframe != null) {
while (true) {
try {
int available_next_byte_count = available;// The number of
// bytes
// received
int expected_next_byte_count = incompleteframe.remaining();// The
// number
// of
// bytes
// to
// complete
// the
// incomplete
// frame
if (expected_next_byte_count > available_next_byte_count) {
// did not receive enough bytes to complete the frame
incompleteframe.put(buffer.array(), 0,
available_next_byte_count);
// assert( buffer.limit() == available_next_byte_count +
// buffer.position() );
// buffer.position( available );
return frames;
}
incompleteframe.put(buffer.array(), 0,
expected_next_byte_count);
// buffer.position( buffer.position() +
// expected_next_byte_count );
cur = translateSingleFrame(incompleteframe, 0,
incompleteframe.limit());
frames.add(cur);
offset = expected_next_byte_count;
incompleteframe = null;
break; // go on with the normal frame receival
} catch (IncompleteException e) {
// extending as much as suggested
ByteBuffer extendedframe = ByteBuffer.allocate(e
.getPreferedSize());
assert (extendedframe.limit() > incompleteframe.limit());
extendedframe.put(incompleteframe.array());
incompleteframe = extendedframe;
}
}
}
while (offset < available) {// Read as much as possible full frames
try {
cur = translateSingleFrame(buffer, offset, available);
// System.out.println ( "index "+offset+":" + cur );
offset = buffer.position();
frames.add(cur);
} catch (IncompleteException e) {
// remember the incomplete data
int pref = e.getPreferedSize();
incompleteframe = ByteBuffer.allocate(pref);
incompleteframe.put(buffer.array(), offset, available - offset);
break;
}
}
return frames;
} | 6 |
public Boolean has4Walls() {
boolean ok = true;
for (Boolean wall : walls) {
if (!wall) {
ok = false;
}
}
return ok;
} | 2 |
public void run() {
decompiler.setOption("verbose", verboseCheck.getState() ? "1" : "0");
decompiler.setOption("pretty", prettyCheck.getState() ? "1" : "0");
errorArea.setText("");
// /#ifdef AWT10
// / saveButton.disable();
// /#else
saveButton.setEnabled(false);
// /#endif
lastClassName = classField.getText();
String newClassPath = classpathField.getText();
if (!newClassPath.equals(lastClassPath)) {
decompiler.setClassPath(newClassPath);
lastClassPath = newClassPath;
}
try {
Writer writer = new BufferedWriter(new AreaWriter(sourcecodeArea),
512);
try {
decompiler.decompile(lastClassName, writer, null);
} catch (IllegalArgumentException ex) {
sourcecodeArea.setText("`" + lastClassName
+ "' is not a class name.\n"
+ "You have to give a full qualified classname "
+ "with '.' as package delimiter \n"
+ "and without .class ending.");
return;
}
// /#ifdef AWT10
// / saveButton.enable();
// /#else
saveButton.setEnabled(true);
// /#endif
} catch (Throwable t) {
sourcecodeArea.setText("Didn't succeed.\n"
+ "Check the below area for more info.");
t.printStackTrace();
} finally {
synchronized (this) {
decompileThread = null;
// /#ifdef AWT10
// / startButton.enable();
// /#else
startButton.setEnabled(true);
// /#endif
}
}
} | 5 |
void addLightTrailPart(Position position) {
if (!player.getGrid().validPosition(position))
throw new IllegalArgumentException("Invalid Position");
final LightTrailPart part = new LightTrailPart(player.getGrid(), this);
player.getGrid().addElementToPosition(part, position);
lightTrail.offer(part);
} | 1 |
private HGAtomRef.Mode getReferenceMode(Class<?> javaClass, PropertyDescriptor desc)
{
//
// Retrieve or recursively create a new type for the nested
// bean.
//
try
{
Field field = JavaTypeFactory.findDeclaredField(javaClass, desc.getName());
if (field == null)
return null;
AtomReference ann = (AtomReference)field.getAnnotation(AtomReference.class);
if (ann == null)
return null;
String s = ann.value();
if ("hard".equals(s))
return HGAtomRef.Mode.hard;
else if ("symbolic".equals(s))
return HGAtomRef.Mode.symbolic;
else if ("floating".equals(s))
return HGAtomRef.Mode.floating;
else
throw new HGException("Wrong annotation value '" + s +
"' for field '" + field.getName() + "' of class '" +
javaClass.getName() + "', must be one of \"hard\", \"symbolic\" or \"floating\".");
}
catch (Throwable ex)
{
// Perhaps issue a warning here if people are misspelling
// unintentionally? Proper spelling is only useful for
// annotation, so a warning/error should be really issued if
// we find an annotation for a field that we can't make
// use of?
return null;
}
} | 7 |
@Override
public void Play(PlayerResponse response) {
// Send all Users the players and their positions relative to User
for (PinochlePlayer player : mP.getPlayers()) {
PinochleMessage message = new PinochleMessage();
message.setPlayers(mP.getUserNamesAndPositions(player));
player.setMessage(message);
}
mP.updateAll();
if(mP.isGameFull()) {
mP.setState(mP.getDeal());
mP.Play(null);
}
} | 2 |
private void writeExcel() {
double[] test0 = new double [64];
double[] test1 = new double [64];
double[] test2 = new double [64];
double base = 0;
double sequence = 0;
int pos = 0;
int posY = 6;
//on aditionne tout les excel chromosomes.xls des enfants
for(int k = 0; k < filelist.size(); k++) {
try {
Workbook workbookread = Workbook.getWorkbook(filelist.get(k));
Sheet sheet = workbookread.getSheet(0);
base += Double.parseDouble(sheet.getCell(10, 7).getContents());
sequence += Double.parseDouble(sheet.getCell(10, 5).getContents());
for(int j = 0; j < 64; j++) {
pos = posY + j;
test0[j] += Double.parseDouble(sheet.getCell(1, pos).getContents());
test1[j] += Double.parseDouble(sheet.getCell(3, pos).getContents());
test2[j] += Double.parseDouble(sheet.getCell(5, pos).getContents());
}
}
catch(Exception e) {
e.printStackTrace();
}
}//for
//on écrit dans chromosome.xls parent
try {
Workbook workbookmodel = Workbook.getWorkbook(new File("Genomes"+App.FILE_SEP+"model.xls"));
WritableWorkbook workbook = Workbook.createWorkbook(new File(path + last), workbookmodel);
WritableSheet sheet1 = workbook.getSheet(0);
WritableFont arial16font = new WritableFont(WritableFont.ARIAL, 16);
WritableCellFormat arial16format = new WritableCellFormat (arial16font);
WritableCellFormat format = new WritableCellFormat();
StringTokenizer token = new StringTokenizer(path, App.FILE_SEP);
int i = 1;
String tmp = "";
//permet d'�crire le chemin
while(token.hasMoreTokens()) {
tmp = token.nextToken();
sheet1.addCell(new Label(i, 1, tmp, format));
i++;
}
//ajouter le nom
sheet1.addCell(new Label(1, 0, tmp, arial16format));
//�crire le nombre de s�quence et de base
sheet1.addCell(new Number(10, 5, sequence, format));
sheet1.addCell(new Number(10, 7, base, format));
double frequence;
//on parcours chaque �l�ment du tableau
for(int k = 0; k < 64; k++) {
pos = posY + k;
frequence = (double) (test0[k]/ base) * 100.0;
//�crire phase0
if(test0[k] > 0) {
sheet1.addCell(new Number(1, pos, test0[k], format));
sheet1.addCell(new Number(2, pos, frequence, format));
}
else {
sheet1.addCell(new Number(1, pos, 0, format));
sheet1.addCell(new Number(2, pos, 0, format));
}
frequence = (double) (test1[k]/ base) * 100.0;
//�crire phase1
if(test1[k] > 0) {
sheet1.addCell(new Number(3, pos, test1[k], format));
sheet1.addCell(new Number(4, pos, frequence, format));
}
else {
sheet1.addCell(new Number(3, pos, 0, format));
sheet1.addCell(new Number(4, pos, 0, format));
}
frequence = (double) (test2[k]/ base) * 100.0;
//�crire phase2
if(test2[k] > 0) {
sheet1.addCell(new Number(5, pos, test2[k], format));
sheet1.addCell(new Number(6, pos, frequence, format));
}
else {
sheet1.addCell(new Number(5, pos, 0, format));
sheet1.addCell(new Number(6, pos, 0, format));
}
}
workbook.write();
workbook.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//writeExcel | 9 |
public static void jogo(String[][] matriz){
for(int a=0; a<=8;a++){
for(int b=0; b<=8;b++){
int valor = Integer.parseInt(String.valueOf(a)+String.valueOf(b));
if(matriz[a][b].equals("")){
Celula celula = new Celula(0, a, b);
sudoku[a][b] = celula;
ArrayList vazio = new ArrayList();
vazio.add(a);
vazio.add(b);
blankcells.put(vazio, celula);
}
else{
Celula celula = new Celula(Integer.parseInt(matriz[a][b]), a, b);
sudoku[a][b] = celula;
}
}
}
} | 3 |
@Override
public void onRepaint(Graphics g) {
final Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if(show) {
g2d.setColor(Constants.BLACK_TRANS);
g2d.fill(Constants.CHATBOX_AREA);
g2d.setColor(Color.PINK);
g2d.setFont(Constants.PAINT_TITLE_FONT);
g2d.drawString("Jadinko Lair Roots", 170, 410);
g2d.drawString("Time running: "+ timer.toElapsedString(), 158, 425);
PaintUtils.drawProgressBar(g2d, 6, 435, 490, 17, Color.BLACK, Color.GREEN, 150, PaintUtils.getPercentToNextLevel(Skills.WOODCUTTING));
PaintUtils.drawProgressBar(g2d, 6, 453, 490, 17, Color.BLACK, Color.ORANGE, 150, PaintUtils.getPercentToNextLevel(Skills.FIREMAKING));
g2d.setColor(Color.BLACK);
g2d.setFont(Constants.PROGRESS_BAR_FONT);
g2d.drawString(PaintUtils.generateString(sd, Skills.WOODCUTTING), 10, 448);
g2d.drawString(PaintUtils.generateString(sd, Skills.FIREMAKING), 10, 466);
g2d.setColor(Color.PINK);
g2d.setFont(Constants.PAINT_TEXT_FONT);
if (Settings.root.getRoot() == 1) {
g2d.drawString("Roots burned: " + Misc.perHourInfo(startTime, burned), 10, 482);
} else if (Settings.root.getRoot() == 2) {
g2d.drawString("Sagaie made: "+ Misc.perHourInfo(startTime, sagaieMade), 10, 482);
} else if (Settings.root.getRoot() == 3) {
g2d.drawString("mutated roots chopped: "+ Misc.perHourInfo(startTime, mutated), 10, 482);
}
g2d.drawString("- Tornado & Kenneh", 385, 506);
}
mt.add(Mouse.getLocation());
mt.draw(g);
} | 4 |
public JSONObject toJson(long uid) throws Exception {
JSONObject apptJo = new JSONObject();
apptJo.put("id", this.getId());
apptJo.put("initiator", User.findById(this.initiatorId).toJson());
apptJo.put("name", this.name);
apptJo.put("venueId", this.venueId);
apptJo.put("startTime", this.startTime);
apptJo.put("endTime", this.endTime);
apptJo.put("info", this.info);
apptJo.put("frequency", this.frequency);
apptJo.put("lastDay", this.lastDay);
if (uid >= 0)
apptJo.put("reminderAhead", this.getReminderAhead(uid));
apptJo.put("isJoint", this.isJoint);
if (this.isJoint)
{
apptJo.put("aWaiting", User.listById(WrapperUtil
.toArray(this.aWaitingId)));
apptJo.put("aAccepted", User.listById(WrapperUtil
.toArray(this.aAcceptedId)));
apptJo.put("aRejected", User.listById(WrapperUtil
.toArray(this.aRejectedId)));
}
return apptJo;
} | 2 |
public byte[] decodeBuffer(String encoded) throws IOException {
StringBuffer buff = new StringBuffer(encoded.length());
for (int i = 0; i < encoded.length(); ++i) {
char c = encoded.charAt(i);
if (c == '-') {
c = '+';
} else if (c == '.') {
c = '/';
} else if (c == '_') {
c = '=';
}
buff.append(c);
}
return Base64.decodeBase64(buff.toString().getBytes());
} | 4 |
public boolean isValid(Integer meeting, Integer timeslot)
{
ArrayList<Integer> connectedMeetings = this.getConnectedMeetings(meeting);
for(Integer m: connectedMeetings)
{
if(this.Assignment.containsKey(m)){
Integer cmTimeslot = this.Assignment.get(m);
if( cmTimeslot == timeslot)
{
return false;
}
}
}
for (Integer e: this.EmployeeMeetingMap.keySet())
{
ArrayList<Integer> meetingsForE = this.EmployeeMeetingMap.get(e);
if(meetingsForE.contains(meeting))
{
if(!checkValidForOneEmployee(meeting, timeslot, meetingsForE))
{
return false;
}
}
}
return true;
} | 6 |
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (isPlainFlavor(flavor)) {
String data = getPlainData();
data = (data == null) ? "" : data;
if (String.class.equals(flavor.getRepresentationClass())) {
return data;
} else if (Reader.class.equals(flavor.getRepresentationClass())) {
return new StringReader(data);
} else if (InputStream.class.equals(flavor.getRepresentationClass())) {
return new StringBufferInputStream(data);
}
// fall through to unsupported
} else if (isStringFlavor(flavor)) {
String data = getPlainData();
data = (data == null) ? "" : data;
return data;
}
throw new UnsupportedFlavorException(flavor);
} | 7 |
public Especificacion getEspecificacionesProd(producto prod){
Especificacion esp = new Especificacion();
Conexionbd.conexion bd = new Conexionbd.conexion();
bd.conectarBase();
try {
ResultSet rs = bd.sentencia.executeQuery("SELECT * FROM ESPECIFICACIONESxPROD WHERE NOMBRE_PROD = '"+prod.getNombre()+"'");
while(rs.next()){
esp.setProd(prod);
String esps = rs.getString("ESPECIFICACIONES");
//JOptionPane.showMessageDialog(null, esps);
List<String> especificaciones = new LinkedList();
StringTokenizer st = new StringTokenizer(esps,"-");
while(st.hasMoreTokens()){
especificaciones.add(st.nextToken());
//JOptionPane.showMessageDialog(null, st.nextToken());
}
esp.setLista(especificaciones);
}
} catch (SQLException ex) {
Logger.getLogger(getLista.class.getName()).log(Level.SEVERE, null, ex);
}
bd.desconectarBaseDeDatos();
/*for (int i = 0;i < esp.getListaEspecificaciones().size();i++){
JOptionPane.showMessageDialog(null, esp.getListaEspecificaciones().get(i));
}*/
return esp;
} | 3 |
public static Method[] getUniqueDeclaredMethods(Class<?> leafClass)
throws IllegalArgumentException {
final List<Method> methods = new ArrayList<Method>(32);
doWithMethods(leafClass, new MethodCallback() {
public void doWith(Method method) {
boolean knownSignature = false;
Method methodBeingOverriddenWithCovariantReturnType = null;
for (Method existingMethod : methods) {
if (method.getName().equals(existingMethod.getName())
&& Arrays.equals(method.getParameterTypes(),
existingMethod.getParameterTypes())) {
// is this a covariant return type situation?
if (existingMethod.getReturnType() != method
.getReturnType()
&& existingMethod.getReturnType()
.isAssignableFrom(
method.getReturnType())) {
methodBeingOverriddenWithCovariantReturnType = existingMethod;
} else {
knownSignature = true;
}
break;
}
}
if (methodBeingOverriddenWithCovariantReturnType != null) {
methods.remove(methodBeingOverriddenWithCovariantReturnType);
}
if (!knownSignature && !isCglibRenamedMethod(method)) {
methods.add(method);
}
}
});
return methods.toArray(new Method[methods.size()]);
} | 9 |
public void enableGPS() throws IllegalAccessError, SocketTimeoutException {
try {
clientSocket.Escribir("ONGPS\n");
serverAnswer = clientSocket.Leer();
} catch (IOException e) {
throw new SocketTimeoutException();
}
if(serverAnswer.contains("529 ERR")) {
throw new IllegalAccessError();
}
System.out.println(serverAnswer);
} | 2 |
public static Thsis searchThsis(Thsis t) throws IOException {
String encodedThsisTitle = t.getTitle().trim().replace(" ", "+");
// 拼接URL
String url = GCR_SEARCH_THSIS_URL + encodedThsisTitle;
// 得到响应
Document htmldoc = connect(url);
if(htmldoc == null){
return null;
}
// 得到论文信息
Elements thsisElements = htmldoc
.getElementsByClass(THSIS_ELEMENT_CLASS);
for (Element e : thsisElements) {
t.setAbstractInfo(getAbstract(e));
t.setCitiedBy(getCitedBy(e));
// 只要第一个
break;
}
// 得到论文数大于1,日志记录
if (thsisElements.size() > 0) {
logger.warn(String.format("返回多条论文数据,size:", thsisElements.size()));
}
return t;
} | 3 |
public static void main(String[] args) {
String fullFileName = "/Users/Johan/Documents/CellTowers/cells_exact_samples67-120_2036.json";
opencellid.Controller cont = new opencellid.Controller();
List<OpenCellIdCell> cells = cont.parseCells(fullFileName, 240, 0, 1000000);
for(OpenCellIdCell cell : cells) {
if(cell.getMcc() == 262 && cell.getNet() == 7 && cell.getArea() == 30605 && cell.getCell() == 342) {
System.out.println(cell.getMeasurements().size());
System.out.println(cell.getCellTowerCoordinates());
System.out.println(cell.getAverageSignal());
System.out.println(cell.getRange());
System.out.println(cell.getSamples());
System.out.println(cell.getRadio());
// DefaultCell averagedCell = Process.averageCellTowerPosition(cell.getMeasurements());
// System.out.println("\n"+averagedCell.getCellTowerCoordinates());
// System.out.println(averagedCell.getMeasurements().size());
// System.out.println(averagedCell.getVectorAngle());
// for(Measurement m : cell.getMeasurements()) {
// if(Geom.sphericalDistance(cell.getCellTowerCoordinates().getX(), cell.getCellTowerCoordinates().getY(), m.getCoordinates().getX(), m.getCoordinates().getY()) > 9450) {
// System.out.println(m.getCoordinates());
// }
// }
}
}
} | 5 |
protected boolean addFirework(Firework f)
{
for(int i = 0; i < MAX_FIREWORKS; i++)
{
if((fireworks[i] == null) || !fireworks[i].isAlive())
{
fireworks[i] = f;
return true;
}
}
return false;
} | 3 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ChangesNotesView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ChangesNotesView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ChangesNotesView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ChangesNotesView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ChangesNotesView(new ProjectUML()).setVisible(true);
}
});
} | 6 |
private void createPath(){
if( path == null ){
EndPointAttachement source = getSourceEndPoint().getAttachement();
EndPointAttachement target = getTargetEndPoint().getAttachement();
Point sl = source.getLanding();
Point sa = source.getApproach();
Point ta = target.getApproach();
Point tl = target.getLanding();
Line2D.Float lineS = new Line2D.Float( sl.x, sl.y, sa.x, sa.y );
Line2D.Float lineT = new Line2D.Float( ta.x, ta.y, tl.x, tl.y );
Line2D.Float revLineS = new Line2D.Float( sa.x, sa.y, sl.x, sl.y );
Line2D.Float revLineT = new Line2D.Float( tl.x, tl.y, ta.x, ta.y );
double dist = Math.sqrt( Geom.dist2( sa.x, sa.y, ta.x, ta.y )) / 2;
Point ctrl1 = Geom.pointAt( sa, source.getDirection(), dist );
Point ctrl2 = Geom.pointAt( ta, target.getDirection(), dist );
CubicCurve2D.Float cc = new CubicCurve2D.Float( sa.x, sa.y, ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y, ta.x, ta.y );
CubicCurve2D.Float revCc = new CubicCurve2D.Float( ta.x, ta.y, ctrl2.x, ctrl2.y, ctrl1.x, ctrl1.y, sa.x, sa.y );
path = new Path2D.Float();
path.append( lineS, true );
path.append( cc, true );
path.append( lineT, true );
closedPath = new Path2D.Float();
closedPath.append( lineS, true );
closedPath.append( cc, true );
closedPath.append( lineT, true );
closedPath.append( revLineT, true );
closedPath.append( revCc, true );
closedPath.append( revLineS, true );
}
} | 1 |
@Override
public boolean equals(Object o) {
if (o == null)
return false;
if (!o.getClass().equals(this.getClass()))
return false;
return getUUID().equals(((Host) o).getUUID());
} | 2 |
public static DefaultFormatterFactory creaFormatoControl(int tipo,
int cantEnt, int cantFra, char caracter){
DefaultFormatterFactory factory = null;
MaskFormatter numcase = null;
String cadena = "";
int i;
for(i=0;i<cantEnt;i++){
cadena = cadena + "#";
}
if(cantFra > 0){
cadena = cadena + ".";
for(i=0;i<cantFra;i++){
cadena = cadena + "#";
}
}
switch(tipo){
case 1:
try {
numcase = new MaskFormatter(cadena);
numcase.setPlaceholderCharacter(caracter);
numcase.setOverwriteMode(true);
numcase.setValidCharacters("0123456789");
factory = new DefaultFormatterFactory(numcase);
}catch (Exception pe) {
Base.mostrar("Error al dar Formato de Numero Entero");
}
break;
case 2:
try {
numcase = new MaskFormatter(cadena);
numcase.setPlaceholderCharacter(caracter);
numcase.setOverwriteMode(true);
numcase.setValidCharacters("0123456789");
factory = new DefaultFormatterFactory(numcase);
}catch (Exception pe) {
Base.mostrar("Error al dar Formato de Numero Real");
}
break;
}
return factory;
} | 7 |
private void handleCancelList(Sim_event ev)
{
boolean success = false;
int tag = -1;
int src = 0;
try
{
// [0]=reservID, [1]=list of Gridlet IDs, [2]=transID, [3]=senderID
Object[] obj = ( Object[] ) ev.get_data();
// get the data inside an array
int reservationID = ( (Integer) obj[0] ).intValue();
ArrayList list = (ArrayList) obj[1];
int transactionID = ( (Integer) obj[2] ).intValue();
src = ( (Integer) obj[3] ).intValue();
// tag = return tag + transaction id
int returnTag = GridSimTags.RETURN_AR_CANCEL;
tag = returnTag + transactionID;
// check whether this resource can support AR or not
success = checkResourceType(src, returnTag, transactionID,
GridSimTags.AR_CANCEL_ERROR_RESOURCE_CANT_SUPPORT,
"can't cancel a reservation");
// if list is empty
if (list == null) {
success = false;
}
// if successful
if (success) {
( (ARPolicy) policy_).handleCancelReservation(reservationID,
src, list, tag);
}
}
catch (ClassCastException c) {
success = false;
}
catch (Exception e) {
success = false;
}
// if there is an exception, then send back an error msg
if (!success && tag != -1)
{
System.out.println(super.get_name() + " : Error - can't cancel a "+
"new reservation.");
super.send(src, 0.0, GridSimTags.RETURN_AR_CANCEL,
new IO_data(new Integer(GridSimTags.AR_CANCEL_ERROR),SIZE,src));
}
} | 6 |
public static void cleanUp() {
ModPack pack = ModPack.getSelectedPack();
File tempFolder = new File(OSUtils.getDynamicStorageLocation(), "ModPacks" + sep + pack.getDir() + sep);
for(String file : tempFolder.list()) {
if(!file.equals(pack.getLogoName()) && !file.equals(pack.getImageName()) && !file.equals("version") && !file.equals(pack.getAnimation())) {
try {
if (Settings.getSettings().getDebugLauncher() || file.endsWith(".zip")) {
Logger.logInfo("debug: retaining modpack file: " + tempFolder + File.separator + file);
} else {
FileUtils.delete(new File(tempFolder, file));
}
} catch (IOException e) {
Logger.logError(e.getMessage(), e);
}
}
}
} | 8 |
public ArrayList<String> find_baseNumOfPublications(){
HashMap<String, String[]> domainSet = DataLoad.loadDomain();
Collection<String> collection = domainSet.keySet();
Iterator<String> iter = collection.iterator();
while(iter.hasNext()){
person = iter.next();
temp = domainSet.get(person);
if(temp.length >= 300){
Master.add(person);
}
}
return Master;
} | 2 |
@Override
public void mouseClicked(MouseEvent e) {
int col = table.getTableHeader().columnAtPoint(e.getPoint());
if (col == 0) {
// Add new row
Object[] data = {"Remove","",""};
model.addRow(data);
model.fireTableDataChanged();
}
} | 1 |
public Integer getContestId() {
return this.contestId;
} | 0 |
public String getStatus()
{
switch(this.status)
{
case 0:
return "Running";
case 1:
return "Wait";
case 2:
return "Idle";
case 3:
return "Terminated";
case 4:
return "Aborted";
default:
return "ERROR: No Status!";
}
} | 5 |
private boolean cvc( String str ) {
int length=str.length();
if ( length < 3 )
return false;
if ( (!vowel(str.charAt(length-1),str.charAt(length-2)) )
&& (str.charAt(length-1) != 'w') && (str.charAt(length-1) != 'x') && (str.charAt(length-1) != 'y')
&& (vowel(str.charAt(length-2),str.charAt(length-3))) ) {
if (length == 3) {
if (!vowel(str.charAt(0),'?'))
return true;
else
return false;
}
else {
if (!vowel(str.charAt(length-3),str.charAt(length-4)) )
return true;
else
return false;
}
}
return false;
} | 9 |
static final public void NewArrayExpr() throws ParseException {
jj_consume_token(NEW);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ID:
jj_consume_token(ID);
break;
case BOOLEAN:
case CHAR:
case VOID:
case INT:
PrimitiveType();
break;
default:
jj_la1[40] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
label_7:
while (true) {
Dimension();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case LSB:
;
break;
default:
jj_la1[41] = jj_gen;
break label_7;
}
}
} | 9 |
private static boolean contains(String name, List<Joueur> list) {
for(Joueur j : list) {
if(j.getNom().equals(name))
return true;
}
return false;
} | 2 |
private void invokeQueue() {
if (active)
return;
synchronized (LOCK_QUEUE) {
if (queue.isEmpty())
return;
}
active = true;
new Thread() {
@Override
public void run() {
report.toggleProcess(true);
boolean queueEmpty;
synchronized (LOCK_QUEUE) {
queueEmpty = queue.isEmpty();
}
while (!queueEmpty) {
CompilationTask task;
synchronized (LOCK_QUEUE) {
task = queue.get(0);
queue.remove(0);
}
task.run(compiler);
synchronized (LOCK_QUEUE) {
queueEmpty = queue.isEmpty();
}
}
report.toggleProcess(false);
active = false;
//invokeQueue();
}
}.start();
} | 3 |
public int getX() {
return x;
} | 0 |
public final ArrayList<Entry<K, V>>[] getOnl() { return onl; } | 0 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.