method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
f9da89a3-c0b7-4c92-a40f-0b8f42371729 | 2 | @SuppressWarnings({ "rawtypes", "unchecked" })
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException{
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
Cache cache = null;
try {
CacheFactory cacheFactory = CacheManager.getInstance()
.getCacheFactory();
Map props = new HashMap();
// 完全キャッシュ有効期間15分
props.put(GCacheFactory.EXPIRATION_DELTA, 60 * 15);
cache = cacheFactory.createCache(props);
} catch (CacheException e) {
}
String column = (String) cache.get("namecolumn");
if (column == null) {
WakeBackends wb = new WakeBackends();
wb.newColumn();
}
StringBuilder sb = new StringBuilder();
sb.append(
"<html><head><title>共演検索マシーン - 共演の基準</title><meta name=\"viewport\" content=\"user-scalable=no\" /><meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />")
.append("<meta name=\"description\" content=\"共演検索マシーンの説明です。\">")
.append("<meta name=\"keywords\" content=\"声優,共演,検索,アニメ\">")
.append("<script type=\"text/javascript\">")
.append("function ChangeSelection1(form, selection) {\n")
.append("form.n.value = selection.options[selection.selectedIndex].value;\n")
.append("change_flag1(false);\n")
.append("}\n")
.append("function ChangeSelection2(form, selection) {\n")
.append("form.m.value = selection.options[selection.selectedIndex].value;\n")
.append("change_flag2(false);\n")
.append("}\n")
.append("function change_flag1(boolean) {\n")
.append("if(boolean)\n")
.append("document.getElementById(\"col_style1\").style.display = \"inline\";\n")
.append("else\n")
.append("document.getElementById(\"col_style1\").style.display = \"none\";\n")
.append("}\n")
.append("function change_flag2(boolean) {\n")
.append("if(boolean)\n")
.append("document.getElementById(\"col_style2\").style.display = \"inline\";\n")
.append("else\n")
.append("document.getElementById(\"col_style2\").style.display = \"none\";\n")
.append("}\n")
.append(" var _gaq = _gaq || [];")
.append(" _gaq.push(['_setAccount', 'UA-28405404-2']);")
.append(" _gaq.push(['_trackPageview']);")
.append(" (function() { var ga = document.createElement('script');")
.append(" ga.type = 'text/javascript'; ga.async = true;")
.append(" ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';")
.append(" var s = document.getElementsByTagName('script')[0];")
.append(" s.parentNode.insertBefore(ga, s); })();")
.append("</script>")
.append("<link href=\"table.css\" rel=\"stylesheet\" type=\"text/css\" />")
.append("</head><body onload=\"change_flag1(false),change_flag2(false)\">")
.append("<div id=\"head\"><a href=\"/\" class=\"top\">サイトTOP</a><a href=\"guide\" class=\"guide\">ガイド</a><a href=\"past\" class=\"past\">検索履歴</a>")
.append("<a href=\"ranking\" class=\"ranking\">総合ランキング</a><a href=\"pair\" class=\"pair\">男女ランキング</a><form action=\"co\" method=\"GET\"><input class=\"text\" type=\"text\" name=\"n\" value=\"")
.append("")
.append("\" onmouseover=\"change_flag1(true),change_flag2(false)\" onclick=\"change_flag1(false)\" />")
.append(" & <input class=\"text\" type=\"text\" name=\"m\" onmouseover=\"change_flag2(true),change_flag1(false)\" onclick=\"change_flag2(false)\"/>")
.append(" の共演を <input type=\"submit\" value=\"調べる\" />")
.append("<div id=\"col_style1\"><select id=\"column1\" onchange=\"ChangeSelection1(this.form, this)\">")
.append(column)
.append("</select></div>")
.append("<div id=\"col_style2\"><select id=\"column2\" onchange=\"ChangeSelection2(this.form, this)\">")
.append(column).append("</select></div></form></div><div id=\"wrap\">")
.append("<br /><div id=\"space\"></div>")
.append("<div id=\"guide\"><h2>ガイド - 共演の基準</h2>")
.append("共演検索マシーンが「共演作品である」と判断する際の基準をご説明します。")
.append("<br />Wikipediaの記事を比較する際に、以下の三点をチェックしています。<ol><li>作品のタイトル</li><li>作品のカテゴリ</li><li>公開された年</li></ol>")
.append("<dl><dt>作品のタイトルについて</dt><dd>Wikipediaの記事の中で、出演作品リストと判断されたブロックの各行から、</dd>")
.append("<dd>キャラクター名と判断される部分を除いた文字列を作品タイトルと判断しており、これが両者で一致する必要があります。</dd>")
.append("<dd>この時、記号文字の差異・アルファベットの大小はある程度許容されます。スペースの有無、-と〜など。</dd>")
.append("<dd>許容されない記号文字としては!や?があります。</dd>")
.append("<dt>作品のカテゴリについて</dt>")
.append("<dd>「テレビアニメ」「劇場アニメ」「ドラマCD」「ゲーム」等を指します。</dd>")
.append("<dd>Wikipediaの見出しからこれらを取得し、各出演作品に付加しています。このカテゴリが両者で一致する必要があります。</dd>")
.append("<dd>Wikipediaでは、同一の作品でも記事によってカテゴリの表記がゆれます。</dd>")
.append("<dd>イベントの様子を収めたDVDソフトを「実写」とするか「その他」とするかは記事によります。</dd>")
.append("<dd>また海外制作のテレビアニメを吹き替えた際に「吹き替え(アニメ)」とするか単に「テレビアニメ」とするか等でも違いがあります。</dd>")
.append("<dd>これらの差異を、現状では一部のケースを除き許容(修正)できていません。(後述の“部分一致”でフォローしています。)</dd>")
.append("<dd>基本的には両者のカテゴリ名が同一である必要があります。</dd>")
.append("<dt>公開された年について</dt>")
.append("<dd>Wikipediaでは、テレビアニメであれば放映年(正確には、対象の声優が出演した回の放映年)、</dd><dd>ゲームであれば発売年、映画であれば公開年が各出演作品には付加されています。</dd>")
.append("<dd>これも参照しており、そのルールはやや複雑です。以下のいずれかを満たせばよいものとします。</dd>")
.append("<dd><ul>" +
"<li>公開された年が完全に同一である。たとえば2005年・2005年など。</li>" +
"<li>公開された年が空欄である。片方、あるいは両方。たとえば2007年・(空欄)。</li>" +
"<li>片方、あるいは両方の役名が“太字”、主要なキャラクターであり、なおかつ、太字でない方のキャラクターは、太字のキャラクターよりも後の年に登場している。</li></ul></dd>")
.append("<dd>条件を満たさないのは、違う年が明記されており、なおかつお互いが主要キャラクターでない場合。</dd>")
.append("<dd>あるいは、違う年が明記されており、なおかつ非主要キャラクターが主要キャラクターよりも前の年に登場している場合です。</dd></dl>")
.append("<br />タイトル・カテゴリ・放映年と、全ての条件を満たしたものが「完全一致」となり、この件数が簡易履歴に表示されます。また、ランキングにも登録されます。")
.append("<h2>部分一致</h2>")
.append("表記のゆれなどの理由で、本来は共演しているのに漏れてしまったタイトルがあります。それらをすくい上げる意味で、部分一致カテゴリを用意しています。<br />")
.append("部分一致が参照しているのは<i>“Wikipediaで各出演タイトルに関連づけられているリンク先”</i>です。<br />")
.append("桑谷夏子さんの出演タイトルに「魔法先生ネギま! 〜白き翼 ALA ALBA〜」がありますが、Wikipediaでタイトル名をクリックすると<br />")
.append("Wikipediaの記事「魔法先生ネギま!_(OVA)」にジャンプします。共演検索マシーンでは、このジャンプ先の記事が同一であれば、")
.append("<br />いかにタイトル・カテゴリ・公開された年が違っていても“部分一致”としてリストの下段に表示します。")
.append("<h2>当サイトの「共演」の定義</h2>")
.append("以上のことから、当サイトでいう「共演」とはかなり範囲の広い言葉になっています。<br />")
.append("厳密には共演とは、「同じスタジオで一緒にアフレコした」ということを指すのだと思いますが、<br />")
.append("当サイトでは共演とは、<b>「同一カテゴリの同一タイトルに、同じ年に関わっていた(あるいは違う年に関わっていた)」</b>ということを指します。<br />")
.append("これはWikipediaをソースとしていることからくる仕様です。<br />ご利用の際や、話題にされる際はどうかこの点にご留意ください。")
.append("</div></div></body></html>");
resp.getWriter().println(new String(sb));
} |
a58b1e1a-aafe-41c2-ac60-5f6af9ee4952 | 9 | public void countDiffPixels() {
if (image1 == null || image2 == null) {
return;
}
int w1 = image1.getWidth();
int h1 = image1.getHeight();
int w2 = image2.getWidth();
int h2 = image2.getHeight();
int wmax = Math.max(w1, w2);
int hmax = Math.max(h1, h2);
// check each pair of pixels
numDiffPixels = 0;
for (int y = 0; y < hmax; y++) {
for (int x = 0; x < wmax; x++) {
int pixel1 = (x < w1 && y < h1) ? image1.getRGB(x, y) : 0;
int pixel2 = (x < w2 && y < h2) ? image2.getRGB(x, y) : 0;
if (pixel1 != pixel2) {
numDiffPixels++;
}
}
}
} |
bb805836-2e7f-4ad8-ab02-a430b36782c4 | 8 | public static void jams_wrap(List<String> jars, String srcPath, List<String> className) throws Exception {
if (jars == null || jars.size() == 0) {
throw new RuntimeException("No jar files!");
}
if (srcPath == null) {
throw new RuntimeException("No src path!");
}
if (className == null || className.size() == 0) {
throw new RuntimeException("No components to convert!");
}
URL[] u = new URL[jars.size()];
for (int i = 0; i < jars.size(); i++) {
if (!new File(jars.get(i)).exists()) {
throw new RuntimeException("Not found:" + jars.get(i));
}
u[i] = new File(jars.get(i)).toURI().toURL();
}
URLClassLoader cl = new URLClassLoader(u, Thread.currentThread().getContextClassLoader());
for (String cn : className) {
Class c = Class.forName(cn, true, cl);
Object o = c.newInstance();
String jamsClass = doit(o);
String name = "JAMS" + c.getSimpleName();
String pack = c.getPackage().getName().replace('.', '/');
String file = srcPath + File.separator + pack + File.separator + name + ".java";
File f = new File(file);
f.getParentFile().mkdirs();
PrintWriter pw = new PrintWriter(f);
pw.println(jamsClass);
pw.close();
System.out.println(" Created '" + f + "' for " + c.getName());
}
} |
726e94ef-d110-41fc-bc83-4149a469ffc5 | 8 | final void method3874(Class229 class229, int i, Class229 class229_129_) {
do {
try {
anInt7959++;
boolean bool = false;
if (class229_129_ != (((NativeToolkit) this).aClass229Array8086
[((NativeToolkit) this).anInt8175])) {
((NativeToolkit) this).aClass229Array8086[(((NativeToolkit) this)
.anInt8175)]
= class229_129_;
method3920(10);
bool = true;
}
if (i <= 97)
method3888(89);
if ((((NativeToolkit) this).aClass229Array8092
[((NativeToolkit) this).anInt8175])
!= class229) {
((NativeToolkit) this).aClass229Array8092[(((NativeToolkit) this)
.anInt8175)]
= class229;
bool = true;
method3935(-100);
}
if (!bool)
break;
anInt8100 &= ~0x1d;
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("wga.RI("
+ (class229 != null ? "{...}"
: "null")
+ ',' + i + ','
+ (class229_129_ != null
? "{...}" : "null")
+ ')'));
}
break;
} while (false);
} |
9ae01d30-216a-4c41-9b90-18ac483821d7 | 4 | public PathQuad findContainer(float targetX, float targetY) {
PathQuad temp = this;
// Avoid infinite looping of uncontained coordinates
if(!temp.box.contains(targetX, targetY))
return null;
while(!temp.noChildren()) {
for(int a = 0; a<temp.children.length; a++) {
if(temp.children[a].box.contains(targetX, targetY)) {
temp = temp.children[a];
break;
}
}
}
return temp;
} |
3113da98-c8b4-46a3-a249-44f10641c927 | 0 | @Override
public void setCity(String city) {
super.setCity(city);
} |
6c06c306-7478-41a3-a767-cfbb46691801 | 2 | public String getParameters() {
return middle +
((middle.length() != 0 && trailing.length() != 0) ? " " : "") +
trailing;
} |
d00e406d-09ab-4b24-9354-27030378a6bb | 3 | public void close() {
EIError.debugMsg("Closing");
if (clientReceiveThread != null) {
clientReceiveThread.setRunning(false);
}
if (socket != null) {
try {
sendData("goodbye");
socket.close();
} catch (IOException e) {
//oh well, ain't no thang
}
}
keepRunning = false;
socket = null;
} |
f9174c84-36fe-454d-83e5-0b454a506598 | 3 | public void close() {
logger.debug("DBDao:: close -----------begin ");
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (Exception e) {
logger.error(e, e);
}
logger.debug("DBDao:: close -----------end ");
} |
78839700-76be-49db-a4c1-939e8c3283ff | 5 | public CheckResultMessage checkG09(int day) {
int r1 = get(23, 5);
int c1 = get(24, 5);
int r2 = get(30, 5);
int c2 = get(31, 5);
if (checkVersion(file).equals("2003")) {
try {
in = new FileInputStream(file);
hWorkbook = new HSSFWorkbook(in);
if (0 != (getValue(r1 + 7, c1 + day, 5).add(
getValue(r2 + 2 + day, c2 + 2, 7))
.compareTo(new BigDecimal(0)))) {
return error("支付机构汇总报表<" + fileName
+ ">办理预付卡先行现金赎回业务 G09 + I03 = 0:" + day + "日错误");
}
in.close();
} catch (Exception e) {
}
} else {
try {
in = new FileInputStream(file);
xWorkbook = new XSSFWorkbook(in);
if (0 != (getValue1(r1 + 7, c1 + day, 5).add(
getValue1(r2 + 2 + day, c2 + 2, 7))
.compareTo(new BigDecimal(0)))) {
return error("支付机构汇总报表<" + fileName
+ ">办理预付卡先行现金赎回业务 G09 + I03 = 0:" + day + "日错误");
}
in.close();
} catch (Exception e) {
}
}
return pass("支付机构汇总报表<" + fileName + ">向备付金银行缴存现金形式预付卡押金F08 = N3:"
+ day + "日正确");
} |
35f2af5a-177e-4752-b769-c5395abdbdb0 | 5 | public void transferToOtherCustomerAccount(double amount, BasicAccount source, BasicAccount destination){
if(amount > 0){
if(source.getAccountOwner() == this){
if(source instanceof CustomerTransferSource){
if(source.getCurrentAccountBalance() - amount > 0){
if(destination.getAccountOwner() != this){
Transaction withdraw = new Transaction(amount, this, this, Transaction.WITHDRAWAL);
source.appendTransaction(withdraw, this);
Transaction transfer = new Transaction(amount, destination.getAccountOwner(), this, Transaction.TRANSFER);
destination.appendTransaction(transfer, this);
}
else throw new IllegalArgumentException("This function is for transferring into another user's account!");
}
else throw new IllegalArgumentException("Insufficient funds!");
}
else throw new IllegalArgumentException("You may only initiate a transfer from Checking, COD, or Savings account!");
}
else throw new IllegalArgumentException("You may only transfer from an account you own");
}
else throw new IllegalArgumentException("Transfer amounts must be positive");
} |
b4773bca-f67f-471f-af46-49ace8a7af36 | 0 | public String toString(){
return "devide by ";
} |
2901cb65-9673-47ec-b62a-314a80c9580d | 9 | private void visitStandardCall(Node node, Node child)
{
if (node.getType() != Token.CALL) throw Codegen.badTree();
Node firstArgChild = child.getNext();
int childType = child.getType();
String methodName;
String signature;
if (firstArgChild == null) {
if (childType == Token.NAME) {
// name() call
String name = child.getString();
cfw.addPush(name);
methodName = "callName0";
signature = "(Ljava/lang/String;"
+"Lorg/mozilla/nb/javascript/Context;"
+"Lorg/mozilla/nb/javascript/Scriptable;"
+")Ljava/lang/Object;";
} else if (childType == Token.GETPROP) {
// x.name() call
Node propTarget = child.getFirstChild();
generateExpression(propTarget, node);
Node id = propTarget.getNext();
String property = id.getString();
cfw.addPush(property);
methodName = "callProp0";
signature = "(Ljava/lang/Object;"
+"Ljava/lang/String;"
+"Lorg/mozilla/nb/javascript/Context;"
+"Lorg/mozilla/nb/javascript/Scriptable;"
+")Ljava/lang/Object;";
} else if (childType == Token.GETPROPNOWARN) {
throw Kit.codeBug();
} else {
generateFunctionAndThisObj(child, node);
methodName = "call0";
signature = "(Lorg/mozilla/nb/javascript/Callable;"
+"Lorg/mozilla/nb/javascript/Scriptable;"
+"Lorg/mozilla/nb/javascript/Context;"
+"Lorg/mozilla/nb/javascript/Scriptable;"
+")Ljava/lang/Object;";
}
} else if (childType == Token.NAME) {
// XXX: this optimization is only possible if name
// resolution
// is not affected by arguments evaluation and currently
// there are no checks for it
String name = child.getString();
generateCallArgArray(node, firstArgChild, false);
cfw.addPush(name);
methodName = "callName";
signature = "([Ljava/lang/Object;"
+"Ljava/lang/String;"
+"Lorg/mozilla/nb/javascript/Context;"
+"Lorg/mozilla/nb/javascript/Scriptable;"
+")Ljava/lang/Object;";
} else {
int argCount = 0;
for (Node arg = firstArgChild; arg != null; arg = arg.getNext()) {
++argCount;
}
generateFunctionAndThisObj(child, node);
// stack: ... functionObj thisObj
if (argCount == 1) {
generateExpression(firstArgChild, node);
methodName = "call1";
signature = "(Lorg/mozilla/nb/javascript/Callable;"
+"Lorg/mozilla/nb/javascript/Scriptable;"
+"Ljava/lang/Object;"
+"Lorg/mozilla/nb/javascript/Context;"
+"Lorg/mozilla/nb/javascript/Scriptable;"
+")Ljava/lang/Object;";
} else if (argCount == 2) {
generateExpression(firstArgChild, node);
generateExpression(firstArgChild.getNext(), node);
methodName = "call2";
signature = "(Lorg/mozilla/nb/javascript/Callable;"
+"Lorg/mozilla/nb/javascript/Scriptable;"
+"Ljava/lang/Object;"
+"Ljava/lang/Object;"
+"Lorg/mozilla/nb/javascript/Context;"
+"Lorg/mozilla/nb/javascript/Scriptable;"
+")Ljava/lang/Object;";
} else {
generateCallArgArray(node, firstArgChild, false);
methodName = "callN";
signature = "(Lorg/mozilla/nb/javascript/Callable;"
+"Lorg/mozilla/nb/javascript/Scriptable;"
+"[Ljava/lang/Object;"
+"Lorg/mozilla/nb/javascript/Context;"
+"Lorg/mozilla/nb/javascript/Scriptable;"
+")Ljava/lang/Object;";
}
}
cfw.addALoad(contextLocal);
cfw.addALoad(variableObjectLocal);
addOptRuntimeInvoke(methodName, signature);
} |
9a98e892-e005-4f7c-9bf6-35c022c6402c | 2 | @RequestMapping(value = {"/SucursalBancaria/id/{idSucursalBancaria}"}, method = RequestMethod.GET)
public void read(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse, @PathVariable("idSucursalBancaria") int idSucursalBancaria) {
ObjectMapper jackson = new ObjectMapper();
String json = null;
try {
json = jackson.writeValueAsString(sucursalBancariaDAO.read(idSucursalBancaria));
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
httpServletResponse.setContentType("application/json; charset=UTF-8");
noCache(httpServletResponse);
httpServletResponse.getWriter().println(json);
} catch (Exception ex) {
noCache(httpServletResponse);
httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
httpServletResponse.setContentType("text/plain; charset=UTF-8");
try {
noCache(httpServletResponse);
ex.printStackTrace(httpServletResponse.getWriter());
} catch (Exception ex1) {
noCache(httpServletResponse);
}
}
} |
e0b2c49f-b362-469e-9c99-223a26570ac1 | 6 | public void update(GameContainer container, StateBasedGame game, int delta)
throws SlickException {
Input input = container.getInput();
// redemarrer le jeu
if (input.isKeyPressed(Input.KEY_R)) {
init(container, game);
return;
}
//mettre le jeu en pause
if (input.isKeyPressed(Input.KEY_P))
paused = !paused;
//afficher/cacher les fps
if(input.isKeyPressed(Input.KEY_F))
{
affichageFPS = !affichageFPS;
container.setShowFPS(affichageFPS);
}
// met a jour le monde s'il n'est pas en pause et que la fenetre a le focus
if (!paused && container.hasFocus()==true)
monde.update(container, game, delta);
//si le robot est mort, on rentre dans l'etat de la mort du robot et redemarre le jeu
if (player.getVie() <= 0) {
game.enterState(RoboTech.MORTETAT);
init(container, game);
}
// calcule la zone affichee par la camera
cameraX = player.getX() - 400;
cameraY = player.getY() - 300;
} |
1f151efa-6e87-4c49-8fd7-a95387ca7aa4 | 5 | void readFromCpp() throws FileNotFoundException {
Scanner in = new Scanner(file);
String line, section = "";
while (in.hasNext()) {
line = in.nextLine();
if (line.trim().contains("/*")) {
section = "Settings";
}
if (line.trim().contains("*/")) {
break;
}
if (section.equals("Settings")) {
if (line.startsWith(" "))
parseEntry(line, section);
}
}
} |
6f869196-8e4b-4735-876a-82bae10f132a | 7 | public ProfilePanel(final String emailName, final String emailUser, final FacelookAppGUI a) {
super();
container = a;
this.setBackground(Color.decode("#3b5998"));
this.setPreferredSize(new Dimension(770,539));
setLayout(null);
JLabel lblFacelook = new JLabel("Facelook");
lblFacelook.setFont(new Font("Lucida Fax", Font.PLAIN, 32));
lblFacelook.setForeground(Color.WHITE);
lblFacelook.setBounds(12, 13, 199, 32);
add(lblFacelook);
ClientHandler chh = new ClientHandler();
String name = chh.getUserInfo(emailName);
//GET THE NAME THAT IS TIED TO THE EMAIL ADDRESS
JLabel nameLabel = new JLabel(name);
nameLabel.setForeground(Color.WHITE);
nameLabel.setBounds(173, 17, 199, 32);
nameLabel.setFont(new Font("Lucida Fax", Font.PLAIN, 21));
add(nameLabel);
JLabel lblLatest = new JLabel("Latest Posts");
lblLatest.setFont(new Font("Lucida Fax", Font.PLAIN, 20));
lblLatest.setForeground(Color.WHITE);
lblLatest.setBounds(12, 87, 166, 40);
add(lblLatest);
JPanel panel = new JPanel();
panel.setBounds(22, 147, 719, 379);
add(panel);
panel.setLayout(new GridLayout(5, 2, 5, 5));
/*
* Fill this GridLayout with StatusPost buttons for the status's
* It is ok to generate this at the beginning and only refresh when coming back to this page.
* If there are less than 10 then leave the remainder of the grid blank. These don't need to link back to same page.
*/
List<Status> posts;
if(emailUser.equals(emailName)){
posts = chh.getFriendUpdates(emailName);
}
else {
posts = chh.getStatuses(emailName);
}
for (Status post : posts) {
StatusPost p = new StatusPost(post.getPoster().getFullname(), post.getTimestamp(), post.getMessage());
final String friendEmail = post.getPoster().getFullname();
p.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
container.replace(new ProfilePanel(friendEmail, emailUser, a));
}
});
panel.add(p);
}
if(!emailUser.equals(emailName)){//Only show these when it is not your own profile
JButton btnAddFriend = new JButton("Add/Remove Friend");
btnAddFriend.setBounds(12, 49, 155, 25);
add(btnAddFriend);
//=====================================//
btnAddFriend.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO FILL IN CODE TO ADD/REMOVE FRIEND
ClientHandler ch = new ClientHandler();
if(ch.areFriends(emailUser,emailName)) {
ch.removeFriend(emailUser, emailName);
}
else {
ch.addFriend(emailUser, emailName);
}
}
});
//=====================================//
}
JButton btnNewsFeed = new JButton("News Feed");
btnNewsFeed.setBounds(661, 49, 97, 25);
add(btnNewsFeed);
btnNewsFeed.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
container.replace(new NewsFeedPanel(emailUser, container));
}
});
if(emailUser.equals(emailName)){
textField = new JTextField("What's on your mind?");
textField.setBounds(12, 60, 300, 32);
add(textField);
textField.setColumns(10);
textField.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
if (textField.getText().equals("What's on your mind?")) {
textField.setText("");
}
}
public void focusLost(FocusEvent e) {
if ("".equalsIgnoreCase(textField.getText().trim())) {
textField.setText("What's on your mind?");
}
}});
JButton btnNewButton = new JButton("Post Status");
btnNewButton.setBounds(312, 60, 97, 32);
add(btnNewButton);
//=====================================//
btnNewButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
ClientHandler ch = new ClientHandler();
ch.updateStatus(emailUser, textField.getText());
textField.setText("Posted!");
}
});
//=====================================//
}
} |
7c244d47-daff-40af-a8d7-0484c4d67156 | 6 | public void update(InputHandler inHandler){
setX_Point(getX_Point()+(getxVel()*getDir()));
if(getDamage()>0){
setDamage(getDamage()-getDamageLoss());
}else if(getDamage()<0){
setDamage(0);
}
if(timer==null){
timer= new Timer(200);
}
if(timer.isReady()){
if(timeVar==0){
timeVarPosi=1;
}else if(timeVar==1){
timeVarPosi=-1;
}
timeVar+=timeVarPosi;
timer= new Timer(200);
}
} |
384d7acf-d069-4146-9c34-81b03add7b58 | 4 | public boolean isInBox(int clickX, int clickY, int boxLeftTopX, int boxLeftTopY, int boxRightBottomX, int boxRightBottomY){
if(clickX >= boxLeftTopX + cornerX && clickX <= boxRightBottomX + cornerX
&& clickY >= boxLeftTopY + cornerY && clickY <= boxRightBottomY + cornerY){
return true;
}
return false;
} |
93ce4632-7f00-47d3-b876-9f5394d80bb3 | 7 | @EventHandler
public void WitherFastDigging(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getZombieConfig().getDouble("Wither.FastDigging.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (damager instanceof WitherSkull) {
WitherSkull a = (WitherSkull) event.getDamager();
LivingEntity shooter = a.getShooter();
if (plugin.getWitherConfig().getBoolean("Wither.FastDigging.Enabled", true) && shooter instanceof Wither && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, plugin.getWitherConfig().getInt("Wither.FastDigging.Time"), plugin.getWitherConfig().getInt("Wither.FastDigging.Power")));
}
}
} |
478c621d-013a-451a-81e4-344c4c1fa1db | 7 | static public RealLabelledData dataFromTextFile(String filename, int forcelabel, String split)
{
String line = "";
RealLabelledData ret = new RealLabelledData();
BufferedReader reader = null;
if (split == null)
split = " +"; // if we don't get split information, we assume separated by spaces
try
{
reader = new BufferedReader(new FileReader(new File(filename)));
}
catch (Exception e)
{
System.err.print("[RealLabelledDataFactory] Error loading file: " + e);
return null;
}
try
{
while ((line = reader.readLine()) != null)
{
ObservationReal dt; // Zeratul
int c = 0;
double[] dd;
String[] input = line.split(split);
if (forcelabel == -1) // first element is the class
{
dd = new double[input.length - 1];
for (int i = 0; i < dd.length; i++)
dd[i] = Double.parseDouble(input[i+1]);
c = (int)Math.round(Double.parseDouble(input[0]));
}
else
{
dd = new double[input.length];
for (int i = 0; i < dd.length; i++)
dd[i] = Double.parseDouble(input[i]);
c = forcelabel;
}
dt = new ObservationReal(c,dd);
ret.addObservation(dt);
}
}
catch (Exception e)
{
System.err.println("[RealLabelledDataFactory] Error reading file (" + filename + "):" + e.getMessage());
System.err.println("I could not read this line: "+line);
System.exit(1);
}
return ret;
} |
d224825f-dd2b-4d4d-8ee3-a3ae455527da | 5 | public void createPanel() {
setTitle("Global Preferences");
setSize(500, 600);
setLocationRelativeTo(getParent());
setIconImage(Images.G_PREFS_ICON);
contentPanel.setLayout(null);
FileNameExtensionFilter ff = new FileNameExtensionFilter("Image files *(.jpg, .jpeg, .gif, .png)", "jpg", "jpeg", "gif", "png");
imgChooser.setFileFilter(ff);
lblProjectViewWidth.setBounds(32, 34, 94, 14);
contentPanel.add(lblProjectViewWidth);
SpinnerModel widthModel = new SpinnerNumberModel(Constants.PROJ_VIEW_MIN_WIDTH, Constants.PROJ_VIEW_MIN_WIDTH, Constants.PROJ_VIEW_MAX_WIDTH, 1);
pvWidthSpinner.setModel(widthModel);
pvWidthSpinner.setBounds(32, 52, Constants.SPINNER_WIDTH, 20);
contentPanel.add(pvWidthSpinner);
lblProjectViewHeight.setBounds(32, 83, 109, 14);
contentPanel.add(lblProjectViewHeight);
SpinnerModel heightModel = new SpinnerNumberModel(Constants.PROJ_VIEW_MIN_HEIGHT, Constants.PROJ_VIEW_MIN_HEIGHT, Constants.PROJ_VIEW_MAX_HEIGHT, 1);
pvHeightSpinner.setModel(heightModel);
pvHeightSpinner.setBounds(32, 98, Constants.SPINNER_WIDTH, 20);
contentPanel.add(pvHeightSpinner);
lblDefaultTableColor.setBounds(32, 129, 109, 14);
contentPanel.add(lblDefaultTableColor);
tableColor.setBounds(32, 148, 20, 20);
tableColor.setBorder(BorderFactory.createLineBorder(Color.BLACK));
tableColor.setEditable(false);
contentPanel.add(tableColor);
btnChooseTableColor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
curTableColor = JColorChooser.showDialog(GlobalPreferences.this, "Choose Table Color", curTableColor);
tableColor.setBackground(curTableColor);
}
});
btnChooseTableColor.setBounds(62, 148, 114, 23);
contentPanel.add(btnChooseTableColor);
lblProjectViewBackground.setBounds(32, 179, 162, 14);
contentPanel.add(lblProjectViewBackground);
backgroundColor.setBounds(32, 201, 20, 20);
backgroundColor.setBorder(BorderFactory.createLineBorder(Color.BLACK));
backgroundColor.setEditable(false);
contentPanel.add(backgroundColor);
btnBackgroundColor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
curPVBackColor = JColorChooser.showDialog(GlobalPreferences.this, "Chooser Background Color", curPVBackColor);
backgroundColor.setBackground(curPVBackColor);
}
});
btnBackgroundColor.setBounds(62, 198, 114, 23);
contentPanel.add(btnBackgroundColor);
btnApply.setBounds(370, 490, 89, 23);
btnApply.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applyChanges();
}
});
contentPanel.add(btnApply);
lblTableSpeed.setBounds(225, 129, 75, 14);
contentPanel.add(lblTableSpeed);
lblTableWidth.setBounds(225, 34, 61, 14);
contentPanel.add(lblTableWidth);
lblTableHeight.setBounds(225, 83, 75, 14);
contentPanel.add(lblTableHeight);
SpinnerModel speedModel = new SpinnerNumberModel(1, 1, Constants.TABLE_MAX_SPEED, 1);
tSpeedSpinner.setModel(speedModel);
tSpeedSpinner.setBounds(225, 148, Constants.SPINNER_WIDTH, 20);
contentPanel.add(tSpeedSpinner);
SpinnerModel tHeightModel = new SpinnerNumberModel(0, 0, Constants.TABLE_MAX_HEIGHT, 1);
tHeightSpinner.setBounds(225, 98, 75, 20);
tHeightSpinner.setModel(tHeightModel);
contentPanel.add(tHeightSpinner);
SpinnerModel tWidthModel = new SpinnerNumberModel(0, 0, Constants.TABLE_MAX_WIDTH, 1);
tWidthSpinner.setBounds(225, 52, Constants.SPINNER_WIDTH, 20);
tWidthSpinner.setModel(tWidthModel);
contentPanel.add(tWidthSpinner);
lblMainFontColor.setBounds(32, 281, 94, 14);
contentPanel.add(lblMainFontColor);
fontColor.setEditable(false);
fontColor.setBorder(BorderFactory.createLineBorder(Color.BLACK));
fontColor.setBounds(32, 301, 20, 20);
contentPanel.add(fontColor);
btnFontColor.setBackground(new Color(50, 50, 50));
btnFontColor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
curFontColor = JColorChooser.showDialog(GlobalPreferences.this, "Choose Table Color", curTableColor);
fontColor.setBackground(curFontColor);
}
});
btnFontColor.setBounds(62, 298, 114, 23);
contentPanel.add(btnFontColor);
backColor.setEditable(false);
backColor.setBorder(BorderFactory.createLineBorder(Color.BLACK));
backColor.setBounds(32, 351, 20, 20);
contentPanel.add(backColor);
btnBackColor.setBackground(new Color(50, 50, 50));
btnBackColor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
curBackColor = JColorChooser.showDialog(GlobalPreferences.this, "Choose Table Color", curTableColor);
backColor.setBackground(curBackColor);
}
});
btnBackColor.setBounds(62, 348, 114, 23);
contentPanel.add(btnBackColor);
lblMainBackgroundColor.setBounds(32, 332, 120, 14);
contentPanel.add(lblMainBackgroundColor);
boxShowInfo.setBounds(29, 378, 188, 23);
contentPanel.add(boxShowInfo);
lblTableImage.setBounds(225, 281, 75, 14);
contentPanel.add(lblTableImage);
lblImage.setBounds(225, 336, 229, 128);
contentPanel.add(lblImage);
btnChooseImage.setBounds(297, 277, 128, 23);
btnChooseImage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(imgChooser.showDialog(GlobalPreferences.this, "Open") == JFileChooser.APPROVE_OPTION) {
File imgFile = imgChooser.getSelectedFile();
String f = imgFile.getName();
if(!(f.endsWith(".jpg") || f.endsWith(".jpeg") || f.endsWith(".png") || f.endsWith(".gif"))) {
JOptionPane.showMessageDialog(GlobalPreferences.this, "File must be valid image file.\n*(.jpg, .jpeg, .png, .gif)");
} else {
ProjectView.TABLE_IMAGE = Util.getImage(imgFile);
ProjectView.TABLE_IMAGE_LOC = imgFile.getAbsolutePath();
lblImage.setIcon(new ImageIcon(ProjectView.TABLE_IMAGE));
}
}
}
});
contentPanel.add(btnChooseImage);
btnUseDefault.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ProjectView.TABLE_IMAGE_LOC = "Default";
ProjectView.TABLE_IMAGE = Images.TABLE_IMAGE;
lblImage.setIcon(new ImageIcon(ProjectView.TABLE_IMAGE));
}
});
btnUseDefault.setBounds(297, 302, 128, 23);
contentPanel.add(btnUseDefault);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applyChanges();
dispose();
}
});
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
setBackgroundColor(Constants.BACKGROUND);
setFontColor(Constants.FONT_COLOR);
} |
65603ffe-b8cc-41ab-adf3-b270485ec8fc | 3 | public GameConfiguration load() {
try {
if (istream == null) {
istream = new FileInputStream(f);
}
JAXBContext context = JAXBContext
.newInstance(GameConfiguration.class);
Unmarshaller umarsh = context.createUnmarshaller();
GameConfiguration ret = (GameConfiguration) umarsh
.unmarshal(istream);
logger.info("Configuration file loaded: " + f);
return ret;
} catch (JAXBException e) {
logger.error("Could not load configuration file " + f);
logger.debug("Error message is: " + e.getMessage());
return null;
} catch (FileNotFoundException e) {
logger.error("Could not load world description file " + f
+ ", file not found.");
return null;
}
} |
befe7e53-0f78-45f4-bc2c-2610d658ac55 | 7 | BenevolentRobot() {
// On construction, load an english dictionary and word frequency list.
// Dictionary source: SCOWL (wordlist.sourceforge.net)
// Frequency count: BNC Frequency list (http://www.kilgarriff.co.uk/bnc-readme.html)
// Read in (frequency, word) pairs, hash them by word.
freqMap = new HashMap<String, Integer>();
for(File f : new File("resource/freq/").listFiles()) {
try {
BufferedReader in = new BufferedReader(new FileReader(f));
for(String str; (str = in.readLine()) != null;) {
String[] tokens = str.split("\\s+");
assert(tokens.length > 2);
freqMap.put(tokens[1], Integer.parseInt(tokens[0]) +
Utils.coalesce(freqMap.get(tokens[1]), 0));
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Read in words, hash them by length.
wordMap = new HashMap<Integer, List<String>>();
for(File f : new File("resource/words/").listFiles()) {
BufferedReader in;
try {
in = new BufferedReader(new FileReader(f));
for(String str; (str = in.readLine()) != null;) {
str = str.trim();
if(!wordMap.containsKey(str.length())) {
wordMap.put(str.length(), new ArrayList<String>());
}
wordMap.get(str.length()).add(str);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
a57cd499-535a-42d5-9219-11e1d15eefaf | 1 | public ClassInfo getSuperclass() {
if ((status & HIERARCHY) == 0)
loadInfo(HIERARCHY);
return superclass;
} |
1fbe7eaa-8177-46e1-a62c-07e23a07f7b3 | 3 | public static boolean Validate(String xmlFile, String xsdFile, StringBuilder message){
Source schemaFile = new StreamSource(new File(xsdFile));
Source xmlSrc = new StreamSource(new File(xmlFile));
SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = null;
try {
schema = schemaFactory.newSchema(schemaFile);
} catch (SAXException e) {
e.printStackTrace();
}
javax.xml.validation.Validator validator = schema.newValidator();
try {
validator.validate(xmlSrc);
} catch (SAXException e) {
message.append(e.getLocalizedMessage());
return false;
} catch (IOException e) {
e.printStackTrace();
}
message.append("xml is valid");
return true;
} |
7f521a10-a8c6-4cad-a7c8-dade1a64452a | 9 | public static int[] FH(String[] h) {
int[] r = new int[2];
r[0] = -1;
Map<Character, Integer> m = new HashMap<Character, Integer>();
Integer i;
for (String s : h) {
i = m.get(s.charAt(0));
if (i == null) {
i = 0;
}
i++;
m.put(s.charAt(0), i);
}
if (m.keySet().size() == 2) {
List<Integer> l = new ArrayList<Integer>();
l.addAll(m.values());
if ((l.get(0) == 3 && l.get(1) == 2) || (l.get(0) == 2 && l.get(1) == 3)) {
r[0] = 7;
for (Character c : m.keySet()) {
if (m.get(c) == 3) {
r[1] = c;
return r;//true
}
}
}
}
return r;//false
} |
f7a31a92-5496-414f-863b-c08c02c9c909 | 9 | private void init(Properties config) {
// keepAliveInterval
String interval = config.getProperty("keepAliveInterval");
try {
keeper = new AliveKeeper(Integer.parseInt(interval));
} catch (Exception e) {
keeper = new AliveKeeper();
}
keeper.start();
// servers
setServers(config.getProperty("servers"));
// protocol
String protocol = config.getProperty("protocol");
try {
setProtocol(Protocol.valueOf(protocol));
} catch (Exception e) {
}
// transcoder
SerializingTranscoder transcoder = new SerializingTranscoder();
String ct = config.getProperty("compressionThreshold");
try {
transcoder.setCompressionThreshold(Integer.parseInt(ct));
} catch (Exception e) {
}
setTranscoder(transcoder);
// opTimeout
String opt = config.getProperty("opTimeout");
try {
setOpTimeout(Long.parseLong(opt));
} catch (Exception e) {
}
// timeoutExceptionThreshold
String tet = config.getProperty("timeoutExceptionThreshold");
try {
setTimeoutExceptionThreshold(Integer.parseInt(tet));
} catch (Exception e) {
}
// hashAlg
String hashAlg = config.getProperty("hashAlg");
try {
setHashAlg(DefaultHashAlgorithm.valueOf(hashAlg));
} catch (Exception e) {
}
// locatorType
String locatorType = config.getProperty("locatorType");
try {
setLocatorType(Locator.valueOf(locatorType));
} catch (Exception e) {
}
// failureMode
String failureMode = config.getProperty("failureMode");
try {
setFailureMode(FailureMode.valueOf(failureMode));
} catch (Exception e) {
}
// useNagleAlgorithm
String useNagleAlgorithm = config.getProperty("useNagleAlgorithm");
try {
setUseNagleAlgorithm(Boolean.parseBoolean(useNagleAlgorithm));
} catch (Exception e) {
}
setDaemon(true);
} |
4aa14e34-cade-4633-ae0f-c85e66bf5a10 | 5 | HashSet<String> findWord(char[][] matrix, HashSet<String> dict) {
TreeNode root = new TreeNode((char) 0);
for (String s : dict)
root.addWord(s.trim());
HashSet<String> res = new HashSet<String>();
boolean[][] flag = new boolean[matrix.length][matrix[0].length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (root.hasChild(matrix[i][j])) {
for (boolean[] tmp : flag)
Arrays.fill(tmp, false);
res.addAll(find(matrix, flag, i, j,
new StringBuilder().append(matrix[i][j]),
root.getChild(matrix[i][j])));
}
}
}
return res;
} |
b0361b5a-a171-4ba0-a33d-1ecf13d4e897 | 4 | public String getTIN(){
String s = (String)personnelCBox.getSelectedItem();
int i;
if(s == null || s.length() == 0){
return null;
}
for(i = 0;i < s.length(); i++){
if(s.charAt(i) == '~'){
break;
}
}
return s.substring(i + 2, s.length());
} |
0e1c6e17-f88a-461b-8b63-83e8383d3798 | 4 | public static void UpperTitle(){
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
conn.setAutoCommit(false);
PreparedStatement stmnt = conn.prepareStatement("UPDATE Media set title = CONCAT( UPPER( LEFT( title, 1 ) ) , SUBSTRING( title, 2 ))");
stmnt.execute();
conn.commit();
conn.setAutoCommit(true);
}catch(SQLException e){
e.printStackTrace();
}
} |
b87c3784-3302-40a2-96a6-0ed9f56e9719 | 9 | public void setQueue3(FloatQueue t) throws MismatchException {
if (t == null)
throw new NullPointerException("the arg cannot be null");
if (q1 != null) {
if (t.getLength() != q1.getLength())
throw new MismatchException("queue 1 and 3 have different lengths!");
if (t.getPointer() != q1.getPointer())
throw new MismatchException("queue 1 and 3 have different pointer indices!");
if (t.getInterval() != q1.getInterval())
throw new MismatchException("queue 1 and 3 have different intervals!");
}
if (q2 != null) {
if (t.getLength() != q2.getLength())
throw new MismatchException("queue 2 and 3 have different lengths!");
if (t.getPointer() != q2.getPointer())
throw new MismatchException("queue 2 and 3 have different pointer indices!");
if (t.getInterval() != q2.getInterval())
throw new MismatchException("queue 2 and 3 have different intervals!");
}
q3 = t;
} |
858bc64f-b73a-4365-8940-ce5ee6455123 | 1 | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((banckAccount == null) ? 0 : banckAccount.hashCode());
return result;
} |
61be6013-ae8e-42f2-b113-cc5dc6a5ac72 | 4 | @Override
public boolean isAchieved()
{
Belief clientStateGoal = new Belief("Drinking");
for(Table table : tables)
{
if( !table.isFree() )
{
for( Client client : table.getClients() )
{
if( !table.getClientState(client).getName().equalsIgnoreCase( clientStateGoal.getName() ))
return false;
}
}
}
return true;
} |
dd848542-bd6e-4b44-b67f-80f8c094193d | 6 | public int checkSidwaysDown(int originLetter, int originNum, int newLetter, int newNum, Board b)
{
valid = 0;
int diagnalDownLetter = originLetter;
int diagnalDownNumber = originNum;
if(newLetter > originLetter)
{
int downRightValid = 0;
for(int counter = 0; counter < ((newNum-originNum)-1); counter++)
{
diagnalDownLetter = diagnalDownLetter + 1;
diagnalDownNumber = diagnalDownNumber + 1;
if(b.checkBoard(diagnalDownLetter,diagnalDownNumber).matches(chessPieces))
{
System.out.println(error);
}
else
{
downRightValid = 1;
}
valid = downRightValid;
}
}
else if(originLetter > newLetter)
{
int downLeftValid = 0;
for(int counter = 0; counter < ((newNum-originNum)-1); counter++)
{
diagnalDownLetter = diagnalDownLetter - 1;
diagnalDownNumber = diagnalDownNumber + 1;
if(b.checkBoard(diagnalDownLetter,diagnalDownNumber).matches(chessPieces))
{
System.out.println(error);
}
else
{
downLeftValid = 1;
}
valid = downLeftValid;
}
}
return valid;
} |
9f155437-9b91-44b1-8b49-04726c5de046 | 6 | public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
out.write(">ACCEPTED");
out.flush();
//DataInputStream is = new DataInputStream(client.getInputStream());
try {
SystemInputExecutor key = SystemInputExecutor.getInstance();
boolean done = false;
while (!done) {
String message = (String) in.readLine();
System.out.println(message);
if (">NEXT".equalsIgnoreCase(message)) {
key.right();
} else if (">PREV".equalsIgnoreCase(message)) {
key.left();
}
// String message = null;
// byte[] bytes = new byte[1024];
// int r;
//
// while ((r = is.read(bytes)) > 0) {
// message = new String(bytes, 0, r);
// System.out.println(message);
//
// if (">NEXT".equalsIgnoreCase(message)) {
// key.right();
// } else if (">PREV".equalsIgnoreCase(message)) {
// key.left();
// }
//
// }
done = ".quit".equals(message);
}
} catch (AWTException e) {
e.printStackTrace();
}
client.disconnect();
System.out.println("Client disconnected");
} catch (IOException e) {
try {
client.disconnect();
System.out.println("Client disconnected");
} catch (IOException ex) {
System.out.println("Cannot disconnect client. " + ex.getMessage());
}
}
} |
7f5a32da-92d8-49ae-afa0-9f7154027b89 | 1 | public void draw(Graphics g,Location origin, double scale, Color color, int xdiff, int ydiff){
g.setColor(this.color);
for(int i = 0; i < locationPoints.size()-1; i++){
Location loc1 = locationPoints.get(i);
Location loc2 = locationPoints.get(i+1);
Point p1 = loc1.getPoint(origin, scale);
Point p2 = loc2.getPoint(origin, scale);
g.drawLine(p1.x + xdiff, p1.y+ydiff, p2.x+xdiff, p2.y+ydiff);
}
} |
048301d4-b329-48cc-ab62-e2499aaa14af | 0 | public float getB() {
return b;
} |
50b19abf-b27f-4fd1-9b8d-c20d782c20b3 | 7 | private void addExp(ArrayList<String> players, String job, String level, CommandSender sender) {
job = job.toLowerCase();
double experience = 1.0D;
if(StringToNumber.isPositiveNumber(level))
experience = Double.parseDouble(level);
if (PlayerJobs.getJobsList().get(job) == null) {
sender.sendMessage(ChatColor.RED + _modText.getAdminCommand("exist", PlayerCache.getLang(sender.getName())).addVariables(job, "", sender.getName()));
return;
}
Iterator<String> it = players.iterator();
while (it.hasNext()) {
String play = (String)it.next();
if (play == null) {
sender.sendMessage(ChatColor.RED + _modText.getAdminAdd("offline", PlayerCache.getLang(sender.getName())).addVariables(job, "", sender.getName()));
return;
}
if (!PlayerCache.hasJob(play, job))
sender.sendMessage(ChatColor.RED + _modText.getExperience("nojob", PlayerCache.getLang(sender.getName())).addVariables(job, play, level));
else if (PlayerCache.addExp(play, job, experience)) {
sender.sendMessage(ChatColor.GRAY + _modText.getExperience("added_xp", PlayerCache.getLang(sender.getName())).addVariables(job, play, level));
if (Bukkit.getPlayer(play) != null) {
PrettyText text = new PrettyText();
String str = ChatColor.GRAY + _modText.getExperience("padded_xp", PlayerCache.getLang(sender.getName())).addVariables(job, play, level);
text.formatPlayerText(str, Bukkit.getPlayer(play));
}
}
}
} |
e00d7ab3-f54e-44f0-be57-2085c55866ce | 1 | int repeatSub (int num){
while(num>=10){
num=num-10;
}
return num;
} |
71757c56-f9d1-4533-a2f2-5f396671b73f | 2 | public void visitArithExpr(final ArithExpr expr) {
if (isLeaf(expr.left()) && isLeaf(expr.right())) {
firstOrder = true;
}
} |
8b852439-9e43-47d8-b7a2-8a7c11c631c4 | 0 | public String getPassword(){
return password;
} |
a77e33d3-fb1f-444d-b27b-12da26088d89 | 2 | protected List<Author> getAuthors() {
io.println("Give authors(\"Firstname, Lastname\") separated by newline. Empty line stops.");
Author element = io.getAuthor(": ");
List<Author> list = new LinkedList<Author>();
while (element != null) {
list.add(element);
element = io.getAuthor(": ");
}
return list.isEmpty() ? null : list;
} |
63a154df-6941-452d-90f0-6054894f5f91 | 5 | @Override
public void handle(HttpExchange exchange) throws IOException {
System.out.println("In join game handler");
String responseMessage = "";
if(exchange.getRequestMethod().toLowerCase().equals("post")) {
try { // check user login cookie and if valid get params
exchange.getResponseHeaders().set("Content-Type", "appliction/json");
String unvalidatedCookie = exchange.getRequestHeaders().get("Cookie").get(0);
System.out.println("logged in cookie: " + unvalidatedCookie);
CookieParams cookie = Cookie.verifyCookie(unvalidatedCookie, translator);
BufferedReader in = new BufferedReader(new InputStreamReader(exchange.getRequestBody()));
String inputLine;
StringBuffer requestJson = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
requestJson.append(inputLine);
}
in.close();
System.out.println(requestJson);
JoinGameRequest request = (JoinGameRequest) translator.translateFrom(requestJson.toString(), JoinGameRequest.class);
exchange.getRequestBody().close();
if(this.gamesFacade.joinGame(request, cookie.getName(), cookie.getPlayerID())) {
System.out.println("Request Accepted!");
// create cookie for user
List<String> cookies = new ArrayList<String>();
String joinCookie = Cookie.createJoinCookie(request.getID());
System.out.println("join cookie: " + joinCookie);
cookies.add(joinCookie);
// send success response headers
exchange.getResponseHeaders().put("Set-cookie", cookies);
exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
this.gamesLog.Store(new JoinCommand(gamesFacade, request, cookie.getName(), cookie.getPlayerID()));
}
else {
System.out.println("join game request had invalid color (duplicate or unrecognized)");
responseMessage = "Unable to join game b/c invalid color and/or color is already taken and/or game is full";
exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0);
}
// TODO join game in gameModels list
} catch (InvalidCookieException | InvalidGamesRequest e) { // else send error message
System.out.println("unrecognized / invalid join game request");
responseMessage = e.getMessage();
exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0);
}
}
else {
// unsupported request method
responseMessage = "Error: \"" + exchange.getRequestMethod() + "\" is no supported!";
exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0);
}
if (!responseMessage.isEmpty()) {
//send failure response message
OutputStreamWriter writer = new OutputStreamWriter(
exchange.getResponseBody());
writer.write(responseMessage);
writer.flush();
writer.close();
}
exchange.getResponseBody().close();
} |
6a29822b-57a9-4cc2-b70e-533cd295b58d | 9 | public String stateToString()
{
String stateString = "";
boolean ticker = false;
if ((STATE_TRACKING_GAZE & state) != 0)
{
stateString += "STATE_TRACKING_GAZE";
ticker = true;
}
if ((STATE_TRACKING_GAZE & state) != 0)
{
stateString += (ticker ? " | " : "") + "STATE_TRACKING_EYES";
ticker = true;
}
if ((STATE_TRACKING_PRESENCE & state) != 0)
{
stateString += (ticker ? " | " : "") + "STATE_TRACKING_PRESENCE";
ticker = true;
}
if ((STATE_TRACKING_FAIL & state) != 0)
{
stateString += (ticker ? " | " : "") + "STATE_TRACKING_FAIL";
ticker = true;
}
if ((STATE_TRACKING_LOST & state) != 0)
{
stateString += (ticker ? " | " : "") + "STATE_TRACKING_LOST";
ticker = true;
}
return stateString;
} |
cae0f0c6-ae86-4c77-b9eb-b7982f32ef97 | 3 | private static void showIndividualSummaries() {
StringBuilder out = new StringBuilder();
out.append("\n===========================================\n");
out.append("===== Total System Time per/thread =====\n");
out.append("===========================================\n");
Object[] keys = points.keySet().toArray();
Arrays.sort(keys);
if (keys.length < 1) {
out.append("No reporting stats gathered.\n");
} else {
int index;
for (index = 0; index < keys.length; index++) {
String key = keys[index].toString();
BigDecimal value = points.get(keys[index]);
out.append(key + ":\t\t" + formatter.format(value.divide(new BigDecimal(NANO))) + "\n");
}
}
out.append("\n");
if (consoleOutput)
System.out.print(out.toString());
LOG.info(out.toString());
} |
11bfffe9-833c-43d3-9e06-2dd4fdb1fdea | 9 | public void teleportHome(CommandSender cs, Command cmd, String string,
final String[] args) {
if (args.length == 0) {
final Player player = (Player) cs;
if (player.hasPermission("warpsandports.homes.tp.default") || player.isOp()) {
if(MainClass.players
.contains(player.getUniqueId()
+ ".Homes.0")){}
else{
player.sendMessage(ChatColor.RED + "That home is not set!");
return;
}
player.sendMessage(ChatColor.GREEN + "Teleporting you in "
+ ChatColor.AQUA
+ MainClass.getConfig().getLong("Homes.HomeDelaySeconds")
+ ChatColor.GREEN + " seconds!");
BukkitScheduler scheduler = Bukkit.getScheduler();
id = scheduler.scheduleSyncDelayedTask(MainClass,
new Runnable() {
public void run() {
Location loc = new Location(
Bukkit.getWorld(MainClass.players
.getString(player.getUniqueId()
+ ".Homes.0.world")),
MainClass.players.getInt(player
.getUniqueId() + ".Homes.0.x"),
MainClass.players.getInt(player
.getUniqueId() + ".Homes.0.y"),
MainClass.players.getInt(player
.getUniqueId() + ".Homes.0.z"),
MainClass.players.getInt(player
.getUniqueId() + ".Homes.0.yaw"),
MainClass.players.getInt(player
.getUniqueId()
+ ".Homes.0.pitch"));
player.teleport(loc);
player.sendMessage(ChatColor.GREEN
+ "Welcome home!");
}
}, 20 * MainClass.getConfig().getLong("Homes.HomeDelaySeconds"));
} else {
player.sendMessage(ChatColor.RED
+ "You do not have permission to do that!");
}
} else if (args.length == 1) {
final Player player = (Player) cs;
try {
Integer.parseInt(args[0]);
} catch (Exception e) {
player.sendMessage(ChatColor.RED + "Correct usage "
+ ChatColor.AQUA + "/setwarp <Number>");
return;
}
if (player.hasPermission("warpsandports.homes.tp." + args[0]) || player.isOp()) {
if(MainClass.players
.contains(player.getUniqueId()
+ ".Homes." + args[0])){}
else{
player.sendMessage(ChatColor.RED + "That home is not set!");
return;
}
player.sendMessage(ChatColor.GREEN + "Teleporting you in "
+ ChatColor.AQUA
+ MainClass.getConfig().getLong("Homes.HomeDelaySeconds")
+ ChatColor.GREEN + " seconds!");
BukkitScheduler scheduler = Bukkit.getScheduler();
id = scheduler
.scheduleSyncDelayedTask(MainClass, new Runnable() {
public void run() {
Location loc = new Location(Bukkit
.getWorld(MainClass.players
.getString(player.getUniqueId()
+ ".Homes." + args[0]
+ ".world")),
MainClass.players.getInt(player
.getUniqueId()
+ ".Homes."
+ args[0] + ".x"),
MainClass.players.getInt(player
.getUniqueId()
+ ".Homes."
+ args[0] + ".y"),
MainClass.players.getInt(player
.getUniqueId()
+ ".Homes."
+ args[0] + ".z"),
MainClass.players.getInt(player
.getUniqueId()
+ ".Homes."
+ args[0] + ".yaw"),
MainClass.players.getInt(player
.getUniqueId()
+ ".Homes."
+ args[0] + ".pitch"));
player.teleport(loc);
player.sendMessage(ChatColor.GREEN
+ "Welcome home!");
}
}, 20 * MainClass.getConfig().getLong("Homes.HomeDelaySeconds"));
}
} else {
cs.sendMessage(ChatColor.RED + "Correct usage " + ChatColor.AQUA
+ "/home [Number]");
}
} |
3fd4aec9-843f-4af2-a355-77af6ef9acba | 3 | private static VendorInventory getVendorInventory(int invId) {
QueryExecutor qe = new QueryExecutor();
qe.SendQuery("SELECT * FROM RPG372DB_Inventory WHERE invId='" + invId
+ "'");
if (qe.resultSize() == 0)
return null;
VendorInventory venInv = new VendorInventory(null);
int tempId;
for (int i = 0; i < 16; i++) {
tempId = Integer.parseInt(qe.vals.get(i).get(2));
if (tempId == 0)
continue;
else {
venInv.addItem(ItemFactory.getItem(tempId));
}
}
return venInv;
} |
16224b8b-aa93-498e-aa6f-5d8b035ba2b6 | 0 | public String editblogDetails() {
String outcome = null;
Blog blog = this.blogDelegate.getBlogDetail(this.blogId);
this.setBlogId(blog.getBlogId());
this.setBlogContent(blog.getBlogContent());
this.setBlogLabel(blog.getBlogContentLable());
this.setBlogCreatedDate(blog.getCreatedDate());
outcome = "/admin/editblog.xhtml";
return outcome;
} |
c71cf4cb-ef62-44d7-b7c2-fcd2d21ca4ca | 2 | public Chessboard()
{
fields = new Field[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
char row = 0;
byte column = 0;
for(int r = 0; r < NUMBER_OF_ROWS; r++)
{
row = (char) (FIRST_ROW + r);
column = FIRST_COLUMN;
for(int c = 0; c < NUMBER_OF_COLUMNS; c++)
{
fields[r][c] = new Field(row, column);
}
}
} |
dfa23b94-237d-4ac4-8b06-bc3726e4a192 | 3 | @Override
public void start()
{
worker = new Thread()
{
@Override
public void run()
{
while (!this.isInterrupted() && currentScene != null)
{
renderScene(currentScene);
currentScene = cachedScene;
cachedScene = null;
}
}
};
if (singleThreaded)
{
worker.run();
}
else
{
worker.start();
}
} |
ddb756ff-d75d-41be-9145-2dd38ff31d1d | 0 | public CheckResultMessage check30(int day) {
return checkReport.check30(day);
} |
898a0b47-d586-44b0-a732-e85b62ed2736 | 6 | protected boolean isFinished() {
final long timeDiff = System.currentTimeMillis() - startTime;
//TODO make sure things get finished (time to be on target)
return (((state != ClawPivotSubsystem.PICKUP && clawPID.onTarget() && timeDiff > 1500) || timeDiff > 4000) && (driveFinishedChecker == null || driveFinishedChecker.bool)) && DriverStation.getInstance().getMatchTime() > timeToFinish;
} |
ce434d9c-0608-48ba-ae8c-d54fc81f916c | 0 | @Override
public Object clone() {
return new Buchi((HashSet<Character>) alphabet.clone(), (HashSet<Integer>) states.clone(), initialState, (HashSet<Integer>) acceptanceCondition.clone(), (HashSet<Transition>) transitionRelation.clone());
} |
eda29b7d-57e0-43f1-8f19-81af2c8f3e8f | 2 | public static String getMessage(String message, Locale locale){
ResourceBundle resourceBundle = null;
if(locale!=null)
resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME, locale);
else
resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME);
if(resourceBundle!=null){
message = resourceBundle.getString(message);
}
return message;
} |
01e5e4cb-4a08-4867-bcc2-ab7e43b136a6 | 4 | @Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attr) {
if (attr.isRegularFile()) {
String name = "" + file;
if (name.endsWith(".txt")) {
for (JSONArray comments : extractor.extractFromCrawler(file, related)) {
this.docs.addJSONComments(comments);
}
} else if (Character.isDigit(name.charAt(name.length() - 1))) {
this.docs.addComments(extractor.extractFromDUC(file));
}
}
return CONTINUE;
} |
e7424e81-689b-450b-9ba2-7ddce7c7d82c | 9 | public List performSynchronousInference()
throws IOException, TimeOutException, CycApiException {
if (getStatus() == SubLWorkerStatus.NOT_STARTED_STATUS) {
start();
}
if (getStatus() == SubLWorkerStatus.WORKING_STATUS) {
try {
synchronized (lock) {
lock.wait(getTimeoutMsecs());
if (getStatus() == SubLWorkerStatus.WORKING_STATUS) {
try {
this.abort();
} catch (IOException xcpt) {
throw xcpt;
} finally {
this.fireSubLWorkerTerminatedEvent(new SubLWorkerEvent(this,
SubLWorkerStatus.EXCEPTION_STATUS,
new TimeOutException("Communications took more than: "
+ getTimeoutMsecs() + " msecs.\nWhile trying to execute inference: \n"
+ getSubLCommand().toPrettyCyclifiedString(""))));
}
}
}
} catch (Exception xcpt) {
throw new RuntimeException(xcpt);
}
}
if (getException() != null) {
try {
throw getException();
} catch (IOException ioe) {
throw ioe;
} catch (Exception xcpt) {
if (xcpt instanceof RuntimeException) {
throw (RuntimeException)xcpt;
} else {
throw new RuntimeException(xcpt);
}
}
}
return getAnswers();
} |
8146936b-b6df-459c-ae26-9f2a351ef009 | 2 | public AjoutMotClefDialog(ArrayList<CategorieMotClef> categories) {
setResizable(false);
setModalityType(ModalityType.APPLICATION_MODAL);
setTitle("Ajout d'un mot clef pour une catégorie");
setBounds(100, 100, 486, 168);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
{
JLabel lblCatgorieDeMot = new JLabel("Catégorie de mot clef :");
lblCatgorieDeMot.setHorizontalAlignment(SwingConstants.RIGHT);
lblCatgorieDeMot.setBounds(12, 12, 184, 24);
contentPanel.add(lblCatgorieDeMot);
}
catMotClefList = new JComboBox();
catMotClefList.setBounds(214, 12, 240, 24);
contentPanel.add(catMotClefList);
for (CategorieMotClef c : categories) {
catMotClefList.addItem(c);
}
JLabel lblNouveauMotClef = new JLabel("Nouveau mot clef :");
lblNouveauMotClef.setHorizontalAlignment(SwingConstants.RIGHT);
lblNouveauMotClef.setBounds(12, 48, 184, 24);
contentPanel.add(lblNouveauMotClef);
motClefField = new JTextField();
motClefField.setBounds(214, 49, 240, 24);
contentPanel.add(motClefField);
motClefField.setColumns(10);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (motClefField.getText().isEmpty()) {
JOptionPane.showMessageDialog(AjoutMotClefDialog.this,"Vous devez indiquer le mot clef.");
return;
}
((CategorieMotClef) catMotClefList.getSelectedItem()).addMotClef(motClefField.getText());
result = FileDialogResultEnum.ok;
AjoutMotClefDialog.this.setVisible(false);
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Annuler");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
result = FileDialogResultEnum.canceled;
AjoutMotClefDialog.this.setVisible(false);
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
} |
dff8d58d-e2ba-49dd-a20b-785a6e1ce842 | 8 | public Node FindLoopBeginning(Node head) {
Node fastrunner = head;
Node slowrunner = head;
while (fastrunner != null && slowrunner != null)
{
fastrunner = fastrunner.next.next;
slowrunner = slowrunner.next;
if (slowrunner == fastrunner)
break;
}
if (fastrunner == null)
return null;
fastrunner = head;
while (fastrunner != null && slowrunner != null)
{
fastrunner = fastrunner.next;
slowrunner = slowrunner.next;
if (fastrunner == slowrunner)
break;
}
if (fastrunner == null)
return null;
return fastrunner;
} |
557074de-cdd5-4765-8d43-8b13a831d43e | 3 | @Override
public ExecutionContext run(ExecutionContext context) throws InterpretationException {
int x = DrawingZone.turtle.getPosX();
int y = DrawingZone.turtle.getPosY();
DrawingZone dw = UserInterface.dw;
Value value = ((AbsValueNode) this.getChildAt(0)).evaluate(context);
if (value.getType() == VariableType.NUMBER) {
Number num = (Number) value.getValue();
num = -num.doubleValue();
int _X = (int) (num.intValue() * Math.cos((double) Math.toRadians(DrawingZone.turtle.getHeading())));
int _Y = -(int) (num.intValue() * Math.sin((double) Math.toRadians(DrawingZone.turtle.getHeading())));
DrawingZone.turtle.setPos(x + _X, y + _Y);
Color color;
if(DrawingZone.turtle.getErase())
color = dw.getBackground();
else
color = dw.getCurrentColor();
if (DrawingZone.turtle.getPen())
dw.toDraw.add(new Shape(new Line2D.Float(x, y, x + _X, y + _Y), color));
UserInterface.dw.revalidate();
} else
throw new InterpretationException(InterpretationErrorType.INVALID_ARGUMENT, line, null);
return context;
} |
7491f259-3e7b-47fb-9221-7135c9b96ed1 | 8 | private void updatePlayers(GameContainer c, int delta, Input in){
for(int i = 0; i < players.length; i++){
if(players[i].isAlive()){
Vector2f direction = new Vector2f(0, 0);
if (in.isKeyDown(playerControls.get("P"+(i+1)+"N"))) {
direction.add(new Vector2f(0, -1));
}
else if (in.isKeyDown(playerControls.get("P"+(i+1)+"S"))) {
direction.add(new Vector2f(0, 1));
}
else if (in.isKeyDown(playerControls.get("P"+(i+1)+"W"))) {
direction.add(new Vector2f(-1, 0));
}
else if (in.isKeyDown(playerControls.get("P"+(i+1)+"E"))) {
direction.add(new Vector2f(1, 0));
}
if (in.isKeyDown(playerControls.get("P"+(i+1)+"B"))) {
players[i].actionPressed();
}
players[i].setDirection(direction);
try {
players[i].update(c, delta, this);
} catch (SlickException e) {
e.printStackTrace();
}
}
}
} |
2c4969f0-7b3e-4ebb-9c83-fd2045554659 | 2 | public void paintComponent(Graphics g)
{
g.setColor(java.awt.Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(java.awt.Color.BLACK);
if (background != null)
{
g.drawImage(background, 0, 0, null);
}
for (Shape s : new ArrayList<Shape>(shapes))
{
Graphics2D g2 = (Graphics2D) g.create();
s.paintShape(g2);
g2.dispose();
}
} |
a79f7d26-ff86-4b6b-add9-26fe98db719f | 5 | public String add(Properties serviceProperties)
{String GETCommand="", ret="";
if(serviceProperties!=null && !serviceProperties.equals(""))
{
GETCommand="";
Enumeration e = serviceProperties.propertyNames();
while (e.hasMoreElements())
{
String key = (String) e.nextElement();
GETCommand+= key+"="+serviceProperties.getProperty(key)+"&";
}
}//if(serviceProperties!=null)
ret=this.readURL(this.registry_url+"/add.php?"+GETCommand);
if(ret==null || ret.equals("")) return null;
return ret;
}//public Properties search() |
4621f60e-3ad3-40b8-9fd1-9f5bb76524f3 | 4 | public void saveToDB() {
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
NewsInfo newsInfo = new NewsInfo();
newsInfo.title = TitleUtils.half2Fullchange(dataInfo.title);
newsInfo.url = dataInfo.source;
newsInfo.newspaper = dataInfo.newspaper;
newsInfo.page = dataInfo.page;
newsInfo.publish_date = new Date(format.parse(dataInfo.publishDate).getTime());
newsInfo.crawl_date = new Date(format.parse(dataInfo.crawlDate).getTime());
String body = dataInfo.body + "\n";
for ( String imgSrc:dataInfo.img ) {
body += "<img src=\"" + imgSrc + "\">\n";
}
newsInfo.body = body;
int count = mapper.selectIsExist(newsInfo); //首先判断当前记录是否已经获取过
if ( count > 0 ) { //返回值大于0表示已经获取过该条记录
System.out.println("[数据已存在] " + newsInfo.url);
NewsEyeSpider.logger.info("[数据已存在] " + newsInfo.url);
return; //获取过即退出
}
Integer news_id = mapper.selectWireCopy(newsInfo.title); //判断当前记录是否在通稿中出现
if ( news_id == null ) //返回值为null表示没有出现
return; //未在通告出现的记录略过
newsInfo.news_id = news_id;
mapper.insertNewsInfo(newsInfo); //将该条记录插入数据库中
mapper.updateWireCopy(news_id); //更新wire_copy中数据
System.out.print("[匹配成功] " + newsInfo.url + "\t" + newsInfo.title + "\n");
NewsEyeSpider.logger.info("[匹配成功] " + newsInfo.url + "\t" + newsInfo.title + "\n");
session.commit(); //提交事物
}catch (Exception e) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(baos));
NewsEyeSpider.logger.debug(baos.toString());
}
} |
4b924eb9-ac61-4e4d-9c7f-230366d190a0 | 7 | private void jButton6ChangDispalyMode(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ChangDispalyMode
// TODO add your handling code here:
if (this.testState != this.playback) {
return;
}
if (this.tstErrors) {
System.out.println("================");
System.out.println("Event lengh before noise loading: " + events.size());
this.EventListLoad();
System.out.println("Event lengh after noise loading: " + events.size());
this.tstErrors = false;
}
int numTrials = seqStartIndexes.size() - 1;
int sumSuccess = 0;
int len = this.partialCueLength;
boolean fromLast = this.partialCueBackwards;
curSeq.removeAllElements();
curPSeq.removeAllElements();
int selidx = ((Integer) seqStartIndexes.get(this.seq_ptr)).intValue();
int epiLen = ((Integer) seqLenIndexes.get(this.seq_ptr)).intValue();
if (len > epiLen) {
len = epiLen;
}
int sidx = 0;
//System.out.println("IDXs: " + selidx + " " + len + " " + sidx);
if (selidx == 0) {
this.isNewStart = true;
} else if (events.get(selidx - 1).isForcedTer(events.get(selidx - 1))) {
this.isNewStart = true;
} else {
this.isNewStart = false;
}
//get CurrentSeq list
for (int i = 0; i < epiLen; i++) {
this.curSeq.add(this.events.get(selidx + i));
}
int winidx = this.seq_ptr;
if (winidx >= 0) {
// System.out.println("play a sequence");
curPSeq = episodic.getSeqEvents(episodic.seqLearner.getOneSeq(((Integer) seqWinIndexes.get(winidx)).intValue()));
}
this.jLabel10.setText("PREDICTION ACCURACY " + "(" + selidx + "~" + (selidx + epiLen - 1) + ")" + "/(" + 0 + "~" + (events.size() - 1) + ")");
//curStory=getStoryString(curSeq);
curPStory = getStoryString(curPSeq);
this.jLabel9.setText("Retrieved Episode: (" + winidx + "/" + (this.episodic.seqLearner.numCode - 1) + ")");
this.jLabel11.setText("");
timer.start();
}//GEN-LAST:event_jButton6ChangDispalyMode |
8c1fe416-c8bf-48eb-9157-22d6a40ce5e2 | 9 | private void AppendPolygon(TEdge e1, TEdge e2) {
// get the start and ends of both output polygons ...
OutRec outRec1 = m_PolyOuts.get(e1.outIdx);
OutRec outRec2 = m_PolyOuts.get(e2.outIdx);
OutRec holeStateRec;
if(Param1RightOfParam2(outRec1, outRec2))
holeStateRec = outRec2;
else if(Param1RightOfParam2(outRec2, outRec1))
holeStateRec = outRec1;
else
holeStateRec = GetLowermostRec(outRec1, outRec2);
OutPt p1_lft = outRec1.pts;
OutPt p1_rt = p1_lft.prev;
OutPt p2_lft = outRec2.pts;
OutPt p2_rt = p2_lft.prev;
EdgeSide side;
// join e2 poly onto e1 poly and delete pointers to e2 ...
if(e1.side == EdgeSide.esLeft) {
if(e2.side == EdgeSide.esLeft) {
// z y x a b c
ReversePolyPtLinks(p2_lft);
p2_lft.next = p1_lft;
p1_lft.prev = p2_lft;
p1_rt.next = p2_rt;
p2_rt.prev = p1_rt;
outRec1.pts = p2_rt;
} else {
// x y z a b c
p2_rt.next = p1_lft;
p1_lft.prev = p2_rt;
p2_lft.prev = p1_rt;
p1_rt.next = p2_lft;
outRec1.pts = p2_lft;
}
side = EdgeSide.esLeft;
} else {
if(e2.side == EdgeSide.esRight) {
// a b c z y x
ReversePolyPtLinks(p2_lft);
p1_rt.next = p2_rt;
p2_rt.prev = p1_rt;
p2_lft.next = p1_lft;
p1_lft.prev = p2_lft;
} else {
// a b c x y z
p1_rt.next = p2_lft;
p2_lft.prev = p1_rt;
p1_lft.prev = p2_rt;
p2_rt.next = p1_lft;
}
side = EdgeSide.esRight;
}
outRec1.bottomPt = null;
if(holeStateRec == outRec2) {
if(outRec2.firstLeft != outRec1)
outRec1.firstLeft = outRec2.firstLeft;
outRec1.isHole = outRec2.isHole;
}
outRec2.pts = null;
outRec2.bottomPt = null;
outRec2.firstLeft = outRec1;
int OKIdx = e1.outIdx;
int ObsoleteIdx = e2.outIdx;
e1.outIdx = -1; // nb: safe because we only get here via AddLocalMaxPoly
e2.outIdx = -1;
TEdge e = m_ActiveEdges;
while(e != null) {
if(e.outIdx == ObsoleteIdx) {
e.outIdx = OKIdx;
e.side = side;
break;
}
e = e.nextInAEL;
}
outRec2.idx = outRec1.idx;
} |
9a2f6cbf-cd1d-4ebb-ba35-bb0796378f8f | 0 | Template(String name, Vector points)
{
this.Name = name;
this.Points = Utils.Resample(points, Recognizer.NumPoints);
this.Points = Utils.RotateToZero(this.Points);
this.Points = Utils.ScaleToSquare(this.Points, Recognizer.SquareSize);
this.Points = Utils.TranslateToOrigin(this.Points);
} |
59eb8f65-5469-45f8-9bca-0dace9b928bd | 4 | public static Collection<String> getLinks(String article) {
Document doc = null;
try {
doc = Jsoup.connect(article).get();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Element body = doc.getElementById("mw-content-text");
Elements anchors = body.select("a[href]");
HashSet<String> links = new HashSet<String>();
for (Element anchor : anchors) {
String link = anchor.attr("href");
if (link.startsWith("/wiki/") && !link.contains(":")) {
links.add(anchor.attr("abs:href"));
}
}
return links;
} |
d13e07f5-870c-425a-b505-67c5f60440b9 | 7 | public Volume(Element ul) {
Element header = ul;
while(!header.tagName().equals("body")) {
Element candidate = findHeader(header);
if(candidate == null) {
header = header.parent();
} else {
header = candidate;
break;
}
}
if(!header.tagName().equals("body")) {
title = header.select(".headline, .mw-headline").text().replaceAll("\\(.*$", "").trim();
} else {
title = "Unknown Volume " + counter++;
}
for(Element el : ul.select("li")) {
Element link = el.select("a:not(.new)").first();
if(link == null) continue;
String name = link.attr("href").replaceAll("^.+title=", "");
if(name.contains("Illustrations") && illustrationsPage == null) {
illustrationsPage = new IllustrationsPage(name);
} else {
chapters.add(new Chapter(name, link.text()));
}
}
} |
083fe3e4-0107-4b6b-b6e0-b0aca41d2e21 | 5 | public static void main(String[] args) {
int r,proceso;
int valorx = Integer.parseInt(JOptionPane.showInputDialog("Ingrese el valor del entero X"));
int valory=Integer.parseInt(JOptionPane.showInputDialog("Ingrese el valor del entero Y"));
if (valorx<=0 || valorx>255)
{
r=-1;
JOptionPane.showMessageDialog(null,"Resultado de la serie es: "+r);
}
else
{
int[] arreglo=new int[valory];
arreglo[0]=valorx;
for (int i = 1;i<arreglo.length; i++)
{
proceso=valorx/(i+1);
arreglo[i]=proceso;
}
for (int i = 0; i < arreglo.length; i++)
{
if(i==(valory-1))
{
JOptionPane.showMessageDialog(null,"Resultado de la serie "+arreglo[i]);
}
}
}
} |
01d4ff51-b810-4388-819b-13e1780fcfe2 | 2 | public boolean Move(Tile tile)
{
// Concise method of checking if both tile.Enter(this)
// and this.Enter(tile) succeed.
boolean success = (tile.Enter(this) && this.Enter(tile));
// If the movement succeeded, update stuff and notify everyone.
if(success)
{
this.setLoc(tile);
tile.Entered(this);
this.Entered(tile);
}
return success;
} |
aecab698-8110-4583-9029-f63dc52a4e5d | 4 | public boolean save(WorldDescriptor descr) {
boolean ostreamCreatedHere = false;
try {
if (ostream == null) {
ostream = new FileOutputStream(f);
ostreamCreatedHere = true;
}
JAXBContext context = JAXBContext
.newInstance(WorldDescriptor.class);
Marshaller marsh = context.createMarshaller();
marsh.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marsh.marshal(descr, ostream);
return true;
} catch (JAXBException e) {
logger.error("Could not save world descriptor to " + f);
logger.error("Error message is: " + e.getMessage());
return false;
} catch (FileNotFoundException e) {
logger.error("Could create world descriptor file " + f);
return false;
} finally {
if (ostreamCreatedHere)
ostream = null;
}
} |
702220d6-08a9-47a9-a5e1-281b01379365 | 2 | @EventHandler
public void onDamage(EntityDamageEvent e) {
if(!RushPlugin.isGameRunning() || RushPlugin.isGameFinished()) {
e.setCancelled(true);
return;
}
} |
59790bf1-e91e-44be-9399-4978f087eff3 | 6 | @Override
public void deserialize(Buffer buf) {
super.deserialize(buf);
honor = buf.readUShort();
if (honor < 0 || honor > 20000)
throw new RuntimeException("Forbidden value on honor = " + honor + ", it doesn't respect the following condition : honor < 0 || honor > 20000");
honorGradeFloor = buf.readUShort();
if (honorGradeFloor < 0 || honorGradeFloor > 20000)
throw new RuntimeException("Forbidden value on honorGradeFloor = " + honorGradeFloor + ", it doesn't respect the following condition : honorGradeFloor < 0 || honorGradeFloor > 20000");
honorNextGradeFloor = buf.readUShort();
if (honorNextGradeFloor < 0 || honorNextGradeFloor > 20000)
throw new RuntimeException("Forbidden value on honorNextGradeFloor = " + honorNextGradeFloor + ", it doesn't respect the following condition : honorNextGradeFloor < 0 || honorNextGradeFloor > 20000");
pvpEnabled = buf.readBoolean();
} |
5e1418dc-4a02-4f11-8a7d-42bd0346e4d1 | 2 | public static void main(String[] args){
int i=0;
int sum = 0;
for (i=1;i<Integer.MAX_VALUE;i++){
sum+=i;
int divs = dividers(sum);
if (divs > 500) break;
}
System.out.println(sum);
} |
6f3f6f93-94a0-4a1d-b8bb-05530006ffe9 | 4 | public static void main(String[] args)
{
int number1;
int number2;
String operator;
Scanner input = new Scanner(System.in);
System.out.print("Enter the first number: ");
number1 = input.nextInt();
System.out.print("Enter the second number: ");
number2 = input.nextInt();
Scanner op = new Scanner(System.in);
System.out.print("Please enter operation (+, -, /, *): ");
operator = op.next();
if (operator.equals("+"))
{
System.out.println("Your answer is " + (number1 + number2));
}
else if (operator.equals("-"))
{
System.out.println("Your answer is " + (number1 - number2));
}
else if (operator.equals("/"))
{
System.out.println("Your answer is " + (number1 / number2));
}
else if (operator.equals("*"))
{
System.out.println("Your answer is " + (number1 * number2));
}
} |
53437ae7-ee34-4896-958b-c6565bb8ce1a | 3 | public static void toggleCommentForSingleNode(Node node, CompoundUndoable undoable) {
int oldValue = node.getCommentState();
int newValue = Node.COMMENT_INHERITED;
boolean isComment = node.isComment();
if (oldValue == Node.COMMENT_FALSE) {
node.setCommentState(Node.COMMENT_TRUE);
newValue = Node.COMMENT_TRUE;
} else if (oldValue == Node.COMMENT_TRUE) {
node.setCommentState(Node.COMMENT_FALSE);
newValue = Node.COMMENT_FALSE;
} else {
if (isComment) {
node.setCommentState(Node.COMMENT_FALSE);
newValue = Node.COMMENT_FALSE;
} else {
node.setCommentState(Node.COMMENT_TRUE);
newValue = Node.COMMENT_TRUE;
}
}
undoable.addPrimitive(new PrimitiveUndoableCommentChange(node, oldValue, newValue));
} |
8c35ccc7-ae3c-4cc9-970d-af41c71198b2 | 4 | public double rollOut(StateObservationMulti state)
{
int thisDepth = this.m_depth;
while (!finishRollout(state,thisDepth)) {
//random move for all players
Types.ACTIONS[] acts = new Types.ACTIONS[no_players];
for (int i = 0; i < no_players; i++) {
acts[i] = actions[i][m_rnd.nextInt(NUM_ACTIONS[i])];
}
state.advance(acts);
thisDepth++;
}
double delta = value(state);
if(delta < bounds[0])
bounds[0] = delta;
if(delta > bounds[1])
bounds[1] = delta;
//double normDelta = Utils.normalise(delta ,lastBounds[0], lastBounds[1]);
return delta;
} |
ae1a4a55-3d06-4951-9592-b5ae87270ef1 | 5 | @Override
public void update(double delta, World w)
{
super.update(delta, w);
if(follow!= null)
{
this.setDx(((follow.getX()+follow.getxLen()/2)-(this.getX()+this.cameraWidth/2))/20);
this.setDy(((follow.getY()+follow.getyLen()/2)-(this.getY()+this.cameraHeight/2))/20);
}else{
this.setDx(this.getDx()*.9f);
this.setDy(this.getDy()*.9f);
if(InputInfo.mouseX<100)
{
this.setDx(-(100-InputInfo.mouseX)/5);
}
if(InputInfo.mouseX>WeekendGame.WIDTH-100)
{
this.setDx((InputInfo.mouseX-(WeekendGame.WIDTH-100))/5);
}
if(InputInfo.mouseY<100)
{
this.setDy(-(100-InputInfo.mouseY)/5);
}
if(InputInfo.mouseY>WeekendGame.HEIGHT-100)
{
this.setDy((InputInfo.mouseY-(WeekendGame.HEIGHT-100))/5);
}
}
} |
f21e2fa3-fd48-4553-bb0e-7e28ad7627c8 | 8 | public boolean compress(int maxX, int maxY)
{
boolean needRepaint = false;
for( ; ; )
{ Rectangle r = cardBounds();
if(r.width > maxWidth() || r.x + r.width >= maxX && dX > 5)
{ --dX;
needRepaint = true;
}
else if(r.height > maxHeight() || r.y + r.height >= maxY && dY > 5)
{ --dY;
needRepaint = true;
}
else
break;
}
if(needRepaint)
repaint();
return needRepaint;
} |
74738b6e-1806-4493-bbd5-a08a21fffce3 | 6 | @Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_RELEASED) {
char key = e.getKeyChar();
if (key >= 'a' && key <= 'z') key=(char) (key-32);
if ((key >= '1' && key <= 'Z')){
KEYBORD.jButtonActionPerformed(key);
} else if (key == KeyEvent.VK_ENTER){
KEYBORD.jButtonCRActionPerformed();
}
}
return false;
} |
02c25a09-c84d-41f3-b570-add143436067 | 6 | public List<Class<?>> getClasses(String packageName) throws ClassValidationException {
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String path = packageName.replace('.', '/');
Enumeration<URL> resources = classLoader.getResources(path);
List<File> dirs = new ArrayList<File>();
while (resources.hasMoreElements()) {
URI resource = resources.nextElement().toURI();
dirs.add(new File(resource));
}
List<Class<?>> classes = new ArrayList<Class<?>>();
for (File directory : dirs) {
classes.addAll(findClasses(directory, packageName));
}
return classes;
} catch (Exception e) {
throw new ClassValidationException(e);
}
} |
dd17c2b5-bbdc-418d-b1ba-0640c81754bc | 4 | private boolean checkValidUser_basicAuthentication( URI requestURI,
HTTPHeaders headers,
HypertextAccessFile htaccess,
String authMethod,
File authUserFile,
Map<String,BasicType> additionalSettings,
Map<String,BasicType> optionalReturnSettings
)
throws IOException,
ConfigurationException {
BasicType wrp_authUser = additionalSettings.get( Constants.KEY_AUTHORIZATION_USER );
BasicType wrp_authPass = additionalSettings.get( Constants.KEY_AUTHORIZATION_PASS );
if( wrp_authUser == null || wrp_authPass == null )
return false; // No authorization credentials passed (at least one missing)
String authUser = wrp_authUser.getString();
char[] authPassData = wrp_authPass.getString().toCharArray();
// Locate user in the AuthUserFile
char[] filePassData = null;
try {
filePassData = HypertextPasswordFile.getPasswordData( authUserFile,
authUser,
this.strictMode );
// Found in file?
if( filePassData == null )
return false; // Not in the user list
// Password data exists -> store into returnSettings
this.storeAuthUserSettings( filePassData, optionalReturnSettings );
} catch( ParseException e ) {
this.logger.log( Level.WARNING,
getClass().getName() + ".checkValidUser_basicAuthentication(...)",
"Cannot verify user. Malformed AuthUserFile: " + e.getMessage() );
throw new ConfigurationException( "Cannot verify user. Malformed AuthUserFile.", e );
}
return compareMD5Passwords( filePassData, authPassData );
} |
1b54e1a9-32a1-437b-a6f2-037478466505 | 8 | protected void stepToSquare(){
if (this.nextSquare==this.currentSquare+1){ //if the next square is to the right
this.parent.setX(this.parent.getX()+this.parent.speed);
} else if (this.nextSquare==this.currentSquare-1) { //if the next square is to the left
this.parent.setX(this.parent.getX()-this.parent.speed);
} else if (this.nextSquare==this.currentSquare-this.parent.size) { //if the next square is up
this.parent.setY(this.parent.getY()-this.parent.speed);
} else if (this.nextSquare==this.currentSquare+this.parent.size) { //if the next square is down
this.parent.setY(this.parent.getY()+this.parent.speed);
//DIAGONALS
}else if (this.nextSquare==this.currentSquare-this.parent.size-1) { //if the next square is to the up-left
this.parent.setX(this.parent.getX()-this.parent.speed/2);
this.parent.setY(this.parent.getY()-this.parent.speed/2);
} else if (this.nextSquare==this.currentSquare-this.parent.size+1) { //if the next square is up-right
this.parent.setX(this.parent.getX()+this.parent.speed/2);
this.parent.setY(this.parent.getY()-this.parent.speed/2);
} else if (this.nextSquare==this.currentSquare+this.parent.size-1) { //if the next square is down-left
this.parent.setX(this.parent.getX()-this.parent.speed/2);
this.parent.setY(this.parent.getY()+this.parent.speed/2);
} else if (this.nextSquare==this.currentSquare+this.parent.size+1) { //if the next square is down-right
this.parent.setX(this.parent.getX()+this.parent.speed/2);
this.parent.setY(this.parent.getY()+this.parent.speed/2);
}
} |
a685bee5-1774-466a-a380-1464d7511d54 | 2 | *
* @return a list of the backchaining implication rules which might apply to the given predicate
*
* @throws UnknownHostException if cyc server host not found on the network
* @throws IOException if a data communication error occurs
* @throws CycApiException if the api request results in a cyc server error
*/
public CycList getBackchainImplicationRules(CycConstant predicate,
CycList formula, CycObject mt)
throws UnknownHostException, IOException, CycApiException {
StringBuilder command = new StringBuilder();
if (makeELMt(mt).equals(inferencePSC) || makeELMt(mt).equals(
everythingPSC)) {
command.append("(clet (backchain-rules formula) ");
command.append(" (with-all-mts ");
command.append(" (do-predicate-rule-index (rule ").
append(predicate.stringApiValue()).
append(" :pos nil :backward) ");
command.append(" (csetq formula (assertion-el-formula rule)) ");
command.append(" (pwhen (cand (eq (first formula) #$implies) ");
command.append(" (unify-el-possible ").
append(formula.stringApiValue()).
append(" ");
command.append(" (third formula))) ");
command.append(" (cpush formula backchain-rules)))) ");
command.append(" backchain-rules)");
} else {
command.append("(clet (backchain-rules formula) ");
command.append(" (with-inference-mt-relevance ").
append(makeELMt(mt).stringApiValue()).
append(" ");
command.append(" (do-predicate-rule-index (rule ").
append(predicate.stringApiValue()).
append(" :pos nil :backward) ");
command.append(" (csetq formula (assertion-el-formula rule)) ");
command.append(" (pwhen (cand (eq (first formula) #$implies) ");
command.append(" (unify-el-possible ").
append(formula.stringApiValue()).
append(" ");
command.append(" (third formula))) ");
command.append(" (cpush formula backchain-rules)))) ");
command.append(" backchain-rules)");
}
//this.traceOn();
return converseList(command.toString());
} |
98305bad-f8f1-4708-aa18-4273f2231363 | 8 | public void update(Update query) throws IOException, Error, ClassNotFoundException{
Condition cond = query.getCondition();
ArrayList< ArrayList<Value> > tupleList;
ArrayList<AttrAssign> attrAssignList = query.getAttrAssignList();
Hashtable<String, Table> tables = null;
Table table;
File tableFile = new File(databaseDefUrl);
if(tableFile.exists()){
tables = this.getTableDef();
}else{
throw new Error("UPDATE: No database defined");
}
if((table = tables.get(query.getTableName()) )!= null ){
String tableName = table.getTableName();
File tupleFile = new File(tableName + ".db");
if(!tupleFile.exists()){
throw new Error("UPDATE: No tuple in the table " + tableName);
}else{
tupleList = this.getTupleList(tupleFile);
if(tupleList.size() == 0){
throw new Error("UPDATE: No tuple in the table " + tableName);
}
}
Hashtable<String, Integer> nameTable = table.getAttrPosHashtable();
//Check if all attributes needed are in this table throw Error if invalid
this.checkUpdateAttributesExist(nameTable, cond, attrAssignList);
//Evaluate check constraints of updating values
ArrayList<Attribute> attrList = table.getAttrList();
for(AttrAssign attrAssign : attrAssignList){
int attrPos = table.getAttrPos(attrAssign.getAttrName());
Condition checkCond = attrList.get(attrPos).getCheckCond();
Value assignValue = attrAssign.getValue();
if(checkCond != null){
Exp exp = checkCond.getExp();
Object ret = exp.accept(this, assignValue);
if(ret instanceof Boolean){
if(((Boolean) ret).booleanValue() == false){
throw new Error("UPDATE: Attribute " + attrAssign.getAttrName() + " Check constraints violated");
}
}else{
//throw new Error("UPDATE: Check constraints evaluation failed");
}
}
}
//Update tuple list
TuplesWithNameTable updatedTable = this.updateTuplesByCond(cond, attrAssignList, table.getPrimaryList(), new TuplesWithNameTable(nameTable, tupleList) );
int updatedTuplesNum = updatedTable.getUpdatedTuplesNum();
ArrayList<ArrayList<Value>> updatedTupleList = updatedTable.getTupleList();
this.saveTupleList(tupleFile, updatedTupleList);
System.out.println( updatedTuplesNum + " rows affected");
}
} |
7e89f36c-05b5-406c-b704-dfd643d444cd | 1 | public Set adjacent(Object vertex) {
if (!verticesToNeighbors.containsKey(vertex))
verticesToNeighbors.put(vertex, new HashSet());
return (Set) verticesToNeighbors.get(vertex);
} |
79fbc40a-1e96-415f-8059-59873f652a79 | 5 | public void move() {
if (userKick) {
userKick = false;
cleverBall = ball.getCopy();
while (cleverBall.getY() >= this.getTop()) {
cleverBall.move();
}
futureOfX = cleverBall.getX();
moveToBall = true;
}
if (moveToBall == true) {
if (Math.abs(futureOfX - getMiddleX()) > speed) {
if (futureOfX >= getMiddleX()) {
this.x += speed;
} else {
this.x -= speed;
}
}
else{
moveToBall = false;
}
}
} |
f3f7e642-03a3-4978-8ce0-e8640dfd6185 | 8 | private static void executeFunctionalTestCase(File file) {
ArrayList<Command> commands = new ArrayList<Command>();
System.out.println("Executing test case " + file.getName());
// Start up a server
ServerThread server = new ServerThread();
server.start();
// Hashmap to keep track of the clients that have been spawned off
HashMap<String, ClientThread> clients = new HashMap<String, ClientThread>();
// Open the file for reading
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e1) {
System.out.println("ERROR: File not found");
return;
}
// Start processing the test case
try {
String line = reader.readLine();
while (line != null) {
String[] split = line.split(",");
// Create a new client
if (split[0].equals(ServerLogger.PLAYER)) {
System.out.println("Adding new player: " + split[1]);
ClientThread clientThread = new ClientThread(split[1]);
clients.put(split[1], clientThread);
clientThread.start();
// Add the command into the array list to track what has
// been done
commands.add(new Command(split[1], Operation.JOIN_GAME));
// Sleep for a time
Thread.sleep(2000);
}
// Process the command
if (split[0].equals(ServerLogger.COMMAND)) {
System.out.println("Executing command: " + split[2] + " (" + split[1] + ")");
// Add the command into the array list to track what has
// been done
Command.Operation operation = Command.Operation.valueOf(split[2].toUpperCase());
commands.add(new Command(split[1], operation));
// Send the command to the correct client
ClientThread clientThread = clients.get(split[1]);
clientThread.getClient().processCommand(Command.Operation.valueOf((split[2]).toUpperCase()));
// Sleep for a time
Thread.sleep(500);
}
line = reader.readLine();
}
} catch (IOException e) {
System.out.println("ERROR: Error reading file");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Shutdown all the clients
shutdownClients(clients.values());
String logFile = server.getLogFile();
// Shutdown the server
shutdownServer(server);
// Verify the commands were received by the server
if (!verifyServerLog(logFile, commands)) {
System.out.println("Server log file does not match the list of commands " + "sent by the test case.\n" + "Test case DID NOT execute successfully.\n");
} else {
System.out.println("Test case completed successfully\n");
}
} |
a7c6dfeb-957c-4c2a-bd96-f7f211c89a37 | 4 | public static LinkedList<String> benchmarkIcebergs(Path path, double frequency){
Hashtable<String, Integer> tab = new Hashtable<String, Integer>();
int comp = 0;
for (String s : new WordReader(path)){
if (!tab.containsKey(s))
tab.put(s, 1);
else{
int d = tab.remove(s);
tab.put(s, d+1);
}
comp++;
}
LinkedList<String> l = new LinkedList<String>();
for(String s: tab.keySet())
if(tab.get(s)>=frequency*comp)
l.add(s);
return l;
} |
0ebb549d-6109-49e1-a83a-e7406de8b0e6 | 2 | public ArrayList<UserModelBean> getAllUser() {
// return value
ArrayList<UserModelBean> userList = new ArrayList<UserModelBean>();
try {
// create connection
connection = java.sql.DriverManager.getConnection("jdbc:mysql://"
+ dB_HOST + ":" + dB_PORT + "/" + dB_NAME, dB_USER, dB_PWD);
// Cr�ation de la requ�te
java.sql.Statement query;
// Creation de l'�l�ment de requ�te
query = connection.createStatement();
// Executer puis parcourir les r�sultats
java.sql.ResultSet rs = query
.executeQuery("SELECT * FROM User");
while (rs.next()) {
// Cr�ation de l'utilisateur
UserModelBean user = new UserModelBean(
rs.getString("lastname"), rs.getString("firstname"), rs.getString("email"),
rs.getInt("age"), rs.getString("login"),
rs.getString("pwd"));
System.out.println("User : " + user);
// ajout de l'utilisateur r�cup�r� � la liste
userList.add(user);
}
rs.close();
query.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return userList;
} |
a6f61636-db73-4e74-9ff8-b0d8bb08e91a | 4 | public Grid getGridObj() {
boolean test = false;
if (test || m_test) {
System.out.println("FileManager :: getGridObj() BEGIN");
}
if (test || m_test) {
System.out.println("FileManager :: getGridObj() END");
}
return m_gridObj;
} |
b574e77e-9ce3-4e15-ab55-699e3667b21e | 8 | public int moverDeA(int deFila, int deColumna, int aFila,int aColumna){
if(esObjetoUno(aFila, aColumna)){
int valorACorrer=matriz[deFila][deColumna];
actualizarCasilla(deFila,deColumna, ID_VACIA);
actualizarCasilla(aFila,aColumna, valorACorrer);
robot.setCarga(pesoObjetoUno);
if(retornarCoordenadaDe(ID_SITIO_UNO)==null)
actualizarCasilla(sitioUno.getFila(), sitioUno.getColumna(), ID_SITIO_UNO);
return calcularCostoMovimiento(aFila, aColumna);
}
if(esObjetoDos(aFila, aColumna)){
int valorACorrer=matriz[deFila][deColumna];
actualizarCasilla(deFila,deColumna,ID_VACIA);
actualizarCasilla(aFila, aColumna,valorACorrer);
robot.setCarga(pesoObjetoDos);
if(retornarCoordenadaDe(ID_SITIO_DOS)==null)
actualizarCasilla(sitioDos.getFila(),sitioDos.getColumna(),ID_SITIO_DOS);
return calcularCostoMovimiento(aFila, aColumna);
}
if(esSitioUno(aFila,aColumna)){
int valorACorrer=matriz[deFila][deColumna];
this.sitioUno.setCoordenadas(aFila, aColumna);
actualizarCasilla(deFila,deColumna,ID_VACIA);
if(retornarCoordenadaDe(ID_OBJETO_UNO)==null)
actualizarCasilla(aFila,aColumna,valorACorrer);
else
actualizarCasilla(aFila, aColumna,ID_SITIO_UNO_CON_ROBOT);
return calcularCostoMovimiento(aFila, aColumna);
}
if(esSitioDos(aFila,aColumna)){
this.sitioDos.setCoordenadas(aFila, aColumna);
actualizarCasilla(deFila,deColumna,ID_VACIA);
if(retornarCoordenadaDe(ID_OBJETO_DOS)==null)
actualizarCasilla(aFila, aColumna,ID_ROBOT);
else
actualizarCasilla(aFila, aColumna, ID_SITIO_DOS_CON_ROBOT);
return calcularCostoMovimiento(aFila, aColumna);
}
int valorACorrer=matriz[deFila][deColumna];
actualizarCasilla(deFila,deColumna, ID_VACIA);
actualizarCasilla(aFila, aColumna,valorACorrer);
return calcularCostoMovimiento(aFila, aColumna);
} |
ef37e5e3-e41a-4ba3-9f46-887ff0bb994c | 0 | public String getCountry() {
return country;
} |
01b584f8-b279-4ce5-b64e-8da4e3f490fe | 7 | private BoundType getBoundTypeForTerminalIntegerLiteral(Class<?> type, boolean array)
throws SynException
{
if (int.class.equals(type)) {
return IntBoundType.INSTANCE;
} else if (type.isAssignableFrom(Integer.class)) {
return IntegerBoundType.INSTANCE;
} else if (long.class.equals(type)) {
return LongBoundType.INSTANCE;
} else if (type.isAssignableFrom(Long.class)) {
return LongWrapperBoundType.INSTANCE;
} else if (type.isAssignableFrom(IntToken.class)) {
return IntTokenBoundType.INSTANCE;
} else if (type.isAssignableFrom(LongToken.class)) {
return LongTokenBoundType.INSTANCE;
} else {
throw typeMissmatchFail(array, int.class, Integer.class);
}
} |
660c3ce5-31b0-4b96-8215-d8052c1b0264 | 6 | @SuppressWarnings("static-access")
public boolean approveSelection(){
boolean seccheck = false;
File f = listener.getJfchooser().getSelectedFile();
if(f.exists() && listener.getJfchooser().getDialogType() == listener.getJfchooser().SAVE_DIALOG){
int result = JOptionPane.showConfirmDialog(frame,"The file already exists, overwrite?","Existing file",JOptionPane.YES_NO_CANCEL_OPTION);
switch(result){
case JOptionPane.YES_OPTION:
listener.getJfchooser().approveSelection();
seccheck = true;
break;
case JOptionPane.NO_OPTION:
seccheck = false;
break;
case JOptionPane.CLOSED_OPTION:
seccheck = false;
break;
case JOptionPane.CANCEL_OPTION:
listener.getJfchooser().cancelSelection();
seccheck = false;
break;
}
}else{
seccheck = true;
}
return seccheck;
} |
42392000-eaea-42cc-8689-429b73faf28f | 9 | public static String generatePossibleMoves()
{
String list="";
for (int i=0; i<64; i++)
{
switch (chessBoard[i/8][i%8])
{
case "P": list+=Pawn.possiblePawnMoves(i);
break;
case "R": list+=Rook.possibleRookMoves(i);
break;
case "N": list+=Knight.possibleKnighMoves(i);
break;
case "B": list+=Bishop.possibleBishopMoves(i);
break;
case "Q": list+=Queen.possibleQueenMoves(i);
break;
case "K": list+=King.possibleKingMoves(i);
break;
}
}
if(ParameterFileParse.BRANCH_FACTOR==1000 || list.length()/5<=ParameterFileParse.BRANCH_FACTOR)
{
return list;
}
else
{
//Only few moves are observed in the analysis
return list.substring(0, ParameterFileParse.BRANCH_FACTOR*5);
}
} |
995bb16d-f449-4662-9880-53c0804db2fc | 0 | public HashMap<Character, Vehicle> getVehicles() {
return vehicles;
} |
1d7aa490-7cb4-4336-99a9-29c3dd27472d | 1 | public void testMinus_Seconds() {
Seconds test2 = Seconds.seconds(2);
Seconds test3 = Seconds.seconds(3);
Seconds result = test2.minus(test3);
assertEquals(2, test2.getSeconds());
assertEquals(3, test3.getSeconds());
assertEquals(-1, result.getSeconds());
assertEquals(1, Seconds.ONE.minus(Seconds.ZERO).getSeconds());
assertEquals(1, Seconds.ONE.minus((Seconds) null).getSeconds());
try {
Seconds.MIN_VALUE.minus(Seconds.ONE);
fail();
} catch (ArithmeticException ex) {
// expected
}
} |
7439d4f5-3e81-4906-b8cf-72b7678c9095 | 6 | public void update(int delta) {
int index = 0;
Object projectileArray[] = projectiles.toArray();
while(index < projectileArray.length) {
if(projectileArray[index] instanceof Projectile) {
Projectile projectile = (Projectile) projectileArray[index];
if((projectile.getX() < GameConcept.width && projectile.getX() > 0) && (projectile.getY() < GameConcept.height && projectile.getY() > 0)) {
projectile.setX(projectile.getX() + (delta * (projectile.getVelocity() * Math.cos(projectile.getAngle())) / 1000));
projectile.setY(projectile.getY() + (delta * (projectile.getVelocity() * Math.sin(projectile.getAngle())) / 1000));
projectiles.set(index, projectile);
projectileArray = projectiles.toArray();
index++;
}
else {
projectile = null;
remove(index);
projectiles.trimToSize();
projectileArray = projectiles.toArray();
}
}
}
} |
Subsets and Splits