text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public boolean isFlying() {
return isAlive();
}
| 0 |
public int[] find_ant(int id, Colour col){
int p[] = new int[2];
if(ant_is_alive(id, col)){
boolean found = false;
int x = 0;
int y = 0;
while(x < world.getRows() && !found){
while(y < world.getColumns() && !found){
p[0] = x;
p[1] = y;
Cell c = world.getCell(p[0],p[1]);
if(c.isAnt()){
if(c.getAnt().getId()==id && c.getAnt().getColour()==col){
found = true;
}
}
y++;
}
y = 0;
x++;
}
}
else{
return null;
}
return p;
}
| 8 |
public CachedLocations(){
List<EndPoint> north = new ArrayList<>();
List<EndPoint> south = new ArrayList<>();
List<EndPoint> east = new ArrayList<>();
List<EndPoint> west = new ArrayList<>();
for( EndPoint endPoint : endPoints ){
switch( calcPosition( endPoint )){
case WEST:
west.add( endPoint );
break;
case EAST:
east.add( endPoint );
break;
case NORTH:
north.add( endPoint );
break;
case SOUTH:
south.add( endPoint );
break;
}
}
createAttachements( west, Side.WEST );
createAttachements( east, Side.EAST );
createAttachements( south, Side.SOUTH );
createAttachements( north, Side.NORTH );
}
| 5 |
public void handle(HttpExchange exchange) throws IOException {
String requestMethod = exchange.getRequestMethod();
if (!requestMethod.equalsIgnoreCase("GET")) { // GET requests only.
return;
}
// Print the user request header.
Headers requestHeaders = exchange.getRequestHeaders();
_logger.debug("Incoming request: ");
for (String key : requestHeaders.keySet()) {
_logger.debug("{} : {} ;", key, requestHeaders.get(key));
}
// Validate the incoming request.
String uriQuery = exchange.getRequestURI().getQuery();
String uriPath = exchange.getRequestURI().getPath();
if (uriPath == null || uriQuery == null) {
respondWithMsg(exchange, "Something wrong with the URI!");
}
if (!uriPath.equals("/search")) {
respondWithMsg(exchange, "Only /search is handled!");
}
_logger.debug("Query: {}", uriQuery);
// Process the CGI arguments.
CgiArguments cgiArgs = new CgiArguments(uriQuery);
if (cgiArgs._query.isEmpty()) {
respondWithMsg(exchange, "No query is given!");
}
// Create the ranker.
Ranker ranker = new RankerFactory(_indexer).create(cgiArgs._rankerType);
assert ranker != null;
// Processing the query.
Query processedQuery = new Query(cgiArgs._query);
// Ranking.
Vector<ScoredDocument> scoredDocs = ranker.runQuery(processedQuery,
cgiArgs._numResults);
StringBuffer response = new StringBuffer();
switch (cgiArgs._outputFormat) {
case TEXT:
constructTextOutput(scoredDocs, response);
break;
case HTML:
// @CS2580: Plug in your HTML output
response = convertToString(cgiArgs._query, scoredDocs);
break;
default:
// nothing
}
respondWithMsg(exchange, response.toString());
_logger.debug("Finished query: {}", cgiArgs._query);
}
| 8 |
public static String getHttp(String url, String body) //getHTTP method called in Main() for Coinbase connections
throws InvalidKeyException, NoSuchAlgorithmException, // Error handling
ClientProtocolException, IOException {
String nonce = String.valueOf(System.currentTimeMillis()); // Nonce creation
String message = nonce + url + (body != null ? body : null);
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(API_SECRET.getBytes(), "HmacSHA256"));
String signature = new String(Hex.encodeHex(mac.doFinal(message.getBytes()))); //General security for POST
HttpRequestBase request;
if (body == null || body.length() == 0)
request = new HttpGet(url);
else {
HttpPost post = new HttpPost(url);
post.setEntity(new StringEntity(body)); //Sets POST body (ie: JSON info)
request = post;
}
System.out.println("Message:" + message); //For Debugging, can remove at later date
System.out.println("Signature:" + signature);
System.out.println("Nonce:" + nonce);
request.setHeader("ACCESS_KEY", API_KEY); //Sets POST header
request.setHeader("ACCESS_SIGNATURE", signature);
request.setHeader("ACCESS_NONCE", nonce);
request.setHeader("Content-Type", "application/json"); //Had to add to the vanilla script for buy/sell
HttpClient httpClient = HttpClientBuilder.create().build(); // Sends final POST request
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity(); //Grabs response from Coinbase server
if (entity != null)
return EntityUtils.toString(entity);
return null;
}
| 4 |
@Override
public void actionPerformed(ActionEvent event) {
if(event.getSource() == this.environments) {
this.methods.removeAllItems();
Environment env = (Environment) this.environments.getSelectedItem();
if(env != null) {
for(ServiceMethod method : env.getMethods()) {
if(NewQueryDialog.operationPanels.containsKey(method.getRequestClass())) {
this.methods.addItem(method);
} else {
logger.warn("No operation panel for method: " + method.getDisplayName());
}
}
}
} else if(event.getSource() == this.createBtn) {
if(!Utilities.isNullOrWhitespace(this.getName())) {
this.toCreate = true;
this.setVisible(false);
this.dispose();
} else {
JOptionPane.showMessageDialog(this, "Unable to create service without a name", "Invalid name", JOptionPane.ERROR_MESSAGE);
this.nameField.requestFocus();
}
} else if(event.getSource() == this.cancelBtn) {
this.setVisible(false);
this.dispose();
}
}
| 7 |
private Class getClassImpl(String name) throws UtilEvalError {
Class c = null;
// Check the cache
if (classCache != null) {
c = classCache.get(name);
if (c != null)
return c;
}
// Unqualified (simple, non-compound) name
boolean unqualifiedName = !Name.isCompound(name);
// Unqualified name check imported
if (unqualifiedName) {
// Try imported class
if (c == null)
c = getImportedClassImpl(name);
// if found as imported also cache it
if (c != null) {
cacheClass(name, c);
return c;
}
}
// Try absolute
c = classForName(name);
if (c != null) {
// Cache unqualified names to prevent import check again
if (unqualifiedName)
cacheClass(name, c);
return c;
}
// Not found
if (Interpreter.DEBUG)
Interpreter.debug("getClass(): " + name + " not found in " + this);
return null;
}
| 8 |
private static void extractFromZip(
String szZipFilePath, String szExtractPath,
String szName,
ZipFile zf, ZipEntry ze)
{
if(ze.isDirectory())
return;
String szDstName = slash2sep(szName);
String szEntryDir;
if(szDstName.lastIndexOf(File.separator) != -1)
{
szEntryDir =
szDstName.substring(
0, szDstName.lastIndexOf(File.separator));
}
else
szEntryDir = "";
//System.out.print(szDstName);
long nSize = ze.getSize();
long nCompressedSize =
ze.getCompressedSize();
//System.out.println(" " + nSize + " (" + nCompressedSize + ")");
try
{
File newDir = new File(szExtractPath +
File.separator + szEntryDir);
newDir.mkdirs();
FileOutputStream fos =
new FileOutputStream(szExtractPath +
File.separator + szDstName);
InputStream is = zf.getInputStream(ze);
byte[] buf = new byte[1024];
int nLength;
while(true)
{
try
{
nLength = is.read(buf);
}
catch (EOFException ex)
{
break;
}
if(nLength < 0)
break;
fos.write(buf, 0, nLength);
}
is.close();
fos.close();
}
catch(Exception ex)
{
System.out.println(ex.toString());
//System.exit(0);
}
}
| 6 |
public static void main(String[] args) throws Exception
{
HashMap<String, FastaSequence> fastaMap =
FastaSequence.getFirstTokenSequenceMap(ConfigReader.getChinaDir() + File.separator +
"ncbi" + File.separator + "ncib16.fasta");
BufferedWriter writer= new BufferedWriter(new FileWriter(new File(ConfigReader.getChinaDir()+
File.separator + "mostWanted" + File.separator + "abundantOTUMostWanted.txt")));
OtuWrapper wrapper = new OtuWrapper(ConfigReader.getChinaDir() +
File.separator + "abundantOTU" + File.separator +
"abundantOTUForwardTaxaAsColumns.txt");
writer.write("otuID\tpValue\tadjustedp\thigherIn\tmeanRural\tmeanUrban\truralDivUrban\ttargetId\tqueryAlignmentLength\tpercentIdentity\tbitScore\tnumSequences\t" +
"mostWantedID\tmostWantedPriority\tmaxFraction\tstoolSubjectFraction\trelativeAbundanceStool\tgoldGlobalMostWanted\tgoldGlobalBestHit\trdpMetadata\t" + ""
+ "ncbiPercentIdentity\tncbiHeader\tgreengenesPercentIdentity\tgreengenesIdentifier\n");
HashMap<String, MostWantedMetadata> mostMetaMap = MostWantedMetadata.getMap();
HashMap<String, HitScores> topHitMap =
HitScores.getTopHitsAsQueryMap(ConfigReader.getChinaDir() + File.separator +
"mostWanted" + File.separator + "forwardToMostWanted16S.txt.gz");
HashMap<String, HitScores> ncbiMap=
HitScores.getTopHitsAsQueryMap(ConfigReader.getChinaDir() + File.separator +
"ncbi" + File.separator + "forwardTo16S.txt.gz");
HashMap<String, HitScores> greengensMap=
HitScores.getTopHitsAsQueryMap(ConfigReader.getChinaDir() + File.separator +
"greengenes" + File.separator + "forwardToNamed.txt.gz");
BufferedReader reader = new BufferedReader(new FileReader(new File(ConfigReader.getChinaDir()+
File.separator + "abundantOTU" + File.separator + "pValuesFromMixedLinearModel.txt")));
reader.readLine();
for(String s= reader.readLine(); s != null; s= reader.readLine())
{
String[] splits = s.split("\t");
String key = "Consensus" + splits[1].replaceAll("X", "").replaceAll("\"", "");
System.out.println(key);
if(! key.equals("ConsensusunRarifiedRichness")
&& ! key.equals("ConsensusshannonEveness") &&
!key.equals("ConsensusshannonDiversity"))
{
writer.write(key + "\t");
writer.write(splits[0] + "\t");
writer.write(splits[5] + "\t");
writer.write( (Double.parseDouble(splits[2]) >
Double.parseDouble(splits[3]) ? "rural" : "urban" ) + "\t");
writer.write(splits[2] + "\t");
writer.write(splits[3] + "\t");
writer.write(splits[4] + "\t");
HitScores hs = topHitMap.get(key);
if( hs != null)
{
writer.write(hs.getTargetId() + "\t");
writer.write(hs.getQueryAlignmentLength() + "\t");
writer.write(hs.getPercentIdentity() + "\t");
writer.write(hs.getBitScore() + "\t");
}
else
{
writer.write("NA\t0\t0\t0\t");
}
writer.write(wrapper.getCountsForTaxa(splits[1].replaceAll("X", "").replaceAll("\"", "")) + "\t");
if( hs != null)
{
MostWantedMetadata mostMeta = mostMetaMap.get(hs.getTargetId());
if( mostMeta == null)
throw new Exception("Could not find " + hs.getTargetId());
writer.write(hs.getTargetId() + "\t");
writer.write(mostMeta.getPriority() + "\t");
writer.write(mostMeta.getMaxFraction() + "\t");
writer.write(mostMeta.getSubjectFractionStool() + "\t");
writer.write(mostMeta.getRelativeAbundanceStool() + "\t");
writer.write(mostMeta.getGoldGlobal() + "\t");
writer.write(mostMeta.getGoldGlobalBestHit() + "\t");
writer.write(mostMeta.getRdpSummaryString() + "\t");
}
else
{
writer.write("NA\tNA\t0\t0\t0\t0\tNA\tNA\t");
}
writer.write(ncbiMap.get(key).getPercentIdentity() + "\t");
writer.write(fastaMap.get(ncbiMap.get(key).getTargetId()).getHeader().substring(1) + "\t");
writer.write(greengensMap.get(key).getPercentIdentity() + "\t");
writer.write(greengensMap.get(key).getTargetId() + "\n");
}
}
writer.flush(); writer.close();
}
| 8 |
public void setIdConnection(Long idConnection) {
this.idConnection = idConnection;
}
| 0 |
@Override
public TypeOfValue peek() throws EmptyStackException {
if (null == this.firstNode) {
throw new EmptyStackException();
}
return (TypeOfValue) firstNode.getObject();
}
| 1 |
public Enumeration<?> getKeys() {
return properties.propertyNames();
}
| 1 |
private void initCommandBtnFontMenu(Color bg) {
this.commandBtnPanel = new JPanel();
this.commandBtnPanel.setBackground(bg);
this.commandBtnPanel.setLayout(new VerticalLayout(5, VerticalLayout.LEFT));
String initFontTmp = this.skin.getCommandButtonFont();
int initFontSizeTmp = this.skin.getCommandButtonFontsize();
Color initFontColorTmp = new Color(this.skin.getCommandButtonFontcolor()[1], this.skin.getCommandButtonFontcolor()[2],
this.skin.getCommandButtonFontcolor()[3]);
boolean boldTmp = this.skin.getCommandButtonFonttype() == Fonttype.BOLD;
boolean underlineTmp = (this.skin.getCommandButtonFontstyle() == Fontstyle.UNDERLINE)
|| (this.skin.getCommandButtonFontstyle() == Fontstyle.SHADOWUNDERLINE);
boolean shadowTmp = (this.skin.getCommandButtonFontstyle() == Fontstyle.SHADOW)
|| (this.skin.getCommandButtonFontstyle() == Fontstyle.SHADOWUNDERLINE);
this.commandButtonFontfield = new FontField(bg, strFontFieldTitle, initFontTmp, initFontSizeTmp, initFontColorTmp, boldTmp,
underlineTmp, shadowTmp) {
private final long serialVersionUID = 1L;
@Override
public void fontChosen(String input) {
if (!input.equals("")) {
FontChangesMenu.this.skin.setCommandButtonFont(input);
updateFont(FontChangesMenu.this.skin.getCommandButtonFont());
} else {
FontChangesMenu.this.skin.setCommandButtonFont(null);
}
}
@Override
public void sizeTyped(String input) {
if (input != null) {
FontChangesMenu.this.skin.setCommandButtonFontsize(parseInt(input));
updateSize(FontChangesMenu.this.skin.getCommandButtonFontsize());
} else {
FontChangesMenu.this.skin.setCommandButtonFontsize(-1);
}
}
@Override
public void colorBtnPressed(int[] argb) {
FontChangesMenu.this.skin.setCommandButtonFontcolor(argb);
updateColor(new Color(FontChangesMenu.this.skin.getCommandButtonFontcolor()[1],
FontChangesMenu.this.skin.getCommandButtonFontcolor()[2],
FontChangesMenu.this.skin.getCommandButtonFontcolor()[3]));
}
@Override
public void boldPressed(boolean selected) {
FontChangesMenu.this.skin.setCommandButtonFonttype(selected ? Fonttype.BOLD : Fonttype.NORMAL);
updateBold(FontChangesMenu.this.skin.getCommandButtonFonttype() == Fonttype.BOLD);
}
@Override
public void underlinePressed(boolean selected) {
FontChangesMenu.this.skin.setCommandButtonFontstyle(getUnderlineFontstyle(selected,
FontChangesMenu.this.skin.getCommandButtonFontstyle()));
updateUnderline((FontChangesMenu.this.skin.getCommandButtonFontstyle() == Fontstyle.UNDERLINE)
|| (FontChangesMenu.this.skin.getCommandButtonFontstyle() == Fontstyle.SHADOWUNDERLINE));
}
@Override
public void shadowPressed(boolean selected) {
FontChangesMenu.this.skin.setCommandButtonFontstyle(getShadowFontstyle(selected,
FontChangesMenu.this.skin.getCommandButtonFontstyle()));
updateShadow((FontChangesMenu.this.skin.getCommandButtonFontstyle() == Fontstyle.SHADOW)
|| (FontChangesMenu.this.skin.getCommandButtonFontstyle() == Fontstyle.SHADOWUNDERLINE));
}
};
this.commandBtnPanel.add(this.commandButtonFontfield);
}
| 7 |
public void execute() {
receiver.turnOn();
}
| 0 |
@EventHandler
public void onInventoryOpenEvent(InventoryOpenEvent e){
if (e.getInventory().getHolder() instanceof Chest || e.getInventory().getHolder() instanceof DoubleChest){
System.out.println("Opened chest!");
}
}
| 2 |
*/
private void setSystemObjectKeeping(SystemObject systemObject) {
// die Liste der in Bearbeitung befindlichen Objekte wird durchgearbeitet
for(ConfigurationArea configurationArea : _editingObjects.keySet()) {
for(CheckedObject checkedObject : _editingObjects.get(configurationArea)) {
if(checkedObject.getSystemObject() == systemObject) {
_debug.finer("Ein in Bearbeitung befindliches Objekt '" + systemObject.getPidOrNameOrId() + "' wurde gefunden und wird markiert.");
checkedObject.setObjectKeeping(true);
return; // gesucht - gefunden
}
}
}
// die Liste der zur Übernahme / Aktivierung freigegebenen Objekte wird durchgearbeitet
for(ConfigurationArea configurationArea : _newObjects.keySet()) {
for(CheckedObject checkedObject : _newObjects.get(configurationArea)) {
if(checkedObject.getSystemObject() == systemObject) {
_debug.finer(
"Ein zur Übernahme / Aktivierung freigegebenes Objekt '" + systemObject.getPidOrNameOrId() + "' wurde gefunden und wird markiert."
);
checkedObject.setObjectKeeping(true);
return; // gesucht - gefunden
}
}
}
// die Liste der aktuellen Objekte wird durchgearbeitet
for(ConfigurationArea configurationArea : _currentObjects.keySet()) {
for(CheckedObject checkedObject : _currentObjects.get(configurationArea)) {
if(checkedObject.getSystemObject() == systemObject) {
_debug.finer("Ein aktuelles Objekt '" + systemObject.getPidOrNameOrId() + "' wurde gefunden und wird markiert.");
checkedObject.setObjectKeeping(true);
return; // gesucht - gefunden
}
}
}
}
| 9 |
@Override
public int hashCode() {
return (int) this.user.getId();
}
| 0 |
public void visitLookupSwitchInsn(final Label dflt, final int[] keys,
final Label[] labels) {
buf.setLength(0);
for (int i = 0; i < labels.length; ++i) {
declareLabel(labels[i]);
}
declareLabel(dflt);
buf.append("mv.visitLookupSwitchInsn(");
appendLabel(dflt);
buf.append(", new int[] {");
for (int i = 0; i < keys.length; ++i) {
buf.append(i == 0 ? " " : ", ").append(keys[i]);
}
buf.append(" }, new Label[] {");
for (int i = 0; i < labels.length; ++i) {
buf.append(i == 0 ? " " : ", ");
appendLabel(labels[i]);
}
buf.append(" });\n");
text.add(buf.toString());
}
| 5 |
public int retrieveScore() {
FileHandle file = Gdx.files.local(filePath);//internal does not work
String stringa = file.readString();
int score = -1;
if(stringa!=null||stringa!=""){
score=Integer.parseInt(stringa);
}
return score;
}
| 2 |
public static byte[] gzip(String input) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzos != null) try {
gzos.close();
} catch (IOException ignore) {
}
}
return baos.toByteArray();
}
| 3 |
public String getParagraph()
{
return paragraph;
}
| 0 |
private XinWen initXinWen(ResultSet rs) throws SQLException {
XinWen xinWen = new XinWen();
xinWen.setId(rs.getString("ID") == null ? "" : rs.getString("ID"));
xinWen.setTitle(rs.getString("TITLE") == null ? "" : rs.getString("TITLE"));
xinWen.setEntitle(rs.getString("ENTITLE") == null ? "" : rs.getString("ENTITLE"));
xinWen.setContent(rs.getString("CONTENT") == null ? "" : rs.getString("CONTENT"));
xinWen.setEncontent(rs.getString("ENCONTENT") == null ? "" : rs.getString("ENCONTENT"));
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
// Date createdDate = rs.getTimestamp("createddate");
// sdf.format(createdDate);
xinWen.setCreatedDate(rs.getTimestamp("CREATEDDATE"));
xinWen.setCreatedBy(rs.getString("CREATEDBY") == null ? "" : rs.getString("CREATEDBY"));
xinWen.setUpdatedDate(rs.getTimestamp("UPDATEDDATE"));
xinWen.setUpdatedBy(rs.getString("UPDATEDBY") == null ? "" : rs.getString("UPDATEDBY"));
xinWen.setLink(rs.getString("LINK") == null ? "" : rs.getString("LINK"));
return xinWen;
}
| 8 |
private int getPlacement (final String checkSkill) {
for (int i = 0; i < SKILLS.length; i++) {
if (SKILLS[i].equalsIgnoreCase(checkSkill))
return i;
}
return -1;
}
| 2 |
public String patchToString(Path path, Patch patch){
String s = path.toString()+" differs:\n";
for(Delta d : patch.getDeltas()){
s+= StringUtils.trim(d.toString())+"\n";
}
return s;
}
| 1 |
@Override
public void run() {
//obtiene el pescator
plyr = plugin.getServer().getPlayer(plugin.getConfig().getString("thePescator"));
final Calendar cal = new GregorianCalendar();
final int segActual = cal.get(Calendar.SECOND);
timeDone = plugin.getConfig().getInt("users.TimePescado." + plyr.getDisplayName());
sec = plugin.getConfig().getInt("users.TimePescadoAux." + plyr.getDisplayName());
if(plugin.getConfig().getBoolean("users.TimePescadoAux2." + plyr.getDisplayName()))
{
sec = segActual;
plugin.getConfig().set("users.TimePescadoAux2." + plyr.getDisplayName(), false);
plugin.saveConfig();
}
if( timeDone < limit )
{
if( sec <= segActual && one )
{
timeDone += segActual - sec;
//cambiar a 10
if(timeDone%10 == 0)
{
BukkitTask checktas = new SendMsgTask(plugin, plyr.getWorld(), plyr, plugin.getConfig().getString("translate.EventAnnouncement") +" " + timeDone + " "
+ plugin.getConfig().getString("translate.EventAnnouncement2") ).runTask(plugin);
BukkitTask chec = new giveSwordTask(plugin, plyr.getWorld()).runTask(plugin);
}
plugin.getConfig().set("users.TimePescado." + plyr.getDisplayName(), timeDone );
plugin.getConfig().set("users.TimePescadoAux." + plyr.getDisplayName(), segActual );
}else if( sec > segActual && one )
{
timeDone += segActual + (60 - sec);
plugin.getConfig().set("users.TimePescado." + plyr.getDisplayName(), timeDone );
plugin.getConfig().set("users.TimePescadoAux." + plyr.getDisplayName(), segActual );
}
// plugin.getConfig().set("users.TimePescado." + plyr.getDisplayName() , sec);
}
else
{
if(one)
{
for (Player p : w.getPlayers()) {
p.sendMessage( ChatColor.GOLD + "The winner is : " + plyr.getDisplayName() );
}
one = false;
}
//encontrar una forma para que se acabe por si solo la tarea
}
plugin.saveConfig();
}
| 9 |
public Map<String, String> handleProbe(String... keys) {
Map<String, String> map=new TreeMap<>();
for(String key: keys) {
if(key.startsWith("jmx")) {
handleJmx(map, key);
continue;
}
if(key.startsWith("reset-stats")) {
resetAllStats();
continue;
}
if(key.startsWith("invoke") || key.startsWith("op")) {
int index=key.indexOf('=');
if(index != -1) {
try {
handleOperation(map, key.substring(index+1));
}
catch(Throwable throwable) {
log.error(Util.getMessage("OperationInvocationFailure"), key.substring(index+1), throwable);
}
}
}
}
return map;
}
| 7 |
private static IStrategy getUserFixedStrategy(BufferedReader br) {
System.out.println("Insert the fix value");
while (true) {
try {
int value = Integer.parseInt(br.readLine());
return new FixedStrategy(value);
} catch (Exception e) {
System.out.println("Insert valid value");
}
}
}
| 2 |
public void update() {
while (!m_shell.isDisposed()) {
if (!m_display.readAndDispatch()) {
m_display.sleep();
}
for (int i = 0; i < m_clients.size(); ++i) {
if (!m_shell.isDisposed())
clientLogic(m_clients.get(i));
}
if(!m_shell.isDisposed())
serverLogic(m_server);
}
m_display.dispose();
}
| 5 |
@Override
public boolean equals(Object o) {
if (this == o) { return true; }
if (o == null || this.getClass() != o.getClass()) { return false; }
Result n = (Result) o;
return word.equals(n.word);
}
| 3 |
@Override
public int analyse(LexicalAnalyser analyser, int beginIndex) throws AnalyseException {
String content = analyser.getSentence();
if (!WordTable.isDigit(content.charAt(beginIndex))) {
throw new AnalyseException(String.format("Error Undefined String [%c] ", content.charAt(beginIndex)));
}
for (int index = beginIndex; index < content.length(); index++) {
char c = content.charAt(index);
if (!WordTable.isDigit(c)) {
int endIndex = index;
if (!WordTable.isDelimiter(c) &&/* !WordTable.isDelimiterPart(c) && */!WordTable.isOverableLetter(c)) {
throw new AnalyseException(String.format("Error Undefined String [%s] ", content.substring(beginIndex, endIndex + 1)));
}
return addResultToAnalyserAndGetResult(analyser, beginIndex, endIndex);
}
}
return addResultToAnalyserAndGetResult(analyser, beginIndex, content.length());
}
| 5 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Equation other = (Equation) obj;
if (a == null) {
if (other.a != null)
return false;
} else if (!a.equals(other.a))
return false;
if (b == null) {
if (other.b != null)
return false;
} else if (!b.equals(other.b))
return false;
return true;
}
| 9 |
public String kNearestNeighbour(Datum point, int k) {
HashMap<Double,String> vals = new HashMap<Double,String>();
ArrayList<Double> dists = new ArrayList<Double>();
double dist;
for (Datum d : data) {
dist = point.getDistSquared(d);
vals.put(dist, d.name);
dists.add(dist);
}
Double[] sortedDists = dists.toArray(new Double[dists.size()]);
Arrays.sort(sortedDists);
int most = 0;
int val = 0;
LinkedHashMap<String, Integer> kNearest = new LinkedHashMap<String, Integer>();
for (int i=0; i<k; i++) {
String name = vals.get(sortedDists[i]);
if (!kNearest.containsKey(name)) {
val = 1;
}
else {
val = kNearest.get(name)+1;
}
kNearest.put(name,val);
if (val > most) {
most = val;
}
}
ArrayList<String> winners = new ArrayList<String>();
for (String name : kNearest.keySet()) {
if (kNearest.get(name) == most) {
winners.add(name);
}
}
for (String letter : kNearest.keySet()) {
for (String l : winners) {
if (l.equals(letter)) {
return letter;
}
}
}
return null;
}
| 9 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SimpleAuthenticationCredentialProvider other = (SimpleAuthenticationCredentialProvider) obj;
if (sharedSecret == null) {
if (other.sharedSecret != null)
return false;
} else if (!sharedSecret.equals(other.sharedSecret))
return false;
if (userId == null) {
if (other.userId != null)
return false;
} else if (!userId.equals(other.userId))
return false;
return true;
}
| 9 |
@Test(expected = Exception.class)
public void NullName() throws Exception {
LoginCheck logCh = new LoginCheck();
name = "";
if (kesh.containsKey(name)) {
kesh.get(name);
} else {
boolean result = logCh.validate(name);
kesh.put(name, result);
}
}
| 1 |
@Override
public boolean onCommand(CommandSender sender, org.bukkit.command.Command cmd, String[] args) {
if(args.length > 0) return false;
if(!Commands.isPlayer(sender)) return false;
Player p = (Player) sender;
Messenger.tell(p, Msg.GLOBAL_CHAT_ENTERED);
PlayerChat.plugin.CustomChat.remove(p.getName());
PlayerChat.plugin.ModChat.remove(p.getName());
PlayerChat.plugin.AdminChat.remove(p.getName());
return true;
}
| 2 |
public void normalize() {
if (x != 0.0 || y != 0.0 || z != 0.0) {
double modulo = modulo();
x /= modulo;
y /= modulo;
z /= modulo;
}
}
| 3 |
@Override
public Piece getPieceAt(Location location)
{
Piece result = null;
if (location.equals(redMarshalLocation) && gameStarted && !gameOver) {
result = redMarshal;
} else if (location.equals(redFlagLocation)) {
result = redFlag;
} else if (location.equals(blueFlagLocation)) {
result = gameOver ? redMarshal : blueFlag;
} else if (location.equals(blueMarshalLocation)) {
result = blueMarshal;
}
return result;
}
| 7 |
public boolean myTurn(int player) {
if (player == currentPlayer) return true;
else return false;
}
| 1 |
private boolean isBinary(final ClientServices client, final String filename,
final Map<StringPattern, KeywordSubstitutionOptions> directoryLevelWrappers)
throws CommandException {
KeywordSubstitutionOptions keywordSubstitutionOptions = getKeywordSubst();
if (keywordSubstitutionOptions == KeywordSubstitutionOptions.BINARY) {
return true;
}
// The keyWordSubstitutions was set based on MIME-types by
// CVSAdd which had no notion of cvswrappers. Therefore some
// filetypes returned as text may actually be binary within CVS
// We check for those files here
boolean wrapperFound = false;
if (wrapperMap == null) {
// process the wrapper settings as we have not done it before.
wrapperMap = WrapperUtils.mergeWrapperMap(client);
}
for (final StringPattern stringPattern : wrapperMap.keySet()) {
final SimpleStringPattern pattern = (SimpleStringPattern) stringPattern;
if (pattern.doesMatch(filename)) {
keywordSubstitutionOptions = wrapperMap.get(pattern);
wrapperFound = true;
break;
}
}
// if no wrappers are found to match the server and local settings, try
// the wrappers for this local directory
if (!wrapperFound && (directoryLevelWrappers != null) && (directoryLevelWrappers != EMPTYWRAPPER)) {
for (final StringPattern stringPattern : directoryLevelWrappers.keySet()) {
final SimpleStringPattern pattern = (SimpleStringPattern) stringPattern;
if (pattern.doesMatch(filename)) {
keywordSubstitutionOptions = directoryLevelWrappers.get(pattern);
wrapperFound = true;
break;
}
}
}
return keywordSubstitutionOptions == KeywordSubstitutionOptions.BINARY;
}
| 9 |
public String getAlgorythmName(){
return algorythmName;
}
| 0 |
public boolean benutzerLoeschen(String benutzername) {
Benutzer benutzer = dbZugriff.getBenutzervonBenutzername(benutzername);
if(benutzer != null){
try{
benutzer.loeschen();
return true;
}
catch(SQLException e){
System.out.println(e);
}
}
return false;
}
| 2 |
protected <T> List<T> readFromListElement(String tagName, XMLStreamReader in, Class<T> type)
throws XMLStreamException {
if (!in.getLocalName().equals(tagName)) {
throw new XMLStreamException(tagName + " expected, not:" + in.getLocalName());
}
final int length = Integer.parseInt(in.getAttributeValue(null, ARRAY_SIZE));
List<T> list = new ArrayList<T>(length);
for (int x = 0; x < length; x++) {
try {
final String value = in.getAttributeValue(null, "x" + Integer.toString(x));
final T object;
if (value != null) {
Constructor<T> c = type.getConstructor(type);
object = c.newInstance(new Object[] {value});
} else {
object = null;
}
list.add(object);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
if (in.nextTag() != XMLStreamConstants.END_ELEMENT) {
throw new XMLStreamException(tagName + " end expected, not: " + in.getLocalName());
}
return list;
}
| 8 |
protected void createStatment() throws SQLException {
if ((stmt == null || stmt.isClosed()) &&
(conn != null && !conn.isClosed())) {
stmt = conn.createStatement();
}
}
| 4 |
public void abrirFactura(String path){
try {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(new File(path));
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
| 2 |
public void run(){
//Try to establish write connection with client.
try{
output = new PrintWriter(userSocket.getOutputStream(), true);
}catch(IOException e){
System.out.println("Error writing to client: " + user.getName() + "(" + user.getIP() + ").");
e.printStackTrace();
}
//Try to establish read connection with client.
try{
clientInput = new BufferedReader( new InputStreamReader(userSocket.getInputStream()) );
}catch(IOException e){
System.out.println("Error reading from client: " + user.getName() + "(" + user.getIP() + ").");
e.printStackTrace();
}
System.out.println("User I/O established: " + user.getName() + "(" + user.getIP() + ")!");
//Say that user has joined.
parentServer.log.add("User " + user.getName() + " has joined the chat!");
while(stopThread = false){
String a = getClientInput();
analyzeInput(a);
sendMessages();
}
//Say that user is leaving.
parentServer.log.add("User " + user.getName() + " has left.");
//Try to disconnect input and output streams.
try{
clientInput.close();
output.close();
}catch(IOException e){
System.out.println("Error closing input and output streams for client: " + user.getName() + "(" + user.getIP() + ").");
e.printStackTrace();
}
//Try to disconnect input and output streams.
try{
userSocket.close();
}catch(IOException e){
System.out.println("Error disconnecting client " + "(" + user.getIP() + ").");
e.printStackTrace();
}
}
| 5 |
private static Node findPredecessor(Node r, Node t) {
if (t.left != null) {
Node p = t.left;
while (p.right != null) {
p = p.right;
}
return p;
} else {
Node p = r;
Node prev = null;
while (p != t) {
if (p == null)
return null;
if (p.v < t.v) {
prev = p;
p = p.right;
} else {
p = p.left;
}
}
return prev.v<t.v?prev:null;
}
}
| 6 |
public List<LngLatAlt> getExteriorRing()
{
assertExteriorRing();
return coordinates.get(0);
}
| 0 |
public Compass getOctant() {
if (isOrigin()) return Compass.CENTER;
double angle = rep.arg();
if (angle < OCT1) return Compass.W;
if (angle < OCT2) return Compass.SW;
if (angle < OCT3) return Compass.S;
if (angle < OCT4) return Compass.SE;
if (angle < OCT5) return Compass.E;
if (angle < OCT6) return Compass.NE;
if (angle < OCT7) return Compass.N;
if (angle < OCT8) return Compass.NW;
return Compass.W;
}
| 9 |
public List<BranchLeader> findBranchLeadersByEventBranchId(final Long eventBranchId) {
return new ArrayList<BranchLeader>();
}
| 0 |
public Event getNextEvent(){
Event a,b;
a=this.listCustAr.peek();
b=this.listOrderArrival.peek();
if (a!=null && b!=null) {
if (b.getTime()>a.getTime()) return this.listCustAr.remove();
else return this.listOrderArrival.remove();
}
else if (b!=null) return this.listOrderArrival.remove();
else if (a!=null) return this.listCustAr.remove();
else return null;
}
| 5 |
public static void main(String args[]) {
String s = JOptionPane
.showInputDialog("Vilken text vill du ska rulla?");
CharController c = new CharController(s);
Array7x7[] characterArray = c.getCharacterArray();
RollingTextViewer theWindow = new RollingTextViewer();
Array7x7[] theBlocks = new Array7x7[4];
for (int i = 0; i < 4; i++) {
theBlocks[i] = new Array7x7(new int[][] {
{ Color.BLACK, Color.BLACK, Color.BLACK, Color.BLACK,
Color.BLACK, Color.BLACK, Color.BLACK },
{ Color.BLACK, Color.BLACK, Color.BLACK, Color.BLACK,
Color.BLACK, Color.BLACK, Color.BLACK },
{ Color.BLACK, Color.BLACK, Color.BLACK, Color.BLACK,
Color.BLACK, Color.BLACK, Color.BLACK },
{ Color.BLACK, Color.BLACK, Color.BLACK, Color.BLACK,
Color.BLACK, Color.BLACK, Color.BLACK },
{ Color.BLACK, Color.BLACK, Color.BLACK, Color.BLACK,
Color.BLACK, Color.BLACK, Color.BLACK },
{ Color.BLACK, Color.BLACK, Color.BLACK, Color.BLACK,
Color.BLACK, Color.BLACK, Color.BLACK },
{ Color.BLACK, Color.BLACK, Color.BLACK, Color.BLACK,
Color.BLACK, Color.BLACK, Color.BLACK } });
}
while (true) {
for (int i = 0; i < characterArray.length; i++) {
for (int k = 0; k < 7; k++) {
Array7 nextArr7 = characterArray[i].getCol(k);
theBlocks[0].moveLeft(theBlocks[1].moveLeft(theBlocks[2]
.moveLeft(theBlocks[3].moveLeft(nextArr7))));
for (int blockNbr = 0; blockNbr < 4; blockNbr++) {
theWindow.setBlock(theBlocks[blockNbr].getArray(),
blockNbr);
}
theWindow.updateViewer();
}
}
}
}
| 5 |
public String findDataFile(File[] files) {
for (File file : files) {
String s = file.getAbsolutePath();
if (s.endsWith(".dat")) {
if (s.contains("file_cache")) {
return s;
}
}
}
return null;
}
| 3 |
private JLabel getJLabel3() {
if (jLabel3 == null) {
jLabel3 = new JLabel();
jLabel3.setText("CsvName:");
}
return jLabel3;
}
| 1 |
public boolean removeProtocol(String protocolName) {
for (int i = 0, limit = protocols.size(); i < limit; i++) {
FileProtocol protocol = (FileProtocol) protocols.get(i);
if (protocol.getName().equals(protocolName)) {
protocols.remove(i);
// Also remove it from the list of formats stored in the preferences
Preferences.FILE_PROTOCOLS.remove(i);
return true;
}
}
return false;
}
| 2 |
public Sign(float x, float y) {
super("");
this.x = x;
this.y = y;
this.width = 12;
this.height = 18;
try {
texture = TextureLoader.getTexture("PNG", this.getClass()
.getResourceAsStream("sign.png"));
System.out.println(texture.getImageWidth());
} catch (IOException e) {
e.printStackTrace();
}
}
| 1 |
public static String getModelId(Class model) {
if (model.isAssignableFrom(Model.class))
throw new IllegalArgumentException(EXC_NOTAMODEL);
Method[] all = model.getDeclaredMethods();
String id = "";
boolean found = false;
for (Method m : all)
/*TODO: make conventions ind. */
if (m.isAnnotationPresent(Id.class)) {
found = true;
id = m.getName().substring(3, m.getName().length());
}
if (!found) {
List<Class> supers = CommonStatic.getSupers(model);
if (supers.size() > 1)
throw new MalformedModelRuntimeException("You have to define an" +
" Id for multiple inheritance.");
else if (supers.size() == 1)
id = CommonStatic.tableName(
supers.get(0)) + getModelId(supers.get(0));
else id = "Id"; /* no inheritance */
}
return id;
}
| 6 |
public int maxProfit(int[] prices) {
if(prices == null || prices.length <= 1) return 0;
int L = prices.length;
int [] maxLeft = new int [L+1];
int [] maxRight = new int [L+1];
int curMin = prices[0];
int maxL = -1;
for(int i = 0; i < L; ++i){
if(prices[i] - curMin > maxL){
maxL = prices[i] - curMin;
}
maxLeft[i] = maxL;
if(prices[i] < curMin) curMin = prices[i];
}
int curMax = prices[L-1];
int maxR = -1;
for(int i = L-1; i >= 0; --i){
if(curMax - prices[i] > maxR){
maxR = curMax - prices[i];
}
maxRight[i] = maxR;
if(prices[i] > curMax) curMax = prices[i];
}
int res = -1;
for(int i = 0; i < L; ++i){
res = Math.max(res, maxLeft[i] + maxRight[i+1]);
}
return res;
}
| 9 |
public void run() {
RevEnglishCustomerBean bean = (RevEnglishCustomerBean) context.getBean("revEnglishCustomerBean");
bean.writeTemplate(template);
LinkedList<String> templates = new LinkedList<String>();
Integer currentPrice = Integer.MAX_VALUE;
Date start = new Date();
Template match = bean.waitForMatch(template, Integer.MAX_VALUE);
while(true) {
Template tpl = bean.waitForMatch(template, 1000);
if (tpl != null) {
match = tpl;
}
if (match.getPrice() < currentPrice) {
currentPrice = match.getPrice();
template.setPrice(currentPrice);
templates.addFirst(match.getUid());
}
if (start.getTime() + TIMEOUT < (new Date()).getTime()) {
break;
}
}
if (!templates.isEmpty()) {
for (String templateId : templates) {
try {
bean.writeMatch(templateId, id);
} catch (TransactionAbortedException e) {
System.out.println("Customer " + id + " was to late for template " + templateId);
}
}
}
}
| 7 |
public static boolean checkCellInDirection(Board board, int x, int y, DirectionX dirx, DirectionY diry) {
boolean finished = false;
int count = 0;
Counter turn = board.getPosition(x, y);
//Iterate check if the cell is connected
while((count <= Game.WINCON) && !finished &&
(x >= Board.MINWIDTH) && (y >= Board.MINHEIGHT) &&
(x <= board.getWidth()) && (y <= board.getHeight()) &&
(board.getPosition(x, y) == turn) && (board.getPosition(x, y) != Counter.EMPTY)){
/**
* Change x and y according to the direction, to get the next cell
*/
x = x + Util.convertDirX(dirx);
y = y + Util.convertDirY(diry);
count++;
}
if (count >= Game.WINCON) {
finished = true;
} else {
count = 0;
}
return finished;
}
| 9 |
@Override
public boolean isCommonSubexpression(Instruction i) {
if(i instanceof UnaryInstruction) {
UnaryInstruction u = (UnaryInstruction)i;
return this.getOpcode() == u.getOpcode()
&& this.argument.equals(u.argument);
}
return false;
}
| 2 |
@Override
public OreLookup lookup(String player, Integer time, List<Integer> restrict) {
List<Block> blocks = new ArrayList<Block>();
int i = 0;
for (int value : restrict){
blocks.add(i,new Block(value, -1));
i++;
}
OreLookup ore = new OreLookup(player);
for (String w : plugin.getConfiguration().getWorlds()) {
QueryParams params = new QueryParams(this.logblock);
params.bct = BlockChangeType.DESTROYED;
params.since = time / 60;
params.limit = -1;
params.setPlayer(player);
params.types = blocks;
params.world = Bukkit.getWorld(w);
params.needType = true;
try {
for (BlockChange bc : this.logblock.getBlockChanges(params)) {
ore.add(bc.replaced);
}
}
catch (SQLException ex) {
plugin.log("Unexpected Exception while fetching Data from LogBlock: "+ex.getMessage());
}
}
return ore;
}
| 4 |
@Override
public PermissionType getType() {
return PermissionType.RCON;
}
| 0 |
public int[] getBestTranslations(int sourceWord, int transCount){
int totalTransCount = translations[sourceWord].length;
if(totalTransCount < transCount) transCount = totalTransCount;
int[] bestTranslation = new int[transCount];
double[] bestScores = new double[transCount];
for(int i=0; i<transCount; i++){
bestTranslation[i] = -1;
bestScores[i] = -1f;
}
for(int i=0; i<totalTransCount; i++){
double s = translations[sourceWord][i];
for(int a=0; a<transCount; a++){
if(s > bestScores[a]){
for(int a2=transCount-1; a2>a; a2--){
bestTranslation[a2] = bestTranslation[a2-1];
bestScores[a2] = bestScores[a2-1];
}
bestTranslation[a] = i;
bestScores[a] = s;
break;
}
}
}
return bestTranslation;
}
| 6 |
@Override
public final int find(final IAMArray key) throws NullPointerException {
if (key == null) throw new NullPointerException("key = null");
int i = this._rangeMask_;
if (i != 0) {
final IAMArray range = this._rangeOffset_;
i = key.hash() & i;
for (int l = range._get_(i), r = range._get_(i + 1); l < r; l++) {
if (this.key(l).equals(key)) return l;
}
} else {
int l = 0, r = this._entryCount_;
while (l < r) {
i = (l + r) >> 1;
i = key.compare(this.key(i));
if (i < 0) {
r = i;
} else if (i > 0) {
l = i + 1;
} else return i;
}
}
return -1;
}
| 7 |
@Override
public void run()
{
try
{
/*
// get login information
String username = _in.readLine();
String password = _in.readLine();
String responseMessage;
if (validateLogin(username, password))
{
responseMessage = "ok";
}
else
{
responseMessage = "nok";
}
responseMessage = "ok";
_clientInfo.getSender().sendMessage(responseMessage);
*/
while (!isInterrupted())
{
String message = _in.readLine();
if (message == null)
{
// if the received message is null, it means that the
// client was closed, so there is no need to listen
// for anymore messages.
break;
}
System.out.println("received message: " + message);
JSONObject json = JSONObject.fromObject(message);
switch (json.getInt("type")) {
case JSON_TYPE_LOGIN:
System.out.println("JSON_TYPE_LOGIN");
_clientInfo.setId(json.getString("id"));
break;
case JSON_TYPE_MAKE_ROOM:
System.out.println("JSON_TYPE_MAKE_ROOM");
int groupNo = _serverDispatcher.makeRoom();
_clientInfo.setGroupNumber(groupNo);
break;
case JSON_TYPE_JOIN:
System.out.println("JSON_TYPE_JOIN");
_clientInfo.setGroupNumber(json.getInt("group"));
//if 2인용 게임이라면 여기서 start
break;
case JSON_TYPE_MESSAGE:
System.out.println("JSON_TYPE_MESSAGE");
break;
default:
break;
}
// forward the received message to the ServerDispatcher object
_serverDispatcher.dispatchMessage(_clientInfo, message);
}
}
catch (IOException e)
{
// error reading from the socket
}
// communication ended, so interrupt the sender too
_clientInfo.getSender().interrupt();
// also delete the current client from the ServerDispatcher clients list.
_serverDispatcher.deleteClient(_clientInfo);
}
| 7 |
private void InfectSurroundingHumans( int rowPosition, int columnPosition )
{
int[] infectLeft = CalculateMove( rowPosition, columnPosition, "Left" );
int[] infectRight = CalculateMove( rowPosition, columnPosition, "Right" );
int[] infectUp = CalculateMove( rowPosition, columnPosition, "Up" );
int[] infectDown = CalculateMove( rowPosition, columnPosition, "Down" );
if( world[ infectLeft[0] ][ infectLeft[1] ] == "Hunter" )
{
world[ infectLeft[0] ][ infectLeft[1] ] = "Zombie";
huntersBitten++;
}
else if( world[ infectLeft[0] ][ infectLeft[1] ] == "Victim" )
{
world[ infectLeft[0] ][ infectLeft[1] ] = "Zombie";
victimsBitten++;
}
if( world[ infectRight[0] ][ infectRight[1] ] == "Hunter" )
{
world[ infectRight[0] ][ infectRight[1] ] = "Zombie";
huntersBitten++;
}
else if( world[ infectRight[0] ][ infectRight[1] ] == "Victim" )
{
world[ infectRight[0] ][ infectRight[1] ] = "Zombie";
victimsBitten++;
}
if( world[ infectUp[0] ][ infectUp[1] ] == "Hunter" )
{
world[ infectUp[0] ][ infectUp[1] ] = "Zombie";
huntersBitten++;
}
else if( world[ infectUp[0] ][ infectUp[1] ] == "Victim" )
{
world[ infectUp[0] ][ infectUp[1] ] = "Zombie";
victimsBitten++;
}
if( world[ infectDown[0] ][ infectDown[1] ] == "Hunter" )
{
world[ infectDown[0] ][ infectDown[1] ] = "Zombie";
huntersBitten++;
}
else if( world[ infectDown[0] ][ infectDown[1] ] == "Victim" )
{
world[ infectDown[0] ][ infectDown[1] ] = "Zombie";
victimsBitten++;
}
}
| 8 |
@Override
public void startDocument() throws SAXException {
System.out.println("start Document");
}
| 0 |
public static boolean validateEvent(){
boolean isValid=false;
return isValid;
}
| 0 |
private static void validerSujet(Sujet sujet) throws ChampInvalideException, ChampVideException {
if (sujet.getSujet() == null|| sujet.getSujet().isEmpty())
throw new ChampVideException("Le sujet n'a pas de titre");
if (!sujet.getCategorie().peutCreerSujet(sujet.getCreateur()))
throw new InterditException("Vous n'avez pas les droits requis pour créer une discussion dans cette catégorie");
}
| 3 |
public void flush()
{
if (isOpen())
{
flushImpl();
}
}
| 1 |
public void listPaare(){
for(Paar p : paare){
if(p == null)
continue;
System.out.println("Paar: " + p.paarnummer + ", Name Herr: "+ p.nameH + ", Name Dame: "+ p.nameD);
}
}
| 2 |
@Override
protected boolean collidingWithWall() {
if(!collidable)
return false;
if(game.getCurrentLevel().isBlockAtPixelCollidable((int)tx+(width/2)-4,(int)ty-(height/4)) && game.getCurrentLevel().isBlockAtPixelCollidable((int)tx+(width/2)-4,(int)ty+(height/4)) ){
return true;
} else if(game.getCurrentLevel().isBlockAtPixelCollidable((int)tx-(width/2)+4,(int)ty-(height/4)) && game.getCurrentLevel().isBlockAtPixelCollidable((int)tx-(width/2)+4,(int)ty+(height/4)) ){
return true;
}
return false;
}
| 5 |
public Object invokeConstructor(Reference ref, Object[] params)
throws InterpreterException, InvocationTargetException {
Constructor c;
try {
String[] paramTypeSigs = TypeSignature.getParameterTypes(ref
.getType());
Class clazz = TypeSignature.getClass(ref.getClazz());
Class[] paramTypes = new Class[paramTypeSigs.length];
for (int i = 0; i < paramTypeSigs.length; i++) {
params[i] = toReflectType(paramTypeSigs[i], params[i]);
paramTypes[i] = TypeSignature.getClass(paramTypeSigs[i]);
}
try {
c = clazz.getConstructor(paramTypes);
} catch (NoSuchMethodException ex) {
c = clazz.getDeclaredConstructor(paramTypes);
}
} catch (ClassNotFoundException ex) {
throw new InterpreterException(ref + ": Class not found");
} catch (NoSuchMethodException ex) {
throw new InterpreterException("Constructor " + ref + " not found");
} catch (SecurityException ex) {
throw new InterpreterException(ref + ": Security exception");
}
try {
return c.newInstance(params);
} catch (IllegalAccessException ex) {
throw new InterpreterException("Constructor " + ref
+ " not accessible");
} catch (InstantiationException ex) {
throw new InterpreterException("InstantiationException in " + ref
+ ".");
}
}
| 7 |
public static String toString(Inventory i) {
YamlConfiguration configuration = new YamlConfiguration();
configuration.set("Title", i.getTitle());
configuration.set("Size", i.getSize());
for (int a = 0; a < i.getSize(); a++) {
ItemStack s = i.getItem(a);
if (s != null)
configuration.set("Contents." + a, s);
}
return Base64Coder.encodeString(configuration.saveToString());
}
| 2 |
private void setSequence(URL midiSource) {
if (sequencer == null) {
errorMessage("Unable to update the sequence in method "
+ "'setSequence', because variable 'sequencer' "
+ "is null");
return;
}
if (midiSource == null) {
errorMessage("Unable to load Midi file in method 'setSequence'.");
return;
}
try {
sequence = MidiSystem.getSequence(midiSource);
} catch (IOException ioe) {
errorMessage("Input failed while reading from MIDI file in "
+ "method 'setSequence'.");
printStackTrace(ioe);
return;
} catch (InvalidMidiDataException imde) {
errorMessage("Invalid MIDI data encountered, or not a MIDI "
+ "file in method 'setSequence' (1).");
printStackTrace(imde);
return;
}
if (sequence == null) {
errorMessage("MidiSystem 'getSequence' method returned null "
+ "in method 'setSequence'.");
} else {
try {
sequencer.setSequence(sequence);
} catch (InvalidMidiDataException imde) {
errorMessage("Invalid MIDI data encountered, or not a MIDI "
+ "file in method 'setSequence' (2).");
printStackTrace(imde);
return;
} catch (Exception e) {
errorMessage("Problem setting sequence from MIDI file in "
+ "method 'setSequence'.");
printStackTrace(e);
return;
}
}
}
| 7 |
private void readFile(BufferedReader reader) throws IOException{
startTime = System.nanoTime();
textfields.setControlfile("Starting assembly ...");
for ( String line; ( line = reader.readLine() ) != null; )
{
textfields.setProgramfile(linecounter + " " + line);
linecounter++;
line = line.trim();
if (line.startsWith("define")){
line = line.replaceFirst("define", "");
line = line.trim();
if(line.startsWith("#")){
errorcounter++;
textfields.setControlfile((linecounter-1) + ": The number of operands for this opcode is incorrect.");
continue;
}
parts = line.split("\\s+");
try {
definitions.put(parts[0],Integer.parseInt(parts[1]));
}
catch(NumberFormatException e) {
errorcounter++;
textfields.setControlfile((linecounter-1) + ": The number of operands for this opcode is incorrect.");
}
}
else if(line.startsWith("#")){
}
else {
parts = line.split("\\s+");
if(parts.length==3){
definitions.put(parts[0],counter);
}
for (String part : parts) {
if (part.startsWith("#")) {
break;
}
programMemory.add(part);
counter++;
//programMemory.remove("");
}
}
}
endTime = System.nanoTime();
duration = endTime - startTime;
seconds = (double)duration / 1000000000.0;
if (errorcounter == 0){
textfields.setControlfile("BUILD SUCCESSFUL. Assembly time: " + seconds + " sec.");
}
else{
textfields.setControlfile("BUILD FAILED. Assembly time: " + seconds + " sec. Number of invalid statements: " + errorcounter);
}
}
| 9 |
@Override
protected Object doInBackground() throws Exception {
socketChannel.register(selector, SelectionKey.OP_CONNECT);
while (running) {
selector.select();
for (Iterator<SelectionKey> it = selector.selectedKeys().iterator(); it
.hasNext();) {
SelectionKey key = it.next();
it.remove();
try {
if (key.isReadable()) {
read(key);
} else if (key.isWritable()) {
write(key);
} else if (key.isConnectable()) {
connect(key);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
return null;
}
| 6 |
private void checkEarning() {
if (cb.isCanCreateMeoMeo()) {
pp.addMeoMeo();
cb.setCanCreateMeoMeo(false);
}
if (cb.isCanUpgradeMeoMeo()) {
pp.upgradeMeoMeo();
cb.setCanUpgradeMeoMeo(false);
}
}
| 2 |
@Test
public void testRunStartServerSpotStudent()throws Exception{
AccessControlServer server = new AccessControlServer(1931);
server.start();
SpotStub spot = new SpotStub("312",1931);
spot.start();
sleep(1000);
String ans = "";
int x = 0;
while(x != -1 && x<=50){ //if no response is recieved in 10 seconds, test is deemed failed.
x++;
ans = spot.getAnswer();
sleep(100);
if(ans != ""){
x = -1;
}
}
assertEquals("Student",ans);
}
| 3 |
public void setBody( final Foil f )
{
final StringBuilder sB = new StringBuilder();
final int count = f.size();
final int digits = String.valueOf( count ).length();
sB.append( "<html>" );
sB.append( "<pre>" );
final int eC = f.getErrorCount();
int index = 0;
if ( eC > 0 )
{
sB.append( "<font color=\"blue\">Errors found on <font color=\"red\">" + eC + "</font> lines:<br><br>" );
for ( final Line l : f )
{
index ++;
int cnt = l.errMap.size();
if ( cnt == 0 ) continue;
sB.append( "\tLine <font color=\"red\">" )
.append( index )
.append( "</font>: column " );
boolean newError = true;
for ( final int i : l.errMap.keySet() )
{
sB.append( newError ? "" : "<font color=\"black\">, </font>" )
.append( "<font color=\"red\">" )
.append( i + 1 )
.append( "</font>" );
newError = false;
}
sB.append( "<br>" );
}
sB.append( "<br></font></pre><hr><pre>" );
}
index = 0;
for ( final Line l : f )
{
index ++;
final boolean ok = l.errMap.isEmpty();
if ( !ok )
sB.append( "<font color=\"red\">" );
sB.append( String.format( "%" + digits + "d: ", index ) );
if ( ok )
sB.append( "<font color=\"green\">" );
for ( int i = 0; i < l.bytes.length; i ++ )
{
esc( sB, l.bytes[ i ] );
}
sB.append( "</font>" );
sB.append( "<br>" );
}
sB.append( "</pre>" );
sB.append( "</html>" );
setText( sB.toString() );
setCaretPosition( 0 );
}
| 9 |
public String output() {
String str = "";
if (data<10) {
str+="0";
}
if (data<100) {
str+= "0";
}
str+= "" + data + " data2: " + data2 + " text: " + text;
return str;
}
| 2 |
private void writeFile(byte[] content, String filename) throws IOException {
File file = new File(filename);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fop = new FileOutputStream(file);
fop.write(content);
fop.flush();
fop.close();
}
| 1 |
@Override
public List<Kolegij> fetchAllKolegijList() {
List<Kolegij> listaKolegija = new ArrayList<Kolegij>();
for (int i = 0; i < 10; i++) {
listaKolegija.add(mock(Kolegij.class));
}
return listaKolegija;
}
| 1 |
private void doubleRightRotate (Tree degTree) {
Tree leftChild = degTree.getLeftChild(),
parent = degTree.getParent(),
rightGrandson = leftChild.getRightChild();
leftChild.setParent(rightGrandson);
leftChild.setRightChild(rightGrandson.getLeftChild());
if (rightGrandson.getLeftChild() != null) {
rightGrandson.getLeftChild().setParent(leftChild);
}
if (rightGrandson.getRightChild() != null) {
rightGrandson.getRightChild().setParent(degTree);
}
degTree.setParent(rightGrandson);
degTree.setLeftChild(rightGrandson.getRightChild());
rightGrandson.setParent(parent);
rightGrandson.setLeftChild(leftChild);
rightGrandson.setRightChild(degTree);
if (parent != null){
if (parent.getValue() > rightGrandson.getValue()) {
parent.setLeftChild(rightGrandson);
} else {
parent.setRightChild(rightGrandson);
}
}
recalcHeight(degTree);
Tree tmpTree = leftChild;
while (tmpTree != null) {
recalcHeight(tmpTree);
tmpTree = tmpTree.getParent();
}
if (parent == null) {
tree = rightGrandson;
}
}
| 6 |
@Override
protected boolean xsend (Msg msg_, int flags_)
{
if (pipe == null || !pipe.write (msg_)) {
ZError.errno(ZError.EAGAIN);
return false;
}
if ((flags_ & ZMQ.ZMQ_SNDMORE) == 0)
pipe.flush ();
// Detach the original message from the data buffer.
return true;
}
| 3 |
@Override
public void update() {
/** Coleta eventos de explosão. */
List<Event> explosionEvents = getEntityManager().getEvents(
InAnExplosionEvent.class);
/** Verifica se a lista de eventos não está vazia. */
if (explosionEvents != null) {
for (Event event : explosionEvents) {
InAnExplosionEvent explosion = (InAnExplosionEvent) event;
/**
* @if Confere se o evento de explosão já não foi tratado.
*/
if (!processedEvents.contains(explosion)) {
if (isBlockExplosion(explosion)) {
createPowerUp(explosion);
}
if (isPowerUpExplosion(explosion)) {
destroyPowerUp(explosion.getIdHit());
}
}
/** Processa evento de explosão. */
processedEvents.add(explosion);
}
}
/** Coleta eventos de Colisão. */
List<Event> collisionEvents = getEntityManager().getEvents(
CollisionEvent.class);
/** Verifica se a lista de eventos não está vazia. */
if (collisionEvents != null) {
for (Event event : collisionEvents) {
CollisionEvent collision = (CollisionEvent) event;
/**
* @if Confere se o evento de colisão já não foi tratado.
*/
if (!processedEvents.contains(collision)) {
/**
* @if Confere a possibilidade de criar evento de power up
* adquirido.
*/
if (checkCollision(collision)) {
createPowerUpEvent(collision);
}
/** Processa evento de colisão mesmo se não retirar vida. */
processedEvents.add(collision);
}
}
}
}
| 9 |
public int getYLocation() {
return yLocation;
}
| 0 |
public IdentityDiscGridFactory(Grid grid, FullGridFactory factory) {
if (grid == null)
throw new IllegalArgumentException("Grid can't be null!");
if (factory == null)
throw new IllegalArgumentException("Factory can't be null!");
this.factory = factory;
this.grid = grid;
}
| 2 |
public void updateAllBoard() {
Cell cCell;
for (int y = 0; y < ySize; y++) {
for (int x = 0; x < xSize; x++) {
cCell = curMap.getCell(y, x);
if (cCell.containsRock()) {
board[x][y] = new Hexagon(this, rock);
} else if (cCell.containsBlackAnt()) {
board[x][y] = new Hexagon(this, antB);
} else if (cCell.containsRedAnt()) {
board[x][y] = new Hexagon(this, antR);
} else if (cCell.isContainsFood()) {
board[x][y] = new Hexagon(this, food);
} else if (cCell.containsBlackAntHill()) {
board[x][y] = new Hexagon(this, antHB);
} else if (cCell.containsRedAntHill()) {
board[x][y] = new Hexagon(this, antHR);
} else if (cCell.isClear()) {
board[x][y] = new Hexagon(this, clear);
}
}
}
}
| 9 |
public void run() {
String currentIP = TakitDNS.getIP();
String file = TakitDNS.getURL(
"http://freedns.afraid.org/api/?action=getdyndns&sha=" +
Security.SHA1(username.toLowerCase()+"|"+password)
);
if ( file==null ) {
return;
}
String[] entries = file.split("\n");
String[] entry = null;
for ( int i=0; i<entries.length; ++i ) {
entry = entries[i].split("\\|");
if ( domain.equals(entry[0]) ) {
break;
}
else {
entry = null;
}
}
if ( entry==null ) {
TakitDNS.log.info(String.format(
Messages.DOMAIN_NOT_FOUND,
plugin.getDescription().getName(),
domain
));
return;
}
if ( !currentIP.equals(entry[1]) ) {
TakitDNS.getURL(entry[2]);
TakitDNS.log.info(String.format(
Messages.IP_CHANGED,
plugin.getDescription().getName(),
currentIP
));
}
}
| 5 |
public void method468(int i) {
super.modelHeight = 0;
anInt1650 = 0;
anInt1651 = 0;
anInt1646 = 0xf423f;
anInt1647 = 0xfff0bdc1;
anInt1648 = 0xfffe7961;
anInt1649 = 0x1869f;
for (int j = 0; j < anInt1626; j++) {
int k = anIntArray1627[j];
int l = anIntArray1628[j];
int i1 = anIntArray1629[j];
if (k < anInt1646)
anInt1646 = k;
if (k > anInt1647)
anInt1647 = k;
if (i1 < anInt1649)
anInt1649 = i1;
if (i1 > anInt1648)
anInt1648 = i1;
if (-l > super.modelHeight)
super.modelHeight = -l;
if (l > anInt1651)
anInt1651 = l;
int j1 = k * k + i1 * i1;
if (j1 > anInt1650)
anInt1650 = j1;
}
anInt1650 = (int) Math.sqrt(anInt1650);
anInt1653 = (int) Math.sqrt(anInt1650 * anInt1650 + super.modelHeight
* super.modelHeight);
if (i != 21073) {
return;
} else {
anInt1652 = anInt1653
+ (int) Math.sqrt(anInt1650 * anInt1650 + anInt1651
* anInt1651);
return;
}
}
| 9 |
protected void showFamilyAsChild() {
Person person = personPanel.getPerson();
List<Family> families = person.getFamiliesAsChild();
Family family = null;
if (families != null)
family = families.get(0);
if (family != null) {
familyPage.setFamily(family);
parent.setSelectedIndex(1);
}
}
| 2 |
public void printListBackwards() {
if (previous != null) {
System.out.println(this.getData());
previous.printListBackwards();
} else {
System.out.println(this.getData());
}
}
| 1 |
@Override
public void handle(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
// Cache Validation
String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
SimpleDateFormat dateFormatter = new SimpleDateFormat(HandlerUtil.HTTP_DATE_FORMAT, Locale.US);
Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);
// Only compare up to the second because the datetime format we send to the client
// does not have milliseconds
long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
long fileLastModifiedSeconds = start / 1000;
if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
HandlerUtil.sendNotModified(ctx);
return;
}
}
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(responseStr.getBytes()));
HandlerUtil.setDateAndCacheHeaders(response, start);
response.headers().set(CONTENT_TYPE, "application/javascript; charset=UTF-8");
response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
response.headers().set(CONNECTION, HttpHeaders.Values.CLOSE);
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
| 3 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Perfil)) {
return false;
}
Perfil other = (Perfil) object;
if ((this.idPerfil == null && other.idPerfil != null) || (this.idPerfil != null && !this.idPerfil.equals(other.idPerfil))) {
return false;
}
return true;
}
| 5 |
public void readXML(XMLStreamReader parser) throws IOException, XMLStreamException
{
parser.require(XMLStreamReader.START_ELEMENT, null, "matrix");
m = Integer.parseInt(parser.getAttributeValue(null, "rows"));
n = Integer.parseInt(parser.getAttributeValue(null, "cols"));
A = new double[m][n];
for (int i = 0; i < m; i++)
{
parser.nextTag();
parser.require(XMLStreamReader.START_ELEMENT, null, "matrixrow");
for (int j = 0; j < n; j++)
{
parser.nextTag();
parser.require(XMLStreamReader.START_ELEMENT, null, "cn");
if (!parser.getAttributeValue(null, "type").equals("IEEE-754"))
throw new IOException("a xml stream exception occured");
if (parser.next() != XMLStreamReader.CHARACTERS)
throw new IOException("a xml stream exception occured");
A[i][j] = getDecodedValue(parser.getText());
parser.next();
parser.require(XMLStreamReader.END_ELEMENT, null, "cn");
}
parser.next();
parser.require(XMLStreamReader.END_ELEMENT, null, "matrixrow");
}
parser.next();
parser.require(XMLStreamReader.END_ELEMENT, null,"matrix");
}
| 4 |
protected boolean shouldShowStatePopup() {
return true;
}
| 0 |
private AudioChannel getAudioChannel(int objectId) {
if (channels.containsKey(objectId)) {
return channels.get(objectId);
}
Iterator<Entry<Integer, AudioChannel>> it = channels.entrySet()
.iterator();
while (it.hasNext()) {
Entry<Integer, AudioChannel> entry = it.next();
if (entry.getValue().isFree()) {
AudioChannel result = entry.getValue();
it.remove();
channels.put(objectId, result);
return result;
}
}
AudioChannel result = new AudioChannel();
channels.put(objectId, result);
return result;
}
| 3 |
public static String combineSplit(int startIndex, String[] string, String separator) {
if (string == null) {
return "";
} else {
StringBuilder builder = new StringBuilder();
for (int i = startIndex; i < string.length; i++) {
builder.append(string[i]);
builder.append(separator);
}
builder.deleteCharAt(builder.length() - separator.length());
return builder.toString();
}
}
| 2 |
void cancelLastCommand() {
try {
worker.abort();
} catch (Exception ex) {
}
}
| 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.