blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
f19f27498611d88da65fffc4fe25bfbdcb8b4a52
Java
finos/datahelix
/core/src/test/java/com/scottlogic/datahelix/generator/core/generation/string/IsinStringGeneratorTests.java
UTF-8
5,425
2.3125
2
[ "CC0-1.0", "Apache-2.0", "ICU", "EPL-1.0", "EPL-2.0", "CDDL-1.0", "MIT", "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
/* * Copyright 2019 Scott Logic Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.scottlogic.datahelix.generator.core.generation.string; import com.scottlogic.datahelix.generator.core.generation.string.generators.RegexStringGenerator; import com.scottlogic.datahelix.generator.core.generation.string.generators.StringGenerator; import com.scottlogic.datahelix.generator.core.utils.FinancialCodeUtils; import com.scottlogic.datahelix.generator.core.utils.JavaUtilRandomNumberGenerator; import org.junit.Assert; import org.junit.jupiter.api.Test; import java.util.Iterator; import java.util.concurrent.atomic.AtomicInteger; import static com.scottlogic.datahelix.generator.core.generation.string.generators.ChecksumStringGeneratorFactory.createIsinGenerator; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertTrue; public class IsinStringGeneratorTests { @Test public void shouldEndAllIsinsWithValidCheckDigit() { StringGenerator target = createIsinGenerator(); final int NumberOfTests = 100; final Iterator<String> allIsins = target.generateAllValues().iterator(); for (int ii = 0; ii < NumberOfTests; ++ii) { final String nextIsin = allIsins.next(); final char checkDigit = FinancialCodeUtils.calculateIsinCheckDigit(nextIsin.substring(0, 11)); assertThat(nextIsin.charAt(11), equalTo(checkDigit)); } } @Test public void shouldEndAllRandomIsinsWithValidCheckDigit() { StringGenerator target = createIsinGenerator(); final int NumberOfTests = 100; final Iterator<String> allIsins = target.generateRandomValues(new JavaUtilRandomNumberGenerator()).iterator(); for (int ii = 0; ii < NumberOfTests; ++ii) { final String nextIsin = allIsins.next(); final char checkDigit = FinancialCodeUtils.calculateIsinCheckDigit(nextIsin.substring(0, 11)); assertThat(nextIsin.charAt(11), equalTo(checkDigit)); } } @Test public void shouldUseSedolWhenCountryIsGB() { AtomicInteger numberOfIsinsTested = new AtomicInteger(0); createIsinGenerator().generateRandomValues(new JavaUtilRandomNumberGenerator()) .filter(isinString -> isinString.substring(0, 2).equals("GB")) .limit(100) .forEach(isinString -> { assertThat( FinancialCodeUtils.isValidSedolNsin(isinString.substring(2, 11)), is(true)); numberOfIsinsTested.incrementAndGet(); }); // make sure we tested the number we expected assertThat(numberOfIsinsTested.get(), equalTo(100)); } @Test public void shouldUseCusipWhenCountryIsUS() { AtomicInteger numberOfIsinsTested = new AtomicInteger(0); createIsinGenerator().generateRandomValues(new JavaUtilRandomNumberGenerator()) .filter(isinString -> isinString.substring(0, 2).equals("US")) .limit(100) .forEach(isinString -> { assertThat( FinancialCodeUtils.isValidCusipNsin(isinString.substring(2, 11)), is(true)); numberOfIsinsTested.incrementAndGet(); }); // make sure we tested the number we expected assertThat(numberOfIsinsTested.get(), equalTo(100)); } @Test public void shouldUseGeneralRegexWhenCountryIsNotGbOrUs() { AtomicInteger numberOfIsinsTested = new AtomicInteger(0); createIsinGenerator().generateRandomValues(new JavaUtilRandomNumberGenerator()) .filter(isinString -> { String countryCode = isinString.substring(0, 2); return !countryCode.equals("GB") && !countryCode.equals("US"); }) .limit(100) .forEach(isinString -> { String APPROX_ISIN_REGEX = "[A-Z]{2}[A-Z0-9]{9}[0-9]"; RegexStringGenerator regexStringGenerator = new RegexStringGenerator(APPROX_ISIN_REGEX, true); assertTrue(regexStringGenerator.matches(isinString)); numberOfIsinsTested.incrementAndGet(); }); // make sure we tested the number we expected assertThat(numberOfIsinsTested.get(), equalTo(100)); } @Test public void shouldMatchAValidIsinCodeWhenNotNegated(){ StringGenerator isinGenerator = createIsinGenerator(); boolean matches = isinGenerator.matches("GB0002634946"); Assert.assertTrue(matches); } @Test public void shouldNotMatchAnInvalidIsinCodeWhenNotNegated(){ StringGenerator isinGenerator = createIsinGenerator(); boolean matches = isinGenerator.matches("not an isin"); Assert.assertFalse(matches); } }
true
eee8c0216573f82dbea6d87cfa8d9595bf4b3405
Java
mmotieian/OCP_Proj
/OCP8/src/main/java/functional/interfaces/FunctionalInterface2Args.java
UTF-8
115
1.796875
2
[]
no_license
package functional.interfaces; public interface FunctionalInterface2Args { String take2Args(int a, String s); }
true
f3e0fb35a514d0ab25b91d79cd57554563f5a7d8
Java
Bushido-BB/Java-Progs
/test7.java
UTF-8
453
2.921875
3
[]
no_license
class test7{ public static void main(String args[]){ test7 ob1=new test7(); final int primitive=10; Integer user_defined=10; System.out.println(primitive +" "+user_defined); ob1.proof(primitive,user_defined); System.out.println(primitive +" "+user_defined); System.out.println(ob1); } void proof(int x, Integer y){ x++; y++; System.out.println(x+" "+y); } }
true
8dda367c6bc3d1794128af8fdb5e8ee3bf2b85df
Java
Scenx/javajsp-bookstore
/store/src/com/scen/bookstore/web/servlet/UserServlet.java
UTF-8
15,228
2.265625
2
[]
no_license
package com.scen.bookstore.web.servlet; import com.scen.bookstore.domain.User; import com.scen.bookstore.exception.OrderException; import com.scen.bookstore.exception.UserException; import com.scen.bookstore.service.OrderService; import com.scen.bookstore.service.UserService; import com.scen.bookstore.util.PaymentUtil; import org.apache.commons.beanutils.BeanUtils; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.UUID; /** * @author Scen * @date 2017/12/5 */ @WebServlet(name = "UserServlet", urlPatterns = "/u") public class UserServlet extends BaseServlet { /** * 登录 * * @param request * @param response * @throws ServletException * @throws IOException */ protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); UserService us = new UserService(); try { String path = "/index.jsp"; User user = us.login(username, password); if ("admin".equals(user.getRole())) { path = "/admin/login/home.jsp"; } request.getSession().setAttribute("user", user); request.getRequestDispatcher(path).forward(request, response); } catch (UserException e) { e.printStackTrace(); request.setAttribute("user_msg", e.getMessage()); request.getRequestDispatcher("/login.jsp").forward(request, response); } } /** * 注册 * * @param request * @param response * @throws ServletException * @throws IOException */ protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //处理验证码 String ckcode = request.getParameter("ckcode"); String checkcode_session = (String) request.getSession().getAttribute("checkcode_session"); if (!checkcode_session.equals(ckcode)) { //如果两个验证码不一致,跳回注册页面 request.setAttribute("ckcode_msg", "验证码错误!"); request.getRequestDispatcher("/register.jsp").forward(request, response); return; } //获取表单数据 User user = new User(); try { BeanUtils.populate(user, request.getParameterMap()); user.setActiveCode(UUID.randomUUID().toString()); //调用业务逻辑 UserService us = new UserService(); us.regist(user); //分发转向 request.getSession().setAttribute("user", user); request.getRequestDispatcher("registersuccess.jsp").forward(request, response); } catch (UserException e) { request.setAttribute("user_msg", e.getMessage()); request.getRequestDispatcher("/register.jsp").forward(request, response); return; } catch (Exception e) { e.printStackTrace(); } } /** * 注销 * * @param request * @param response * @throws ServletException * @throws IOException */ protected void logOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //使session销毁 request.getSession().invalidate(); response.sendRedirect(request.getContextPath() + "/index.jsp"); } /** * 根据id查询用户信息 * * @param request * @param response * @throws ServletException * @throws IOException */ protected void findUserById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); UserService us = new UserService(); try { User user = us.findUserById(id); request.setAttribute("u", user); request.getRequestDispatcher("/user/modifyuserinfo.jsp").forward(request, response); } catch (UserException e) { response.sendRedirect(request.getContextPath() + "/login.jsp"); } } /** * 激活用户 * * @param request * @param response * @throws ServletException * @throws IOException */ protected void active(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取激活码 String activeCode = request.getParameter("activeCode"); UserService us = new UserService(); try { us.activeUser(activeCode); request.getRequestDispatcher("/user/activesuccess.jsp").forward(request, response); } catch (UserException e) { e.printStackTrace(); //向用户提示失败信息 response.getWriter().write(e.getMessage()); } } /** * 支付是否成功 * * @param request * @param response * @throws ServletException * @throws IOException */ protected void callBack(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); // 获得回调所有数据 String p1_MerId = request.getParameter("p1_MerId"); String r0_Cmd = request.getParameter("r0_Cmd"); String r1_Code = request.getParameter("r1_Code"); String r2_TrxId = request.getParameter("r2_TrxId"); String r3_Amt = request.getParameter("r3_Amt"); String r4_Cur = request.getParameter("r4_Cur"); String r5_Pid = request.getParameter("r5_Pid"); String r6_Order = request.getParameter("r6_Order"); String r7_Uid = request.getParameter("r7_Uid"); String r8_MP = request.getParameter("r8_MP"); String r9_BType = request.getParameter("r9_BType"); String rb_BankId = request.getParameter("rb_BankId"); String ro_BankOrderId = request.getParameter("ro_BankOrderId"); String rp_PayDate = request.getParameter("rp_PayDate"); String rq_CardNo = request.getParameter("rq_CardNo"); String ru_Trxtime = request.getParameter("ru_Trxtime"); // 身份校验 --- 判断是不是支付公司通知你 String hmac = request.getParameter("hmac"); boolean isOK = PaymentUtil.verifyCallback(hmac, p1_MerId, r0_Cmd, r1_Code, r2_TrxId, r3_Amt, r4_Cur, r5_Pid, r6_Order, r7_Uid, r8_MP, r9_BType, "69cl522AV6q613Ii4W6u8K6XuW8vM1N6bFgyv769220IuYe9u37N4y7rI4Pl"); if (!isOK) { out.print("支付数据有可能被篡改,请联系客服"); } else { if ("1".equals(r1_Code)) { if ("2".equals(r9_BType)) { out.print("success"); } //修改订单状态 OrderService os = new OrderService(); try { os.modifyOrderState(r6_Order); } catch (OrderException e) { System.out.println(e.getMessage()); } response.sendRedirect(request.getContextPath() + "/user/paysuccess.jsp"); } } } /** * 集合中保存所有成语 */ private List<String> words = new ArrayList<String>(); /** * 服务器装入时初始化,仅执行一次 * * @throws ServletException */ @Override public void init() throws ServletException { // 初始化阶段,读取new_words.txt // web工程中读取 文件,必须使用绝对磁盘路径 String path = getServletContext().getRealPath("/WEB-INF/new_words.txt"); try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8")); String line; while ((line = reader.readLine()) != null) { words.add(line); } reader.close(); } catch (IOException e) { e.printStackTrace(); } } protected void checkImg(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 禁止缓存 int width = 120; int height = 30; // 步骤一 绘制一张内存中图片 BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 步骤二 图片绘制背景颜色 ---通过绘图对象 // 得到画图对象 --- 画笔 Graphics graphics = bufferedImage.getGraphics(); // 绘制任何图形之前 都必须指定一个颜色 graphics.setColor(getRandColor(200, 250)); graphics.fillRect(0, 0, width, height); // 步骤三 绘制边框 graphics.setColor(Color.WHITE); graphics.drawRect(0, 0, width - 1, height - 1); // 步骤四 四个随机数字 Graphics2D graphics2d = (Graphics2D) graphics; // 设置输出字体 graphics2d.setFont(new Font("宋体", Font.BOLD, 18)); // 生成随机数 Random random = new Random(); int index = random.nextInt(words.size()); // 获得成语 String word = words.get(index); // 定义x坐标 int x = 10; for (int i = 0; i < word.length(); i++) { // 随机颜色 graphics2d.setColor(new Color(20 + random.nextInt(110), 20 + random .nextInt(110), 20 + random.nextInt(110))); // 旋转 -30 --- 30度 int jiaodu = random.nextInt(60) - 30; // 换算弧度 double theta = jiaodu * Math.PI / 180; // 获得字母数字 char c = word.charAt(i); // 将c 输出到图片 graphics2d.rotate(theta, x, 20); graphics2d.drawString(String.valueOf(c), x, 20); graphics2d.rotate(-theta, x, 20); x += 30; } // 将验证码内容保存session request.getSession().setAttribute("checkcode_session", word); // 步骤五 绘制干扰线 graphics.setColor(getRandColor(160, 200)); int x1; int x2; int y1; int y2; for (int i = 0; i < 30; i++) { x1 = random.nextInt(width); x2 = random.nextInt(12); y1 = random.nextInt(height); y2 = random.nextInt(12); graphics.drawLine(x1, y1, x1 + x2, x2 + y2); } // 将上面图片输出到浏览器 ImageIO graphics.dispose();// 释放资源 ImageIO.write(bufferedImage, "jpg", response.getOutputStream()); } /** * 取其某一范围的color * * @param fc int 范围参数1 * @param bc int 范围参数2 * @return Color */ private Color getRandColor(int fc, int bc) { // 取其随机颜色 Random random = new Random(); if (fc > 255) { fc = 255; } if (bc > 255) { bc = 255; } int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } /** * 修改用户数据 * * @param request * @param response * @throws ServletException * @throws IOException */ protected void modifyUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //封装表单数据 User user = new User(); try { BeanUtils.populate(user, request.getParameterMap()); UserService us = new UserService(); us.modifyUser(user); response.sendRedirect(request.getContextPath() + "/user/modifyUserInfoSuccess.jsp"); } catch (Exception e) { response.getWriter().write(e.getMessage()); } } /** * 判断用户跳转前台还是后台 * * @param request * @param response * @throws ServletException * @throws IOException */ protected void myAccount(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //从session中取出user对象 User user = (User) request.getSession().getAttribute("user"); //判断user是否为null if (user == null) { response.sendRedirect(request.getContextPath() + "/login.jsp"); } else { //普通用户页面 String path = "/user/myAccount.jsp"; if ("admin".equals(user.getRole())) { //管理员页面 path = "/admin/login/home.jsp"; } request.getRequestDispatcher(path).forward(request, response); } } /** * 在线支付 * * @param request * @param response * @throws ServletException * @throws IOException */ protected void payOnline(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取用户数据 String orderid = request.getParameter("orderid"); String money = request.getParameter("money"); String pd_FrpId = request.getParameter("yh"); String p0_Cmd = "Buy"; String p1_MerId = "10001126856"; String p2_Order = orderid; String p3_Amt = money; String p4_Cur = "CNY"; String p5_Pid = "unknow"; String p6_Pcat = "unknow"; String p7_Pdesc = "unknow"; String p8_Url = "http://localhost:8080/bookStore/u?method=callBack"; String p9_SAF = "1"; String pa_MP = "unknow"; String pr_NeedResponse = "1"; String hmac = PaymentUtil.buildHmac(p0_Cmd, p1_MerId, p2_Order, p3_Amt, p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc, p8_Url, p9_SAF, pa_MP, pd_FrpId, pr_NeedResponse, "69cl522AV6q613Ii4W6u8K6XuW8vM1N6bFgyv769220IuYe9u37N4y7rI4Pl"); request.setAttribute("pd_FrpId", pd_FrpId); request.setAttribute("p0_Cmd", p0_Cmd); request.setAttribute("p1_MerId", p1_MerId); request.setAttribute("p2_Order", p2_Order); request.setAttribute("p3_Amt", p3_Amt); request.setAttribute("p4_Cur", p4_Cur); request.setAttribute("p5_Pid", p5_Pid); request.setAttribute("p6_Pcat", p6_Pcat); request.setAttribute("p7_Pdesc", p7_Pdesc); request.setAttribute("p8_Url", p8_Url); request.setAttribute("p9_SAF", p9_SAF); request.setAttribute("pa_MP", pa_MP); request.setAttribute("pr_NeedResponse", pr_NeedResponse); request.setAttribute("hmac", hmac); request.getRequestDispatcher("/user/confirm.jsp").forward(request, response); } }
true
b0512491cbae57492a3fddc40297df150382239d
Java
aayusht/seecret
/app/src/main/java/com/seecret/mdb/seecret/CommentsDatabaseHelper.java
UTF-8
1,334
2.40625
2
[]
no_license
package com.seecret.mdb.seecret; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; /** * Created by innologic2 on 11/22/16. */ public class CommentsDatabaseHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 1; private final String TEXT_TYPE = " TEXT"; private final String COMMA_SEP = ", "; private String tableName; private String getEntries() { Log.i("made new table with", tableName); return "CREATE TABLE " + tableName + " (" + "id" + " INTEGER PRIMARY KEY" + COMMA_SEP + "title" + TEXT_TYPE + COMMA_SEP + "text" + TEXT_TYPE + COMMA_SEP + "time" + TEXT_TYPE + COMMA_SEP + "icon" + " BLOB" + COMMA_SEP + "count" + TEXT_TYPE + " )"; } public CommentsDatabaseHelper(Context context, String name) { super(context, name, null, DATABASE_VERSION); tableName = name; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(getEntries()); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //onUpgrade is not implemented in this demo } }
true
8f0eaa38d5042a643618cc7fc646fb564e18ee37
Java
TagnumElite/ProjectE-Integration
/src/main/java/com/tagnumelite/projecteintegration/addons/AlchemistryAddon.java
UTF-8
7,714
1.789063
2
[ "MIT" ]
permissive
/* * Copyright (c) 2019-2022 TagnumElite * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.tagnumelite.projecteintegration.addons; import com.smashingmods.alchemistry.common.recipe.atomizer.AtomizerRecipe; import com.smashingmods.alchemistry.common.recipe.combiner.CombinerRecipe; import com.smashingmods.alchemistry.common.recipe.compactor.CompactorRecipe; import com.smashingmods.alchemistry.common.recipe.fission.FissionRecipe; import com.smashingmods.alchemistry.common.recipe.fusion.FusionRecipe; import com.smashingmods.alchemistry.common.recipe.liquifier.LiquifierRecipe; import com.smashingmods.alchemistry.registry.RecipeRegistry; import com.smashingmods.alchemylib.api.item.IngredientStack; import com.tagnumelite.projecteintegration.PEIntegration; import com.tagnumelite.projecteintegration.api.recipe.ARecipeTypeMapper; import com.tagnumelite.projecteintegration.api.recipe.nss.NSSInput; import com.tagnumelite.projecteintegration.api.recipe.nss.NSSOutput; import moze_intel.projecte.api.mapper.recipe.RecipeTypeMapper; import moze_intel.projecte.api.nss.NormalizedSimpleStack; import moze_intel.projecte.emc.IngredientMap; import net.minecraft.util.Tuple; import net.minecraft.world.item.crafting.RecipeType; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; public class AlchemistryAddon { public static final String MODID = "alchemistry"; @Contract(pure = true) public static @NotNull String NAME(String name) { return "Alchemistry" + name + "Mapper"; } @RecipeTypeMapper(requiredMods = MODID, priority = 1) public static class AlchemistryAtomizerMapper extends ARecipeTypeMapper<AtomizerRecipe> { @Override public String getName() { return NAME("Atomizer"); } @Override public boolean canHandle(RecipeType<?> recipeType) { return recipeType == RecipeRegistry.ATOMIZER_TYPE.get(); } @Override public NSSInput getInput(AtomizerRecipe recipe) { return NSSInput.createFluid(recipe.getInput()); } } @RecipeTypeMapper(requiredMods = MODID, priority = 1) public static class AlchemistryCombinerMapper extends ARecipeTypeMapper<CombinerRecipe> { @Override public String getName() { return NAME("Combiner"); } @Override public boolean canHandle(RecipeType<?> recipeType) { return recipeType == RecipeRegistry.COMBINER_TYPE.get(); } @Override public NSSInput getInput(CombinerRecipe recipe) { List<IngredientStack> ingredients = recipe.getInput(); if (ingredients.isEmpty()) { PEIntegration.debugLog("Recipe ({}) contains no inputs: {}", recipeID, ingredients); return null; } // A 'Map' of NormalizedSimpleStack and List<IngredientMap> List<Tuple<NormalizedSimpleStack, List<IngredientMap<NormalizedSimpleStack>>>> fakeGroupMap = new ArrayList<>(); IngredientMap<NormalizedSimpleStack> ingredientMap = new IngredientMap<>(); for (IngredientStack ingredient : ingredients) { if (!convertIngredient(ingredient.getCount(), ingredient.getIngredient(), ingredientMap, fakeGroupMap)) { return new NSSInput(ingredientMap, fakeGroupMap, false); } } return new NSSInput(ingredientMap, fakeGroupMap, true); } } @RecipeTypeMapper(requiredMods = MODID, priority = 1) public static class AlchemistryCompactorMapper extends ARecipeTypeMapper<CompactorRecipe> { @Override public String getName() { return NAME("Compactor"); } @Override public boolean canHandle(RecipeType<?> recipeType) { return recipeType == RecipeRegistry.COMPACTOR_TYPE.get(); } @Override public NSSInput getInput(CompactorRecipe recipe) { // A 'Map' of NormalizedSimpleStack and List<IngredientMap> List<Tuple<NormalizedSimpleStack, List<IngredientMap<NormalizedSimpleStack>>>> fakeGroupMap = new ArrayList<>(); IngredientMap<NormalizedSimpleStack> ingredientMap = new IngredientMap<>(); IngredientStack ingredient = recipe.getInput(); if (!convertIngredient(ingredient.getCount(), ingredient.getIngredient(), ingredientMap, fakeGroupMap)) { return new NSSInput(ingredientMap, fakeGroupMap, false); } return new NSSInput(ingredientMap, fakeGroupMap, true); } } //@RecipeTypeMapper(requiredMods = MODID, priority = 1) //public static class AlchemistryDissolverMapper extends ARecipeTypeMapper<DissolverRecipe> { // @Override // public String getName() { // return NAME("Dissolver"); // } // // @Override // public boolean canHandle(RecipeType<?> recipeType) { // return recipeType == RecipeRegistry.DISSOLVER_TYPE; // } //} @RecipeTypeMapper(requiredMods = MODID, priority = 1) public static class AlchemistryFissionMapper extends ARecipeTypeMapper<FissionRecipe> { @Override public String getName() { return NAME("Fission"); } @Override public boolean canHandle(RecipeType<?> recipeType) { return recipeType == RecipeRegistry.FISSION_TYPE.get(); } @Override public NSSOutput getOutput(FissionRecipe recipe) { return mapOutputs(recipe.getOutput1(), recipe.getOutput2()); } } @RecipeTypeMapper(requiredMods = MODID, priority = 1) public static class AlchemistryFusionMapper extends ARecipeTypeMapper<FusionRecipe> { @Override public String getName() { return NAME("Fusion"); } @Override public boolean canHandle(RecipeType<?> recipeType) { return recipeType == RecipeRegistry.FUSION_TYPE.get(); } } @RecipeTypeMapper(requiredMods = MODID, priority = 1) public static class AlchemistryLiquifierMapper extends ARecipeTypeMapper<LiquifierRecipe> { @Override public String getName() { return NAME("Liquifier"); } @Override public boolean canHandle(RecipeType<?> recipeType) { return recipeType == RecipeRegistry.LIQUIFIER_TYPE.get(); } @Override public NSSOutput getOutput(LiquifierRecipe recipe) { return new NSSOutput(recipe.getOutput()); } } }
true
5956a5068543e5f9c137cc8a77d1c0a0c75a12ed
Java
lixiawss/tt-54
/member/modules/interaction_services/app/services/interaction/collect/CollectService.java
UTF-8
4,188
2.0625
2
[ "Apache-2.0" ]
permissive
package services.interaction.collect; import java.util.Arrays; import java.util.Date; import java.util.List; import javax.inject.Inject; import mapper.interaction.ProductCollectMapper; import mapper.product.ProductBaseMapper; import services.interaction.ICollectService; import valueobjects.base.Page; import valueobjects.interaction.CollectCount; import com.google.common.collect.Lists; import dto.interaction.ProductCollect; public class CollectService implements ICollectService{ @Inject ProductCollectMapper productCollectMapper; @Inject ProductBaseMapper productBaseMapper; /* (non-Javadoc) * @see services.interaction.collect.ICollectService#getCollectByMember(java.lang.String, java.lang.String) */ @Override public List<ProductCollect> getCollectByMember(String lid,String email){ List<ProductCollect> cList = productCollectMapper.getCollectByMember(lid, email); return cList; } /* (non-Javadoc) * @see services.interaction.collect.ICollectService#addCollect(java.lang.String, java.lang.String) */ @Override public boolean addCollect(String lid,String email){ ProductCollect p = new ProductCollect(); p.setClistingid(lid); p.setCemail(email); p.setDcreatedate(new Date()); int flag = productCollectMapper.insertSelective(p); return flag>0; } /* (non-Javadoc) * @see services.interaction.collect.ICollectService#delCollect(java.lang.String, java.lang.String) */ @Override public boolean delCollect(String lid,String email){ int flag = productCollectMapper.delCollect(lid, email); return flag>0; } /* (non-Javadoc) * @see services.interaction.collect.ICollectService#delCollectByListingids(java.lang.String, java.lang.String) */ @Override public boolean delCollectByListingids(String lids,String email){ String[] arr = lids.split(","); int flag = productCollectMapper.delCollectByListingids(Arrays.asList(arr), email); return flag>0; } /* (non-Javadoc) * @see services.interaction.collect.ICollectService#getCollectListingIDByEmail(java.lang.String) */ @Override public List<String> getCollectListingIDByEmail(String email){ List<String> list = productCollectMapper.getCollectListingIDByEmail(email); return list; } /* (non-Javadoc) * @see services.interaction.collect.ICollectService#getCountByListingID(java.lang.String) */ @Override public int getCountByListingID(String listingID){ return productCollectMapper.getCountByListingID(listingID); } /* (non-Javadoc) * @see services.interaction.collect.ICollectService#getCollectsPageByEmail(java.lang.String, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.String, java.lang.String, java.lang.Integer) */ @Override public Page<ProductCollect> getCollectsPageByEmail(String email,Integer page, Integer pageSize,Integer language,String sort,String searchname,Integer categoryId){ List<ProductCollect> pclist = productCollectMapper.getCollectsPageByEmail(email,null,null,null,null,null); if(pclist.size()==0){ return new Page<ProductCollect>(Lists.newArrayList(),0,page,pageSize); } List<String> pcListingIds = Lists.transform(pclist, p->p.getClistingid()); List<String> listingids = productBaseMapper.selectListingidBySearchNameAndSort(language, searchname, sort, categoryId, pcListingIds); int pageIndex = (page-1)*pageSize; List<ProductCollect> list = productCollectMapper.getCollectsPageByEmail(email, pageIndex, pageSize,sort,listingids,String.join(",", listingids)); int count = productCollectMapper.getCollectsCountByEmail(email); return new Page<ProductCollect>(list,count,page,pageSize); } /* (non-Javadoc) * @see services.interaction.collect.ICollectService#getCollectCountByListingIds(java.util.List) */ @Override public List<CollectCount> getCollectCountByListingIds(List<String> listingIds){ return productCollectMapper.getCollectCountByListingIds(listingIds); } /* (non-Javadoc) * @see services.interaction.collect.ICollectService#getCollectByListingIds(java.util.List) */ @Override public List<ProductCollect> getCollectByListingIds(List<String> listingIds){ return productCollectMapper.getCollectByListingIds(listingIds); } }
true
eb3d06dd426b40fc39bb9874a0052495bc99cef8
Java
SplendorAnLin/paymentSystem
/boss/src/main/java/com/yl/boss/dao/DevicePurchDao.java
UTF-8
651
2.0625
2
[]
no_license
package com.yl.boss.dao; import com.yl.boss.entity.DevicePurch; /** * 设备订单数据接口 * * @author 聚合支付有限公司 * @since 2016年9月14日 * @version V1.0.0 */ public interface DevicePurchDao { /** * 新增设备订单 * @param device */ public void create(DevicePurch devicePurch); /** * 更新设备订单 * @param device */ public void update(DevicePurch devicePurch); /** * 根据批次号查找订单 * @param batchNumber * @return */ public DevicePurch findDevicePurchBy(String batchNumber); /** * 根据设备id查找设备订单 * @param id * @return */ public DevicePurch findById(long id); }
true
20c302308bfd0ee39739d12f8365c030e8d3742d
Java
RarePika/EcoCityPet
/modules/Bridge/src/main/java/com/dsh105/echopet/bridge/platform/bukkit/entity/BukkitAgeableEntityBridge.java
UTF-8
603
2.3125
2
[ "MIT" ]
permissive
package com.dsh105.echopet.bridge.platform.bukkit.entity; import com.dsh105.echopet.bridge.entity.AgeableEntityBridge; import org.bukkit.entity.Ageable; public class BukkitAgeableEntityBridge<E extends Ageable> extends BukkitLivingEntityBridge<E> implements AgeableEntityBridge { @Override public boolean isAdult() { return getBukkitEntity().isAdult(); } @Override public void setAdult(boolean flag) { if (flag) { getBukkitEntity().setAdult(); } else { getBukkitEntity().setBaby(); } } }
true
e5e70c215e1eb107626bbe89d5e2a55eb593756b
Java
vespa-engine/vespa
/messagebus/src/main/java/com/yahoo/messagebus/routing/Route.java
UTF-8
5,478
3.046875
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.messagebus.routing; import java.util.ArrayList; import java.util.List; /** * <p>A route is a list of {@link Hop hops} that are resolved from first to last * as a routable moves from source to destination. A route may be changed at any * time be either application logic or an invoked {@link RoutingPolicy}, so no * guarantees on actual path can be given without the full knowledge of all that * logic.</p> * * <p>To construct a route you may either use the factory method {@link * #parse(String)} to produce a route instance from a string representation, or * you may build one programatically through the hop accessors.</p> * * @author bratseth * @author Simon Thoresen Hult */ public class Route { private final List<Hop> hops = new ArrayList<>(); private String cache = null; /** * <p>Creates an empty route that contains no hops.</p> */ public Route() { // empty } /** * <p>The copy constructor ignores integrity, it simply duplicates the list * of hops in the other route. If that route is illegal, then so is * this.</p> * * @param route The route to copy. */ public Route(Route route) { this(route.hops); cache = route.cache; } private void setRaw(String s) { cache = s; } /** * Parses the given string as a list of space-separated hops. The {@link #toString()} * method is compatible with this parser. * * @param str the string to parse * @return a route that corresponds to the string */ public static Route parse(String str) { if (str == null || str.length() == 0) { return new Route().addHop(new Hop().addDirective(new ErrorDirective("Failed to parse empty string."))); } RouteParser parser = new RouteParser(str); Route route = parser.route(); route.setRaw(str); return route; } /** * <p>Constructs a route based on a list of hops.</p> * * @param hops The hops to be contained in this. */ public Route(List<Hop> hops) { this.hops.addAll(hops); } /** * <p>Returns whether or not there are any hops in this route.</p> * * @return True if there is at least one hop. */ public boolean hasHops() { return !hops.isEmpty(); } /** * <p>Returns the number of hops that make up this route.</p> * * @return The number of hops. */ public int getNumHops() { return hops.size(); } /** * <p>Returns the hop at the given index.</p> * * @param i The index of the hop to return. * @return The hop. */ public Hop getHop(int i) { return hops.get(i); } /** * <p>Adds a hop to the list of hops that make up this route.</p> * * @param hop The hop to add. * @return This, to allow chaining. */ public Route addHop(Hop hop) { cache = null; hops.add(hop); return this; } /** * <p>Sets the hop at a given index.</p> * * @param i The index at which to set the hop. * @param hop The hop to set. * @return This, to allow chaining. */ public Route setHop(int i, Hop hop) { cache = null; hops.set(i, hop); return this; } /** * <p>Removes the hop at a given index.</p> * * @param i The index of the hop to remove. * @return The hop removed. */ public Hop removeHop(int i) { cache = null; return hops.remove(i); } /** * <p>Clears the list of hops that make up this route.</p> * * @return This, to allow chaining. */ public Route clearHops() { cache = null; hops.clear(); return this; } @Override public boolean equals(Object obj) { if (!(obj instanceof Route)) { return false; } Route rhs = (Route)obj; if (hops.size() != rhs.hops.size()) { return false; } for (int i = 0; i < hops.size(); ++i) { if (!hops.get(i).equals(rhs.hops.get(i))) { return false; } } return true; } @Override public String toString() { if (cache == null) { StringBuilder ret = new StringBuilder(""); for (int i = 0; i < hops.size(); ++i) { ret.append(hops.get(i)); if (i < hops.size() - 1) { ret.append(" "); } } cache = ret.toString(); } return cache; } /** * <p>Returns a string representation of this that can be debugged but not * parsed.</p> * * @return The debug string. */ public String toDebugString() { StringBuilder ret = new StringBuilder("Route(hops = { "); for (int i = 0; i < hops.size(); ++i) { ret.append(hops.get(i).toDebugString()); if (i < hops.size() - 1) { ret.append(", "); } } ret.append(" })"); return ret.toString(); } @Override public int hashCode() { int result = hops != null ? hops.hashCode() : 0; result = 31 * result + (cache != null ? cache.hashCode() : 0); return result; } }
true
38d0274537bdf0a67b033d7aaa9cde31f6953cb2
Java
muhammadhidayah/ayobelajarjaringan
/app/src/main/java/com/muhammadhidayah/apps/EndGameActivity.java
UTF-8
2,077
2.21875
2
[]
no_license
package com.muhammadhidayah.apps; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.muhammadhidayah.apps.model.Constants; import com.muhammadhidayah.apps.model.QuizPlay; import com.muhammadhidayah.apps.model.Results; public class EndGameActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { Log.i("QuizApp", "Created EndGameActivity"); super.onCreate(savedInstanceState); this.setTitle("Quiz"); setContentView(R.layout.activity_end_game); QuizPlay currentGame = ((QuizApplication) getApplication()) .getCurrentQuiz(); String result = "Skormu adalah " + currentGame.getRight() + "/" + currentGame.getNumRounds() + ".. "; String comment = Results.getResultComment(currentGame.getRight(), currentGame.getNumRounds(), getDifficultySettings()); TextView results = (TextView) findViewById(R.id.endgameResult); results.setText(result + comment); Button finishBtn = (Button) findViewById(R.id.finishBtn); Button answerBtn = (Button) findViewById(R.id.answerBtn); } private int getDifficultySettings() { SharedPreferences settings = getSharedPreferences(Constants.SETTINGS, 0); int diff = settings.getInt(Constants.DIFFICULTY, 2); return diff; } public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: return true; } return super.onKeyDown(keyCode, event); } public void onClickAnswers(View view){ Intent i = new Intent(this, AnswerActivity.class); startActivityForResult(i, Constants.PLAYBUTTON); } public void onClickMenu(View view) { finish(); } }
true
dc096ee96c35ef9e7a5f55e486eb1331ff0ed846
Java
init-sfw/agriculture
/agros-main/src/main/java/ar/com/init/agros/model/base/type/EnumUserType.java
UTF-8
5,262
2.421875
2
[]
no_license
package ar.com.init.agros.model.base.type; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.Properties; import org.hibernate.HibernateException; import org.hibernate.usertype.EnhancedUserType; import org.hibernate.usertype.ParameterizedType; /** * @author gmatheu */ public class EnumUserType implements EnhancedUserType, ParameterizedType { protected Class<Enum> enumClass; protected Method idMethod; private static final String DEFAULT_ID_METHOD = "id"; @Override public void setParameterValues(Properties parameters) { String enumClassName = parameters.getProperty("enumClassName"); try { enumClass = (Class<Enum>) Class.forName(enumClassName); } catch (ClassNotFoundException cnfe) { throw new HibernateException("Enum class not found", cnfe); } findMethodName(parameters); } protected void findMethodName(Properties parameters) throws HibernateException { String idMethodName = parameters.getProperty("idMethodName"); if (idMethodName == null) { idMethodName = DEFAULT_ID_METHOD; } try { idMethod = enumClass.getDeclaredMethod(idMethodName); } catch (NoSuchMethodException ex) { throw new HibernateException("Method not found", ex); } catch (SecurityException ex) { throw new HibernateException("SecurityException", ex); } } @Override public Object assemble(Serializable cached, Object owner) throws HibernateException { return cached; } @Override public Object deepCopy(Object value) throws HibernateException { return value; } @Override public Serializable disassemble(Object value) throws HibernateException { return (Enum) value; } @Override public boolean equals(Object x, Object y) throws HibernateException { return x == y; } @Override public int hashCode(Object x) throws HibernateException { return x.hashCode(); } @Override public boolean isMutable() { return false; } @Override public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException { String name = rs.getString(names[0]); return rs.wasNull() ? null : getEnumValue(name); } private Object getEnumValue(String id) { Enum value = null; try { Enum[] values = enumClass.getEnumConstants(); for (Enum val : values) { if (idMethod.invoke(val).equals(id)) { value = val; break; } } } catch (IllegalAccessException ex) { throw new HibernateException("IllegalAccessException", ex); } catch (IllegalArgumentException ex) { throw new HibernateException("IllegalArgumentException", ex); } catch (InvocationTargetException ex) { throw new HibernateException("InvocationTargetException", ex); } catch (SecurityException ex) { throw new HibernateException("SecurityException", ex); } return value; } @Override public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException { if (value == null) { st.setNull(index, Types.VARCHAR); } else { st.setString(index, getEnumId(value)); } } private String getEnumId(Object value) { String r = null; try { Enum[] values = enumClass.getEnumConstants(); for (Enum val : values) { if (val.equals(value)) { r = idMethod.invoke(val).toString(); break; } } } catch (IllegalAccessException ex) { throw new HibernateException("IllegalAccessException", ex); } catch (IllegalArgumentException ex) { throw new HibernateException("IllegalArgumentException", ex); } catch (InvocationTargetException ex) { throw new HibernateException("InvocationTargetException", ex); } catch (SecurityException ex) { throw new HibernateException("SecurityException", ex); } return r; } @Override public Object replace(Object original, Object target, Object owner) throws HibernateException { return original; } @Override public Class returnedClass() { return enumClass; } @Override public int[] sqlTypes() { return new int[]{Types.VARCHAR}; } @Override public Object fromXMLString(String xmlValue) { return Enum.valueOf(enumClass, xmlValue); } @Override public String objectToSQLString(Object value) { return '\'' + ((Enum) value).name() + '\''; } @Override public String toXMLString(Object value) { return ((Enum) value).name(); } }
true
f0b13aa3a7ce661c230540a0717ffe81a771dd95
Java
JayveeHe/WeiboCrawler
/src/demo/testSearch.java
UTF-8
761
2.3125
2
[]
no_license
package demo; import java.io.*; import spider.BasicTools; import spider.FollowCrawler; import spider.KeywordCrawler; public class testSearch { public static void main(String[] args) throws IOException, InterruptedException { //测试关键词的搜索 String keyword = "NLP"; long starttime = System.currentTimeMillis(); String text = KeywordCrawler.KeywordSearch(keyword); File file = new File("关键词搜索-" + keyword + "-" + System.currentTimeMillis() + ".txt"); FileOutputStream fos = null; fos = new FileOutputStream(file); fos.write(text.getBytes("utf-8")); System.out.println("用时:" + (System.currentTimeMillis() - starttime) + "毫秒"); } }
true
15f78b58a93535c2a5bf2141da406de9cb7d14c7
Java
WilliamEyre/Panda
/Panda_TV/app/src/main/java/com/example/laptop/panda_tv/ui/home/adapter/MyHomeWallLiveAdapter.java
UTF-8
1,957
2.21875
2
[]
no_license
package com.example.laptop.panda_tv.ui.home.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.laptop.panda_tv.R; import com.example.laptop.panda_tv.ui.home.bean.MyHomeBean; import java.util.List; /** * Created by Laptop on 2017/12/19. */ public class MyHomeWallLiveAdapter extends RecyclerView.Adapter<MyHomeWallLiveAdapter.ViewHolder>{ private List<MyHomeBean.DataBean.WallliveBean.ListBeanX> wallliveList; private Context context; public MyHomeWallLiveAdapter(List<MyHomeBean.DataBean.WallliveBean.ListBeanX> wallliveList, Context context) { this.wallliveList = wallliveList; this.context = context; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item_home_panda_live,parent,false); ViewHolder viewHolder = new ViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { Glide.with(context).load(wallliveList.get(position).getImage()).into(holder.mImghomePandaLive); holder.mTvhomePandaLive.setText(wallliveList.get(position).getTitle()); } @Override public int getItemCount() { return wallliveList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { public ImageView mImghomePandaLive; public TextView mTvhomePandaLive; public ViewHolder(View itemView) { super(itemView); mImghomePandaLive = (ImageView) itemView.findViewById(R.id.img_homePandaLive); mTvhomePandaLive = (TextView) itemView.findViewById(R.id.tv_homePandaLive); } } }
true
da981d5ab3c10e687e5d39a873544150e9344000
Java
ffekete/WargameV2
/apocalypse/core/src/com/mygdx/mechwargame/screen/galaxy/GalaxyCreatorScreen.java
UTF-8
4,098
2.140625
2
[]
no_license
package com.mygdx.mechwargame.screen.galaxy; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.mygdx.mechwargame.Config; import com.mygdx.mechwargame.core.world.Galaxy; import com.mygdx.mechwargame.core.world.GalaxySetupParameters; import com.mygdx.mechwargame.core.world.generator.*; import com.mygdx.mechwargame.core.world.generator.factions.FactionDistributor; import com.mygdx.mechwargame.core.world.generator.factions.PiratesDistributor; import com.mygdx.mechwargame.core.world.generator.items.BlackMarketItemsGenerator; import com.mygdx.mechwargame.core.world.generator.items.FactoryItemsGenerator; import com.mygdx.mechwargame.core.world.generator.items.MarketItemsDemandGenerator; import com.mygdx.mechwargame.core.world.generator.items.MarketItemsGenerator; import com.mygdx.mechwargame.core.world.generator.star.*; import com.mygdx.mechwargame.screen.GenericScreenAdapter; import com.mygdx.mechwargame.state.GalaxyGeneratorState; import com.mygdx.mechwargame.state.GameData; import com.mygdx.mechwargame.state.GameState; import com.mygdx.mechwargame.ui.factory.UIFactoryCommon; import java.util.Random; public class GalaxyCreatorScreen extends GenericScreenAdapter { private GalaxySetupParameters galaxySetupParameters; private Table screenContentTable = new Table(); private boolean finishedGenerating = false; public GalaxyCreatorScreen(GalaxySetupParameters galaxySetupParameters) { this.galaxySetupParameters = galaxySetupParameters; } @Override public void show() { super.show(); GameData.galaxy = new Galaxy(galaxySetupParameters); stage.getViewport().apply(true); screenContentTable.setSize(Config.SCREEN_WIDTH, Config.SCREEN_HEIGHT); screenContentTable.add(UIFactoryCommon.getDynamicTextLabel(() -> GalaxyGeneratorState.state)) .center() .bottom(); stage.addActor(screenContentTable); Gdx.input.setInputProcessor(stage); Random random = new Random(galaxySetupParameters.seed); StarGMImageGenerator.random = random; StarSpreadGenerator.random = random; GalaxyStarDistributor.random = random; FactionDistributor.random = random; PiratesDistributor.random = random; StarBackgroundImageGenerator.random = random; StarDetailsGenerator.random = random; StarFacilitiesGenerator.random = random; new Thread(new Runnable() { @Override public void run() { GalaxyStarDistributor.distributeStars(galaxySetupParameters); FactionDistributor.distribute(galaxySetupParameters); PiratesDistributor.distribute(galaxySetupParameters); StarDetailsGenerator.generate(galaxySetupParameters); StarFacilitiesGenerator.generate(galaxySetupParameters); MarketItemsGenerator.generate(galaxySetupParameters); FactoryItemsGenerator.generate(galaxySetupParameters); BlackMarketItemsGenerator.generate(galaxySetupParameters); MarketItemsDemandGenerator.generate(galaxySetupParameters); StarGMImageGenerator.generate(galaxySetupParameters); StarSpreadGenerator.spread(galaxySetupParameters); Gdx.app.postRunnable(new Runnable() { @Override public void run() { StarAsteroidImageGenerator.generate(galaxySetupParameters); StarCityImageGenerator.generate(galaxySetupParameters); StarBackgroundImageGenerator.generate(galaxySetupParameters); } }); finishedGenerating = true; } }).start(); } @Override public void render(float delta) { super.render(delta); if (finishedGenerating) { GameState.galaxyViewScreen = new GalaxyViewScreen(); GameState.game.setScreen(GameState.galaxyViewScreen); } } }
true
f3daf513fc2fb4ae86a228677e1eb8d5b14e8140
Java
GnosticOccultist/Alchemy-Framework
/alchemy-editor/core.src/fr/alchemy/editor/core/ui/component/dialog/ExternalFileBrowserDialog.java
UTF-8
5,474
2.609375
3
[ "MIT" ]
permissive
package fr.alchemy.editor.core.ui.component.dialog; import java.awt.Point; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.function.Consumer; import com.ss.rlib.common.util.array.Array; import fr.alchemy.editor.api.AlchemyDialog; import fr.alchemy.editor.core.event.AlchemyEditorEvent; import fr.alchemy.editor.core.ui.component.asset.tree.AssetTree; import fr.alchemy.editor.core.ui.component.asset.tree.elements.AssetElement; import fr.alchemy.utilities.Validator; import fr.alchemy.utilities.event.SingletonEventBus; import javafx.scene.control.TreeItem; import javafx.scene.layout.VBox; /** * <code>ExternalFileBrowserDialog</code> is an implementation of the {@link AlchemyDialog}. * It is used to browse and select a folder in the disk hierarchy. * * @author GnosticOccultist */ public class ExternalFileBrowserDialog extends AlchemyDialog { /** * The dialog size (500;500). */ protected static final Point DIALOG_SIZE = new Point(500, 500); /** * The consumer which handles the selection. */ protected final Consumer<Path> consumer; /** * The asset tree. */ protected AssetTree tree; /** * The initial directory to look for. */ protected Path initDirectory; /** * Instantiates a new <code>ExternalFileBrowserDialog</code> with * the specified consumer to be used during selection. * * @param consumer The consumer called when selecting a folder. */ public ExternalFileBrowserDialog(Consumer<Path> consumer) { this.consumer = consumer; } /** * Creates the content of the <code>ExternalFileBrowserDialog</code>, mainly * adding an {@link AssetTree} to it. */ @Override protected void createContent(VBox container) { this.tree = new AssetTree(this::openWorkspace).setOnlyFolders(true).enableLazyMode(); this.tree.prefHeightProperty().bind(heightProperty()); this.tree.prefWidthProperty().bind(widthProperty()); this.tree.setShowRoot(false); this.tree.getSelectionModel().selectedItemProperty().addListener( (observable, oldValue, newValue) -> processSelected(newValue)); container.getChildren().add(tree); } private void openWorkspace(AssetElement element) { SingletonEventBus.publish(AlchemyEditorEvent.CHANGED_CURRENT_WORKSPACE, AlchemyEditorEvent.newChangedCurrentWorkspaceEvent(element.getFile())); processClose(); } /** * Adds the selection processor for the <code>AssetTree</code>. * * @param newValue The selected tree item. */ private void processSelected(TreeItem<AssetElement> newValue) { AssetElement element = newValue == null ? null : newValue.getValue(); Path file = element == null ? null : element.getFile(); okButton.setDisable(file == null || !Files.isWritable(file)); } /** * Shows the <code>ExternalFileBrowserDialog</code> and fill the * <code>AssetTree</code>. */ @Override public void show() { super.show(); Path directory = getInitDirectory(); if(directory == null) { directory = Paths.get(System.getProperty("user.home")); } Path toExpand = directory; Array<Path> rootFolders = Array.ofType(Path.class); FileSystem fileSystem = FileSystems.getDefault(); fileSystem.getRootDirectories().forEach(rootFolders::add); AssetTree tree = getTree(); tree.setPostLoad(finished -> { if (finished) { tree.expandTo(toExpand, true); } }); if (rootFolders.size() < 2) { tree.fill(rootFolders.first()); } else { tree.fill(rootFolders); } tree.requestFocus(); } /** * Specify the action when the 'OK' button is pressed. * <p> * The function will run the {@link #consumer} with the selected * folder from the <code>AssetTree</code>. */ @Override protected void processOK() { super.processOK(); Path folder = getTree().getSelectionModel() .getSelectedItem().getValue().getFile(); consumer.accept(folder); } /** * Specify the <code>ExternalFileBrowserDialog</code> that an 'OK' button is needed. */ @Override protected boolean needOKButton() { return true; } /** * Specify the <code>ExternalFileBrowserDialog</code> that it can't be resized. */ @Override protected boolean isResizable() { return false; } /** * Specify the <code>ExternalFileBrowserDialog</code> that a 'Close' button is needed. */ @Override protected boolean needCloseButton() { return true; } /** * Specify the <code>ExternalFileBrowserDialog</code> to set the size to {@value #DIALOG_SIZE}. */ @Override protected Point getSize() { return DIALOG_SIZE; } /** * Return the asset tree used by the <code>ExternalFileBrowserDialog</code>. * The tree cannot be null. * * @return The tree used by the dialog. */ private AssetTree getTree() { return Validator.nonNull(tree); } /** * Return the initial directory of the <code>ExternalFileBrowserDialog</code>. * * @return The initial directory for the tree. */ private Path getInitDirectory() { return initDirectory; } /** * Sets the initial directory of the <code>ExternalFileBrowserDialog</code>, * to specify which path the tree should show first. * * @param initDirectory The initial directory for the tree. */ public void setInitDirectory(Path initDirectory) { this.initDirectory = initDirectory; } }
true
67b8bd12730c84a13a435701cbf936157e92e2fc
Java
woltsu/Pongbreaker
/Pongbreaker/src/main/java/pongbreaker/peli/RajojenTarkkailija.java
UTF-8
2,723
2.890625
3
[]
no_license
package pongbreaker.peli; import pongbreaker.gui.PisteidenKasittelija; import pongbreaker.domain.Maila; import pongbreaker.domain.Pallo; /** * Luokka pitää huolen siitä, ettei mm. maila ja pallo lähde pois pelikentältä. * * @author wolli */ public class RajojenTarkkailija { private int leveys; private int korkeus; private int paatyrajanLeveys; private PisteidenKasittelija p; /** * Luokan konstruktori. * * @param leveys Tarkasteltavan kentän leveys. * @param korkeus Tarkasteltavan kentän korkeus. * @param paatyrajanLeveys Tarkasteltavan kentän päätyrajojen leveys. */ public RajojenTarkkailija(int leveys, int korkeus, int paatyrajanLeveys) { this.leveys = leveys; this.korkeus = korkeus; this.paatyrajanLeveys = paatyrajanLeveys; } /** * Metodi pitää huolen siitä, ettei pallo liiku pois kentältä. * * @param pallo Tarkasteltava pallo. */ public void tarkistaOsuukoPalloReunoihin(Pallo pallo) { if (pallo.getX() <= pallo.getR()) { pallo.setX(pallo.getR()); pallo.kaannaXNopeus(); } else if (pallo.getX() >= leveys - pallo.getR() - 10) { pallo.setX(leveys - pallo.getR() - 10); pallo.kaannaXNopeus(); } if (pallo.getY() <= pallo.getR()) { pallo.setY(pallo.getR()); pallo.kaannaYNopeus(); } else if (pallo.getY() >= this.korkeus - pallo.getR() - 30) { pallo.setY(korkeus - pallo.getR() - 30); pallo.kaannaYNopeus(); } } /** * Metodi tarkastaa onko pelin pallo ylittänyt päätyrajan, jolloin peli * loppuu. * * @param pallo Tarkasteltava pallo. * @return true jos pallo on ylittänyt päätyrajan, false jos ei. */ public boolean tarkistaOhittaakoPalloPaatyrajan(Pallo pallo) { if (pallo.getX() <= paatyrajanLeveys) { return true; } else if (pallo.getX() >= this.leveys - paatyrajanLeveys - 10) { return true; } return false; } /** * Metodi tarkastaa ettei maila poistu pelikentältä. * * @param maila Maila, jota tarkastellaan. * @return true jos maila on poistunut pelikentältä, false jos ei. */ public boolean tarkistaMeneekoMailaYliRajojen(Maila maila) { if (maila.getY() < maila.getKorkeus() / 2) { maila.setY(maila.getKorkeus() / 2); return true; } else if (maila.getY() > this.korkeus - 30 - maila.getKorkeus() / 2) { maila.setY(this.korkeus - 30 - maila.getKorkeus() / 2); return true; } return false; } }
true
20c1550e853a44a6930fe23cc4a41c2655499c08
Java
vardemin/FaceScannerPattern
/app/src/main/java/com/appelsin/olympicsportfacescanner/ThirdActivity.java
UTF-8
5,588
2.015625
2
[]
no_license
package com.appelsin.olympicsportfacescanner; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.InterstitialAd; import java.io.File; public class ThirdActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = ThirdActivity.class.getSimpleName(); private AdView mAdView; ImageView image; private Button btn; InterstitialAd mInterstitialAd; MediaPlayer mp; private boolean canShow = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_third); image = (ImageView) findViewById(R.id.source_img); btn = (Button) findViewById(R.id.btn_analyze); btn.setOnClickListener(this); btn.setEnabled(false); btn.setBackgroundResource(R.mipmap.btn_start_off); String _path = Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator+"AppAcheImages"+File.separator+"Image.jpg"; BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; Bitmap bitmap = BitmapFactory.decodeFile(_path, options); image.setImageBitmap(bitmap); triggerScannerAnimation(); mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder() .build(); mAdView.loadAd(adRequest); mInterstitialAd = new InterstitialAd(this); mInterstitialAd.setAdListener(new AdListener() { @Override public void onAdClosed() { super.onAdClosed(); Intent intent = new Intent(getApplicationContext(), FourthActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); finish(); startActivity(intent); } @Override public void onAdLoaded() { super.onAdLoaded(); canShow = true; } @Override public void onAdFailedToLoad(int i) { super.onAdFailedToLoad(i); canShow = false; } }); mInterstitialAd.setAdUnitId(getString(R.string.banner_fullID)); // Load ads into Interstitial Ads mInterstitialAd.loadAd(adRequest); mp = MediaPlayer.create(this , R.raw.five); } private void showInterstitial() { if (mInterstitialAd.isLoaded()) { mInterstitialAd.show(); } } private void triggerScannerAnimation() { Log.d(TAG, "Starting scanner animation"); final ImageView scannerBar = (ImageView) findViewById(R.id.scannerBar); Animation scannerAnimation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.anim); scannerAnimation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { //Show scanner bar scannerBar.setVisibility(View.VISIBLE); //Vibrate /*Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(VIBRATOR_SERVICE); vibrator.vibrate(2000);*/ } @Override public void onAnimationEnd(Animation animation) { //Hide scanner bar scannerBar.setVisibility(View.INVISIBLE); //Show result screen btn.setEnabled(true); btn.setText(R.string.btn_getresult); btn.setBackgroundResource(R.mipmap.btn_start_on); } @Override public void onAnimationRepeat(Animation animation) { //empty } }); scannerBar.startAnimation(scannerAnimation); } @Override public void onPause() { if (mAdView != null) { mAdView.pause(); } super.onPause(); } @Override public void onResume() { super.onResume(); if (mAdView != null) { mAdView.resume(); } if(mInterstitialAd!=null) { AdRequest adRequest = new AdRequest.Builder() .build(); mInterstitialAd.loadAd(adRequest); } } @Override public void onDestroy() { if (mAdView != null) { mAdView.destroy(); } super.onDestroy(); } @Override public void onClick(View v) { if (v.getId()==R.id.btn_analyze) { if (btn.isEnabled()) { mp.start(); showInterstitial(); if (!canShow) { Intent intent = new Intent(getApplicationContext(), FourthActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); finish(); startActivity(intent); } } } } }
true
7c67b0615d9899e1ecfcab361992e2e63a955400
Java
kewl-deus/SteamParser
/hl2stats/src/de/dengot/hl2stats/logic/DatabaseManager.java
UTF-8
2,422
2.703125
3
[]
no_license
package de.dengot.hl2stats.logic; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; public class DatabaseManager { private static DatabaseManager instance; private Connection con; private DatabaseManager() { } public static synchronized DatabaseManager getInstance() { if (instance == null) { instance = new DatabaseManager(); instance.init(); } return instance; } private synchronized void init() { try { DriverManager.registerDriver(new org.hsqldb.jdbcDriver()); // HSQLDB In-Memory this.con = DriverManager.getConnection("jdbc:hsqldb:mem:hl2stats", "sa", ""); // this.con = DriverManager.getConnection("jdbc:hsqldb:hl2stats", "sa", ""); this.createDataModel(); } catch (SQLException e) { System.out.println(this.getClass().getName() + ".init(): " + e.getMessage()); } catch (IOException e) { System.out.println(this.getClass().getName() + ".init(): " + e.getMessage()); } } private void createDataModel() throws SQLException, IOException { BufferedReader r = new BufferedReader(new InputStreamReader( getResourceStream("de.dengot.hl2stats.resources", "create_datamodel.sql"))); Statement stmt = this.getConnection().createStatement(); ArrayList<String> sqlStrings = new ArrayList<String>(); while (r.ready()) { String line = r.readLine(); if (line != null && line.length() > 0 && (! line.startsWith("--"))) { sqlStrings.add(line); // stmt.addBatch(line); int retCode = stmt.executeUpdate(line); if (retCode != 0 && retCode != 1) { System.out.println("RC: " + retCode + " FOR " + line); } } } // int retCodes[] = stmt.executeBatch(); // for (int i = 0; i < retCodes.length; i++) // { // if (retCodes[i] != 0) // { // System.out.println("RC: " + retCodes[i] + " FOR " // + sqlStrings.get(i)); // } // } } private InputStream getResourceStream(String pkgname, String fname) { String resname = "/" + pkgname.replace('.', '/') + "/" + fname; Class clazz = getClass(); InputStream is = clazz.getResourceAsStream(resname); return is; } public Connection getConnection() { if (this.con == null) { this.init(); } return con; } }
true
33a6f5a45c4ee0368e96a7edccea6078d3e8712a
Java
BulkSecurityGeneratorProject/musicroad
/src/main/java/com/nullpoint/musicroad/web/rest/errors/NumberException.java
UTF-8
318
2.03125
2
[]
no_license
package com.nullpoint.musicroad.web.rest.errors; public class NumberException extends BadRequestAlertException { private static final long serialVersionUID = 1L; public NumberException() { super(ErrorConstants.NUMBER_ERROR, "Component number more than 0", "band", "messages.error.CNumber"); } }
true
4f39daecf33b6754aa1e0da311d1609cf1eb69ba
Java
Storken/BestWebapp4eva
/src/main/java/se/chalmers/bestwebapp4eva/dao/ICategoryDAO.java
UTF-8
1,868
2.6875
3
[]
no_license
package se.chalmers.bestwebapp4eva.dao; import java.util.List; import java.util.Map; import javax.ejb.Local; import org.primefaces.model.SortOrder; import se.chalmers.bestwebapp4eva.entity.Category; /** * Interface defining functions for CategoryDAO. * * @author simon */ @Local public interface ICategoryDAO extends IDAO<Category, Long> { public List<Category> getByName(String name); /** * Method for getting a specific list of categories from the db. The list * might be sorted and filtered. * * @param first The position of the first result to retrieve. * @param pageSize Maximum number of results to retrieve. * @param sortField Which field the list should be sorted by. * @param sortOrder In which order the list should be sorted * (SortOrder.ASCENDING, SortOrder.DECENDING etc.). * @param filters A map with filters. The keys are the names of the * attributes and the values are the wanted values of the attributes. * @return A list of results from the db that's sorted and filtered * according to the parameters. */ public List<Category> getResultList(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters); /** * Method for getting the number of items in the database that applies to * the provided filters. * * @param sortField Which field the list should be sorted by. * @param sortOrder In which order the list should be sorted * (SortOrder.ASCENDING, SortOrder.DECENDING etc.). * @param filters A map with filters. The keys are the names of the * attributes and the values are the wanted values of the attributes. * @return The number of items that applies to the provided filters. */ public int count(String sortField, SortOrder sortOrder, Map<String, Object> filters); }
true
2e9bbc2ed5d22977c4f124ff0d90bc48a7fc0cae
Java
JohnSnowLabs/spark-nlp-workshop
/java/healthcare/DeidentificationExample.java
UTF-8
3,607
2.1875
2
[ "Apache-2.0" ]
permissive
import com.johnsnowlabs.nlp.AnnotatorApproach; import com.johnsnowlabs.nlp.DocumentAssembler; import com.johnsnowlabs.nlp.annotators.Tokenizer; import com.johnsnowlabs.nlp.annotators.deid.DeIdentification; import com.johnsnowlabs.nlp.annotators.deid.DeIdentificationModel; import com.johnsnowlabs.nlp.annotators.ner.MedicalNerModel; import com.johnsnowlabs.nlp.annotators.ner.NerConverterInternal; import com.johnsnowlabs.nlp.annotators.ner.dl.NerDLModel; import com.johnsnowlabs.nlp.annotators.sbd.pragmatic.SentenceDetector; import com.johnsnowlabs.nlp.embeddings.WordEmbeddingsModel; import org.apache.spark.ml.Pipeline; import org.apache.spark.ml.PipelineModel; import org.apache.spark.ml.PipelineStage; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Encoders; import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; import scala.collection.JavaConverters; import java.util.Arrays; import java.util.LinkedList; public class DeidentificationExample { public static void main(String args[]) { SparkSession spark = SparkSession .builder() .appName("PipelineExample") .config("spark.master", "local") .config("spark.driver.memory", "6G") .config("spark.kryoserializer.buffer.max", "1G") .config("spark.serializer", "org.apache.spark.serializer.KryoSerializer") .getOrCreate(); LinkedList<String> text = new LinkedList<String>(); text.add("My name is Jesus and Live in Spain."); Dataset<Row> data = spark.createDataset(text, Encoders.STRING()).toDF("text"); DocumentAssembler document = new DocumentAssembler(); document.setInputCol("text"); document.setOutputCol("document"); SentenceDetector sentenceDetector = new SentenceDetector(); sentenceDetector.setInputCols(new String[]{"document"}); sentenceDetector.setOutputCol("sentence"); Tokenizer tokenizer = new Tokenizer(); tokenizer.setInputCols(new String[]{"sentence"}); tokenizer.setOutputCol("token"); WordEmbeddingsModel wordEmbeddings = WordEmbeddingsModel.pretrained("embeddings_clinical", "en", "clinical/models"); wordEmbeddings.setInputCols(new String[]{"sentence", "token"}); wordEmbeddings.setOutputCol("embeddings"); MedicalNerModel nerDlModel = MedicalNerModel.pretrained("ner_deid_large", "en", "clinical/models"); nerDlModel.setInputCols(new String[]{"sentence", "token","embeddings"}); nerDlModel.setOutputCol("ner"); NerConverterInternal ner_chunk = new NerConverterInternal(); ner_chunk.setInputCols(new String[]{"sentence", "token","ner"}); ner_chunk.setOutputCol("ner_chunk"); ner_chunk.setPreservePosition(false); DeIdentification deIdentification = new DeIdentification(); deIdentification.setInputCols(JavaConverters.asScalaBuffer(Arrays.asList("sentence", "token", "ner_chunk"))); deIdentification.setOutputCol("dei"); deIdentification.setConsistentObfuscation(true); deIdentification.setMode("obfuscate"); deIdentification.setObfuscateRefSource("faker"); Pipeline pipeline = new Pipeline(); pipeline.setStages(new PipelineStage[] {document, sentenceDetector,tokenizer,wordEmbeddings,nerDlModel,ner_chunk,deIdentification}); PipelineModel pipelineModel = pipeline.fit(data); Dataset<Row> outputDf = pipelineModel.transform(data); outputDf.select("dei.result").show(); } }
true
591869971773f7532fad9086d03bd23a66987af8
Java
juanchos2018/AppCovid19
/app/src/main/java/com/apk/appinfocovid19/Model/Noticias.java
UTF-8
629
2.34375
2
[]
no_license
package com.apk.appinfocovid19.Model; public class Noticias { String url_imagen; String descripcion; public Noticias(){ } public Noticias(String url_imagen, String descripcion) { this.url_imagen = url_imagen; this.descripcion = descripcion; } public String getUrl_imagen() { return url_imagen; } public void setUrl_imagen(String url_imagen) { this.url_imagen = url_imagen; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } }
true
55d491988fb79876c5bb1dd3ef753b983eed88fa
Java
guangmomo/TimerTest
/app/src/main/java/com/xlw/test/fragmenttest/bp/samAc/Fragment2.java
UTF-8
1,281
2.015625
2
[]
no_license
package com.xlw.test.fragmenttest.bp.samAc; import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import com.xlw.test.R; /** * A simple {@link Fragment} subclass. */ public class Fragment2 extends Fragment { EditText editText; public static final String RESPONSE_EVALUATE = "response_evaluate"; public Fragment2() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view= inflater.inflate(R.layout.fragment_fragment2, container, false); editText= (EditText) view.findViewById(R.id.et_fragment2); setResult(); return view; } private void setResult(){ if(getTargetFragment()==null){ return; } Intent intent=new Intent(); intent.putExtra(RESPONSE_EVALUATE,"response_evaluate"); getTargetFragment().onActivityResult(Fragment1.REQUEST_EVALUATE, Activity.RESULT_OK,intent); } }
true
03dc86fd1f464f07e6473b6721bff9b31fb38c2c
Java
MicroRefact/HotelManageSystemMs
/15/com/hmm/finance/financeReportDaily/domain/FinanceReportDaily.java
UTF-8
1,820
2.546875
3
[]
no_license
import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonFormat; @Entity @Table(name = "t_financeReportDaily") public class FinanceReportDaily { private Long financeReportDailyId; private Date date; private float roomIncome; private float logisticstCost; private float salaryCost; private float totalIncome; private float totalCost; private float profit; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Long getFinanceReportDailyId(){ return financeReportDailyId; } public float getLogisticstCost(){ return logisticstCost; } public float getRoomIncome(){ return roomIncome; } public void setProfit(float profit){ this.profit = profit; } public void setSalaryCost(float salaryCost){ this.salaryCost = salaryCost; } public float getTotalIncome(){ return totalIncome; } public float getTotalCost(){ return totalCost; } public void setFinanceReportDailyId(Long financeReportDailyId){ this.financeReportDailyId = financeReportDailyId; } public void setLogisticstCost(float logisticstCost){ this.logisticstCost = logisticstCost; } public float getProfit(){ return profit; } public void setTotalIncome(float totalIncome){ this.totalIncome = totalIncome; } public float getSalaryCost(){ return salaryCost; } public void setDate(Date date){ this.date = date; } @JsonFormat(pattern = "yyyy/MM/dd", timezone = "GMT+8") public Date getDate(){ return date; } public void setRoomIncome(float roomIncome){ this.roomIncome = roomIncome; } public void setTotalCost(float totalCost){ this.totalCost = totalCost; } }
true
d7691d2b641488823b7c15fc9244a0b6da8209d5
Java
phick/reader-project
/src/main/java/com/readingapp/model/Customer.java
UTF-8
1,855
3
3
[]
no_license
package com.readingapp.model; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class Customer { private String name; private String surname; private int age; public Customer() { } public Customer(String name, String surname, int age) { this.name = name; this.surname = surname; this.age = age; } private List<Contact> contacts; public void addContact(Contact contact) { if (contacts == null) this.contacts = new ArrayList<>(); contacts.add(contact); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List<Contact> getContacts() { return contacts; } @Override public String toString() { return "Customer{" + "name='" + name + '\'' + ", surname='" + surname + '\'' + ", age=" + age + ", contacts=" + contacts + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Customer customer = (Customer) o; return age == customer.age && Objects.equals(name, customer.name) && Objects.equals(surname, customer.surname) && Objects.equals(contacts, customer.contacts); } @Override public int hashCode() { return Objects.hash(name, surname, age, contacts); } }
true
e70da13680173bf5e432fda131b41240fce7f316
Java
raviassis/EngenhariaDeSoftware
/Semestre2/ProgramacaoModular/Lista3/Lista3_Ex2/src/Caminhao.java
ISO-8859-1
900
2.96875
3
[]
no_license
public class Caminhao extends Carro { private int carga; private static String tipo = "Caminhao"; public Caminhao(int vel, double preco, String cor, int carga2) { // TODO Auto-generated constructor stub super(vel, preco, cor); carga2 = (carga2 < 0) ? 0 : carga2 ; setCarga(carga2); } public int getCarga() { return carga; } public void setCarga(int carga) {this.carga = carga;} public static String getTipo() {return tipo;} @Override public double getPrecoVenda() { // TODO Auto-generated method stub if (carga > 2000 ) { return super.getPrecoVenda() * 0.9; } else return super.getPrecoVenda() * 0.8; } @Override public String toString() { // TODO Auto-generated method stub return "Tipo de veculo: " + getTipo() + " Cor: " + getCor() + " Velocidade: " + getVelocidade() + " Preco: " + getPrecoVenda() + " Carga: " + getCarga(); } }
true
f57606c73c80d03b38af662fa8aadea5304ce888
Java
JeF11037/Java-Sandbox
/Crashtest/Sandbox/Point.java
UTF-8
972
3.21875
3
[]
no_license
import java.awt.Color; public class Point { private int x = 0; private int y = 0; private int radius = 0; private Color color; public Point(int _x, int _y, int _radius, Color _color) { x = _x; y = _y; radius = _radius; color = _color; } public int getX(){ return x; } public void setX(int value){ x = value; } public int getY(){ return y; } public void setY(int value){ y = value; } public int getRadius() { return radius; } public void setRadius(int value){ radius = value; } public Color getColor(){ return color; } public void setColor(Color value){ color = value; } public int[] GetCoords() { int[] coords = new int[2]; coords[0] = x; coords[1] = y; return coords; } }
true
df73486f13315a0ae7775b78d143fd98d461ef88
Java
liangliangmax/liang-lagou-ssm
/src/main/java/com/liang/spring/core/annotation/Autowired.java
UTF-8
235
2.078125
2
[]
no_license
package com.liang.spring.core.annotation; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @Target({ElementType.FIELD}) public @interface Autowired { boolean required() default true; }
true
db3c36aff1d09a2e6b1c6c9c29bdc9279d72b1ed
Java
viktorburka/jellyfish
/src/main/java/Sender.java
UTF-8
740
2.546875
3
[]
no_license
import java.io.InputStream; import java.util.Map; public interface Sender { void openConnection(String url, Map<String,String> options) throws SenderOperationError; long writePart(InputStream reader, Map<String,String> options) throws SenderOperationError; void cancel() throws SenderOperationError; void closeConnection() throws SenderOperationError; static Sender getSenderForScheme(String scheme, long fileSize) { switch (scheme) { case "s3": return new SenderS3Simple(); default: return null; } } class SenderOperationError extends Exception { SenderOperationError(String error) { super(error); } } }
true
5bfcba3f0598329520b538047139e4219a7324b8
Java
zlren/sip-app
/sample-src/com/zczg/heart/Realm.java
UTF-8
754
2.671875
3
[]
no_license
package com.zczg.heart; public class Realm { private String realmId; private String serverIp; private String name; public Realm() { } public Realm(String realmId, String serverIp, String name) { this.realmId = realmId; this.serverIp = serverIp; this.name = name; } public String getRealmId() { return realmId; } public void setRealmId(String realmId) { this.realmId = realmId; } public String getServerIp() { return serverIp; } public void setServerIp(String serverIp) { this.serverIp = serverIp; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "[realmId = " + realmId + ", ip = " + serverIp + "]"; } }
true
002f69a8baa27d209addecf802d1a0cb2ffc2c83
Java
KeshavAgarwal2/Data-Structures-and-Algorithms
/lecture008/waveh.java
UTF-8
1,045
3.390625
3
[]
no_license
import java.util.Scanner; public class waveh{ static Scanner scn=new Scanner (System.in); public static void input(int[][]arr){ for(int row=0;row<arr.length;row++){ for(int col=0;col<arr[0].length;col++){ arr[row][col]=scn.nextInt(); } } } public static void print(int[][]arr){ for(int[] ar:arr){ for(int i:ar){ System.out.print(i+" "); } System.out.println(); } } public static void waveh(int[][] arr){ for(int row=0;row<arr.length;row++){ if(row%2==0){ for(int col=0;col<arr[0].length;col++) System.out.print(arr[row][col]); } else{ for(int col=arr.length-1;col>=0;col--) System.out.print(arr[row][col]); } } } public static void main(String[]args){ System.out.println("Enter row and column"); int n=scn.nextInt(); int m=scn.nextInt(); int[][]arr=new int[n][m]; input(arr); print(arr); waveh(arr); System.out.println(); } }
true
1f1ee67813c231375eb0da5e31d884e3e99fbcea
Java
agarridogarcia/Boletin5_6
/src/boletin5_6/Ventas.java
UTF-8
613
3.296875
3
[]
no_license
package boletin5_6; public class Ventas { private double num1; //const. public Ventas(){ num1=0; } public Ventas(double n1){ num1=n1; } public void amosar(double n1){ if (n1<=100) System.out.println("O artigo é de baixo consumo"); else if (n1>100&&n1<500) System.out.println("O artigo é de consumo medio"); else if (n1>500&&n1<1000) System.out.println("O artigo é de alto consumo"); else System.out.println("O artigo é de primeira necesidade"); } }
true
70a7a613fda253a71014fde5c395a156d685fb5a
Java
palawindu/bc-core
/lib-common/src/main/java/id/co/sigma/common/form/DisposeablePanel.java
UTF-8
950
2.28125
2
[ "Apache-2.0" ]
permissive
package id.co.sigma.common.form; /** * panel yang bisa <i>safely</i> disposed * @author <a href="mailto:gede.sutarsa@gmail.com">Gede Sutarsa</a> * @version $Id **/ public interface DisposeablePanel { /** * dispose panel **/ public void dispose () ; /** * mendaftarkan child yang disposable dari. ini di chain, jadinya kalau di dispose berantai, semua child akan ke dispose */ public void registerDisposableChild (DisposeablePanel disposableChild); /** * kontra dari #registerDisposableChild, ini untuk meremove widget dari disposable panel. ini di pergunakan dalam usecase widget di detach dari parent */ public void unregisterDisposableChild(DisposeablePanel disposableChild) ; /** * parent dari disposable panel */ public DisposeablePanel getParentDisposablePanel (); /** * setter parent dari disposable panel */ public void setParentDisposablePanel(DisposeablePanel parent); }
true
c26ad8b98c2f3be119e16e8b28060dd44a35d1c2
Java
Yg0R2/tmp
/email-request-spammer-service/src/main/java/com/yg0r2/eress/bes/domain/Order.java
UTF-8
1,040
2.4375
2
[]
no_license
package com.yg0r2.eress.bes.domain; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; @JsonDeserialize(builder = Order.Builder.class) class Order { private final String customerLastName; private final long orderNumber; private Order(Builder builder) { customerLastName = builder.customerLastName; orderNumber = builder.orderNumber; } public String getCustomerLastName() { return customerLastName; } public long getOrderNumber() { return orderNumber; } public static class Builder { private String customerLastName; private Long orderNumber; public Builder withCustomerLastName(String customerLastName) { this.customerLastName = customerLastName; return this; } public Builder withOrderNumber(Long orderNumber) { this.orderNumber = orderNumber; return this; } public Order build() { return new Order(this); } } }
true
c4f76f9662e8b8a892d2bb78fb11ecc68c6ebf75
Java
mnutt/limewire5-ruby
/components/promotion/src/test/java/org/limewire/promotion/SearcherDatabaseImplTest.java
UTF-8
1,633
2.34375
2
[]
no_license
package org.limewire.promotion; import java.util.Date; import java.util.List; import junit.framework.Test; import org.limewire.promotion.containers.PromotionMessageContainer; import org.limewire.util.BaseTestCase; public class SearcherDatabaseImplTest extends BaseTestCase { public SearcherDatabaseImplTest(String name) { super(name); } public static Test suite() { return buildTestSuite(SearcherDatabaseImplTest.class); } public void testQuery() throws Exception { SearcherDatabaseImpl searcherDatabase = new SearcherDatabaseImpl(new KeywordUtilImpl(), null, null, null); searcherDatabase.init(); searcherDatabase.clear(); PromotionMessageContainer promo = new PromotionMessageContainer(); promo.setDescription("I'm a description"); promo.setUniqueID(System.currentTimeMillis()); promo.setKeywords("keyword1\tkeyword2\tjason"); promo.setURL("http://limewire.com/"); promo.setValidStart(new Date(0)); promo.setValidEnd(new Date(Long.MAX_VALUE)); searcherDatabase.ingest(promo, "foo" + System.currentTimeMillis()); List<SearcherDatabase.QueryResult> results = searcherDatabase.query("jaSON"); assertEquals(1, results.size()); assertGreaterThan("Expected uniqueID to be > 1", 1, results.get(0) .getPromotionMessageContainer().getUniqueID()); assertEquals("http://limewire.com/", results.get(0).getPromotionMessageContainer().getURL()); results = searcherDatabase.query("jaSON2"); assertEquals(0, results.size()); } }
true
1e7b6e91af294d41111a73214e27c98f02b8c02f
Java
zoebbmm/CodeTests
/src/AlgorithmAndDataStructureTests/LeetCode/Question226/Solution.java
UTF-8
951
3.21875
3
[]
no_license
package AlgorithmAndDataStructureTests.LeetCode.Question226; import java.util.Arrays; import java.util.Comparator; /** * Created by weizhou on 8/29/16. */ public class Solution { public boolean canAttendMeetings(Interval[] intervals) { if (intervals == null || intervals.length ==0) { return true; } // Sort according to the start time Arrays.sort(intervals, new Comparator<Interval>() { public int compare(Interval a, Interval b) { return a.start - b.start; } }); Interval prev = intervals[0]; for (int i = 1; i < intervals.length; i++) { Interval curr = intervals[i]; if (isOverlapped(prev, curr)) { return false; } prev = curr; } return true; } private boolean isOverlapped(Interval a, Interval b) { return a.end > b.start; } }
true
3fd5e72bff28defd866ef213b0f2716fb20512c0
Java
luke8hogan5/Car-Rental
/src/daoImpl/UserDaoImpl.java
UTF-8
2,300
2.78125
3
[]
no_license
package daoImpl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import dao.UserDao; import database.Database; import models.UserModel; public class UserDaoImpl implements UserDao { /** * Get the id, username, email, loyalty points, and balance of all users from DB * @return Results from DB query */ @Override public ResultSet getAllUsers() { Connection conn; try { conn = Database.getConnection(); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("select user_id, userName, email, loyaltyRating, balanceDue from account where userType = 1;"); return rs; } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Update selected user's details * @param name User's name * @param email User's email * @param id User's ID */ @Override public void updateUserAdm(String name, String email, int id) { Connection conn; try { conn = Database.getConnection(); String sql = "UPDATE `account`SET userName='"+name+"',email='"+email+"'WHERE user_id='"+id +"'"; Statement st = conn.createStatement(); st.execute(sql); } catch (SQLException ex) { ex.printStackTrace(); } } /** * Delete selected user from DB * @param id User's ID */ @Override public void deleteUserAdm(int id ) { Connection conn; try { conn = Database.getConnection(); String sql = "DELETE FROM `account` WHERE user_id='"+id+"'"; Statement st = conn.createStatement(); st.execute(sql); } catch (SQLException ex) { ex.printStackTrace(); } } /** * Update selected user's details in DB * @param user Selected user's details */ @Override public void updateUserInfo(UserModel user ) { Connection conn = Database.getConnection(); try { PreparedStatement ps = conn.prepareStatement("UPDATE account SET userName=?, email=?, address=? WHERE user_id=?;"); ps.setString(1, user.getName()); ps.setString(2, user.getEmail()); ps.setString(3, user.getAddress()); ps.setInt(4, user.getUserId()); ps.execute(); } catch (SQLException ex) { ex.printStackTrace(); } } }
true
aa4b1a0773a119634111a19e082f6c2d7b27d14e
Java
Never4never/EpamBSU
/Homeworks/Homework6/NoNumbers.java
UTF-8
758
3.6875
4
[]
no_license
import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Class for rule which takes string from console and checks if it fits the rule (string is not numeric). * @author Petriakina * @version 0.5 */ public class NoNumbers extends Rule { /** * The regular expression pattern for checking the rule. * @return true if the string fit in the rule. */ @Override protected boolean checkLine (String line) { Pattern p = Pattern.compile("^\\D+$"); Matcher m = p.matcher (line); return m.matches(); } /** * Prints if the string fits in the rule. */ @Override public void printResult () { System.out.println ("String has no numbers."); } }
true
66837cce68b1c838a5cdba9e409e876229b464f6
Java
Y123Y/DesignPatterns
/src/main/java/pattern/proxy/custom/TianNv.java
UTF-8
166
2.34375
2
[]
no_license
package pattern.proxy.custom; public class TianNv implements Person { @Override public void findLove() { System.out.println("我是天女"); } }
true
c9ad3373e8078bf9e4d52f22a6feba8596876108
Java
cha63506/CompSecurity
/nbc_source/src/com/nbcsports/liveextra/ui/player/premierleague/player/PlayerInfoProvider.java
UTF-8
5,047
1.851563
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.nbcsports.liveextra.ui.player.premierleague.player; import com.google.gson.Gson; import com.nbcsports.liveextra.content.models.overlay.premierleague.PlayerInfo; import com.nbcsports.liveextra.content.models.overlay.premierleague.PremiereLeagueFeedName; import com.nbcsports.liveextra.content.overlay.OverlayPollingSubscriber; import com.nbcsports.liveextra.ui.player.premierleague.PremierLeagueEngine; import com.nbcsports.liveextra.ui.player.premierleague.core.PremierLeaguePollingProvider; import com.squareup.okhttp.OkHttpClient; import java.util.ArrayList; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.Predicate; import rx.Observable; import rx.functions.Func1; public class PlayerInfoProvider extends PremierLeaguePollingProvider { public static class PlayerInfoSubscriber extends OverlayPollingSubscriber { public PlayerInfoSubscriber(OkHttpClient okhttpclient, Gson gson) { super(okhttpclient, gson, com/nbcsports/liveextra/content/models/overlay/premierleague/PlayerInfo); } } public PlayerInfoProvider(PremierLeagueEngine premierleagueengine, PlayerInfoSubscriber playerinfosubscriber) { super(premierleagueengine, playerinfosubscriber, PremiereLeagueFeedName.PlayerInfo); } public Observable getPlayer(final int pid) { return getPlayerInfo().flatMap(new Func1() { final PlayerInfoProvider this$0; public volatile Object call(Object obj) { return call((PlayerInfo)obj); } public Observable call(PlayerInfo playerinfo) { if (playerinfo == null || CollectionUtils.isEmpty(playerinfo.getPlayers())) { return Observable.empty(); } else { return Observable.from(new ArrayList(playerinfo.getPlayers())); } } { this$0 = PlayerInfoProvider.this; super(); } }).filter(new Func1() { final PlayerInfoProvider this$0; final int val$pid; public Boolean call(com.nbcsports.liveextra.content.models.overlay.premierleague.PlayerInfo.Player player) { if (player == null) { return null; } boolean flag; if (player.getPid() == pid) { flag = true; } else { flag = false; } return Boolean.valueOf(flag); } public volatile Object call(Object obj) { return call((com.nbcsports.liveextra.content.models.overlay.premierleague.PlayerInfo.Player)obj); } { this$0 = PlayerInfoProvider.this; pid = i; super(); } }); } public Observable getPlayerInfo() { return getObservable(); } public Observable getPlayers(final String key) { return getPlayerInfo().flatMap(new Func1() { final PlayerInfoProvider this$0; final String val$key; public volatile Object call(Object obj) { return call((PlayerInfo)obj); } public Observable call(PlayerInfo playerinfo) { if (playerinfo == null || CollectionUtils.isEmpty(playerinfo.getPlayers())) { return Observable.empty(); } else { playerinfo = new ArrayList(playerinfo.getPlayers()); CollectionUtils.filter(playerinfo, new Predicate() { final _cls1 this$1; public boolean evaluate(com.nbcsports.liveextra.content.models.overlay.premierleague.PlayerInfo.Player player) { return player.getHa().equals(key); } public volatile boolean evaluate(Object obj) { return evaluate((com.nbcsports.liveextra.content.models.overlay.premierleague.PlayerInfo.Player)obj); } { this$1 = _cls1.this; super(); } }); return Observable.just(playerinfo); } } { this$0 = PlayerInfoProvider.this; key = s; super(); } }); } public void showGoLive(boolean flag) { } }
true
a247f8f8714ec201ddfa251ab84e2cb436ddea52
Java
kbrinker1/CR-MacroLabs-OOP-InstructorStudentClassroom
/src/test/java/io/zipcoder/interfaces/TestEducator.java
UTF-8
2,031
3.0625
3
[]
no_license
package io.zipcoder.interfaces; import org.junit.Assert; import org.junit.Test; public class TestEducator { @Test public void testImplementation(){ //then Assert.assertTrue(Educator.LEON instanceof Teacher); } @Test public void testEducatorTeach(){ // Given Instructor instructor = new Instructor(8); Student student = new Student(10); double expected = 150.00; // When Educator.KRIS.teach(student, 150.00); // Then double actual = student.getTotalStudyTime(); Assert.assertEquals(expected, actual, 0); } @Test public void testEducatorLecture(){ // Given Instructor instructor = new Instructor(666); Student student0 = new Student(0); Student student1 = new Student(1); Student student2 = new Student(2); Student[] students = new Student[3]; students[0] = student0; students[1] = student1; students[2] = student2; // When double expected = 50.00; Educator.TARIQ.lecture(students, 150); // Then double actual = student0.getTotalStudyTime(); Assert.assertEquals(expected, actual, 0); } @Test public void testHostLectureEducator(){ //Given ZipCodeWilmington.getInstance().hostLecture(Educator.KRIS,150); Student student = (Student) Students.getInstance().personList.get(0); double expected = 30; //When double actual = student.getTotalStudyTime(); Assert.assertEquals(expected, actual,0); } @Test public void testEducatorGetTimeWorked(){ //Given ZipCodeWilmington.getInstance().hostLecture(Educator.LEON,150); Student student = (Student) Students.getInstance().personList.get(0); double expected = 150; //When double actual = Educator.LEON.getTimeWorked(); Assert.assertEquals(expected, actual,0); } }
true
5306bb8c9becd1719cbaacbc2f96ca65c09f5a00
Java
onixred/TelegramApi
/src/main/java/org/telegram/api/functions/messages/TLRequestMessagesGetAttachedStickers.java
UTF-8
1,774
2.171875
2
[ "MIT" ]
permissive
package org.telegram.api.functions.messages; import org.telegram.api.input.sticker.media.TLAbsInputStickeredMedia; import org.telegram.api.sticker.stickersetconvered.TLAbsStickerSetCovered; import org.telegram.tl.StreamingUtils; import org.telegram.tl.TLContext; import org.telegram.tl.TLMethod; import org.telegram.tl.TLVector; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * The type TL request messages get chats. */ public class TLRequestMessagesGetAttachedStickers extends TLMethod<TLVector<TLAbsStickerSetCovered>> { /** * The constant CLASS_ID. */ public static final int CLASS_ID = 0xcc5b67cc; private TLAbsInputStickeredMedia media; /** * Instantiates a new TL request messages get chats. */ public TLRequestMessagesGetAttachedStickers() { super(); } public int getClassId() { return CLASS_ID; } public TLVector<TLAbsStickerSetCovered> deserializeResponse(InputStream stream, TLContext context) throws IOException { return StreamingUtils.readTLVector(stream, context, TLAbsStickerSetCovered.class); } public TLAbsInputStickeredMedia getMedia() { return media; } public void setMedia(TLAbsInputStickeredMedia media) { this.media = media; } public void serializeBody(OutputStream stream) throws IOException { StreamingUtils.writeTLObject(media, stream); } public void deserializeBody(InputStream stream, TLContext context) throws IOException { media = StreamingUtils.readTLObject(stream, context, TLAbsInputStickeredMedia.class); } public String toString() { return "messages.getAttachedStickers#cc5b67cc"; } }
true
61cec33564d79d1b667215f6e7bf3e7ca6abe5b4
Java
felipemostardas/APS-CDM-Fadergs
/app/src/main/java/com/aps_cdm_fadergs/aps_cdm_fadergs/ListaProdutosActivity.java
UTF-8
3,257
1.9375
2
[]
no_license
package com.aps_cdm_fadergs.aps_cdm_fadergs; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import java.util.List; public class ListaProdutosActivity extends AppCompatActivity { ListView lvLista; List<Produto> lista; AdapterProduto adapter; int codLista; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lista_produtos); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); codLista = getIntent().getExtras().getInt("codLista"); lvLista = (ListView) findViewById(R.id.lvProdutos); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(ListaProdutosActivity.this, ProdutoActivity.class); startActivity(intent); } }); lvLista.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { final Produto produtoSelecionado = lista.get(position); AlertDialog.Builder alerta = new AlertDialog.Builder(ListaProdutosActivity.this); alerta.setTitle("Excluir Produto..."); alerta.setMessage("Confirma a exclusão do produto " + produtoSelecionado.getNome() + "?"); alerta.setPositiveButton("Sim", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ProdutoDAO.excluir(produtoSelecionado.getId(), ListaProdutosActivity.this); carregarLista(); } }); alerta.setNeutralButton("Cancelar", null); alerta.show(); return true; } }); } private void carregarLista(){ lista = ProdutoDAO.listar(this, codLista); adapter = new AdapterProduto(this, lista); lvLista.setAdapter(adapter); } @Override protected void onResume() { super.onResume(); carregarLista(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_lista_produtos, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings){ return true; } return super.onOptionsItemSelected(item); } }
true
94f719e1c940ba01067b962d92ad230d8aef2d07
Java
ziccardi/yaclp
/src/main/java/it/jnrpe/yaclp/Argument.java
UTF-8
4,441
2.5625
3
[]
no_license
/******************************************************************************* * Copyright (c) 2017 Massimiliano Ziccardi * <P/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <P/> * http://www.apache.org/licenses/LICENSE-2.0 * <P/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package it.jnrpe.yaclp; import it.jnrpe.yaclp.validators.IArgumentValidator; import java.util.List; /** * Consumes the command line by removing the arguments of the current option. */ class Argument implements IArgument { /** * Whether this argument is mandatory or not. */ private final boolean mandatory; /** * The name of this argument. */ private final String name; /** * The list of validatory for this argument value. */ private final IArgumentValidator[] validators; private final int minRepetitions; private final int maxRepetitions; /** * Create a new argument object. * * @param name the name of the argument * @param mandatory <code>true</code> if the argument is mandatory * @param minRepetitions minimum number of times the argument must be present * @param maxRepetitions maximum number of times the argument must be present * @param validators the list of validators to be used to validate this argument value */ Argument( final String name, final boolean mandatory, final int minRepetitions, final int maxRepetitions, final IArgumentValidator... validators) { this.mandatory = mandatory; this.name = name; this.validators = validators; this.minRepetitions = minRepetitions; this.maxRepetitions = maxRepetitions; } /** * Consumes the argument. After the execution of the method, the argument won't be inside args * anymore. * * @param option Owner option for this argument * @param args command line to be parsed * @param pos position where this argument value should be found in the command line * @param res result * @throws ParsingException on error parsing the argument or ig the argument is not present */ public final void consume(final IOption option, final List<String> args, final int pos, final CommandLine res) throws ParsingException { int numberOfArgsFound = 0; while (pos < args.size() && !args.get(pos).startsWith("-")) { // Argument found String value = args.remove(pos); for (IArgumentValidator validator : validators) { validator.validate(option, this, value); } saveValue(res, option, value); numberOfArgsFound++; if (numberOfArgsFound > maxRepetitions) { throw new ParsingException( "At most %d <%s> arguments for option <%s> must be present", maxRepetitions, getName(), option.getLongName()); } } if (numberOfArgsFound == 0 && mandatory) { throw new ParsingException( "Mandatory argument <%s> for option <%s> is not present", getName(), option.getLongName()); } if (numberOfArgsFound < minRepetitions) { throw new ParsingException( "At least %d <%s> arguments for option <%s> must be present (%d found)", minRepetitions, getName(), option.getLongName(), numberOfArgsFound); } } /** * Saves the value of the argument inside res. * * @param res the command line parsing result * @param option option owning the argument * @param value value to be saved * @throws ParsingException on error saving the argument value */ protected void saveValue(final CommandLine res, final IOption option, final String value) throws ParsingException { res.addValue(option, value); } /** * Returns the name of the argument. * * @return the name of the argument */ public String getName() { return name; } }
true
89c87f39e38727dbb71def27b2eb4936ea6e1038
Java
cha63506/CompSecurity
/pinterest_source/src/com/pinterest/activity/flashlight/BottomSheetLayout$6$1.java
UTF-8
568
1.625
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.pinterest.activity.flashlight; // Referenced classes of package com.pinterest.activity.flashlight: // BottomSheetLayout class this._cls1 implements Runnable { final Sheet this$1; public void run() { if (getSheetView() != null) { peekSheet(); } } () { this$1 = this._cls1.this; super(); } }
true
e35623c7e2eef6975c2fca7c01a63845a741a2ba
Java
seawindnick/javafamily
/kafka/src/main/java/com/java/study/producer/KafkaProducer.java
UTF-8
1,633
2.46875
2
[ "MIT" ]
permissive
package com.java.study.producer; import com.java.study.util.KafkaUtil; import org.apache.kafka.clients.producer.Callback; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import java.util.Objects; import java.util.concurrent.Future; public class KafkaProducer implements Runnable { @Override public void run() { org.apache.kafka.clients.producer.KafkaProducer<String, String> kafkaProducer = KafkaUtil.producerInstance(); for (int i = 0; i < 1; i++) { ProducerRecord<String, String> record = new ProducerRecord<>(KafkaUtil.topic, "{\"businessId\":\"54486957404770704\",\"businessLine\":1,\"businessName\":\"公寓速销\",\"eventType\":\"Paid\",\"id\":201,\"timeStamp\":1629704206136}"); try { Future<RecordMetadata> future = kafkaProducer.send(record); RecordMetadata recordMetadata = future.get(); } catch (Exception ex) { ex.printStackTrace(); } } } public static class KafkaMessageCallback implements Callback{ public ProducerRecord producerRecord; public KafkaMessageCallback(ProducerRecord producerRecord) { this.producerRecord = producerRecord; } @Override public void onCompletion(RecordMetadata recordMetadata, Exception e) { System.out.println(producerRecord.value()); if (Objects.nonNull(e)){ e.printStackTrace(); }else { System.out.println(recordMetadata); } } } }
true
470dbf2086c21b2dcbfe86611ef3e9576c0edff9
Java
asl-ber/untitled5
/src/com/company/amphibia.java
UTF-8
702
2.890625
3
[]
no_license
package com.company; abstract public class amphibia extends Animals { private String habitat; private String tail; private String crawls; public amphibia(boolean alive, String habitat, String tail, String crawls) { super(alive); this.habitat = habitat; this.tail = tail; this.crawls = crawls; } public String getHabitat() { return habitat; } public void setHabitat(String habitat) { this.habitat = habitat; } public String getTail() { return tail; } public void setTail(String tail) { this.tail = tail; } public String getCrawls() { return crawls; } public void setCrawls(String crawls) { this.crawls = crawls; } }
true
ca18704aad12b35aef841785cf4d672c5afcc9da
Java
milkds/multi_thread_scrapper
/src/main/java/scrapper/ProxySupplier.java
UTF-8
2,482
2.703125
3
[]
no_license
package scrapper; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import scrapper.proxy_site_parsers.ProxySiteParser; import scrapper.proxy_site_parsers.ProxypediaParser; import java.util.ArrayList; import java.util.List; import java.util.Map; public class ProxySupplier implements Runnable { private Map<String, String> proxyMap; private List<ProxySiteParser> parsers; //list of threads checking proxy sites private int totalActiveProxies = 10; //later will be changed to reading from properties private int proxyRecheckDelaySec = 60; //later will be changed to reading from properties private boolean isPaused = false; private static final Logger logger = LogManager.getLogger(ProxySupplier.class.getName()); public ProxySupplier(Map<String, String> proxyMap) { this.proxyMap = proxyMap; } @Override public void run() { initParsers(proxyMap); List<Thread> parseThreadsList = launchParseThreads(); while (true){ if (proxyMap.size()>totalActiveProxies){ if (!isPaused){ pauseAllParsers(parseThreadsList); } try { Thread.sleep(proxyRecheckDelaySec*1000); } catch (InterruptedException ignored) { } } else if (isPaused){ wakeUpAllParsers(parseThreadsList); } } } private void wakeUpAllParsers(List<Thread> parseThreadsList) { parseThreadsList.forEach(Object::notify); logger.info("Proxy finder threads notified"); } private void pauseAllParsers(List<Thread> parseThreadsList) { parseThreadsList.forEach(proxyParserThread->{ try { proxyParserThread.wait(); } catch (InterruptedException ignored) { } }); isPaused=true; logger.info("Proxy finder threads paused"); } private List<Thread> launchParseThreads() { List<Thread> result = new ArrayList<>(); parsers.forEach(parser->{ Thread thread = new Thread(parser); result.add(thread); thread.run(); }); logger.info("Proxy finder threads launched"); return result; } private void initParsers(Map<String, String> proxyMap) { parsers = new ArrayList<>(); parsers.add(new ProxypediaParser(proxyMap)); } }
true
74fa43c869932f675ef244dc035431602035239e
Java
lromito/toybox
/Functional/src/main/java/toybox/functional/throwing/consumers/ConsumerChainer.java
UTF-8
1,790
2.921875
3
[ "Apache-2.0" ]
permissive
package toybox.functional.throwing.consumers; import java.util.function.Consumer; import java.util.function.Function; import toybox.functional.throwing.AbstractChainer; public class ConsumerChainer<T> extends AbstractChainer<Consumer<T>, ThrowingConsumer<T>, ConsumerChainer<T>> implements ThrowingConsumer<T> { public ConsumerChainer(ThrowingConsumer<T> function) { super(function); } @Override public void doAccept(T value) throws Throwable { function.doAccept(value); } @Override public ConsumerChainer<T> orTryWith(ThrowingConsumer<T> other) { final ThrowingConsumer<T> f = t -> { try { function.doAccept(t); } catch (Error | RuntimeException e) { throw e; } catch (Throwable e) { other.doAccept(t); } }; return new ConsumerChainer<>(f); } @Override public ConsumerChainer<T> fallbackTo(Consumer<T> other) { final ThrowingConsumer<T> f = t -> { try { function.doAccept(t); } catch (Error | RuntimeException e) { throw e; } catch (Throwable e) { other.accept(t); } }; return new ConsumerChainer<>(f); } public ConsumerChainer<T> elseDoNothing() { final ThrowingConsumer<T> f = t -> { try { function.doAccept(t); } catch (Error | RuntimeException e) { throw e; } catch (Throwable e) { //DO nothing } }; return new ConsumerChainer<>(f); } public ConsumerChainer<T> elseThrow(Function<Throwable, ? extends Throwable> constructor) { final ThrowingConsumer<T> f = t -> { try { function.doAccept(t); } catch (Error | RuntimeException e) { throw e; } catch (Throwable e) { throw constructor.apply(e); } }; return new ConsumerChainer<>(f); } }
true
231e68284f8f8d044c779699922c1b1717ac2fb4
Java
hpbpad/hpbpad-Android
/src/com/justsystems/hpb/pad/util/Debug.java
UTF-8
634
2.34375
2
[]
no_license
package com.justsystems.hpb.pad.util; import android.content.Context; import android.util.Log; import android.widget.Toast; public final class Debug { //ログを出力するか private static final boolean DEBUG = false; public static void logd(String msg) { if (DEBUG) { logd("DEBUG", msg); } } public static void logd(String tag, String msg) { if (DEBUG) { Log.d(tag, msg); } } public static void toast(Context context, String msg) { if (DEBUG) { Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); } } }
true
0fe417fd9e2aa2f32ef6ce0552c5f4fa8ac30799
Java
Ani05/coffeeblend1
/src/main/java/com/example/coffeeblend/controller/DrinkController.java
UTF-8
1,837
2.203125
2
[]
no_license
package com.example.coffeeblend.controller; import com.example.coffeeblend.model.Category; import com.example.coffeeblend.model.Drink; import com.example.coffeeblend.repository.CategoryRepository; import com.example.coffeeblend.repository.DrinkRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; @Controller public class DrinkController { @Value("${image.upload.dir}") private String imagesUploadDir; @Autowired private DrinkRepository drinkRepository; @Autowired private CategoryRepository categoryRepository; @GetMapping("/addDrink") public String getDrink(ModelMap map){ map.addAttribute("categories", categoryRepository.findAll()); return "addDrink"; } @PostMapping("/addDrink") public String addDrink(@ModelAttribute Drink drink, @ModelAttribute Category category, @RequestParam("picture")MultipartFile file) throws IOException { String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename(); File picture= new File(imagesUploadDir+ File.separator+fileName); Category category1= categoryRepository.save(category); file.transferTo(picture); drink.setPicUrl(fileName); drink.setCategory(category1); drinkRepository.save(drink); return "redirect:/admin"; } }
true
86b54276353386c79cf445f6880201bc5cf1d284
Java
PiggyPiglet/RandomSpawn
/src/main/java/me/piggypiglet/randomspawn/mappers/ConfigMapper.java
UTF-8
1,799
2.421875
2
[ "MIT" ]
permissive
package me.piggypiglet.randomspawn.mappers; import me.piggypiglet.framework.file.framework.AbstractFileConfiguration; import me.piggypiglet.framework.file.framework.MutableFileConfiguration; import me.piggypiglet.framework.mapper.ObjectMapper; import me.piggypiglet.randomspawn.data.Config; import me.piggypiglet.randomspawn.data.options.Options; import me.piggypiglet.randomspawn.mappers.options.OptionsMapper; import me.piggypiglet.randomspawn.mappers.spawns.SpawnsMapper; import java.util.HashMap; import java.util.Map; // ------------------------------ // Copyright (c) PiggyPiglet 2019 // https://www.piggypiglet.me // ------------------------------ public final class ConfigMapper implements ObjectMapper<MutableFileConfiguration, Config> { private static final OptionsMapper OPTIONS_MAPPER = new OptionsMapper(); private static final SpawnsMapper SPAWNS_MAPPER = new SpawnsMapper(); private final MutableFileConfiguration config; public ConfigMapper(MutableFileConfiguration config) { this.config = config; } @SuppressWarnings("unchecked") @Override public Config dataToType(MutableFileConfiguration config) { final Options options = OPTIONS_MAPPER.dataToType(((AbstractFileConfiguration) config.getConfigSection("options")).getAll()); OptionsMapper.DEFAULT = options; return new Config( options, SPAWNS_MAPPER.dataToType((Map<String, Map<String, Object>>) config.get("data", new HashMap<>())) ); } @Override public MutableFileConfiguration typeToData(Config config) { this.config.set("options", OPTIONS_MAPPER.typeToData(config.getOptions())); this.config.set("data", SPAWNS_MAPPER.typeToData(config.getSpawns())); return this.config; } }
true
25afc277fc9bfc459cd676fecd3b58e1626b27e9
Java
LeviPorto/manager
/src/test/java/com/levi/manager/repository/PromotionRepositoryTest.java
UTF-8
5,954
2.09375
2
[]
no_license
package com.levi.manager.repository; import com.levi.manager.ManagerApplication; import com.levi.manager.domain.Promotion; import com.levi.manager.domain.Restaurant; import com.levi.manager.domain.enumeration.FoodCategory; import com.levi.manager.domain.enumeration.RestaurantCategory; import org.junit.After; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest(classes = ManagerApplication.class) @ActiveProfiles("test") public class PromotionRepositoryTest { @Autowired private PromotionRepository repository; @Autowired private RestaurantRepository restaurantRepository; private final Integer RESTAURANT_ID = 1; private final String RESTAURANT_COUNTRY = "First Country"; private final String RESTAURANT_CITY = "First City"; private final String RESTAURANT_EMAIL = "First Email"; private final RestaurantCategory RESTAURANT_CATEGORY = RestaurantCategory.ACAI; private final String RESTAURANT_STATE = "First State"; private final Double RESTAURANT_LATITUDE = 12.0; private final Double RESTAURANT_LONGITUDE = 14.0; private final Double RESTAURANT_DELIVERY_FEE = 0.01; private final String RESTAURANT_PHONE = "923392339"; private final Double RESTAURANT_COST = 3.2; private final String RESTAURANT_NAME = "First Name"; private final String RESTAURANT_CNPJ = "First CNPJ"; private final Integer SECOND_RESTAURANT_ID = 2; private final String SECOND_RESTAURANT_COUNTRY = "Second Country"; private final String SECOND_RESTAURANT_CITY = "Second City"; private final String SECOND_RESTAURANT_EMAIL = "Second Email"; private final RestaurantCategory SECOND_RESTAURANT_CATEGORY = RestaurantCategory.BRAZILIAN_FOOD; private final String SECOND_RESTAURANT_STATE = "Second State"; private final Double SECOND_RESTAURANT_LATITUDE = 11.0; private final Double SECOND_RESTAURANT_LONGITUDE = 11.0; private final Double SECOND_RESTAURANT_DELIVERY_FEE = 0.02; private final String SECOND_RESTAURANT_PHONE = "923392338"; private final Double SECOND_RESTAURANT_COST = 4.1; private final String SECOND_RESTAURANT_NAME = "Second Name"; private final String SECOND_RESTAURANT_CNPJ = "Second CNPJ"; private final String COMBO_NAME = "First Promotion Name"; private final Double COMBO_PRICE = 3.0; private final FoodCategory COMBO_FOOD_CATEGORY = FoodCategory.CONVENIENCE; private final String SECOND_COMBO_NAME = "Second Promotion Name"; private final Double SECOND_COMBO_PRICE = 4.0; private final FoodCategory SECOND_COMBO_FOOD_CATEGORY = FoodCategory.CANDY_AND_CAKE; private final Integer COMBO = 0; @After public void tearDown() { repository.deleteAll(); } @Test public void findByRestaurantId() { repository.save(givenFirstPromotion()); repository.save(givenSecondPromotion()); List<Promotion> promotionsByRestaurant = repository.findByRestaurantId(RESTAURANT_ID); Assert.assertEquals(promotionsByRestaurant.get(COMBO).getId(), RESTAURANT_ID); } private Promotion givenFirstPromotion() { Promotion promotion = new Promotion(); Restaurant restaurant = givenFirstRestaurant(); restaurantRepository.save(restaurant); promotion.setRestaurant(restaurant); promotion.setName(COMBO_NAME); promotion.setPrice(COMBO_PRICE); promotion.setCategory(COMBO_FOOD_CATEGORY); return promotion; } private Promotion givenSecondPromotion() { Promotion promotion = new Promotion(); Restaurant restaurant = givenSecondRestaurant(); restaurantRepository.save(restaurant); promotion.setRestaurant(restaurant); promotion.setName(SECOND_COMBO_NAME); promotion.setPrice(SECOND_COMBO_PRICE); promotion.setCategory(SECOND_COMBO_FOOD_CATEGORY); return promotion; } private Restaurant givenFirstRestaurant() { Restaurant restaurant = new Restaurant(); restaurant.setId(RESTAURANT_ID); restaurant.setCountry(RESTAURANT_COUNTRY); restaurant.setCity(RESTAURANT_CITY); restaurant.setEmail(RESTAURANT_EMAIL); restaurant.setCategory(RESTAURANT_CATEGORY); restaurant.setEmail(RESTAURANT_EMAIL); restaurant.setLatitude(RESTAURANT_LATITUDE); restaurant.setLongitude(RESTAURANT_LONGITUDE); restaurant.setDeliveryFee(RESTAURANT_DELIVERY_FEE); restaurant.setPhone(RESTAURANT_PHONE); restaurant.setCost(RESTAURANT_COST); restaurant.setName(RESTAURANT_NAME); restaurant.setCNPJ(RESTAURANT_CNPJ); restaurant.setState(RESTAURANT_STATE); return restaurant; } private Restaurant givenSecondRestaurant() { Restaurant restaurant = new Restaurant(); restaurant.setId(SECOND_RESTAURANT_ID); restaurant.setCountry(SECOND_RESTAURANT_COUNTRY); restaurant.setCity(SECOND_RESTAURANT_CITY); restaurant.setEmail(SECOND_RESTAURANT_EMAIL); restaurant.setCategory(SECOND_RESTAURANT_CATEGORY); restaurant.setEmail(SECOND_RESTAURANT_EMAIL); restaurant.setLatitude(SECOND_RESTAURANT_LATITUDE); restaurant.setLongitude(SECOND_RESTAURANT_LONGITUDE); restaurant.setDeliveryFee(SECOND_RESTAURANT_DELIVERY_FEE); restaurant.setPhone(SECOND_RESTAURANT_PHONE); restaurant.setCost(SECOND_RESTAURANT_COST); restaurant.setName(SECOND_RESTAURANT_NAME); restaurant.setCNPJ(SECOND_RESTAURANT_CNPJ); restaurant.setState(SECOND_RESTAURANT_STATE); return restaurant; } }
true
ecc1a12e13ffa3711b90f45f9976aca1c24ba5c9
Java
anthro2020/SPOJ-1
/3638. Word Counting/Main.java
UTF-8
587
3.15625
3
[]
no_license
import java.util.*; import java.io.*; class Main { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); String temp = sc.nextLine(); while(t-->0) { int c=1,best=0,prev=-1; String s[]=sc.nextLine().split(" "); for(int i=0;i<s.length;i++) { if(s[i].length()==0 ||s[i].equals("")||s[i].equals(null)) { continue; } if(s[i].length()==prev)c++; else { best=Math.max(c,best); c=1; prev=s[i].length(); } } best = Math.max(best, c); System.out.println(best); } } }
true
7aed9d4b8b04a90ee212d5203ee8e894b7e9e7bf
Java
usnistgov/iheos-toolkit2
/xdstools2/src/main/java/gov/nist/toolkit/xdstools2/client/tabs/actorConfigTab/SaveButtonClickHandler.java
UTF-8
3,005
2.125
2
[]
no_license
package gov.nist.toolkit.xdstools2.client.tabs.actorConfigTab; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import gov.nist.toolkit.xdstools2.client.PasswordManagement; import gov.nist.toolkit.xdstools2.client.Xdstools2; import gov.nist.toolkit.xdstools2.client.event.Xdstools2EventBus; import gov.nist.toolkit.xdstools2.client.util.ClientUtils; import gov.nist.toolkit.xdstools2.client.widgets.PopupMessage; class SaveButtonClickHandler implements ClickHandler { /** * */ private ActorConfigTab actorConfigTab; public SaveButtonClickHandler(ActorConfigTab actorConfigTab) { this.actorConfigTab = actorConfigTab; } public void onClick(ClickEvent event) { save(); } public boolean save() { // CurrentEditSite can be null if nothing is selected if (actorConfigTab.currentEditSite == null) { new PopupMessage("Site was not selected or nothing to save."); return false; } if (actorConfigTab.currentEditSite.getName().equals(actorConfigTab.newSiteName)) { new PopupMessage("You must give site a real name before saving"); return false; } if (!Xdstools2.getInstance().isSystemSaveEnabled()) { new PopupMessage("You don't have permission to save/update a System in this Test Session"); return false; } // if (actorConfigTab.currentEditSite.getOwner().equals(TestSession.GAZELLE_TEST_SESSION.getValue())) { // actorConfigTab.currentEditSite.setOwner(Xdstools2.getInstance().getTestSessionManager().getCurrentTestSession()); // } if (!actorConfigTab.currentEditSite.getOwner().equals(Xdstools2.getInstance().getTestSessionManager().getCurrentTestSession()) && !PasswordManagement.isSignedIn) { new PopupMessage("You cannot update a System you do not own"); return false; } actorConfigTab.currentEditSite.cleanup(); StringBuffer errors = new StringBuffer(); actorConfigTab.currentEditSite.validate(errors); if (errors.length() > 0) { new PopupMessage(errors.toString()); return false; } if (Xdstools2.getInstance().isSystemSaveEnabled()) { if (!actorConfigTab.currentEditSite.hasOwner()) actorConfigTab.currentEditSite.setOwner(actorConfigTab.currentEditSite.getTestSession().getValue()); actorConfigTab.saveSignedInCallback.onSuccess(true); ((Xdstools2EventBus) ClientUtils.INSTANCE.getEventBus()).fireActorsConfigUpdatedEvent(); actorConfigTab.loadExternalSites(); } else { if (Xdstools2.getInstance().multiUserModeEnabled && !Xdstools2.getInstance().casModeEnabled) { if (!actorConfigTab.currentEditSite.hasOwner()) actorConfigTab.currentEditSite.setOwner(actorConfigTab.currentEditSite.getTestSession().getValue()); actorConfigTab.saveSignedInCallback.onSuccess(true); actorConfigTab.loadExternalSites(); ((Xdstools2EventBus) ClientUtils.INSTANCE.getEventBus()).fireActorsConfigUpdatedEvent(); } else { new PopupMessage("You must be signed in as admin"); return false; } } return true; } }
true
ac8b3ae47c0246d6887557faeb39aaf6382d4959
Java
uddandam-vijaysekhar/Spring-JWTAuthentication
/src/main/java/com/Spring_JWTAuthentication/service/JwtUserDetailsService.java
UTF-8
787
2.140625
2
[]
no_license
package com.Spring_JWTAuthentication.service; import java.util.ArrayList; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; @Service public class JwtUserDetailsService implements UserDetailsService{ @Override public UserDetails loadUserByUsername(String userName) { if("vijaysekhar".equals(userName)) { return new User("vijaysekhar","$2a$10$pYW6Im5IBdiI/9o.OVSk7e6Rx23Gx9uFI8N1SShwrPbv54xoQr6yG", new ArrayList<>()); }else { throw new UsernameNotFoundException("User Name Not Found"); } } }
true
80029e7df540b369bd5d34964c60884bd1c5845d
Java
zhangjinwei417/crmProject
/src/com/bjsxt/dao/impl/UserDaoImpl.java
UTF-8
659
2.125
2
[]
no_license
package com.bjsxt.dao.impl; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.bjsxt.dao.UserDao; import com.bjsxt.pojo.User; /** * @author:jwzhang * @date:2017年9月4日下午1:15:48 */ public class UserDaoImpl implements UserDao { private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public List<User> fingAll() { Session session = sessionFactory.openSession(); List<User> list = session.createQuery("from User order by id").list(); return list; } }
true
eda904d83a367d8309a9a6d58469fe46df16b6a6
Java
eXtensibleCatalog/NCIP2-Toolkit
/core/tags/1.0/responder/src/main/java/org/extensiblecatalog/ncip/v2/responder/implprof1/NCIPServlet.java
UTF-8
10,154
1.898438
2
[ "MIT" ]
permissive
/** * Copyright (c) 2010 eXtensible Catalog Organization * * This program is free software; you can redistribute it and/or modify it * under the terms of the MIT/X11 license. The text of the license can be * found at http://www.opensource.org/licenses/mit-license.php. */ package org.extensiblecatalog.ncip.v2.responder.implprof1; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.extensiblecatalog.ncip.v2.common.ToolkitStatisticsBean; import org.extensiblecatalog.ncip.v2.service.MessageHandler; import org.extensiblecatalog.ncip.v2.service.NCIPInitiationData; import org.extensiblecatalog.ncip.v2.service.NCIPResponseData; import org.extensiblecatalog.ncip.v2.service.NCIPService; import org.extensiblecatalog.ncip.v2.service.ServiceException; import org.extensiblecatalog.ncip.v2.service.Translator; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; /** * This servlet implements an NCIP responder for HTTP and HTTPS transport according to * the NCIP Implementation Profile 1. */ public class NCIPServlet extends HttpServlet { private static final Logger LOG = Logger.getLogger(NCIPServlet.class); /** * Serial Id */ private static final long serialVersionUID = -8518989441219684952L; /** * Whether or not to include Java stacktraces in the NCIP Problem response elements. Doing so exposes * implementation details about the application code "behind" the responder, which an organization may not * want to do. */ protected static boolean includeStackTracesInProblemResponses = true; /** * The {@link Translator} instance used to translate network octets to instances of {@link NCIPInitiationData} * or {@link NCIPResponseData} for passing to the {@link NCIPService}. */ protected Translator translator; /** * The {@link MessageHandler} instance used to handle {@link NCIPInitiationData} objects representing incoming * NCIP initiation messages. */ protected MessageHandler messageHandler; /** * The {@link org.extensiblecatalog.ncip.v2.common.ToolkitStatisticsBean} instance used to report performance data. */ protected ToolkitStatisticsBean statisticsBean; /** * Construct a new instance of this servlet with no {@link MessageHandler} or {@link Translator} set; these * must be set before any NCIP messages are received. */ public NCIPServlet() { super(); } /** * Construct a new instance of this servlet with the provided {@link MessageHandler} and {@link Translator}. * * @param messageHandler the message handler for this responder instance * @param translator the translator for this responder instance */ public NCIPServlet(MessageHandler messageHandler, Translator translator) { super(); this.messageHandler = messageHandler; this.translator = translator; } /** * Set the {@link MessageHandler} for this responder instance * * @param messageHandler the message handler */ public void setMessageHandler(MessageHandler messageHandler) { this.messageHandler = messageHandler; } /** * Set the {@link Translator} for this responder instance * * @param translator the translator */ public void setTranslator(Translator translator) { this.translator = translator; } public static boolean includeStackTracesInProblemResponses() { return includeStackTracesInProblemResponses; } public static void includeStackTracesInProblemResponses(boolean includeStackTracesInProblemResponses) { NCIPServlet.includeStackTracesInProblemResponses = includeStackTracesInProblemResponses; } @Override public void init(ServletConfig config) throws ServletException { super.init(config); final WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext( config.getServletContext()); messageHandler = (MessageHandler)context.getBean("messageHandler"); translator = (Translator)context.getBean("translator"); statisticsBean = (ToolkitStatisticsBean)context.getBean("toolkitStatistics"); try { includeStackTracesInProblemResponses = (Boolean)context.getBean("includeStackTracesInProblemResponses"); } catch (NoSuchBeanDefinitionException e) { // Use default value } } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("application/xml; charset=\"utf-8\""); ServletInputStream inputStream = request.getInputStream(); NCIPInitiationData initiationData = null; try { initiationData = translator.createInitiationData(inputStream); } catch (ServiceException e) { returnException(response, "Exception creating the NCIPInitiationData object from the servlet's input stream.", e); } if (initiationData != null) { try { long initPerfSvcStartTime = System.currentTimeMillis(); NCIPResponseData responseData = messageHandler.performService(initiationData); long initPerfSvcEndTime = System.currentTimeMillis(); String serviceName = initiationData.getClass().getSimpleName().substring( 0, initiationData.getClass().getSimpleName().length() - "InitiationData".length()); statisticsBean.record(initPerfSvcStartTime, initPerfSvcEndTime, ToolkitStatisticsBean.RESPONDER_PERFORM_SERVICE_LABELS, serviceName); InputStream responseMsgInputStream = translator.createResponseMessageStream(responseData); try { int bytesAvailable = responseMsgInputStream.available(); byte[] responseMsgBytes = new byte[bytesAvailable]; try { int bytesRead = responseMsgInputStream.read(responseMsgBytes, 0, bytesAvailable); if (bytesRead != bytesAvailable) { returnProblem(response, "Bytes read from the response message's InputStream (" + bytesRead + ") are not the same as the number available (" + bytesAvailable + ")."); } response.setContentLength(responseMsgBytes.length); ServletOutputStream outputStream = response.getOutputStream(); outputStream.write(responseMsgBytes); outputStream.flush(); } catch (IOException e) { returnException(response, "Exception reading bytes from the response message's InputStream.", e); } } catch (IOException e) { returnException(response, "Exception getting the count of available bytes from the response message's InputStream.", e); } } catch (Exception e) { LOG.error("Exception creating a response message from the NCIPResponseData object.", e); returnException(response, "Exception creating a response message from the NCIPResponseData object.", e); } } } protected void returnException(HttpServletResponse response, String msg, Throwable e) throws ServletException { if (includeStackTracesInProblemResponses) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.append("Stack trace from NCIP responder: " + System.getProperties().get("line.separator")); e.printStackTrace(pw); returnProblem(response, msg + System.getProperty("line.separator") + sw.getBuffer().toString()); } else { returnProblem(response, msg); } } protected void returnProblem(HttpServletResponse response, String detail) throws ServletException { String problemMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ns1:NCIPMessage ns1:version=\"http://www.niso.org/ncip/v2_0/imp1/xsd/ncip_v2_0.xsd\"" + " xmlns:ns1=\"http://www.niso.org/2008/ncip\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xsi:schemaLocation=\"http://www.niso.org/2008/ncip ncip_v2_0.xsd\">\n" + " <ns1:Problem>\n" + " <ns1:ProblemType ns1:Scheme=\"http://www.niso.org/ncip/v1_0/schemes/processingerrortype/generalprocessingerror.scm\">Temporary Processing Failure</ns1:ProblemType>\n" + " <ns1:ProblemDetail>" + detail + "</ns1:ProblemDetail>\n" + " </ns1:Problem>\n" + "</ns1:NCIPMessage>"; byte[] problemMsgBytes = problemMsg.getBytes(); response.setContentLength(problemMsgBytes.length); try { ServletOutputStream outputStream = response.getOutputStream(); outputStream.write(problemMsgBytes); outputStream.flush(); } catch (IOException e) { throw new ServletException("Exception writing Problem response.", e); } } }
true
66ac76789dc44757188f97658d52c88d7ed33875
Java
klette/featureswitch
/src/main/java/us/klette/featureswitch/FeatureSpec.java
UTF-8
1,192
2.84375
3
[]
no_license
package us.klette.featureswitch; import java.util.Objects; public class FeatureSpec { private final String name; private final short percent; /** * Create a new FeatureSpec instance. * * @param name The name of the feature that is specified. Must be non-null and non-blank. * @param percent The percentage of calls that should have this feature enabled. */ public FeatureSpec(final String name, final short percent) { this.name = Objects.requireNonNull(name, "featurespec must be provided with a name"); this.percent = percent; if (name.isEmpty()) { throw new IllegalArgumentException("FeatureSpec name must be non-blank String"); } } public String getName() { return name; } public short getPercent() { return percent; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } FeatureSpec that = (FeatureSpec) other; return percent == that.percent && Objects.equals(name, that.name); } @Override public int hashCode() { return Objects.hash(name, percent); } }
true
53864d978781256ab224d2f9d7f2f47476aa663a
Java
Icefoxzhx/Omphalos
/src/AST/TypeNode.java
UTF-8
346
2.546875
3
[]
no_license
package AST; import Util.position; public class TypeNode extends ASTNode{ public String Type; public int dim; public TypeNode(position pos, String Type, int dim){ super(pos); this.Type=Type; this.dim=dim; } @Override public void accept(ASTVisitor visitor) { visitor.visit(this); } }
true
2f0be155b02a97f076ab1dd6a96b809fd6196ecd
Java
ValentinRadchenko/SqlCMD
/src/ua/com/juja/sqlcmd/Controller/Command/list.java
UTF-8
735
2.390625
2
[]
no_license
package ua.com.juja.sqlcmd.Controller.Command; import ua.com.juja.sqlcmd.Model.DataBaseManager; import ua.com.juja.sqlcmd.View.View; import java.util.Arrays; import java.util.Set; /** * Created by Valentin_R on 02.01.2018. */ public class list implements Command { DataBaseManager manager; View view; public list(DataBaseManager manager, View view){ this.manager = manager; this.view=view; } @Override public boolean canProcess(String command) { return command.equals("list"); } @Override public void process(String command) { Set<String>tableNames=manager.getTableNames(); String message=tableNames.toString(); view.write(message); } }
true
066ab5d1353ab430082f19591200f0890c8f9ba4
Java
LongFengFan/scan-dir-2-json
/src/main/java/com/yibin/nanxi/scandir2json/controller/DealFilesController.java
UTF-8
4,824
2.359375
2
[]
no_license
package com.yibin.nanxi.scandir2json.controller; import com.yibin.nanxi.scandir2json.service.DealFilesService; import com.yibin.nanxi.scandir2json.util.CommonUtils; import com.yibin.nanxi.scandir2json.vo.ResultVO; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * Created by LongFF on 2018/9/9 */ @RestController public class DealFilesController { @Autowired private DealFilesService dealFilesService; @Autowired private HttpServletRequest request; @RequestMapping("/zip") public ResultVO zipFiles(@RequestParam String orginDir , @RequestParam String destDir,@RequestParam String zipName){ Boolean aBoolean = dealFilesService.ZipFiles(orginDir,destDir,zipName); return aBoolean ? CommonUtils.success(true) : CommonUtils.error("false"); } @RequestMapping(value = "/download" ,method = RequestMethod.GET, produces = "application/json") public ResultVO download() throws IOException { OutputStream os = null; FileInputStream fis = null; BufferedInputStream bi = null; try { HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse(); // path是指欲下载的文件的路径。 String path = "F:/test/test.zip"; File file = new File(path); String fileName = file.getName(); // 设置response的Header response.setHeader("Content-Disposition", "attachment;filename=" + fileName); response.setContentLength((int) file.length()); response.setContentType("application/zip"); response.setCharacterEncoding("UTF-8"); fis = new FileInputStream(file); bi = new BufferedInputStream(fis); byte[] b = new byte[1024]; long i = 0; os = response.getOutputStream(); while (i< file.length()){ int j = bi.read(b,0,1024); i += j; os.write(b,0,1024); } os.flush(); } catch (IOException ex) { ex.printStackTrace(); }finally { if(fis != null){ fis.close(); } if(bi != null){ bi.close(); } if(os != null){ os.close(); } } return CommonUtils.success("ok"); } @RequestMapping("/download2") public HttpServletResponse download(@RequestParam String path, HttpServletResponse response) { try { // path是指欲下载的文件的路径。 File file = new File(path); // 取得文件名。 String filename = file.getName(); // 取得文件的后缀名。 String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase(); // 以流的形式下载文件。 InputStream fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); // 设置response的Header response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes())); response.addHeader("Content-Length", "" + file.length()); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (IOException ex) { ex.printStackTrace(); } return response; } @RequestMapping("/a.zip") public byte[] down3() throws IOException { String path = "F:/test/a.jpg"; File file = new File(path); String fileName = file.getName(); ByteArrayOutputStream bo = new ByteArrayOutputStream(); ZipOutputStream zipOut= new ZipOutputStream(bo); ZipEntry zipEntry = new ZipEntry(file.getName()); zipOut.putNextEntry(zipEntry); zipOut.write(IOUtils.toByteArray(new FileInputStream(file))); zipOut.closeEntry(); zipOut.close(); return bo.toByteArray(); } }
true
7827fc07b3e8628828d3213672e1bcffdcfa9816
Java
chizzy0909/AndrewProgramming-Java
/src/main/java/multithreading/volatileDemo/VolatileDemo.java
UTF-8
1,265
3.953125
4
[]
no_license
package multithreading.volatileDemo; public class VolatileDemo { public static volatile int n = 0; public synchronized static void increase1() { n++; } //这个测试用例,总共是20个线程, 每个限制都加加 10000 次, 最后的结果理论上是 20*10000=200,000 //但是实际上, 每次的结果都小于理论值。 public void testNotThreadSafe1() throws InterruptedException { Thread[] tmpThreads = new Thread[20]; for (int i = 0; i <= tmpThreads.length - 1; i++) { tmpThreads[i] = new Thread(new Runnable() { @Override public void run() { for (int j = 0; j < 10000; j++) { increase1(); } System.out.println("Over."); } }); tmpThreads[i].start(); } Thread.sleep(2000); System.out.println(n);//最后的结果理论上是 20*10000=200,000, } public static void main(String[] args) { VolatileDemo volatileDemo = new VolatileDemo(); try { volatileDemo.testNotThreadSafe1(); } catch (InterruptedException e) { e.printStackTrace(); } } }
true
3da864056c4ef6bf31d49f4aaacc5c5a898f0097
Java
ShivS01/Mulithreaded-Chat
/Server.java
UTF-8
7,902
2.984375
3
[]
no_license
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.net.*; import java.util.*; import javax.swing.*; public class Server { ArrayList clientOutputStream; ArrayList<String> users; JFrame jFrame; ServerSocket serverSock = null; Socket clientSock=null; Thread starter=null,listener=null; PrintWriter writer=null; public Server() { jFrame = new JFrame("Multithreaded Chat - Server Side"); jFrame.setSize(550,500); jFrame.add(jPanel); jFrame.setVisible(true); jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); b_end.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { tellEveryone("Server:is stopping and all users will be disconnected\n:Chat"); ta_chat.append("\nServer stopping..."); try { serverSock.close(); clientSock.close(); //to stop user inputs on server side starter.interrupt(); //to avoid exception when serversocket is closed } catch (IOException ex) { ex.printStackTrace(); } ta_chat.append("\n*Server has been closed.*"); } }); b_start.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ta_chat.setText(" "); starter = new Thread(new ServerStart()); //Initializes Thread to ServerStart starter.start(); //Starts thread of Server which runs parallel to other threads ta_chat.append("Server started..."); } }); b_users.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ta_chat.append("\n Online users : \n"); for (String current_user: users) { ta_chat.append(current_user); ta_chat.append("\n"); } } }); b_clear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ta_chat.setText(" "); } }); } public static void main(String args[]) { Server server = new Server(); } public void userAdd(String data) { String message, add = ": : Connect", done = "Server: :Done", name = data; ta_chat.append("\nBefore "+name+" added."); users.add(name); ta_chat.append("\nAfter "+name+" added. "); String tempList[] = new String[(users.size())]; users.toArray(tempList); for (String token:tempList) { message = (token + add); tellEveryone(message); } tellEveryone(done); } public void userRemove(String data) { String message, add = ": : Connect", done = "Server: :Done", name = data; users.remove(name); String tempList[] = new String[(users.size())]; users.toArray(tempList); for (String token:tempList) { message = (token + add); tellEveryone(message); } tellEveryone(done); } public void tellEveryone(String message) //Displays message to be sent to clients { Iterator it = clientOutputStream.iterator(); while (it.hasNext()) { try { writer = (PrintWriter) it.next(); writer.println(message); ta_chat.append("\nSending: "+ message + ""); writer.flush(); ta_chat.setCaretPosition(ta_chat.getDocument().getLength()); } catch (Exception ex) { ta_chat.append("\nError telling everyone. "); } } } public class ClientHandler implements Runnable { BufferedReader reader; Socket sock; PrintWriter client; public ClientHandler(Socket clientSocket, PrintWriter user) { client = user; try { sock = clientSocket; InputStreamReader isReader= new InputStreamReader(sock.getInputStream()); reader = new BufferedReader(isReader); } catch (Exception ex) { ta_chat.append("\nUnexpected Error... "); } } @Override public void run() { String message,connect = "Connect", disconnect = "Disconnect", chat = "Chat" ; String data[]; try { while((message= reader.readLine())!=null) { ta_chat.append("\nReceived: "+message+"\n"); data = message.split(":"); for (String token:data) { ta_chat.append(token+" "); } if(data[2].equals(connect)) { tellEveryone((data[0]+":"+data[1]+":"+chat)); userAdd(data[0]); } else if (data[2].equals(disconnect)) { tellEveryone((data[0]+":has disconnected."+":"+chat)); userRemove(data[0]); } else if (data[2].equals(chat)) { tellEveryone(message); } else { ta_chat.append("\nNo Conditions were met. "); } } } catch (Exception ex) { ta_chat.append(" Lost a Connection. "); ex.printStackTrace(); users.remove(client); } } } public class ServerStart implements Runnable { @Override public void run() { users = new ArrayList(); clientOutputStream = new ArrayList(); try { serverSock = new ServerSocket(2222); // clientSock = serverSock.accept(); //Input = new DataInputStream(clientSock.getInputStream()); // Output = new DataOutputStream(clientSock.getOutputStream()); while (true) { //serverSock=new ServerSocket(2222); clientSock = serverSock.accept(); writer = new PrintWriter(clientSock.getOutputStream()); clientOutputStream.add(writer); //writer from client is added here, thereby only o/p is diplayed on server frame listener = new Thread(new ClientHandler(clientSock, writer)); listener.start(); ta_chat.append("\nGot a connection. "); } } catch (IOException e) { ta_chat.append("\nError making a connection. "); e.printStackTrace(); } } } private javax.swing.JScrollPane jScrollPane; private javax.swing.JTextArea ta_chat; private JButton b_start; private JButton b_end; private JButton b_users; private JButton b_clear; private JPanel jPanel; }
true
45aac370f7bf1f987cce77bc75b529aef1066fd6
Java
bhagvatulanipun/spring-app
/src/main/java/com/javacodegeeks/example/MainHealthIndicator.java
UTF-8
398
2.125
2
[]
no_license
package com.javacodegeeks.example; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; @Component public class MainHealthIndicator implements HealthIndicator { @Override public Health health() { return Health.up().withDetail("version", "1.1.2").build(); } }
true
c935a68e0d5099b85681a44664850248bd388608
Java
bpweber/PracticeServer
/projects/PracticeServer/src/me/bpweber/practiceserver/LootChests.java
UTF-8
11,833
2.21875
2
[]
no_license
package me.bpweber.practiceserver; import java.io.File; import java.io.IOException; import java.util.HashMap; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Entity; import org.bukkit.entity.Horse; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitRunnable; public class LootChests implements Listener, CommandExecutor { static HashMap<Location, Integer> loot = new HashMap<Location, Integer>(); static HashMap<Location, Integer> respawn = new HashMap<Location, Integer>(); static HashMap<String, Location> creatingloot = new HashMap<String, Location>(); public void onEnable() { Main.log.info("[LootChests] has been enabled."); Bukkit.getServer().getPluginManager().registerEvents(this, Main.plugin); Bukkit.getServer().getPluginManager().registerEvents(this, Main.plugin); new BukkitRunnable() { public void run() { for (Location loc : loot.keySet()) { if (respawn.containsKey(loc)) { if (respawn.get(loc) >= 1) { respawn.put(loc, respawn.get(loc) - 1); } else { respawn.remove(loc); } } else { if (loc.getWorld().getChunkAt(loc).isLoaded()) if (!loc.getWorld().getBlockAt(loc).getType().equals(Material.GLOWSTONE)) loc.getWorld().getBlockAt(loc).setType(Material.CHEST); } } } }.runTaskTimer(Main.plugin, 20, 20); File file = new File(Main.plugin.getDataFolder(), "loot.yml"); YamlConfiguration config = new YamlConfiguration(); if (!(file.exists())) try { file.createNewFile(); } catch (IOException e1) { e1.printStackTrace(); } try { config.load(file); } catch (Exception e) { e.printStackTrace(); } for (String key : config.getKeys(false)) { int val = config.getInt(key); String[] str = key.split(","); World world = Bukkit.getWorld(str[0]); double x = Double.valueOf(str[1]); double y = Double.valueOf(str[2]); double z = Double.valueOf(str[3]); Location loc = new Location(world, x, y, z); loot.put(loc, val); } } public void onDisable() { Main.log.info("[LootChests] has been disabled."); File file = new File(Main.plugin.getDataFolder(), "loot.yml"); if (file.exists()) file.delete(); YamlConfiguration config = new YamlConfiguration(); for (Location loc : loot.keySet()) { String s = loc.getWorld().getName() + "," + (int) loc.getX() + "," + (int) loc.getY() + "," + (int) loc.getZ(); config.set(s, loot.get(loc)); try { config.save(file); } catch (IOException e) { e.printStackTrace(); } } } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (sender instanceof Player) { final Player p = (Player) sender; if (p.isOp()) { if (cmd.getName().equalsIgnoreCase("showloot")) { if (args.length != 1) { p.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "Incorrect Syntax. " + ChatColor.RED + "/showloot <radius>"); return true; } int radius = 0; try { radius = Integer.parseInt(args[0]); } catch (Exception e) { radius = 0; } Location loc = p.getLocation(); World w = loc.getWorld(); int i, j, k; int x = (int) loc.getX(); int y = (int) loc.getY(); int z = (int) loc.getZ(); int count = 0; for (i = -radius; i <= radius; i++) { for (j = -radius; j <= radius; j++) { for (k = -radius; k <= radius; k++) { loc = w.getBlockAt(x + i, y + j, z + k).getLocation(); if (loot.containsKey(loc)) { count++; loc.getBlock().setType(Material.GLOWSTONE); } } } } p.sendMessage(ChatColor.YELLOW + "Displaying " + count + " lootchests in a " + radius + " block radius..."); p.sendMessage(ChatColor.GRAY + "Break them to unregister the spawn point."); } if (cmd.getName().equalsIgnoreCase("hideloot")) { if (args.length != 1) { p.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "Incorrect Syntax. " + ChatColor.RED + "/hideloot <radius>"); return true; } int radius = 0; try { radius = Integer.parseInt(args[0]); } catch (Exception e) { radius = 0; } Location loc = p.getLocation(); World w = loc.getWorld(); int i, j, k; int x = (int) loc.getX(); int y = (int) loc.getY(); int z = (int) loc.getZ(); int count = 0; for (i = -radius; i <= radius; i++) { for (j = -radius; j <= radius; j++) { for (k = -radius; k <= radius; k++) { loc = w.getBlockAt(x + i, y + j, z + k).getLocation(); if (loot.containsKey(loc)) { if (loc.getBlock().getType() == Material.GLOWSTONE) { loc.getBlock().setType(Material.AIR); count++; } } } } } p.sendMessage( ChatColor.YELLOW + "Hiding " + count + " loot chests in a " + radius + " block radius..."); } } } return false; } public boolean isMobNear(Player p) { for (Entity ent : p.getNearbyEntities(6, 6, 6)) if (ent instanceof LivingEntity && !(ent instanceof Player) && !(ent instanceof Horse)) return true; return false; } HashMap<Location, Inventory> opened = new HashMap<Location, Inventory>(); HashMap<Player, Location> viewers = new HashMap<Player, Location>(); @EventHandler public void onChestClick(PlayerInteractEvent e) { if (e.getPlayer() instanceof Player) { Player p = (Player) e.getPlayer(); if (e.hasBlock()) { if (e.getClickedBlock().getType() == Material.CHEST) { Location loc = e.getClickedBlock().getLocation(); if (loot.containsKey(loc)) { e.setCancelled(true); if (e.getAction() == Action.RIGHT_CLICK_BLOCK) { if (isMobNear(p)) { p.sendMessage(ChatColor.RED + "It is " + ChatColor.BOLD + "NOT" + ChatColor.RED + " safe to open that right now."); p.sendMessage(ChatColor.GRAY + "Eliminate the monsters in the area first."); } else { if (!opened.containsKey(loc)) { Inventory inv = Bukkit.createInventory(null, 27, "Loot Chest"); inv.addItem(LootDrops.createLootDrop(loot.get(loc))); p.openInventory(inv); p.playSound(p.getLocation(), Sound.CHEST_OPEN, 1, 1); viewers.put(e.getPlayer(), loc); opened.put(loc, inv); } else { p.openInventory(opened.get(loc)); p.playSound(p.getLocation(), Sound.CHEST_OPEN, 1, 1); viewers.put(e.getPlayer(), loc); } } } else if (e.getAction() == Action.LEFT_CLICK_BLOCK) { if (isMobNear(p)) { p.sendMessage(ChatColor.RED + "It is " + ChatColor.BOLD + "NOT" + ChatColor.RED + " safe to open that right now."); p.sendMessage(ChatColor.GRAY + "Eliminate the monsters in the area first."); } else { if (opened.containsKey(loc)) { loc.getWorld().getBlockAt(loc).setType(Material.AIR); p.playSound(p.getLocation(), Sound.ZOMBIE_WOODBREAK, 0.5F, 1.2F); for (ItemStack is : opened.get(loc).getContents()) if (is != null) loc.getWorld().dropItemNaturally(loc, is); opened.remove(loc); int tier = loot.get(loc); respawn.put(loc, 60 * tier); for (Player v : viewers.keySet()) { if (viewers.get(v).equals(loc)) { viewers.remove(v); v.closeInventory(); v.playSound(v.getLocation(), Sound.ZOMBIE_WOODBREAK, 0.5F, 1.2F); v.playSound(v.getLocation(), Sound.CHEST_CLOSE, 1, 1); } } } else { loc.getWorld().getBlockAt(loc).setType(Material.AIR); loc.getWorld().playEffect(loc, Effect.STEP_SOUND, Material.WOOD); p.playSound(p.getLocation(), Sound.ZOMBIE_WOODBREAK, 0.5F, 1.2F); loc.getWorld().dropItemNaturally(loc, LootDrops.createLootDrop(loot.get(loc))); int tier = loot.get(loc); respawn.put(loc, 60 * tier); for (Player v : viewers.keySet()) { if (viewers.get(v).equals(loc)) { viewers.remove(v); v.closeInventory(); v.playSound(v.getLocation(), Sound.ZOMBIE_WOODBREAK, 0.5F, 1.2F); v.playSound(v.getLocation(), Sound.CHEST_CLOSE, 1, 1); } } } } } } else { if (!p.isOp()) { e.setCancelled(true); p.sendMessage(ChatColor.GRAY + "The chest is locked."); } } } else if (e.getClickedBlock().getType() == Material.GLOWSTONE) { if (p.isOp()) { Location loc = e.getClickedBlock().getLocation(); if (e.getAction() == Action.RIGHT_CLICK_BLOCK) { if (getPlayerTier(p) > 0) { e.setCancelled(true); loot.put(loc, getPlayerTier(p)); p.sendMessage( "" + ChatColor.GREEN + ChatColor.BOLD + " *** LOOT CHEST CREATED ***"); loc.getWorld().getBlockAt(loc).setType(Material.CHEST); loc.getWorld().playEffect(loc, Effect.STEP_SOUND, Material.CHEST); } } } } } } } @EventHandler public void onBlockBreak(BlockBreakEvent e) { Player p = e.getPlayer(); if (p.isOp()) { if (e.getBlock().getType().equals(Material.GLOWSTONE)) { Location loc = e.getBlock().getLocation(); if (loot.containsKey(loc)) { loot.remove(loc); p.sendMessage("" + ChatColor.RED + ChatColor.BOLD + " *** LOOT CHEST REMOVED ***"); loc.getWorld().playEffect(loc, Effect.STEP_SOUND, Material.CHEST); } } } } public static int getPlayerTier(Player e) { ItemStack is = e.getItemInHand(); if (is != null && is.getType() != Material.AIR) { if (is.getType().name().contains("WOOD_")) return 1; if (is.getType().name().contains("STONE_")) return 2; if (is.getType().name().contains("IRON_")) return 3; if (is.getType().name().contains("DIAMOND_")) return 4; if (is.getType().name().contains("GOLD_")) return 5; } return 0; } @EventHandler public void onCloseChest(InventoryCloseEvent e) { if (e.getPlayer() instanceof Player) { Player p = (Player) e.getPlayer(); if (e.getInventory().getName().contains("Loot Chest")) { if (viewers.containsKey(p)) { Location loc = viewers.get(p); viewers.remove(p); p.playSound(p.getLocation(), Sound.CHEST_CLOSE, 1, 1); boolean isempty = true; for (ItemStack itms : e.getInventory().getContents()) if (itms != null && itms.getType() != Material.AIR) isempty = false; if (isempty) { loc.getWorld().getBlockAt(loc).setType(Material.AIR); loc.getWorld().playEffect(loc, Effect.STEP_SOUND, Material.WOOD); p.playSound(p.getLocation(), Sound.ZOMBIE_WOODBREAK, 0.5F, 1.2F); opened.remove(loc); int tier = loot.get(loc); respawn.put(loc, 60 * tier); for (Player v : viewers.keySet()) { if (viewers.get(v).equals(loc)) { viewers.remove(v); v.closeInventory(); v.playSound(v.getLocation(), Sound.ZOMBIE_WOODBREAK, 0.5F, 1.2F); v.playSound(v.getLocation(), Sound.CHEST_CLOSE, 1, 1); } } } } } } } }
true
bfc0dfc7d9304e232f4f60913e10f3247f48bb5a
Java
meksula/computer-alchemist
/src/main/java/com/computeralchemist/domain/creator/compatibility/concreteCheckers/GraphicsCardChecker.java
UTF-8
1,043
2.46875
2
[]
no_license
package com.computeralchemist.domain.creator.compatibility.concreteCheckers; import com.computeralchemist.domain.components.ComputerComponent; import com.computeralchemist.domain.components.gpu.GraphicsCard; import com.computeralchemist.domain.creator.compatibility.CompatibilityChecker; import com.computeralchemist.domain.creator.setTypes.ComputerSet; import java.util.List; /** * @Author * Karol Meksuła * 15-04-2018 * */ public class GraphicsCardChecker extends CompatibilityChecker { @Override public boolean compatibilityCheck(ComputerSet set, ComputerComponent component) { GraphicsCard graphicsCard = (GraphicsCard) component; final String MAIN_CONNECTOR = graphicsCard.getGraphicsCardParameters().getMainConnectorType(); final List<String> MOBO_CONNECTORS = set.getMotherboard().getMotherboardParameters().getOtherSockets(); for (String connector : MOBO_CONNECTORS) { if (connector.contains(MAIN_CONNECTOR)) return true; } return false; } }
true
5e995e8753ca235b0b35ac626660b7030e9bae6a
Java
mj-Fairy/xiaoXian
/Xiaoxian/src/cn/Xiaoxian/servlet/addBasketServlet.java
UTF-8
1,115
2.359375
2
[]
no_license
package cn.Xiaoxian.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.Xiaoxian.dao.addBasket; import cn.Xiaoxian.dao.impl.addBasketImpl; @WebServlet("/addBasketServlet") public class addBasketServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); addBasket add = new addBasketImpl(); String name = request.getParameter("name"); Double price = Double.parseDouble(request.getParameter("price")); add.addPro("果篮" + "(" + name + ")", "" + name, price, "guolan.jpg"); int id = add.getId(); out.print(id); } }
true
de3474f861f2cd52738af9b45e05199ecc305253
Java
Volax-Development/OpalCraftCore
/src/fr/volax/opalcraft/listeners/NoDeathEvent.java
UTF-8
901
2.015625
2
[ "MIT" ]
permissive
package fr.volax.opalcraft.listeners; import fr.volax.opalcraft.utils.Utils; import net.minecraft.server.v1_8_R3.PacketPlayInClientCommand; import org.bukkit.Bukkit; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; public class NoDeathEvent implements Listener { @EventHandler public void noDeathEvent(PlayerDeathEvent event){ Bukkit. getScheduler (). runTaskLater (Utils.getInstance(), new Runnable () { @Override public void run() { PacketPlayInClientCommand paquet = new PacketPlayInClientCommand (PacketPlayInClientCommand.EnumClientCommand.PERFORM_RESPAWN); ((CraftPlayer) event.getEntity()).getHandle().playerConnection.a(paquet); } }, 5L); } }
true
d552efddc3a36154b6d9c96dcd43114e0a7d18d0
Java
RudraNune/WalletHub2
/src/main/java/com/qa/pages/LoginPage.java
UTF-8
998
2.59375
3
[]
no_license
package com.qa.pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import com.qa.base.TestBase; public class LoginPage extends TestBase { WebElement Loginbtn; WebElement emailaddress; WebElement password; // Below constructor initiates the webelements on the Login page public LoginPage(WebDriver driver) { this.driver = driver; Loginbtn = driver.findElement(By.xpath("//*[@id='join-login']/form/div[4]/button[2]")); emailaddress = driver.findElement(By.xpath("//input[@placeholder='Email Address']")); password = driver.findElement(By.xpath("//input[@placeholder='Password']")); } // Login Method takes arguments as email address and password of the user to // Login // And returns the object of insurance company page to be reviewed public ProjHomePage Login(String email, String pass) { emailaddress.sendKeys(email); password.sendKeys(pass); Loginbtn.click(); return new ProjHomePage(driver); } }
true
d4b9e46b06fcee7528c872d56ad1de699529ce71
Java
Jaylim94/DSAassignment092015
/src/adt/StationList.java
UTF-8
6,082
3.15625
3
[]
no_license
package adt; import entity.Station; public class StationList<T> implements StationListInterface<T>{ private Node start; private Node end ; private int size; private int playerPosition; /* Constructor */ public StationList() { start = null; end = null; size = 0; playerPosition = 0; } public void resetRacePath() { ((Station)getAtPosition(playerPosition)).updatePlayerPosition(false); playerPosition = 0; } public int getPlayerPosition() { return playerPosition; } public boolean isPlayerAtStarting() { return playerPosition == 0; } /* Function to check if list is empty */ public boolean isEmpty() { return start == null; } /* Function to get size of list */ public int getSize() { return size; } /* Function to insert element at begining */ public void insertAtStart(T val) { Node nptr = new Node(val, null, null); if(start == null) { start = nptr; end = start; } else { start.setLinkPrevious(nptr); nptr.setLinkNext(start); start = nptr; } size++; } /* Function to insert element at end */ public void insertAtEnd(T val) { Node nptr = new Node(val, null, null); if(start == null) { start = nptr; end = start; } else { nptr.setLinkPrevious(end); end.setLinkNext(nptr); end = nptr; } size++; } /* Function to insert element at position */ public void insertAtPosition(T val , int pos) { Node nptr = new Node(val, null, null); if (pos == 1) { insertAtStart(val); return; } Node ptr = start; for (int i = 2; i <= size; i++) { if (i == pos) { Node tmp = ptr.getLinkNext(); ptr.setLinkNext(nptr); nptr.setLinkPrevious(ptr); nptr.setLinkNext(tmp); tmp.setLinkPrevious(nptr); } ptr = ptr.getLinkNext(); } size++ ; } public T getAtPosition(int pos){ if(pos < 0){ return null; } if(pos == 0){ return (T)start.getData(); }else{ Node pointer = start.getLinkNext(); for(int i = 1; i < pos; i ++){ if(pointer.getLinkNext()== null) return null; pointer = pointer.getLinkNext(); } return (T) pointer.getData(); } } /* Function to delete node at position */ public void deleteAtPosition(int pos) { if (pos == 1) { if (size == 1) { start = null; end = null; size = 0; return; } start = start.getLinkNext(); start.setLinkPrevious(null); size--; return ; } if (pos == size) { end = end.getLinkPrevious(); end.setLinkNext(null); size-- ; } Node ptr = start.getLinkNext(); for (int i = 2; i <= size; i++) { if (i == pos) { Node p = ptr.getLinkPrevious(); Node n = ptr.getLinkNext(); p.setLinkNext(n); n.setLinkPrevious(p); size-- ; return; } ptr = ptr.getLinkNext(); } } /* Function to display status of list */ public void display() { if (size == 0) { System.out.print("empty\n"); return; } if (start.getLinkNext() == null) { System.out.print(((Station)start.getData()).display()+ "\n"); return; } Node ptr; System.out.print(((Station)start.getData()).display()+ "\n"); ptr = start.getLinkNext(); while (ptr.getLinkNext() != null) { System.out.print(((Station)ptr.getData()).display()+ "\n"); ptr = ptr.getLinkNext(); } System.out.print(((Station)ptr.getData()).display()+ "\n"); } public void updatePath(int rollDice) { T currStation = getAtPosition(playerPosition); T nextStation = getAtPosition(playerPosition + rollDice); ((Station)currStation).updatePlayerPosition(false); ((Station)nextStation).updatePlayerPosition(true); playerPosition+=rollDice; } class Node { protected T data; protected Node next, prev; /* Constructor */ public Node() { next = null; prev = null; data = null; } /* Constructor */ public Node(T d, Node n, Node p) { data = d; next = n; prev = p; } /* Function to set link to next node */ public void setLinkNext(Node n) { next = n; } /* Function to set link to previous node */ public void setLinkPrevious(Node p) { prev = p; } /* Funtion to get link to next node */ public Node getLinkNext() { return next; } /* Function to get link to previous node */ public Node getLinkPrevious() { return prev; } /* Function to set data to node */ public void setData(T d) { data = d; } /* Function to get data from node */ public T getData() { return data; } } }
true
e5cd7e6dc47e5b8fd52751463d28f8085e600e00
Java
palava/palava-ipc
/src/main/java/de/cosmocode/palava/ipc/IpcSessionScope.java
UTF-8
1,642
2.0625
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2010 CosmoCode GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.cosmocode.palava.ipc; import com.google.common.base.Preconditions; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Scope; import de.cosmocode.palava.core.inject.Providers; import de.cosmocode.palava.scope.AbstractScope; import de.cosmocode.palava.scope.ScopeContext; /** * Custom {@link Scope} implementation for one {@linkplain IpcSession session}. * * @author Willi Schoenborn * @author Tobias Sarnowski */ final class IpcSessionScope extends AbstractScope { private Provider<IpcConnection> currentConnection = Providers.nullProvider(); @Inject void setCurrentConnection(@Current Provider<IpcConnection> currentConnection) { this.currentConnection = Preconditions.checkNotNull(currentConnection, "CurrentConnection"); } private IpcSession getSession(IpcConnection connection) { return connection == null ? null : connection.getSession(); } @Override public ScopeContext get() { return getSession(currentConnection.get()); } }
true
b6fd13ea3ed74687ac67f4f17bb6366f75e7d891
Java
choucalate/music
/app/src/main/java/com/model/RecManager.java
UTF-8
5,342
2.515625
3
[]
no_license
package com.model; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Set; import android.content.Context; import android.util.Log; public class RecManager { Context mCtx; private String filename = "Rec1.txt"; public RecManager(Context ctx) { mCtx = ctx; } // here we set the thing to be serialized to a file // public void setSerialized(String fileName, ArrayList<ArrayList<RecNotes>> c) // throws IOException { // Context context = this.mCtx; // FileOutputStream fos; // ObjectOutputStream os = null; // try { // fos = context.openFileOutput(fileName, Context.MODE_PRIVATE); // os = new ObjectOutputStream(fos); // } catch (Exception e) { // // TODO Auto-generated catch block // Log.e("winecontroller", " exception in here"); // e.printStackTrace(); // } // os.writeObject(c); // os.close(); // } //HashMap implementation public void setSerialized(String fileName, HashMap<String , ArrayList<RecNotes>> c) throws IOException { Context context = this.mCtx; FileOutputStream fos; ObjectOutputStream os = null; try { fos = context.openFileOutput(fileName, Context.MODE_PRIVATE); os = new ObjectOutputStream(fos); } catch (Exception e) { // TODO Auto-generated catch block Log.e("winecontroller", " exception in here"); e.printStackTrace(); } os.writeObject(c); os.close(); } /*public ArrayList<ArrayList<RecNotes>> getSerialized(String fileName) throws IOException { Context context = this.mCtx; FileInputStream fis = context.openFileInput(fileName); ObjectInputStream is = new ObjectInputStream(fis); ArrayList<ArrayList<RecNotes>> simpleClass = null; try { simpleClass = (ArrayList<ArrayList<RecNotes>>) is.readObject(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch(IOException io) { io.printStackTrace(); } is.close(); return simpleClass; }*/ //HashMap implementation public HashMap<String, ArrayList<RecNotes>> getSerialized(String fileName) throws IOException { Context context = this.mCtx; FileInputStream fis = context.openFileInput(fileName); ObjectInputStream is = new ObjectInputStream(fis); HashMap<String, ArrayList<RecNotes>> simpleClass = null; try { simpleClass = (HashMap<String, ArrayList<RecNotes>>) is.readObject(); //can this^^be a problem??? } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch(IOException io) { io.printStackTrace(); } is.close(); return simpleClass; } public HashMap<String, ArrayList<RecNotes>> loadRec(){ //String name = ""+rn.size(); //HashMap<String, ArrayList<RecNotes>> db = new HashMap<String, ArrayList<RecNotes>>(); try { HashMap<String, ArrayList<RecNotes>> rn = getSerialized(filename); Set<String> rnkeys = rn.keySet(); for (String st : rnkeys) Log.i("option", "printing rn: "+ st + " " +rn.get(st).toString()); return rn; }catch (Exception e){ e.printStackTrace(); return new HashMap<String, ArrayList<RecNotes>>(); } } public void saveRec(ArrayList<RecNotes> newrec, String origin) { HashMap<String, ArrayList<RecNotes>> database = new HashMap<String, ArrayList<RecNotes>>(); try { Log.e("serialize", "starting serializing"); database = getSerialized(filename); String dfnam = "MyJam " + (database.size() + 1) + origin; /*if (rn == null) { Log.i("option", "rn was null, making new"); rn = new HashMap<String, ArrayList<RecNotes>>(); }*/ database.put(dfnam, newrec); setSerialized(filename, database); Log.e("serialize", "finished serializing"); } catch (IOException e) { // if (database == null) { // Log.i("option", "rn was null, making new"); // database = new HashMap<String, ArrayList<RecNotes>>(); // } database = new HashMap<String, ArrayList<RecNotes>>(); String dfnam = "MyJam " + (database.size() + 1) + origin; database.put(dfnam, newrec); try { setSerialized(filename, database); } catch (IOException e1) { Log.e("option", "failed to even set serialize??"); // TODO Auto-generated catch block e1.printStackTrace(); } // TODO Auto-generated catch block Log.e("option", "failed to get serialized"); e.printStackTrace(); } } //update public void renamRec (String newnam, String oldnam){ try { HashMap<String, ArrayList<RecNotes>> rn = getSerialized(filename); ArrayList<RecNotes> record_cp = rn.get(oldnam); //save recording rn.remove(oldnam); // remove recording rn.put(newnam, record_cp); //add recording with new name setSerialized(filename, rn); } catch (IOException e1) { Log.e("option", "failed to even set serialize??"); // TODO Auto-generated catch block e1.printStackTrace(); } } //delete public void delRec (String target){ try { HashMap<String, ArrayList<RecNotes>> rn = getSerialized(filename); rn.remove(target); setSerialized(filename, rn); } catch (IOException e1) { Log.e("option", "failed to even set serialize??"); // TODO Auto-generated catch block e1.printStackTrace(); } } }
true
33e9ce453a99573d1b2efca2054f4dd82fe53c04
Java
yamal-coding/TimeBank
/PaymentProtocolDemo/src/timebank/model/files/network/persistent/DHTEntry.java
UTF-8
263
1.640625
2
[ "MIT" ]
permissive
package timebank.model.files.network.persistent; import rice.p2p.commonapi.Id; import rice.p2p.past.ContentHashPastContent; /** * * @author yamal * */ public class DHTEntry extends ContentHashPastContent { public DHTEntry(Id myId) { super(myId); } }
true
7d5dc90fecb2bf0f958ade7268ec5c0c24ba93e7
Java
nurhidayat-agung/SimpleVideoGalleryPlayer
/app/src/main/java/com/example/kazt/galery/VideoPlayer.java
UTF-8
719
2.09375
2
[]
no_license
package com.example.kazt.galery; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.MediaController; import android.widget.VideoView; public class VideoPlayer extends AppCompatActivity { VideoView vvPlayer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video_player); vvPlayer = (VideoView) findViewById(R.id.vv_player); String path = getIntent().getStringExtra("video"); vvPlayer.setVideoPath(path); vvPlayer.setMediaController(new MediaController(this)); vvPlayer.requestFocus(); vvPlayer.start(); } }
true
9d244fce8906497e5d4d07033252f562499aaffd
Java
Viniprogram/School
/Documents/Cópia Projetos NetBeans/NetBeansProjects/SisEscola/src/br/com/sisescola/dao/TurmaDAO.java
UTF-8
2,651
2.84375
3
[]
no_license
package br.com.sisescola.dao; import br.com.sisescola.accessories.ConexaoEscola; import br.com.sisescola.transferencia.Turma; import java.sql.*; import java.util.Vector; public class TurmaDAO { private ConexaoEscola ce; public TurmaDAO()throws Exception{ ce = new ConexaoEscola(); } public void incluir(Turma t)throws Exception{ PreparedStatement pst = ce.getConexao().prepareStatement( "INSERT INTO TURMA(NOME) " + "VALUES(?,?)", Statement.RETURN_GENERATED_KEYS); pst.setString(1, t.getNome()); pst.executeUpdate(); ce.confirmarTransacao(); ResultSet rs = pst.getGeneratedKeys(); if(rs.next()) t.setCodtur(rs.getInt(1)); rs.close(); pst.close(); } public void alterar(Turma t)throws Exception{ PreparedStatement pst = ce.getConexao().prepareStatement( "UPDATE TURMA SET NOME = ? WHERE CODTUR = ?"); pst.setString(1, t.getNome()); pst.setInt(3, t.getCodtur()); pst.executeUpdate(); pst.close(); ce.confirmarTransacao(); } public void excluir(int codtur)throws Exception{ PreparedStatement pst = ce.getConexao().prepareStatement( "DELETE FROM TURMA WHERE CODTUR = ?"); pst.setInt(1, codtur); pst.executeUpdate(); pst.close(); ce.confirmarTransacao(); } public ResultSet carregarGrade()throws Exception{ Statement stm = ce.getConexao().createStatement(); return stm.executeQuery( "SELECT CODTUR, NOME FROM TURMA ORDER BY NOME"); } public Vector<Turma> carregarCombo()throws Exception{ Statement stm = ce.getConexao().createStatement(); ResultSet rs = stm.executeQuery( "SELECT CODTUR, NOME FROM TURMA ORDER BY NOME"); Vector<Turma> v = new Vector<Turma>(); while(rs.next()) v.add(new Turma(rs.getInt("CODTUR"), rs.getString("NOME"))); return v; } public Turma pesquisar(int codtur)throws Exception{ PreparedStatement pst = ce.getConexao().prepareStatement( "SELECT * FROM TURMA WHERE CODTUR = ?"); pst.setInt(1, codtur); ResultSet rs = pst.executeQuery(); if(!rs.next())return null; return new Turma(rs.getInt("CODTUR"), rs.getString("NOME")); } public Turma pesquisar(String codtur)throws Exception{ return pesquisar(Integer.parseInt(codtur)); } }
true
b5cb6599697c83baf4078ada8d08294950260c36
Java
libing070/vj
/doc/main/java/com/hpe/cmca/job/v2/NotiFileAutoProcessorForYWYJ.java
UTF-8
20,243
1.671875
2
[]
no_license
/** * com.hpe.cmca.job.v2.NotiFileAutoProcessorForWord.java * Copyright (c) 2018 xx Development Company, L.P. * All rights reserved. */ package com.hpe.cmca.job.v2; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.hpe.cmca.common.BaseObject; import com.hpe.cmca.finals.Constants; import com.hpe.cmca.finals.Dict; import com.hpe.cmca.pojo.BgxzData; import com.hpe.cmca.service.BgxzService; import com.hpe.cmca.service.YwyjService; import com.hpe.cmca.util.ExceptionTool; import com.hpe.cmca.util.FileUtil; import com.hpe.cmca.util.FtpUtil; /** * <pre> * Desc: * @author hufei * @refactor hufei * @date 2018-3-31 下午7:04:06 * @version 1.0 * * REVISIONS: * Version Date Author Description * ------------------------------------------------------------------- * 1.0 2018-3-31 hufei 1. Created this class. * </pre> */ public class NotiFileAutoProcessorForYWYJ extends BaseObject implements IFileGenProcessor { @Autowired private YwyjService ywyjService; @Autowired private JdbcTemplate jdbcTemplate; // @Autowired // protected ConcernFileGenService concernFileGenService = null; // @Autowired // protected ConcernService concernService = null; @Autowired protected BgxzService bgxzService = null; @Autowired protected Dict dict = null; protected SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日"); protected SimpleDateFormat yyyyMMddHHmmssSdf = new SimpleDateFormat("yyyyMMddHHmmss"); protected boolean validateRequest(String audTrm, String subjectId, String focusCd, int prvdId, Map<String, Object> request, int modelNotifyId, Map<String, Object> configInfo) { int focusCdsCount = 1;//Integer.parseInt(ywyjService.getPointNumber(subjectId).get("sjqd_point_Number").toString()); List<Map<String,Object>> concernList = ywyjService.selectFinishedConcerns(null, audTrm, subjectId, prvdId); if (concernList.size() < focusCdsCount) {// 代表该省的5个有价卡关注点并未都执行完毕,所以不需要生成审计报告 return false; } return true; } public void genFile(String audTrm, String subjectId, String totalFocusCds, String focusCd, int prvdId, Map<String, Object> request, int modelNotifyId, Map<String, Object> configInfo, Boolean useChineseName, Boolean flag) { this.logger.debug("#### 生成文件:subjectId=" + subjectId + ",汇总关注点totalFocusCds=" + totalFocusCds + ",focusCd=" + focusCd + ",prvdId=" + prvdId + ",audTrm=" + audTrm); if (!validateRequest(audTrm, subjectId, totalFocusCds, prvdId, request, modelNotifyId, configInfo)) { this.logger.error("#### 不满足生成文件的条件,专题处理器无法启动:subjectId=" + subjectId + ",汇总关注点totalFocusCds=" + totalFocusCds + ",focusCd=" + focusCd + ",prvdId=" + prvdId + ",audTrm=" + audTrm); return; } try { if (prvdId != Constants.ChinaCode) {// 生成省csv,doc genPrvdFile(audTrm, subjectId, totalFocusCds, focusCd, prvdId, request, modelNotifyId, configInfo, useChineseName, flag); return; } genAllFile(audTrm, subjectId, focusCd, prvdId, request, modelNotifyId, configInfo, useChineseName);// 生成全国视角的文件doc } finally { this.logger.info("#### 模型数据文件生成完毕"); // concernFileGenService.updateFileRequestExecCount(request); ywyjService.updateFileRequestExecCountBysubjectNew(request);// 按专题更新执行次数 } } /** * <pre> * Desc 生成全国的清单文件zip,doc汇总报告,ftp file,update status,delete file * @author GuoXY * @refactor GuoXY * @date 20161019 * </pre> */ public void genAllFile(String audTrm, String subjectId, String focusCd, int prvdId, Map<String, Object> request, int modelNotifyId, Map<String, Object> configInfo, Boolean useChineseName) { File docFile = null,excelFile =null; try { this.logger.debug("#### 生成全国文件:audTrm=" + audTrm + ",focusCd=" + focusCd); String localFilePath = getLocalFilePath(); // 第三步:从数据库中查询已生成的31各省级审计明细文件名,进行打包 List<String> fileCsvList = ywyjService.selectAuditResultFile(audTrm, subjectId, focusCd, Constants.Model.FileType.AUD_DETAIL); String csvZipFileName = buildFileName(Constants.Model.FileType.AUD_DETAIL, audTrm, subjectId, focusCd, prvdId, useChineseName); csvZipFileName = csvZipFileName.replaceAll("csv", "zip"); FileUtil.zipFile(localFilePath, localFilePath, csvZipFileName, fileCsvList); File csvZipFile = new File(localFilePath + File.separator + csvZipFileName); // 第三步:上传31省的Csv.zip,更新notify请求记录状态为3 Map<String, Object> csvFtpPutResult = transferFileToFtpServer(Constants.Model.FileType.AUD_DETAIL, audTrm, subjectId, focusCd, Constants.ChinaCode, csvZipFile, useChineseName); csvFtpPutResult.put("createTime", request.get("csvFileGenTime")); request.put("csvFileFtpTime", new Date()); // updateFileRequestStatus(modelNotifyId, audTrm, subjectId, focusCd, prvdId, request, Constants.Model.FileRequestStatus.CSV_FTP_FINISHED); updateFileRequestStatusBySubjectId(modelNotifyId, audTrm, subjectId, focusCd, prvdId, request, Constants.Model.FileRequestStatus.CSV_FTP_FINISHED); csvFtpPutResult.put("loginAccount", configInfo.get("loginAccount")); csvFtpPutResult.put("userName", configInfo.get("userName")); csvFtpPutResult.put("num", request.get("num")); // 第五步:删除HPMGR.busi_report_file表中原文件,插入新生成的csv文件记录; insertReportFile(modelNotifyId, audTrm, subjectId, focusCd, prvdId, Constants.Model.FileType.AUD_DETAIL, csvFtpPutResult,configInfo); // 第七步:更新notify请求记录状态为5 // updateFileRequestStatus(modelNotifyId, audTrm, subjectId, focusCd, prvdId, request, Constants.Model.FileRequestStatus.File_FINISHED); updateFileRequestStatusBySubjectId(modelNotifyId, audTrm, subjectId, focusCd, prvdId, request, Constants.Model.FileRequestStatus.File_FINISHED); } catch (Exception e) { logger.error("#### " + e.getMessage(), e); throw new RuntimeException("生成文件异常", e); } finally { String isDelLocalFile = StringUtils.trimToEmpty(propertyUtil.getPropValue("isDelLocalFile")); if ("true".equalsIgnoreCase(isDelLocalFile)) { FileUtil.removeFile(docFile); } } } public void genPrvdFile(String audTrm, String subjectId, String totalFocusCds, String focusCd, int prvdId, Map<String, Object> request, int modelNotifyId, Map<String, Object> configInfo, Boolean useChineseName, Boolean flag) { try { File csvFile = genCsvFile(audTrm, subjectId, focusCd, prvdId, configInfo, request, useChineseName); if (csvFile != null) { // File csvZipFile = FileUtil.zipOneFile(csvFile); //省公司doc.csv文件不应该打包上传,直接传文件即可,用户直接下载文件,直接看 modified by GuoXY 20161121 request.put("csvFileGenTime", new Date()); // modify by pxl 改为按专题更新notify,不再按id更新 // updateFileRequestStatus(modelNotifyId, audTrm, subjectId, focusCd, prvdId, request, Constants.Model.FileRequestStatus.CSV_FILE_FINISHED); updateFileRequestStatusBySubjectId(modelNotifyId, audTrm, subjectId, focusCd, prvdId, request, Constants.Model.FileRequestStatus.CSV_FILE_FINISHED); // 上传Csv文件,更新数据库请求记录状态 Map<String, Object> csvFtpPutResult = transferFileToFtpServer(Constants.Model.FileType.AUD_DETAIL, audTrm, subjectId, focusCd, prvdId, csvFile, useChineseName); request.put("csvFileFtpTime", new Date()); // updateFileRequestStatus(modelNotifyId, audTrm, subjectId, focusCd, prvdId, request, Constants.Model.FileRequestStatus.CSV_FTP_FINISHED); updateFileRequestStatusBySubjectId(modelNotifyId, audTrm, subjectId, focusCd, prvdId, request, Constants.Model.FileRequestStatus.File_FINISHED); // csvFtpPutResult.put("loginAccount", configInfo.get("loginAccount")); // csvFtpPutResult.put("userName", configInfo.get("userName")); // 向文件生成结果表HPMGR.busi_report_file中插入新生成的文件信息 insertReportFile(modelNotifyId, audTrm, subjectId, focusCd, prvdId, Constants.Model.FileType.AUD_DETAIL, csvFtpPutResult, configInfo); } } catch (Exception e) { logger.error("#### 文件上传FTP异常。错误信息为:" + ExceptionTool.getExceptionDescription(e)); } finally { this.logger.info("#### 模型数据文件生成完毕"); } } public File genCsvFile(String audTrm, String subjectId, String focusCd, int prvdId, Map<String, Object> configInfo, Map<String, Object> request, Boolean useChineseName) { // 获取新文件生成目录 String localFilePath = getLocalFilePath(); File localPath = new File(localFilePath); if (localPath.exists() == false) { localPath.mkdirs(); } // 获取新文件名 String localFileName = buildFileName(Constants.Model.FileType.AUD_DETAIL, audTrm, subjectId, focusCd, prvdId, useChineseName); String sql = (String) configInfo.get("csvSql"); File file = new File(FileUtil.buildFullFilePath(localFilePath, localFileName)); Writer streamWriter = null; try { streamWriter = new OutputStreamWriter(new FileOutputStream(file), "GBK"); final PrintWriter printWriter = new PrintWriter(streamWriter); printWriter.println((String) configInfo.get("csvHeader")); jdbcTemplate.query(sql, new Object[] {audTrm, prvdId}, new RowCallbackHandler() { public void processRow(ResultSet rs) throws SQLException { int columCount = rs.getMetaData().getColumnCount(); StringBuilder line = new StringBuilder(100); for (int i = 1; i <= columCount; i++) { line.append(rs.getObject(i)).append(" ,"); } printWriter.println(line.substring(0, line.length() - 1)); } }); printWriter.flush(); } catch (Exception e) { throw new RuntimeException("生成csv文件异常", e); } finally { FileUtil.closeWriter(streamWriter); } return file; } /** * <pre> * Desc 根据请求id更新生成文件请求的状态为 * @param audTrm * @param subjectId * @param focusCd * @param prvdId * @author GuoXY * @refactor GuoXY * @date 20161019 * </pre> */ @Transactional(propagation = Propagation.REQUIRED) public void updateFileRequestStatus(int modelNotifyId, String audTrm, String subjectId, String focusCd, int prvdId, Map<String, Object> configInfo, int status) { } @Transactional(propagation = Propagation.REQUIRED) public void updateFileRequestStatusBySubjectId(int modelNotifyId, String audTrm, String subjectId, String focusCd, int prvdId, Map<String, Object> configInfo, int status) { configInfo.put("audTrm", audTrm); configInfo.put("subjectId", subjectId); configInfo.put("prvdId", prvdId); configInfo.put("status", status); ywyjService.updateFileGenReqStatusAndTimeBySubjectNew(configInfo); } /** * <pre> * Desc 文件生成完毕插入到结果表 * 删除 HPMGR.busi_report_file表中原文件信息,并插入新文件信息(ID与HPMGR.busi_model_notify的ID对应) * @param audTrm * @param subjectId * @param focusCd * @param chinacode * @param configInfo * @param csvFile * @author GuoXY * @refactor GuoXY * @date 20161019 * </pre> */ @Transactional(propagation = Propagation.REQUIRED) public void insertReportFile(int modelNotifyId, String audTrm, String subjectId, String focusCd, int chinacode, String fileType, Map<String, Object> ftpPutResult, Map<String, Object> conf) { String filePath = (String) ftpPutResult.get("filePath"); String fileName = (String) ftpPutResult.get("fileName"); String downloadUrl = (String) ftpPutResult.get("downloadUrl"); Date createTime = ftpPutResult.get("createTime") == null ? new Date() : (Date) ftpPutResult.get("createTime"); BgxzData bgxz = new BgxzData(); bgxz.setAudTrm(audTrm); bgxz.setFilePath(downloadUrl); bgxz.setFileType(fileType); bgxz.setOperType("审计清单自动生成"); bgxz.setCreateType("manual"); bgxz.setSubjectId(subjectId); bgxz.setFocusCd(focusCd); bgxz.setPrvdId(chinacode); bgxz.setLoginAccount("admin"); bgxz.setOperPerson("sys"); bgxz.setCreateDatetime(new Date()); bgxz.setFileName(fileName); bgxz.setDownCount(0); // 判断是否有初始化数据不完整的记录 bgxzService.addReportLog(bgxz, "create"); } /** * <pre> * Desc ftp文件到ftp服务器 * 包括创建目录 * @param csvFile * @param docFile * @author GuoXY * @throws Exception * @refactor GuoXY * @date 20161019 * </pre> */ protected Map<String, Object> transferFileToFtpServer(String fileType, String audTrm, String subjectId, String focusCd, int prvdId, File upFile, Boolean useChineseName) throws Exception { logger.debug("#### 开始上传文件至FTP:" + fileType + "," + audTrm + "," + subjectId + "," + focusCd + "," + prvdId + ","); if (upFile == null) { this.logger.error("#### 文件为空,不需要ftp操作"); return new HashMap<String, Object>(); } Map<String, Object> resuluMap = new HashMap<String, Object>(); String filePath = buildFtpFilePath(fileType, audTrm, subjectId, focusCd, prvdId); logger.debug("#### 构造文件上传路径为:" + filePath); String fileName = upFile.getName();// buildFileName(fileType, audTrm, subjectId, focusCd, prvdId, modelFinTime, useChineseName); String downloadUrl = buildDownloadUrl(audTrm, subjectId, focusCd, prvdId, filePath, fileName); resuluMap.put("filePath", filePath); resuluMap.put("fileName", fileName); resuluMap.put("downloadUrl", downloadUrl); String isTransferFile = propertyUtil.getPropValue("isTransferFile"); if (!"true".equalsIgnoreCase(isTransferFile)) { this.logger.error("由于ftp server 传输配置开关没有打开,暂时文件不传输到ftp server。"); return resuluMap; } logger.debug("#### 开始上传文件(进度:1/2):" + filePath + "," + downloadUrl); // 20161110 add try by GuoXY for 让文件上传不影响web服务word文件的生成 try { uploadFile(upFile, filePath); } catch (Exception e) { logger.error("#### 文件上传FTP( " + fileName + " )异常。错误信息为:" + ExceptionTool.getExceptionDescription(e)); } logger.debug("#### 完成上传文件(进度:2/2):" + filePath + "," + downloadUrl); return resuluMap; } private void uploadFile(File csvFile, String filePath) { FtpUtil ftpTool = null; try { ftpTool = initFtp(); if (ftpTool == null) { return; } ftpTool.uploadFile(csvFile, filePath); } finally { if (ftpTool != null) { ftpTool.disConnect(); } } } /** * <pre> * Desc 初始化ftp服务 * @author GuoXY * @refactor GuoXY * @date 20161019 * </pre> */ private FtpUtil initFtp() { String isTransferFile = propertyUtil.getPropValue("isTransferFile"); if (!"true".equalsIgnoreCase(isTransferFile)) { return null; } FtpUtil ftpTool = new FtpUtil(); String ftpServer = StringUtils.trimToEmpty(propertyUtil.getPropValue("ftpServer")); String ftpPort = StringUtils.trimToEmpty(propertyUtil.getPropValue("ftpPort")); String ftpUser = StringUtils.trimToEmpty(propertyUtil.getPropValue("ftpUser")); String ftpPass = StringUtils.trimToEmpty(propertyUtil.getPropValue("ftpPass")); ftpTool.initClient(ftpServer, ftpPort, ftpUser, ftpPass); return ftpTool; } /** * <pre> * Desc 从配置文件中获取本地文件存放目录 * @return * @author GuoXY * @refactor GuoXY * @date 20161019 * </pre> */ protected String getLocalFilePath() { String tempDir = propertyUtil.getPropValue("tempDirV2"); return tempDir; } /** * <pre> * Desc /yyyymm/subjectId/focusCd/provId * /yyyymm/subjectId/focusCd/10000 * /yyyymm/subjectId/focusCd/10100 * @param fileType * @param audTrm * @param subjectId * @param focusCd * @param prvdId * @return * @author GuoXY * @refactor GuoXY * @date 20161019 * </pre> */ protected String buildFtpFilePath(String fileType, String audTrm, String subjectId, String focusCd, int prvdId) { String ftpPath = propertyUtil.getPropValue("ftpPathV2"); String path = buildRelativePath(audTrm, subjectId, prvdId, focusCd); String finalPath = FileUtil.buildFullFilePath(ftpPath, path); logger.debug("#### ftp中文件存储路径为:" + finalPath); FileUtil.mkdirs(finalPath); return finalPath; } /** * <pre> * Desc 构造相对路径 /yyyymm/subjectId/focusCd/provId * @param audTrm * @param subjectId * @param prvdId * @param focusCd * @return * @author GuoXY * @refactor GuoXY * @date 20161019 * </pre> */ protected String buildRelativePath(String audTrm, String subjectId, int prvdId, String focusCd) { StringBuilder path = new StringBuilder(); path.append(audTrm).append("/").append(subjectId).append("/").append(focusCd).append("/").append(prvdId); logger.error("#### buildRelativePath>>>" + path.toString()); return path.toString(); } /** * <pre> * Desc 构造http形式的下载地址 * @param audTrm * @param subjectId * @param focusCd * @param chinacode * @param filePath * @param fileName * @return * @author GuoXY * @refactor GuoXY * @date 20161019 * </pre> */ protected String buildDownloadUrl(String audTrm, String subjectId, String focusCd, int prvdId, String filePath, String fileName) { String ftpHttpUrlPrefix = propertyUtil.getPropValue("ftpHttpUrlPrefixV2"); StringBuilder url = new StringBuilder(30); url.append(buildRelativePath(audTrm, subjectId, prvdId, focusCd)).append("/").append(fileName); return FileUtil.buildFullFilePath(ftpHttpUrlPrefix, url.toString()); } /** * * <pre> * Desc 生成文件名 * 中文名:上海_201605_虚假家庭宽带审计清单.csv * 非中文:subjectId_focusCd_YYYYMM_prvdId.csv * @param fileType * @param audTrm * @param subjectId * @param focusCd * @param prvdId * @param useChineseName * @return * @author hufei * 2018-4-15 下午1:24:15 * </pre> */ protected String buildFileName(String fileType, String audTrm, String subjectId, String focusCd, int prvdId, Boolean useChineseName) { StringBuilder path = new StringBuilder(); String prvdName = prvdId + ""; if (useChineseName) { // 生成中文名审计报告/csv prvdName = Constants.MAP_PROVD_NAME.get(prvdId); String pointName=ywyjService.getPointName(focusCd); path.append(prvdName).append("_").append(audTrm).append("_").append(pointName); } else { path.append(subjectId).append("_").append(focusCd).append("_").append(audTrm).append("_").append(prvdName); } if (Constants.Model.FileType.AUD_REPORT.equalsIgnoreCase(fileType)) { if (useChineseName) { path.append("审计报告.doc"); } else { path.append(".doc"); } return path.toString(); } if (Constants.Model.FileType.AUD_DETAIL.equalsIgnoreCase(fileType)) { if (useChineseName) { path.append("审计清单.csv"); } else { path.append(".csv"); } } return path.toString(); } }
true
e39ea6656eb630927e7f9e90c82ee9d6cd2b242c
Java
webprograming2018/finalproject-n2_16_webbansach
/web/src/BookStore/src/java/dao/BillDAO.java
UTF-8
3,028
2.78125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dao; import dbconnect.DBConnect; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List; import model.Bill; import model.Bill; import model.BillDetail; /** * * @author TUNGDUONG */ public class BillDAO { public void insertBill(Bill bill) throws SQLException { Connection connection = DBConnect.getConnection(); String sql = "INSERT INTO bill VALUES(?,?,?,?,?,?)"; PreparedStatement ps = connection.prepareCall(sql); ps.setLong(1, bill.getBillID()); ps.setLong(2, bill.getUserID()); ps.setDouble(3, bill.getTotal()); ps.setString(4, bill.getPayment()); ps.setString(5, bill.getAddress()); ps.setTimestamp(6, bill.getDate()); ps.executeUpdate(); } public List<Bill> getListBilllByDay(String day)throws SQLException{ Connection connection = DBConnect.getConnection(); String sql = "select * from bill where date like '%" + day + "%'"; PreparedStatement ps = connection.prepareCall(sql); ResultSet rs = ps.executeQuery(); List<Bill> list = new ArrayList<>(); while (rs.next()) { Bill bill = new Bill(); bill.setBillID(rs.getLong("billID")); bill.setUserID(rs.getLong("userID")); bill.setTotal(rs.getDouble("total")); bill.setPayment(rs.getString("payment")); bill.setAddress(rs.getString("address")); bill.setDate(rs.getTimestamp("date")); list.add(bill); } return list; } public List<Bill> getListBilllByMonth(String month)throws SQLException{ Connection connection = DBConnect.getConnection(); String sql = "select * from bill where date like '%-" + month + "-%'"; PreparedStatement ps = connection.prepareCall(sql); ResultSet rs = ps.executeQuery(); List<Bill> list = new ArrayList<>(); while (rs.next()) { Bill bill = new Bill(); bill.setBillID(rs.getLong("billID")); bill.setUserID(rs.getLong("userID")); bill.setTotal(rs.getDouble("total")); bill.setPayment(rs.getString("payment")); bill.setAddress(rs.getString("address")); bill.setDate(rs.getTimestamp("date")); list.add(bill); } return list; } public static void main(String[] args) throws SQLException { BillDAO billDAO = new BillDAO(); List<Bill> list = billDAO.getListBilllByMonth("1"); for (int i=0;i<list.size();i++){ System.out.println(list.get(i).getBillID()+" "+list.get(i).getDate()); } } }
true
2103cb58ffc38ab1018c20f394fdb4af54f558a8
Java
archanataparia/CodingQuestions
/src/LinkedList/DoublyLinkList.java
UTF-8
1,798
3.40625
3
[]
no_license
package LinkedList; import java.util.*; class dNode{ int data; dNode next; dNode prev; dNode(int d){ data=d; next=null; prev=null; } } public class DoublyLinkList { public static dNode insert(dNode head,int data,int pos) { dNode newNode=new dNode(data); if(head==null) { head=newNode; return head; } if(pos==1)//inserting at beginning { head.prev=newNode; newNode.next=head; head=newNode; return head; } dNode cn=head; int k=1; while(cn.next!=null && k<pos-1) { cn=cn.next; k++; } if(k!=pos) System.out.println("position not found"); newNode.next=cn.next; newNode.prev=cn; if(cn.next!=null) cn.next.prev=newNode; cn.next=newNode; return head; } public static boolean isEmpty(dNode head) {return (head==null);} public static dNode remove(dNode head,int data) { dNode cn=head; if (cn.data==data){return head.next;} while(cn.next!=null){ if(cn.next.data==data) { cn.next= cn.next.next; cn.next.next.prev=cn; } cn=cn.next; } return head; } public static void display(dNode head) { dNode start=head; while(start!=null) { System.out.print(start.data+" "); start=start.next; } } public static void main(String[] args) { Scanner sc=new Scanner(System.in); dNode head=null; int T=sc.nextInt(); while(T-->0){ int ele=sc.nextInt(); int pos=sc.nextInt(); head=insert(head,ele,pos); //display(head); } display(head); int T2=sc.nextInt(); head=remove(head,T2); //display(head); display(head); sc.close(); } }
true
0a5e9bdb1ce0869f6bb81f3556f9d3692ee86f83
Java
tukinokage/aipets-springboot
/src/main/java/com/shay/aipets/entity/result/TestAbsClass.java
UTF-8
123
1.625
2
[]
no_license
package com.shay.aipets.entity.result; public abstract class TestAbsClass<T> { public void setData2(T data){ } }
true
34dc5ecf8d2d36b180911c3aadf28e537bbc6b8f
Java
VasilevichSergey/JD2016
/src/by/it/kust/jd01_12/taskA/TaskA1.java
UTF-8
1,211
3.59375
4
[]
no_license
package by.it.kust.jd01_12.taskA; import java.util.ArrayList; import java.util.Iterator; /** * Created by Tanya Kust. */ public class TaskA1 { /** * Создает список заданной размерности и заполняет его целыми случ.числами от 0 до 10 * @param length - заданная размерность списка * @return заполненный список */ public static ArrayList<Integer> createMarksList(int length) { ArrayList<Integer> marks = new ArrayList<>(); for (int i=0; i<length; i++){ marks.add((int)(Math.random()*11)); } return marks; } /** * Удаляет из списка оценки, меньше 4 * @param list - исходный список со всеми оценками * @return список без оценок < 4 */ public static ArrayList<Integer> deleteBadMarks(ArrayList<Integer> list){ Iterator<Integer> it = list.iterator(); while (it.hasNext()) { Integer mark = it.next(); if (mark < 4) {it.remove();} } list.trimToSize(); return list; } }
true
24448f48f090f28250d2e7225fffae7638ea8190
Java
moodgorning/testbed-runtime
/clients/debugging-gui-client/src/main/java/de/uniluebeck/itm/tr/debuggingguiclient/wsn/WSNServiceDummyImpl.java
UTF-8
8,693
1.523438
2
[ "BSD-3-Clause" ]
permissive
/********************************************************************************************************************** * Copyright (c) 2010, Institute of Telematics, University of Luebeck * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * * following conditions are met: * * * * - Redistributions of source code must retain the above copyright notice, this list of conditions and the following * * disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * * following disclaimer in the documentation and/or other materials provided with the distribution. * * - Neither the name of the University of Luebeck nor the names of its contributors may be used to endorse or promote* * products derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************************************************************/ package de.uniluebeck.itm.tr.debuggingguiclient.wsn; import java.util.ArrayList; import java.util.List; import javax.jws.WebParam; import javax.jws.WebService; import javax.xml.ws.Endpoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; import de.uniluebeck.itm.tr.util.SecureIdGenerator; import de.uniluebeck.itm.tr.util.UrlUtils; import eu.wisebed.api.common.Message; import eu.wisebed.api.wsn.ChannelHandlerConfiguration; import eu.wisebed.api.wsn.ChannelHandlerDescription; import eu.wisebed.api.wsn.Program; import eu.wisebed.api.wsn.WSN; import eu.wisebed.testbed.api.wsn.Constants; @WebService( serviceName = "WSNService", targetNamespace = Constants.NAMESPACE_WSN_SERVICE, portName = "WSNPort", endpointInterface = Constants.ENDPOINT_INTERFACE_WSN_SERVICE ) public class WSNServiceDummyImpl implements WSN { private static final Logger log = LoggerFactory.getLogger(WSNServiceDummyImpl.class); private String endpointUrl; private Endpoint endpoint; private SecureIdGenerator generator = new SecureIdGenerator(); public WSNServiceDummyImpl(String endpointUrl) { this.endpointUrl = endpointUrl; } public void start() throws Exception { String bindAllInterfacesUrl = UrlUtils.convertHostToZeros(endpointUrl); log.debug("Starting WISEBED WSN dummy service..."); log.debug("Endpoint URL: {}", endpointUrl); log.debug("Binding URL: {}", bindAllInterfacesUrl); endpoint = Endpoint.publish(bindAllInterfacesUrl, this); log.info("Started WISEBED WSN dummy service on {}", bindAllInterfacesUrl); } public void stop() { if (endpoint != null) { endpoint.stop(); log.info("Stopped WISEBED WSN dummy service on {}", endpointUrl); } } @Override public void addController( @WebParam(name = "controllerEndpointUrl", targetNamespace = "") String controllerEndpointUrl) { // nothing to do, this is a dummy ;-) } @Override public void removeController( @WebParam(name = "controllerEndpointUrl", targetNamespace = "") String controllerEndpointUrl) { // nothing to do, this is a dummy ;-) } @Override public String send(@WebParam(name = "nodeIds", targetNamespace = "") List<String> nodeIds, @WebParam(name = "message", targetNamespace = "") Message message) { log.info("WSNServiceImpl.send"); return generator.getNextId(); } @Override public String setChannelPipeline(@WebParam(name = "nodes", targetNamespace = "") final List<String> nodes, @WebParam(name = "channelHandlerConfigurations", targetNamespace = "") final List<ChannelHandlerConfiguration> channelHandlerConfigurations) { return generator.getNextId(); } @Override public String getVersion() { log.info("WSNServiceImpl.getVersion"); return "2.3"; } @Override public String areNodesAlive(@WebParam(name = "nodes", targetNamespace = "") List<String> nodes) { log.info("WSNServiceImpl.checkAreNodesAlive"); return generator.getNextId(); } @Override public String destroyVirtualLink(@WebParam(name = "sourceNode", targetNamespace = "") String sourceNode, @WebParam(name = "targetNode", targetNamespace = "") String targetNode) { log.info("WSNServiceImpl.destroyVirtualLink"); return generator.getNextId(); } @Override public String disableNode(@WebParam(name = "node", targetNamespace = "") String node) { log.info("WSNServiceImpl.disableNode"); return generator.getNextId(); } @Override public String disablePhysicalLink(@WebParam(name = "nodeA", targetNamespace = "") String nodeA, @WebParam(name = "nodeB", targetNamespace = "") String nodeB) { log.info("WSNServiceImpl.disablePhysicalLink"); return generator.getNextId(); } @Override public String enableNode(@WebParam(name = "node", targetNamespace = "") String node) { log.info("WSNServiceImpl.enableNode"); return generator.getNextId(); } @Override public String enablePhysicalLink(@WebParam(name = "nodeA", targetNamespace = "") String nodeA, @WebParam(name = "nodeB", targetNamespace = "") String nodeB) { log.info("WSNServiceImpl.enablePhysicalLink"); return generator.getNextId(); } @Override public String flashPrograms(@WebParam(name = "nodeIds", targetNamespace = "") List<String> nodeIds, @WebParam(name = "programIndices", targetNamespace = "") List<Integer> programIndices, @WebParam(name = "programs", targetNamespace = "") List<Program> programs) { log.info("WSNServiceImpl.flashPrograms"); return generator.getNextId(); } @Override public List<ChannelHandlerDescription> getSupportedChannelHandlers() { log.info("WSNServiceImpl.getSupportedChannelHandlers()"); return Lists.newArrayList(); } @Override public List<String> getFilters() { log.info("WSNServiceImpl.getFilters"); return new ArrayList<String>(); } @Override public String getNetwork() { log.info("WSNServiceImpl.getNetwork"); return "<network>dummy network description</network>"; } @Override public String resetNodes(@WebParam(name = "nodes", targetNamespace = "") List<String> nodes) { log.info("WSNServiceImpl.resetNodes"); return generator.getNextId(); } @Override public String setVirtualLink(@WebParam(name = "sourceNode", targetNamespace = "") String sourceNode, @WebParam(name = "targetNode", targetNamespace = "") String targetNode, @WebParam(name = "remoteServiceInstance", targetNamespace = "") String remoteServiceInstance, @WebParam(name = "parameters", targetNamespace = "") List<String> parameters, @WebParam(name = "filters", targetNamespace = "") List<String> filters) { log.info("WSNServiceImpl.setVirtualLink"); return generator.getNextId(); } }
true
087f208bbcc4334d672ac75319a21d9cd5c203c3
Java
zhouxiaopin/sk-elementui-bg
/sk-api/src/main/java/cn/sk/api/sys/pojo/SysSqlConf.java
UTF-8
1,364
1.890625
2
[]
no_license
package cn.sk.api.sys.pojo; import cn.sk.api.base.pojo.BaseModel; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import lombok.EqualsAndHashCode; import java.io.Serializable; @Data @EqualsAndHashCode(callSuper = true) @TableName("tb_sys_sql_conf") public class SysSqlConf extends BaseModel { /** * 主键 */ @TableId(value = "sc_id", type = IdType.AUTO) private Integer scId; /** * 语句编码 */ private String scCode; /** * 语句名 */ private String scName; /** * 语句 */ private String scStatement; /** * 类型(01=sql语句,02=存储过程) */ private String scType; /** * 描述 */ private String descri; private Integer optId; /** * 预留字段1 */ private String field1; /** * 预留字段2 */ private String field2; /** * 预留字段3 */ private String field3; /** * 预留字段4 */ private String field4; @TableField(exist = false) private String recordStatusStr; @Override public Serializable getPkVal() { return scId; } }
true
6b5d1faf2ad5194a8e2da34e99a5b3d228e31d0a
Java
AswAce/Java-OOP-prep-Exams
/Java OOP Retake Exam - 15 Aug 2019/HeroRepository/src/test/java/heroRepository/HeroRepositoryTests.java
UTF-8
2,692
3.125
3
[]
no_license
package heroRepository; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.stream.Collectors; public class HeroRepositoryTests { //TODO: TEST ALL THE FUNCTIONALITY OF THE PROVIDED CLASS HeroRepository private HeroRepository heroRepository; private Hero hero; @Before public void constructor() { this.heroRepository = new HeroRepository(); this.hero = new Hero("Asen", 1); } @Test public void testConstructorCreation() { ; Assert.assertEquals(0, heroRepository.getCount()); } @Test public void testConstructorSze() { heroRepository.create(hero); Assert.assertEquals(1, heroRepository.getCount()); } @Test(expected = NullPointerException.class) public void testHeroCreation() { heroRepository.create(null); } @Test(expected = IllegalArgumentException.class) public void testHeroAlreadyCreated() { heroRepository.create(hero); heroRepository.create(hero); } @Test public void testSuccessfullyAddedHero() { Assert.assertEquals(String.format("Successfully added hero %s with level %d", this.hero.getName(), hero.getLevel()), heroRepository.create(hero)); } @Test(expected = NullPointerException.class) public void testRemoveNullHero() { heroRepository.remove(null); } @Test(expected = NullPointerException.class) public void testRemoveEmptyHero() { heroRepository.remove(""); } @Test public void testSuccessesfullyRemovedHero() { heroRepository.create(hero); Assert.assertTrue(heroRepository.remove("Asen")); } @Test public void testWrongNameRemoved() { heroRepository.create(hero); Assert.assertFalse(heroRepository.remove("AAsen")); } @Test public void testGetHeroWithHighestLevel() { heroRepository.create(hero); Hero hero1 = new Hero("TestLevel", 99); heroRepository.create(hero1); Assert.assertEquals(hero1, heroRepository.getHeroWithHighestLevel()); } @Test public void testGetHeroByName(){ heroRepository.create(hero); Assert.assertEquals(hero, heroRepository.getHero("Asen")); } @Test public void testGetHeroCollection(){ HeroRepository heroRepository1 =new HeroRepository(); heroRepository.create(hero); Collection<Hero>expected= new ArrayList<>(); expected.add(hero); Assert.assertEquals(expected, new ArrayList<>(heroRepository.getHeroes())); } }
true
499d26808ebd4c373d23a49a1debbe3d6982df06
Java
kpg1983/likepet
/app/src/main/java/com/likelab/likepet/volleryCustom/AppController.java
UTF-8
5,200
1.632813
2
[]
no_license
package com.likelab.likepet.volleryCustom; import android.app.Application; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.content.res.Resources; import android.os.Build; import android.telephony.TelephonyManager; import android.util.Log; import android.widget.Toast; import com.android.volley.RequestQueue; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.Volley; import com.crashlytics.android.Crashlytics; import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.analytics.Tracker; import com.likelab.likepet.R; import com.likelab.likepet.global.GlobalSharedPreference; import com.likelab.likepet.global.GlobalVariable; import com.twitter.sdk.android.Twitter; import com.twitter.sdk.android.core.TwitterAuthConfig; import java.util.ArrayList; import io.fabric.sdk.android.Fabric; import kr.co.fingerpush.android.GCMFingerPushManager; import kr.co.fingerpush.android.NetworkUtility; public class AppController extends Application { private Tracker mTracker; /** * Gets the default {@link Tracker} for this {@link Application}. * @return tracker */ synchronized public Tracker getDefaultTracker() { if (mTracker == null) { GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG mTracker = analytics.newTracker(R.xml.global_tracker); } return mTracker; } // Note: Your consumer key and secret should be obfuscated in your source code before shipping. private static final String TWITTER_KEY = "2QM9iK7Q8azv9nDSbVHYsEJSi"; private static final String TWITTER_SECRET = "mnornpMetyd2F8L3Uv3TDTq80VxeBtsrCOzgk6hryEHd2jgNyC"; public static final String TAG = AppController.class.getSimpleName(); private RequestQueue mRequestQueue; private ImageLoader mImageLoader; private Resources res; private static AppController mInstance; @Override public void onCreate() { super.onCreate(); TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET); Fabric.with(this, new Twitter(authConfig), new Crashlytics()); TelephonyManager tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String networkOperator = tel.getNetworkOperator(); String countryCode = getApplicationContext().getResources().getConfiguration().locale.getCountry(); if (networkOperator != null) { if(networkOperator.length() != 0) { System.out.println("mcc "+ networkOperator); int mcc = Integer.parseInt(networkOperator.substring(0, 3)); int mnc = Integer.parseInt(networkOperator.substring(3)); GlobalSharedPreference.setAppPreferences(this, "mcc", networkOperator.substring(0, 3)); GlobalSharedPreference.setAppPreferences(this, "mnc", networkOperator.substring(3)); GlobalVariable.mcc = networkOperator.substring(0, 3); GlobalVariable.mnc = networkOperator.substring(3); } else { GlobalVariable.mcc = "null"; GlobalVariable.mnc = "null"; GlobalSharedPreference.setAppPreferences(this, "mcc", "null"); GlobalSharedPreference.setAppPreferences(this, "mnc", "null"); } } if(countryCode != null) { GlobalVariable.countryCode = countryCode; } else { GlobalVariable.countryCode = "null"; } PackageInfo pi = null; try { pi = getPackageManager().getPackageInfo(getPackageName(), 0); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } String version = pi.versionName; GlobalSharedPreference.setAppPreferences(this, "appVersion", version); GlobalSharedPreference.setAppPreferences(this, "deviceName", Build.DEVICE); mInstance = this; AssetManager asset = this.getAssets(); GlobalVariable.appVersion = version; GlobalVariable.deviceName = Build.DEVICE; GlobalVariable.deviceOS = Build.VERSION.RELEASE; //[리스너를 사용한 경우] GCMFingerPushManager.getInstance(this).setDevice(new NetworkUtility.NetworkDataListener() { @Override public void onError(String code, String errorMessage) { // TODO Auto-generated method stub Log.e("", "code ::: " + code); Toast.makeText(AppController.this, errorMessage, Toast.LENGTH_SHORT).show(); } @Override public void onComplete(String code, String resultMessage, ArrayList<?> DataList, Integer TotalArticleCount, Integer CurrentPageNo) { // TODO Auto-generated method stub Log.e("", "code ::: "+code); Toast.makeText(AppController.this, resultMessage, Toast.LENGTH_SHORT).show(); } @Override public void onCancel() { // TODO Auto-generated method stub } }); } public static synchronized AppController getInstance() { return mInstance; } public RequestQueue getRequestQueue() { if (mRequestQueue == null) { mRequestQueue = Volley.newRequestQueue(getApplicationContext()); } return mRequestQueue; } public ImageLoader getImageLoader() { getRequestQueue(); if (mImageLoader == null) { mImageLoader = new ImageLoader(this.mRequestQueue, new LruMemoryDiskBitmapCache(getApplicationContext())); } return this.mImageLoader; } }
true
1714c96682aff51a8ac3f6ef644bca44486d7c4a
Java
BaoBaoTang/Expense-Reimbursement-System
/src/test/java/controller/UserControllerTest.java
UTF-8
4,665
2.28125
2
[]
no_license
package controller; import com.fasterxml.jackson.databind.ObjectMapper; import config.ConfigurationFile; import model.Response; import model.User; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import javax.servlet.http.*; import java.io.*; import static org.junit.jupiter.api.Assertions.*; /** * @author Zimi Li */ class UserControllerTest { HttpServletRequest req = Mockito.mock(HttpServletRequest.class); HttpServletResponse resp = Mockito.mock(HttpServletResponse.class); HttpSession session = Mockito.mock(HttpSession.class); UserController userController = UserController.getInstance(); @Test void login() throws IOException { User user = new User(); user.setUsername("zimi"); user.setPassword("OPHHiRHj](2r=N:d"); StringWriter userString = new StringWriter(); userString.write(new ObjectMapper().writeValueAsString(user)); BufferedReader reader = new BufferedReader(new StringReader(userString.toString())); Mockito.when(req.getReader()).thenReturn(reader); StringWriter sw = new StringWriter(); Mockito.when(resp.getWriter()).thenReturn(new PrintWriter(sw)); Mockito.when(req.getSession(true)).thenReturn(session); userController.login(req, resp); StringWriter expected = new StringWriter(); expected.write(new ObjectMapper().writeValueAsString(new Response(true, "Login Succeed", null))); expected.write("\n"); expected.flush(); assertEquals(sw.toString(), expected.toString()); Mockito.verify(session, Mockito.times(1)).setAttribute(Mockito.isA(String.class), Mockito.isA(User.class)); } @Test void loginTest2() throws IOException { User user = new User(); user.setUsername("ers1"); user.setPassword("incorrect"); StringWriter userString = new StringWriter(); userString.write(new ObjectMapper().writeValueAsString(user)); BufferedReader reader = new BufferedReader(new StringReader(userString.toString())); Mockito.when(req.getReader()).thenReturn(reader); StringWriter sw = new StringWriter(); Mockito.when(resp.getWriter()).thenReturn(new PrintWriter(sw)); userController.login(req, resp); StringWriter expected = new StringWriter(); expected.write(new ObjectMapper().writeValueAsString(new Response(false, "Login Failed", null))); expected.write("\n"); expected.flush(); assertEquals(sw.toString(), expected.toString()); } @Test void getUser() throws IOException { Mockito.when(session.getAttribute("User")).thenReturn(null); Mockito.when(req.getSession()).thenReturn(session); StringWriter sw = new StringWriter(); Mockito.when(resp.getWriter()).thenReturn(new PrintWriter(sw)); userController.getUser(req, resp); StringWriter expected = new StringWriter(); expected.write(new ObjectMapper().writeValueAsString(new Response(false, "", null))); expected.write("\n"); expected.flush(); assertEquals(sw.toString(), expected.toString()); } @Test void getUserTest2() throws IOException { User user = new User(); user.setUsername("username"); user.setPassword("password"); user.setRole(1); user.setEmail("test@revature.com"); Mockito.when(session.getAttribute("User")).thenReturn(user); Mockito.when(req.getSession()).thenReturn(session); StringWriter sw = new StringWriter(); Mockito.when(resp.getWriter()).thenReturn(new PrintWriter(sw)); userController.getUser(req, resp); StringWriter expected = new StringWriter(); expected.write(new ObjectMapper().writeValueAsString(new Response(true, ConfigurationFile.MANAGER.toString(), req.getSession().getAttribute("User")))); expected.write("\n"); expected.flush(); assertEquals(sw.toString(), expected.toString()); } @Test void logout() throws IOException { Mockito.when(req.getSession()).thenReturn(session); StringWriter sw = new StringWriter(); Mockito.when(resp.getWriter()).thenReturn(new PrintWriter(sw)); userController.logout(req, resp); StringWriter expected = new StringWriter(); expected.write(new ObjectMapper().writeValueAsString(new Response(true, "Logout Succeed, redirecting in 3s...", null))); expected.write("\n"); expected.flush(); assertEquals(sw.toString(), expected.toString()); Mockito.verify(session, Mockito.times(1)).invalidate(); } }
true
a00e8a8e88af2efd9acd58d1baa2610c466e10ae
Java
GONZAGAJACQUEV/AnimeDownloader
/src/main/java/test/TestMain.java
UTF-8
453
2.453125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package test; import java.io.IOException; /** * * @author jdomugho */ public class TestMain { public static void main(String args[]) throws IOException { float percentage = ((float) 10 / 100) * 100; System.out.println(percentage); } }
true
4703ef11e3c45a823e18af0ec2bfb96f3916f959
Java
starsw001/ruoyi-vue-elective
/ruoyi/src/main/java/com/ruoyi/project/elective/course/mapper/ElectiveCourseMapper.java
UTF-8
1,383
1.953125
2
[ "MIT" ]
permissive
package com.ruoyi.project.elective.course.mapper; import com.ruoyi.project.elective.course.domain.ElectiveCourse; import java.util.List; /** * 课程Mapper接口 * * @author Sunss * @date 2020-02-12 */ public interface ElectiveCourseMapper { /** * 查询课程 * * @param id 课程ID * @return 课程 */ public ElectiveCourse selectElectiveCourseById(Long id); /** * 查询课程列表 * * @param electiveCourse 课程 * @return 课程集合 */ public List<ElectiveCourse> selectElectiveCourseList(ElectiveCourse electiveCourse); /** * 新增课程 * * @param electiveCourse 课程 * @return 结果 */ public int insertElectiveCourse(ElectiveCourse electiveCourse); /** * 修改课程 * * @param electiveCourse 课程 * @return 结果 */ public int updateElectiveCourse(ElectiveCourse electiveCourse); /** * 删除课程 * * @param id 课程ID * @return 结果 */ public int deleteElectiveCourseById(Long id); /** * 批量删除课程 * * @param ids 需要删除的数据ID * @return 结果 */ public int deleteElectiveCourseByIds(Long[] ids); /** * * @param electiveCourse */ List<ElectiveCourse> selectPlainList(ElectiveCourse electiveCourse); }
true
60bf63178fdb7f3465affd6bcaf4282e7fb33c79
Java
adaptris/interlok
/interlok-core/src/main/java/com/adaptris/core/jms/JmsUtils.java
UTF-8
4,304
2.421875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2015 Adaptris Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.adaptris.core.jms; import javax.jms.Connection; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TemporaryQueue; import javax.jms.TemporaryTopic; public abstract class JmsUtils { public static JMSException wrapJMSException(Throwable e) { return wrapJMSException(e.getMessage(), e); } public static JMSException wrapJMSException(String msg, Throwable e) { if (e instanceof JMSException) { return (JMSException) e; } JMSException exc = new JMSException(msg); exc.initCause(e); return exc; } public static void rethrowJMSException(Throwable e) throws JMSException { rethrowJMSException(e.getMessage(), e); } public static void rethrowJMSException(String msg, Throwable e) throws JMSException { throw wrapJMSException(msg, e); } /** * Delete a {@link TemporaryQueue} without logging any errors. * * @param q the queue. */ public static void deleteQuietly(TemporaryQueue q) { if (q == null) return; try { q.delete(); } catch (Exception e) { } } /** * Delete a {@link TemporaryTopic} without logging any errors. * * @param t the topic */ public static void deleteQuietly(TemporaryTopic t) { if (t == null) return; try { t.delete(); } catch (Exception e) { } } /** * Delete a temporary destnation without logging any errors. * * @param d the topic */ public static void deleteTemporaryDestination(Destination d) { if (d == null) return; if (d instanceof TemporaryQueue) { deleteQuietly((TemporaryQueue) d); } if (d instanceof TemporaryTopic) { deleteQuietly((TemporaryTopic) d); } } /** * Close a {@link Connection} without logging any errors or stopping the connection first. * * @param con the queue. * @see #closeQuietly(Connection, boolean) */ public static void closeQuietly(Connection con) { closeQuietly(con, false); } /** * Close a {@link Connection} without logging any errors. * * @param con the queue. * @param stopFirst whether or not to stop the connection first. */ public static void closeQuietly(Connection con, boolean stopFirst) { if (con == null) return; try { if (stopFirst) { stopQuietly(con); } con.close(); } catch (Exception ex) { } } public static void stopQuietly(Connection con) { if (con == null) return; try { con.stop(); } catch (Exception e) { } } /** * Close a {@link Session} without logging any errors. * * @param session the session. */ public static void closeQuietly(Session session) { if (session == null) return; try { session.close(); } catch (Exception ex) { } } /** * Close a {@link MessageProducer} without logging any errors. * * @param producer the producer. */ public static void closeQuietly(MessageProducer producer) { if (producer == null) return; try { producer.close(); } catch (Exception ex) { } } /** * Close a {@link MessageConsumer} without logging any errors. * * @param consumer the consumer. */ public static void closeQuietly(MessageConsumer consumer) { if (consumer == null) return; boolean wasInterrupted = Thread.interrupted(); try { consumer.close(); } catch (Exception ex) { } finally { if (wasInterrupted) { // Reset the interrupted flag as it was before. Thread.currentThread().interrupt(); } } } }
true
bcc5d23065c5061255c4f966b8351d31d6022d55
Java
hgashish/datastructure-practice
/src/main/java/com/ahg/stack/common/DynamicArrayStack.java
UTF-8
2,961
3.609375
4
[]
no_license
package com.ahg.stack.common; import java.util.Arrays; public class DynamicArrayStack<T> implements Stack<T> { private static final int MIN_CAPACITY = 4; private int capacity; private int top = -1; private T[] array; public DynamicArrayStack() { this(MIN_CAPACITY); } public DynamicArrayStack(int capacity) { this.capacity = capacity; this.array = (T[]) new Object[capacity]; } public int size() { return (top + 1); } public boolean isEmpty() { return size() == 0; } public void push(T item) { if(size() == capacity) { increaseCapacity(); } array[++top] = item; } private void increaseCapacity() { int currentSize = size(); int newCapacity = currentSize * 2; T[] newArray = Arrays.copyOf(array, newCapacity); array = newArray; this.capacity = newCapacity; } private void shrinkCapacity() { if(capacity / 2 >= MIN_CAPACITY) { int newCapacity = capacity / 2; T[] newArray = Arrays.copyOf(array, newCapacity); array = newArray; this.capacity = newCapacity; } } public T pop() throws StackEmptyException { if(size() <= 0) { throw new StackEmptyException(); } if(size() <= (capacity / 4)) { shrinkCapacity(); } return array[top--]; } public T top() throws StackEmptyException { if(size() <= 0) { throw new StackEmptyException(); } return array[top]; } @Override public String toString() { StringBuilder sb = new StringBuilder("capacity=").append(capacity) .append(", top=").append(top).append(", array=["); for(int i = 0; i < size(); i++) { sb.append(array[i]).append(", "); } sb.append(" TOP]"); return sb.toString(); } public static void main(String[] args) throws StackEmptyException { DynamicArrayStack<Integer> stack = new DynamicArrayStack<>(); stack.push(1); System.out.println(stack); stack.push(2); System.out.println(stack); stack.push(3); System.out.println(stack); stack.push(4); System.out.println(stack); stack.push(5); System.out.println(stack); System.out.println(stack.top()); System.out.println(stack); System.out.println(stack.pop()); System.out.println(stack); System.out.println(stack.pop()); System.out.println(stack); System.out.println(stack.pop()); System.out.println(stack); System.out.println(stack.pop()); System.out.println(stack); System.out.println(stack.pop()); System.out.println(stack); System.out.println(stack.pop()); System.out.println(stack); } }
true
e4462e981d8e5d9102603931b693bb82bce6f079
Java
Udyatbhanu/CoreLib
/lib/src/main/java/ubbs/home/com/core/lib/ui/activity/UBBSSlidingMenuBaseActivity.java
UTF-8
8,297
1.921875
2
[]
no_license
package ubbs.home.com.core.lib.ui.activity; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarDrawerToggle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import ubbs.home.com.core.lib.R; import ubbs.home.com.core.lib.ui.adapter.NavDrawerListAdapter; import ubbs.home.com.core.lib.ui.data.NavDrawerItem; /** * Created by udyatbhanu-mac on 7/3/15. */ public abstract class UBBSSlidingMenuBaseActivity extends UBBSBaseActivity { private static final String TAG = UBBSSlidingMenuBaseActivity.class.getSimpleName(); private DrawerLayout mDrawerLayout; private ActionBarDrawerToggle mDrawerToggle; private ListView mDrawerList; private List<NavDrawerItem> navDrawerItems; private NavDrawerListAdapter adapter; // nav drawer title private CharSequence mDrawerTitle; String[] fragmentsArray; // used to store app title private CharSequence mTitle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_base_ubbs); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.list_slidermenu); mTitle = mDrawerTitle = getTitle(); //Set transparency mDrawerList.getBackground().setAlpha(200); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); mDrawerToggle = new android.support.v7.app.ActionBarDrawerToggle( this, mDrawerLayout, R.string.app_name, // nav drawer open - description for accessibility R.string.app_name ) { public void onDrawerClosed(View view) { invalidateOptionsMenu(); } public void onDrawerOpened(View drawerView) { invalidateOptionsMenu(); } }; } @Override public void setTitle(CharSequence title) { mTitle = title; getActionBar().setTitle(mTitle); } @Override public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // toggle nav drawer on selecting action bar app icon/title if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } // Handle action bar actions click switch (item.getItemId()) { case 0: return true; default: return super.onOptionsItemSelected(item); } } /** * Slide menu item click listener * */ private class SlideMenuClickListener implements ListView.OnItemClickListener { String[] fragments = null; public SlideMenuClickListener(String []fragmentName){ fragments = fragmentName; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { displayView(position,fragments); } } private void displayView(int position, String[] fragments) { // if(restoreStateOnOrientationChange){ // String fragMentTag = (String)ApplicationSession.getSessionParam(ApplicationConstants.fragmentTag); // Fragment fragment = getSupportFragmentManager().findFragmentByTag(fragMentTag); // FragmentManager fragmentManager = getSupportFragmentManager(); // fragmentManager.beginTransaction() // .replace(R.id.frame_container, fragment, fragMentTag).commit(); // } // // else{ // Fragment fragment = Fragment.instantiate(this,fragments[position]); // FragmentManager fragmentManager = getSupportFragmentManager(); // fragmentManager.beginTransaction() // .replace(R.id.frame_container, fragment, fragments[position]).commit(); // } Fragment fragment = Fragment.instantiate(this,fragments[position]); FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.frame_container, fragment, fragments[position]).commit(); // update selected item and title, then close the drawer mDrawerList.setItemChecked(position, true); mDrawerList.setSelection(position); // ApplicationSession.setSessionParam(ApplicationConstants.fragmentTag, fragments[position] ); mDrawerLayout.closeDrawer(mDrawerList); } /** * */ protected void restoreState(){ displayView(mDrawerList.getSelectedItemPosition(),fragmentsArray); } /* * * Called when invalidateOptionsMenu() is triggered */ @Override public boolean onPrepareOptionsMenu(Menu menu) { // if nav drawer is opened, hide the action items // boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); // menu.findItem(R.id.action_settings).setVisible(!drawerOpen); return super.onPrepareOptionsMenu(menu); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggls mDrawerToggle.onConfigurationChanged(newConfig); } /** * * @param menuItemsConfigResource */ protected void setUpMenu(int menuItemsConfigResource, Bundle savedInstanceState){ InputStream inputStream = getResources().openRawResource(menuItemsConfigResource); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line; StringBuilder text = new StringBuilder(); navDrawerItems = new ArrayList<NavDrawerItem>(); try { while (( line = bufferedReader.readLine()) != null) { text.append(line); } JSONObject jObject = new JSONObject(text.toString()); JSONObject jObjectResult = jObject.getJSONObject("MenuItems"); fragmentsArray = new String[jObjectResult.length()]; for(int i=0; i<jObjectResult.length();i++){ JSONObject jItem = jObjectResult.getJSONObject("option"+(i+1)); String title = jItem.getString("title"); String frgament = jItem.getString("fragment"); navDrawerItems.add(new NavDrawerItem(title)); fragmentsArray[i]=frgament; } adapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems); mDrawerList.setAdapter(adapter); mDrawerList.setOnItemClickListener(new SlideMenuClickListener(fragmentsArray)); mDrawerLayout.setDrawerListener(mDrawerToggle); // display the home fragment i.e. the first fragment in the array if(savedInstanceState==null){ displayView(0,fragmentsArray); } Log.i(TAG,text.toString()); }catch (JSONException ex) { Log.e(TAG,"Exception"); } catch (IOException e) { Log.e(TAG,"Exception"); } } }
true
5e0bdbede31a531e632c2947fe155dec534bfbbf
Java
claudio-cavalcante/ControleDeVendas
/src/br/ufg/inf/menu/OpcaoMenuEmitirRelatorioEstoque.java
UTF-8
627
2.3125
2
[]
no_license
package br.ufg.inf.menu; import java.util.function.Supplier; import br.ufg.inf.menu.MensagensSistema; import br.ufg.inf.relatorio.Relatorio; import br.ufg.inf.relatorio.RelatorioDeEstoque; public class OpcaoMenuEmitirRelatorioEstoque implements IOpcaoMenu { @Override public String getNome() { return MensagensSistema.EMITIR_RELATORIO_ESTOQUE; } @Override public Supplier<Boolean> getAcao() { Relatorio relatorio = new RelatorioDeEstoque(); System.out.println(relatorio.emitir()); return () -> true; } @Override public EnumPapel[] papeisAutorizados() { return new EnumPapel[]{ EnumPapel.GERENTE }; } }
true
760eb8599d16224090887336a018e1ed5d87195b
Java
Nazar32/SocialNetwork
/src/main/java/res/R.java
UTF-8
1,125
2.6875
3
[]
no_license
package res; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.regex.Pattern; public final class R { private static Pattern eMail = Pattern.compile("^([a-z0-9_-]+\\.)*[a-z0-9_-]+@[a-z0-9_-]+(\\.[a-z0-9_-]+)*\\.[a-z]{2,6}$"); private static Pattern password = Pattern.compile("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\\s).*$"); private static Pattern name = Pattern.compile("^[A-Za-z]{1,20}$"); private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static boolean matchEmail(String email) { return eMail.matcher(email).matches(); } public static boolean matchPassword(String pass) { return password.matcher(pass).matches(); } public static boolean matchName(String n) { return name.matcher(n).matches(); } public static String formatDate(Date date) { return sdf.format(date); } public static Date parseDate(String date) throws ParseException { return sdf.parse(date); } public static void main(String[] args) { } }
true
77f4452265710d66e4540a604f6db7ca8e05e6f2
Java
AndyReckt/xCore-SRC
/src/main/java/net/helydev/com/commands/staff/SkullCommand.java
UTF-8
1,589
2.28125
2
[]
no_license
package net.helydev.com.commands.staff; import net.helydev.com.utils.Color; import net.helydev.com.utils.commands.Command; import net.helydev.com.utils.commands.CommandArgs; import net.helydev.com.xCore; import net.md_5.bungee.api.ChatColor; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.SkullMeta; public class SkullCommand { private ItemStack playerSkullForName(String name) { ItemStack is = new ItemStack(Material.SKULL_ITEM, 1); is.setDurability((short)3); SkullMeta meta = (SkullMeta)is.getItemMeta(); meta.setOwner(name); is.setItemMeta(meta); return is; } @Command(name = "skull", permission = "core.command.skull", inGameOnly = true) public boolean skulls(CommandArgs command) { Player sender = command.getPlayer(); String[] args = command.getArgs(); if (sender == null) { assert false; sender.sendMessage(ChatColor.RED + "You are not a player"); return true; } if (args.length != 1) { sender.sendMessage(Color.translate(xCore.getPlugin().getMessageconfig().getConfiguration().getString("skull.usage"))); return true; } sender.getInventory().addItem(playerSkullForName(args[0])); sender.sendMessage(Color.translate(xCore.getPlugin().getMessageconfig().getConfiguration().getString("skull.given").replace("%player%", args[0]))); return true; } }
true
96f7146ea6d3795546d6fca97815371f433590dc
Java
weisuodexiongmao/guoyulei20171221
/app/src/main/java/bwe/com/bawei/guoyulei20171221/register/vview/V_View.java
UTF-8
276
1.914063
2
[]
no_license
package bwe.com.bawei.guoyulei20171221.register.vview; import bwe.com.bawei.guoyulei20171221.register.bean.reg_Bean; /** * Created by 猥琐的熊猫 on 2017/12/21. */ public interface V_View { void regdata(reg_Bean reg_bean); String name(); String pass(); }
true
0b14f77db98f3cd9db4f22cb952f82c81f000028
Java
carolaraujo/mangaHq-mjv-java
/src/main/java/br/com/mjv/mangahq/usuario/service/UsuarioServiceImpl.java
UTF-8
2,590
2.59375
3
[ "MIT" ]
permissive
package br.com.mjv.mangahq.usuario.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import br.com.mjv.mangahq.exceptions.ImpossibleInsertException; import br.com.mjv.mangahq.exceptions.UserNotFoundException; import br.com.mjv.mangahq.usuario.dao.UsuarioDao; import br.com.mjv.mangahq.usuario.model.Usuario; @Service public class UsuarioServiceImpl implements UsuarioService { private static final Logger LOGGER = LoggerFactory.getLogger(UsuarioServiceImpl.class); @Autowired private UsuarioDao dao; @Override public Usuario buscarPorLogin(String login) throws UserNotFoundException { LOGGER.info("UsuarioServiceImpl - Inicio do método buscarPorLogin"); Usuario usuario = dao.buscarPorLogin(login); if(usuario == null) { LOGGER.error("Não foi possível encontrar o usuário com o login indicado"); throw new UserNotFoundException("Não foi possível encontrar o usuário com o login indicado"); } LOGGER.info("UsuarioServiceImpl - F do método buscarPorLogin"); return usuario; } @Override public Usuario buscarPorId(Integer id) throws UserNotFoundException { LOGGER.info("UsuarioServiceImpl - Inicio do método buscarPorId"); Usuario usuario = dao.buscarPorId(id); if(usuario == null) { LOGGER.error("Não foi possível encontrar o usuário com o id indicado"); throw new UserNotFoundException("Não foi possível encontrar o usuário com o id indicado"); } LOGGER.info("UsuarioServiceImpl - Fim do método buscarPorId"); return usuario; } @Override public Integer cadastrarUsuario(Usuario usuario) throws ImpossibleInsertException { LOGGER.info("UsuarioServiceImpl - Inicio do método cadastrarUsuario"); Integer id = dao.cadastrarUsuario(usuario); if(id == 0) { LOGGER.error("Não foi possível cadastrar o usuario, tente mais tarde"); throw new ImpossibleInsertException("Não foi possível encontrar o usuário com o id indicado"); } LOGGER.info("UsuarioServiceImpl - Fim do método cadastrarUsuario"); return id; } @Override public Boolean verificarSeUsuarioExiste(Usuario usuario) { try { LOGGER.info("UsuarioServiceImpl - Inicio do método verificarSeUsuarioExiste"); buscarPorLogin(usuario.getLogin()); return true; } catch (UserNotFoundException e) { LOGGER.info("UsuarioServiceImpl - Usuário não encontrado, realizando cadastro..."); return false; }finally { LOGGER.info("UsuarioServiceImpl - Fim do método verificarSeUsuarioExiste"); } } }
true
25c33055d436c505c29277444edba61bfbc0df86
Java
awsaavedra/coding-practice
/java/udemy-java/Classes/src/com/company/Car.java
UTF-8
1,031
3.5
4
[]
no_license
package com.company; /** * Created by awsaavedra on 12/11/16. */ public class Car { //state component, aka characteristics //private variables means no class besides Car class can access this private int doors; private int wheels; private String model; private String engine; private String color; //setters public void setModel(String model){ String validModel = model.toLowerCase(); if(validModel.equals("carrera") || validModel.equals("commodore")){ this.model = model; //updating model using a method, instead of accessing it (model) //directly, encapsulation }else{ this.model = "Unknown"; } } //getters public String getModel(){ return this.model; } /* Purpose of getters and setters (data encapsulation): useful b.c validation key idea: the code CANNOT create invalid objects, AKA objects that are created are valid and correct * */ }
true
35fb2336d9a4283ff6efd8a8d7bd06e8a6e87f4d
Java
inniy2/raziel-web
/src/main/java/com/bae/raziel/login/LoginEntity.java
UTF-8
854
2.125
2
[]
no_license
package com.bae.raziel.login; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "raziel_user") public class LoginEntity { @Id @Column(name = "razie_user", nullable = false) private String razielUser; @Column(name = "raziel_password", nullable = false) private String razielPassword; public String getRazielUser() { return razielUser; } public void setRazielUser(String razielUser) { this.razielUser = razielUser; } public String getRazielPassword() { return razielPassword; } public void setRazielPassword(String razielPassword) { this.razielPassword = razielPassword; } @Override public String toString() { return "RazielUserEntity [razielUser=" + razielUser + ", razielPassword=" + razielPassword + "]"; } }
true
29b3a3ddb0bc668bb0e5fc28c2c3440f74e0cef8
Java
flowidcom/calypso
/calypso/src/main/java/com/flowid/refd/config/AppConfig.java
UTF-8
2,231
1.984375
2
[ "Apache-2.0" ]
permissive
package com.flowid.refd.config; import org.springframework.beans.factory.config.PropertiesFactoryBean; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import com.fasterxml.jackson.jaxrs.cfg.Annotations; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; @Configuration public class AppConfig { static private final String APP_NAME = "calypso"; @Bean static public PropertyPlaceholderConfigurer readAllProperties() { PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); ppc.setLocations(new Resource[] { new FileSystemResource(appPropertiesUrl()), new FileSystemResource(etcPropertiesUrl()) }); ppc.setIgnoreResourceNotFound(true); ppc.setIgnoreUnresolvablePlaceholders(true); return ppc; } @Bean(name = "appProps") static public PropertiesFactoryBean getPropertieFactoryBean() { PropertiesFactoryBean props = new PropertiesFactoryBean(); props.setLocations(new Resource[] { new FileSystemResource(appPropertiesUrl()) }); props.setIgnoreResourceNotFound(true); props.setIgnoreResourceNotFound(true); return props; } static public String appPropertiesUrl() { String appConfigDir = System.getProperty("app.config.dir"); return String.format("%s/%s-app.properties", appConfigDir, APP_NAME); } static private String etcPropertiesUrl() { String appEnv = System.getProperty("app.env"); String userHome = System.getProperty("user.home"); return String.format("%s/.apps/%s-etc-%s.properties", userHome, APP_NAME, appEnv); } @Bean(name = "jsonProvider") public JacksonJsonProvider getJsonProvider() { return new JacksonJaxbJsonProvider(new JacksonObjectMapper(), new Annotations[0]); } }
true