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
dceadbba132e0d528d38e8d3d3bb4492aff2a1cb
Java
IanDarwin/annabot
/src/main/java/demo/MyAnnotation.java
UTF-8
455
2.484375
2
[ "LicenseRef-scancode-bsd-simplified-darwin" ]
permissive
package demo; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * A sample annotation for types (classes, interfaces); * it will be available at run time. */ @Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { public boolean useless() default false; }
true
7b780ea93cf8b2d820f573d8df85447889eb34a2
Java
moutainhigh/LYProject
/src/main/java/com/liaoyin/lyproject/entity/TSystemNews.java
UTF-8
2,487
2.265625
2
[]
no_license
package com.liaoyin.lyproject.entity; import java.util.Date; import javax.persistence.*; @Table(name = "t_system_news") public class TSystemNews { /** * id主键 */ @Id private Integer id; /** * 标题 */ private String title; /** * 消息分类:0-投票通知 */ private Integer type; /** * 持有人id */ @Column(name = "systemUserId") private Integer systemuserid; /** * 创建时间 */ @Column(name = "createDate") private Date createdate; /** * 内容 */ private String body; /** * 获取id主键 * * @return id - id主键 */ public Integer getId() { return id; } /** * 设置id主键 * * @param id id主键 */ public void setId(Integer id) { this.id = id; } /** * 获取标题 * * @return title - 标题 */ public String getTitle() { return title; } /** * 设置标题 * * @param title 标题 */ public void setTitle(String title) { this.title = title; } /** * 获取消息分类:0-投票通知 * * @return type - 消息分类:0-投票通知 */ public Integer getType() { return type; } /** * 设置消息分类:0-投票通知 * * @param type 消息分类:0-投票通知 */ public void setType(Integer type) { this.type = type; } /** * 获取持有人id * * @return systemUserId - 持有人id */ public Integer getSystemuserid() { return systemuserid; } /** * 设置持有人id * * @param systemuserid 持有人id */ public void setSystemuserid(Integer systemuserid) { this.systemuserid = systemuserid; } /** * 获取创建时间 * * @return createDate - 创建时间 */ public Date getCreatedate() { return createdate; } /** * 设置创建时间 * * @param createdate 创建时间 */ public void setCreatedate(Date createdate) { this.createdate = createdate; } /** * 获取内容 * * @return body - 内容 */ public String getBody() { return body; } /** * 设置内容 * * @param body 内容 */ public void setBody(String body) { this.body = body; } }
true
3b88f5bdff9dc60ea3f6f03cd5766e7c3cf96d70
Java
Patrick-Edouard/HomeVoiceControler
/src/main/java/fr/uds/info907/view/AbstractItemView.java
UTF-8
1,724
2.671875
3
[]
no_license
package fr.uds.info907.view; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JDialog; import javax.swing.JLabel; public class AbstractItemView extends JDialog{ private static final long serialVersionUID = 6923897570573385201L; private static final String defaultImage = "image-not-found.png"; private String name; private String iconPath; protected AbstractItemView(String name, String iconPath) { super(); this.name=name; this.iconPath=iconPath; this.initialize(); } private void initialize(){ this.setTitle(this.name); this.getContentPane().add(new JLabel(this.getIcon())); this.pack(); this.setVisible(true); } public void changeImageIcon(String newImageIcon){ this.setIconPath(newImageIcon); this.getContentPane().removeAll(); this.getContentPane().add(new JLabel(this.getIcon())); this.repaint(); this.pack(); } private void setIconPath(String iconPath){ if(iconPath!=null){ this.iconPath = iconPath; } else{ this.iconPath = defaultImage; } } private ImageIcon getIcon(){ InputStream image = Thread.currentThread().getContextClassLoader().getResourceAsStream(this.iconPath); BufferedImage bufferedImage = null; try { bufferedImage = ImageIO.read(image); } catch (Exception e) { image = Thread.currentThread().getContextClassLoader().getResourceAsStream(AbstractItemView.defaultImage); try { bufferedImage = ImageIO.read(image); } catch (IOException e1) { // N'est pas sencé foiré avec une image par défault e1.printStackTrace(); } } return new ImageIcon(bufferedImage); } }
true
4a90573d7cadd15c5e7542076ac650be39d0afef
Java
oudream/hello-java
/referto/bookcode/core8th5/v1ch4/CardDeck/CardDeck.java
UTF-8
1,587
3.6875
4
[]
no_license
/** * @version 1.20 27 Mar 1998 * @author Cay Horstmann */ import corejava.*; public class CardDeck { public CardDeck() { deck = new Card[52]; fill(); shuffle(); } public void fill() { int i; int j; for (i = 1; i <= 13; i++) for (j = 1; j <= 4; j++) deck[4 * (i - 1) + j - 1] = new Card(i, j); cards = 52; } public void shuffle() { int next; for (next = 0; next < cards - 1; next++) { int r = new RandomIntGenerator(next, cards - 1).draw(); Card temp = deck[next]; deck[next] = deck[r]; deck[r] = temp; } } public Card draw() { if (cards == 0) return null; cards--; return deck[cards]; } void play(int rounds) { int i; int wins = 0; for (i = 1; i <= rounds; i++) { Card yours = draw(); System.out.print("Your draw: " + yours + " "); Card mine = draw(); System.out.print("My draw: " + mine + " "); if (yours.rank() > mine.rank()) { System.out.println("You win"); wins++; } else System.out.println("I win"); } System.out.println("Your wins: " + wins + " My wins: " + (rounds - wins)); } public static void main(String[] args) { CardDeck d = new CardDeck(); d.play(10); // play ten rounds } private Card[] deck; private int cards; }
true
ca15632620638add283ccdeff4b78c415b8602a6
Java
xiaocaimeng007/Hong1.0-
/app/src/main/java/net/sourceforge/simcpux/PayActivity.java
UTF-8
6,287
1.796875
2
[]
no_license
package net.sourceforge.simcpux; import android.os.Bundle; import android.widget.Toast; import com.example.aaron.library.MLog; import com.hongbao5656.base.App; import com.hongbao5656.base.BaseActivity; import com.hongbao5656.okhttp.HttpDataHandlerListener; import com.hongbao5656.okhttp.HttpException; import com.hongbao5656.util.NU; import com.hongbao5656.util.ParamsService; import com.hongbao5656.util.ResponseParams; import com.hongbao5656.util.TU; import com.hongbao5656.util.TimeUtils; import com.squareup.okhttp.Request; import com.tencent.mm.sdk.constants.Build; import com.tencent.mm.sdk.modelpay.PayReq; import com.tencent.mm.sdk.openapi.IWXAPI; import com.tencent.mm.sdk.openapi.WXAPIFactory; import org.json.JSONException; import java.util.LinkedHashMap; public class PayActivity extends BaseActivity implements HttpDataHandlerListener { private IWXAPI api; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.pay); api = WXAPIFactory.createWXAPI(this, "wxc10276fc4a4853ff"); // Button appayBtn = (Button) findViewById(R.id.appay_btn); if (api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT) { paytest(); } else { TU.show(this, "当前微信版本不支持支付,请升级后再试!"); } // appayBtn.setOnClickListener(new View.OnClickListener() { // // @Override // public void onClick(View v) { // paytest(); // } // }); // Button checkPayBtn = (Button) findViewById(R.id.check_pay_btn); // checkPayBtn.setOnClickListener(new View.OnClickListener() { // // @Override // public void onClick(View v) { // boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT; // Toast.makeText(PayActivity.this, String.valueOf(isPaySupported), Toast.LENGTH_SHORT).show(); // } // }); } private void paytest() { String url = "http://www.56hb.net/api/PayNotify"; // Button payBtn = (Button) findViewById(R.id.appay_btn); // payBtn.setEnabled(false); Toast.makeText(PayActivity.this, "获取订单中...", Toast.LENGTH_SHORT).show(); try { // byte[] buf = Util.httpGet(url); // if (buf != null && buf.length > 0) { // String content = new String(buf); // LU.i("get server pay params:", content); // JSONObject json = new JSONObject(content); // if(null != json && !json.has("retcode") ){ // PayReq req = new PayReq(); // //req.appId = "wxf8b4f85f3a794e77"; // 测试用appId // req.appId = json.getString("appid");//appId // req.partnerId = json.getString("partnerid");//商户号 // req.prepayId = json.getString("prepayid"); // req.nonceStr = json.getString("noncestr"); // req.timeStamp = json.getString("timestamp"); // req.packageValue = json.getString("package"); // req.sign = json.getString("sign");//签名 // req.extData = "app data"; // optional // Toast.makeText(PayActivity.this, "正常调起支付", Toast.LENGTH_SHORT).show(); // // 在支付之前,如果应用没有注册到微信,应该先调用IWXMsg.registerApp将应用注册到微信 // api.sendReq(req); // }else{ // LU.i("PAY_GET", "返回错误" + json.getString("retmsg")); // Toast.makeText(PayActivity.this, "返回错误"+json.getString("retmsg"), Toast.LENGTH_SHORT).show(); // } // }else{ // LU.i("PAY_GET", "服务器请求错误"); // Toast.makeText(PayActivity.this, "服务器请求错误", Toast.LENGTH_SHORT).show(); // } requestServer(); } catch (Exception e) { MLog.i("PAY_GET", "异常:" + e.getMessage()); Toast.makeText(PayActivity.this, "异常:" + e.getMessage(), Toast.LENGTH_SHORT).show(); } // payBtn.setEnabled(true); } String body = "货源信息费"; int total_fee = 1; private void requestServer() { // sendPostRequest( // com.hongbao5656.util.Constants.wxpay, // new ParamsService().wxpay( // body,total_fee, NU.getIpAddress(), // TimeUtils.getSureTime("yyyyMMddHHmmss",System.currentTimeMillis()), // TimeUtils.getSureTime("yyyyMMddHHmmss",System.currentTimeMillis()+1000*60*6), // "http://www.56hb.net/api/PayNotify" // ), // this, // false); } public void setHandlerData(int connectionId, ResponseParams<LinkedHashMap> iParams, int errcode) throws JSONException { } @Override public void setHandlerPostDataSuccess(int connectionId, Object data) throws JSONException { ResponseParams<LinkedHashMap> iParams = jiexiData(data); if (connectionId == com.hongbao5656.util.Constants.wxpay) { // TU.show(mContext, "删除成功"); // initDatas(1); PayReq req = new PayReq(); //req.appId = "wxf8b4f85f3a794e77"; // 测试用appId req.appId = iParams.getData1().get("appid").toString();//appId req.partnerId = iParams.getData1().get("partnerid").toString();//商户号 req.prepayId = iParams.getData1().get("prepayid").toString(); req.nonceStr = iParams.getData1().get("noncestr").toString(); req.timeStamp = iParams.getData1().get("timestamp").toString(); req.packageValue = iParams.getData1().get("package").toString(); req.sign = iParams.getData1().get("sign").toString();//签名 // req.extData = "app data"; // optional // Toast.makeText(PayActivity.this, "正常调起支付", Toast.LENGTH_SHORT).show(); // 在支付之前,如果应用没有注册到微信,应该先调用IWXMsg.registerApp将应用注册到微信 api.registerApp(Constants.APP_ID); api.sendReq(req); // TU.show(this,bb+""); } } @Override public void setHandlerPostDataError(int connectedId, Request request, HttpException httpException, String params, String content) throws JSONException { } @Override public void setHandlerGetDataSuccess(int connectionId, Object data) throws JSONException { } @Override public void setHandlerGetDataError(int connectionId, Object data) throws JSONException { } }
true
12803a7958c400f9d9d1234a752b79cfceef2503
Java
cckmit/bhshop
/bhshop/bh-admin/src/main/java/com/bh/admin/service/TopicBargainLogService.java
UTF-8
514
1.679688
2
[]
no_license
package com.bh.admin.service; import com.bh.admin.pojo.goods.TopicBargainLog; import com.bh.admin.pojo.user.Member; import com.bh.utils.PageBean; public interface TopicBargainLogService { //添加 int add(TopicBargainLog entity, Member member); //获取 TopicBargainLog get(Integer id); //列表 PageBean<TopicBargainLog> listPage(TopicBargainLog entity); //扫描活动有效期 int checkTimeChangeStatus(); //添加 int wxAdd(TopicBargainLog entity, Member member); }
true
8086f2be6ff01199aa1a9b395257407ff97eee85
Java
yangfeit19/auc-miner
/auc-miner/src/aucminer/handlers/MiningRulesThread.java
WINDOWS-1252
1,741
2.03125
2
[]
no_license
package aucminer.handlers; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import aucminer.AucMinerActivator; import aucminer.core.AssociationRuleList; import aucminer.core.Configuration; import aucminer.rulegenerator.ApiChangeRuleGenerator; public class MiningRulesThread extends Job { private Configuration rauaConfig; public MiningRulesThread() { super("Run ALL"); String workingDirectory = AucMinerActivator.getDefault().getConfiguration().getResultStorage().getFileStoragePath(); String oldVersionProject = AucMinerActivator.getDefault().getConfiguration().getOldVersion(); String newVersionProject = AucMinerActivator.getDefault().getConfiguration().getNewVersion(); this.rauaConfig = new Configuration(workingDirectory, oldVersionProject, newVersionProject); } @Override protected IStatus run(IProgressMonitor monitor) { boolean includeField = true; boolean storeToFile = true; boolean usingSplit = false; // Note int splitThreshold = 6; int minSupport = 2; float minConfidence = 100; long start = System.currentTimeMillis(); ApiChangeRuleGenerator generator = new ApiChangeRuleGenerator(rauaConfig); AssociationRuleList apiChangeRules = generator.generateApiChangeRules(includeField, storeToFile, usingSplit, splitThreshold, minSupport, minConfidence); System.out.println(String.format("Generate %d API change rules", apiChangeRules.getRules().size())); long end = System.currentTimeMillis(); System.out.println("ʱ䣺" + (end - start) / 1000.0 + ""); return Status.OK_STATUS; } }
true
798ec3eb38946e45e54abcb5d52db6ed630c846b
Java
talk2alie/csc1051
/Arrays/ReadingFiles.java
UTF-8
1,088
4.28125
4
[ "Apache-2.0" ]
permissive
// 1. Import the Scanner class from the java.util package import java.util.Scanner; /** * ReadingFiles */ public class ReadingFiles { public static void main(String[] args) { // 2. Instantiate a Scanner object. // Note that System.in is how Java represents the keyboard. // So when you create a scanner, you have to tell it from where you // are reding the input data. Because you are reading from the // keyboard, you must pass System.in to the Scanner class' // constructor Scanner keyboard = new Scanner(System.in); // 3. Ask the user for some input System.out.print("Please enter your name: "); // 4. Use one of the nextXXX methods of the Scanner object to read the // data. For example, if what you want to read is an entire line, // you use the nextLine method String name = keyboard.nextLine(); // 5. Close the scanner keyboard.close(); // 6. Use the data System.out.println("Hi there, " + name); } }
true
ca8fd8ab538ca9809eba979370ab28eb55be1b53
Java
wang-jun-hao/discrete-event-simulator
/RestEvent.java
UTF-8
754
3.25
3
[]
no_license
package cs2030.simulator; /** * RestEvent class that extends Event and represents the event whereby a server * temporarily pauses its service after finishing serving a customer. */ class RestEvent extends Event { // constructor /** * Constructs a RestEvent at given time involving given server. * @param time time of event of server taking a break * @param server the server taking break */ RestEvent(double time, Server server) { super(time, new TypicalCustomer(), server); } @Override public boolean isRestEvent() { return true; } @Override public boolean isBackEvent() { return false; } @Override public String toString() { return ""; } }
true
6cb2f11022dced37a0989d62d6466d2a613f3412
Java
green-fox-academy/rolandcsa
/week-04/day-3/src/Sum.java
UTF-8
231
3.015625
3
[]
no_license
import java.util.List; public class Sum { public Integer sumElements(List<Integer> numbers) { int sum = 0; for (Integer number : numbers) { sum = sum + number; } return sum; } }
true
0081b96f15fe6729dbca67696296094a7991ff0b
Java
UrQA/stresstest_android
/libraries/URQANative/src/com/urqa/rank/ErrorRank.java
UTF-8
255
2.46875
2
[ "MIT" ]
permissive
package com.urqa.rank; public enum ErrorRank { Nothing(-1),Unhandle(0),Native(1),Critical(2),Major(3),Minor(4); private final int value; ErrorRank(int value) { this.value = value; } public int value() { return value; } }
true
5f4d0e9079091460cca78b06053572817e97aebc
Java
jeevan-patil/hearth
/src/main/java/org/hearth/march14/Password.java
UTF-8
2,559
3.84375
4
[]
no_license
package org.hearth.march14; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /** * * @author jeevan * @orgaization :) * @date 18-Mar-2014 10:35:39 PM * * Danny has a possible list of passwords of Manny's facebook account. All * passwords length is odd. But Danny knows that Manny is a big fan of * palindromes. So, his password and reverse of his password both should * be in the list. * * You have to print the length of Manny's password and it's middle * character. * * Note : The solution will be unique. * * INPUT The first line of input contains the integer N, the number of * possible passwords. Each of the following N lines contains a single * word, its length being an odd number greater than 2 and lesser than 14. * All characters are lowercase letters of the English alphabet. * * OUTPUT The first and only line of output must contain the length of the * correct password and its central letter. * * CONSTRAINTS 1 ≤ N ≤ 100 * * Sample Input (Plaintext Link) 4 abc def feg cba * * Sample Output (Plaintext Link) 3 b */ public class Password { public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Password pass = new Password(); try { String input = br.readLine(); String palindrome; int cases = Integer.parseInt(input); List<String> passList = new ArrayList<String>(cases); for (int i = 0; i < cases; i++) { input = br.readLine(); passList.add(input); palindrome = pass.reverse(input); if (passList.contains(palindrome)) { System.out.println(input.length() + " " + pass.getMiddleChar(input)); } } } catch (Exception e) { // System.out.println(0); } finally { try { br.close(); } catch (IOException e) { } } } /** * Reverse the string * * @param word * @return */ private String reverse(String word) { if (word == null) { return word; } int length = word.length(); String reverse = ""; for (int i = length - 1; i >= 0; i--) reverse = reverse + word.charAt(i); return reverse; } /** * Get middle characters in the word * * @param word * @return */ private String getMiddleChar(String word) { char middleOne; char[] arr = word.toCharArray(); middleOne = arr[word.length() / 2]; return String.valueOf(middleOne); } }
true
68985f2555e2ea3836f67ee657945318a07ba0d6
Java
phwd/quest-tracker
/hollywood/com.oculus.socialplatform-base/sources/X/AnonymousClass0f0.java
UTF-8
1,057
1.992188
2
[]
no_license
package X; import com.google.common.collect.Multiset; import org.checkerframework.checker.nullness.compatqual.NullableDecl; /* renamed from: X.0f0 reason: invalid class name */ public abstract class AnonymousClass0f0<E> extends AbstractC05580wA<Multiset.Entry<E>> { public abstract AbstractC05490vp<E> A00(); public final boolean contains(@NullableDecl Object obj) { if (!(obj instanceof AnonymousClass0f2)) { return false; } AnonymousClass0f2 r4 = (AnonymousClass0f2) obj; if (r4.A00() <= 0 || A00().A2J(r4.A01()) != r4.A00()) { return false; } return true; } public final boolean remove(Object obj) { if (obj instanceof AnonymousClass0f2) { AnonymousClass0f2 r5 = (AnonymousClass0f2) obj; E e = (E) r5.A01(); int A00 = r5.A00(); if (A00 != 0) { return A00().A9o(e, A00, 0); } } return false; } public final void clear() { A00().clear(); } }
true
0fd90c09372ab27f0ff5c09a6f8f9621462030d7
Java
MrEyeballs29/Decoblocks
/src/main/java/mreyeballs29/decoblocks/utils/ConfigManagerIssacCore.java
UTF-8
4,562
2.015625
2
[ "MIT" ]
permissive
package mreyeballs29.decoblocks.utils; import java.io.File; import net.minecraftforge.common.config.Configuration; public class ConfigManagerIssacCore { public static String CATERGORY_WORLD = "world"; public static String CATERGORY_INTREGRATED_WORLD = "worldIntergation"; public static String CATERGORY_BIOME_GEMS = "biomeGems"; // World Generator public static boolean enableCopperGen; public static boolean enableTinGen; public static boolean enableSilverGen; public static boolean enableLeadGen; public static boolean enableNickelGen; public static boolean enablePlatinumGen; public static boolean enableAluminumGen; public static boolean enableCobaltGen; public static boolean enableMithrilGen; public static boolean enableChromiumGem; public static boolean enableZincGen; public static boolean enableEndIslands; public static boolean enableMoonGoldGen; public static boolean enableMoonLeadGen; public static boolean enableMoonIronGen; public static boolean enableMoonNickelGen; public static boolean enableTemperateGemGen; public static boolean enableConiferousGemGen; public static boolean enableDesertGemGen; public static boolean enableTropicalGemGen; public static boolean enableCanyonGemGen; public static boolean enableFrozenGemGen; public static boolean enableHellishGemGen; public static boolean enableVoidGemGen; public static void Main(File file) { Configuration config = new Configuration(file); try { enableCopperGen = config.getBoolean("copperWorldGen", CATERGORY_WORLD, true, "Should Copper Be Generated"); enableTinGen = config.getBoolean("tinWorldGen", CATERGORY_WORLD, true, "Should Tin Be Generated"); enableSilverGen = config.getBoolean("silverWorldGen", CATERGORY_WORLD, true, "Should Silver Be Generated"); enableLeadGen = config.getBoolean("leadWorldGen", CATERGORY_WORLD, true, "Should Lead Be Generated"); enableNickelGen = config.getBoolean("nickelWorldGen", CATERGORY_WORLD, true, "Should Nickel Be Generated"); enablePlatinumGen = config.getBoolean("platinumWorldGen", CATERGORY_WORLD, true, "Should Platinum Be Generated"); enableAluminumGen = config.getBoolean("aluminumWorldGen", CATERGORY_WORLD, true, "Should Aluminum Be Generated"); enableCobaltGen = config.getBoolean("cobaltWorldGen", CATERGORY_WORLD, true, "Should Cobalt Be Generated"); enableMithrilGen = config.getBoolean("mithrilWorldGen", CATERGORY_WORLD, true, "Should Mithril Be Generated"); enableChromiumGem = config.getBoolean("chromiumWorldGen", CATERGORY_WORLD, true, "Should Chrome/Chromium Be Generated"); enableZincGen = config.getBoolean("zincWorldGen", CATERGORY_WORLD, true, "Should Zinc Be Generated"); enableEndIslands = config.getBoolean("endIslandWorldGen", CATERGORY_WORLD, true, "Should End Islands Be Generated"); enableMoonIronGen = config.getBoolean("moonIronWorldGen", CATERGORY_INTREGRATED_WORLD, true, "Should Moon Iron Be Generated"); enableMoonGoldGen = config.getBoolean("moonGoldWorldGen", CATERGORY_INTREGRATED_WORLD, true, "Should Moon Gold Be Generated"); enableMoonLeadGen = config.getBoolean("moonLeadWorldGen", CATERGORY_INTREGRATED_WORLD, true, "Should Moon Lead Be Generated"); enableMoonNickelGen = config.getBoolean("moonNickelWorldGen", CATERGORY_INTREGRATED_WORLD, true, "Should Moon Nickel Be Generated"); enableDesertGemGen = config.getBoolean("yellowSapphireWorldGen", CATERGORY_BIOME_GEMS, true, "Should Yellow Sapphire Be Generated on Deserts"); enableTemperateGemGen = config.getBoolean("greenSapphireWorldGen", CATERGORY_BIOME_GEMS, true, "Should Green Sapphire Be Generated on Forests"); enableConiferousGemGen = config.getBoolean("sapphireWorldGen", CATERGORY_BIOME_GEMS, true, "Should Sapphire Be Generated on Taiga"); enableTropicalGemGen = config.getBoolean("peridotWorldGen", CATERGORY_BIOME_GEMS, true, "Should Peridot Be Generated on Jungle"); enableCanyonGemGen = config.getBoolean("topazWorldGen", CATERGORY_BIOME_GEMS, true, "Should Topaz Be Generated on Both Savanna and Badlands"); enableFrozenGemGen = config.getBoolean("blueTopazWorldGen", CATERGORY_BIOME_GEMS, true, "Should Blue Topaz Be Generated on Frozen Biomes"); enableHellishGemGen = config.getBoolean("rubyWorldGen", CATERGORY_BIOME_GEMS, true, "Should Ruby Be Generated on Nether"); enableVoidGemGen = config.getBoolean("amethystWorldGen", CATERGORY_BIOME_GEMS, true, "Should Amethyst Be Generated on End"); } catch (Exception e) { System.err.print("Oh noes: " + e.getClass().getName()); } finally { config.save(); } } }
true
aa1d239b0283e504239f7c5f17c35f83d05eaff9
Java
killghost/Interface
/mobile_interface_1/src/main/java/zxjt/intfc/dao/trade/ptyw/A03SJKMMSLCXRepository.java
UTF-8
347
1.632813
2
[]
no_license
package zxjt.intfc.dao.trade.ptyw; import org.springframework.stereotype.Repository; import zxjt.intfc.dao.common.BaseRepository; import zxjt.intfc.entity.trade.ptyw.A03SJKMMSLCX; @Repository public interface A03SJKMMSLCXRepository extends BaseRepository<A03SJKMMSLCX> { //查询 public A03SJKMMSLCX findOneByFunctionid(int functionid); }
true
87f3f5a4d87b43c834ffe1eb70a75b354a1a769d
Java
cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
/ast_results/domogik_domodroid/Domodroid/src/main/java/Entity/Entity_Map.java
UTF-8
2,292
1.625
2
[]
no_license
// isComment package Entity; import android.app.Activity; import misc.tracerengine; public class isClassOrIsInterface extends Entity_Feature { private int isVariable; private int isVariable; private int isVariable; private String isVariable; private String isVariable; private Boolean isVariable = true; // isComment private Entity_client isVariable; public isConstructor(tracerengine isParameter, Activity isParameter, String isParameter, int isParameter, int isParameter, String isParameter, String isParameter, String isParameter, String isParameter, String isParameter, String isParameter, String isParameter, String isParameter, int isParameter, int isParameter, String isParameter) { super(isNameExpr, isNameExpr, isNameExpr, isNameExpr, isNameExpr, isNameExpr, isNameExpr, isNameExpr, isNameExpr, isNameExpr, isNameExpr, isNameExpr, isNameExpr); this.isFieldAccessExpr = isNameExpr; this.isFieldAccessExpr = isNameExpr; this.isFieldAccessExpr = isNameExpr; this.isFieldAccessExpr = isNameExpr; this.isFieldAccessExpr = true; } public int isMethod() { return isNameExpr; } public void isMethod(int isParameter) { this.isFieldAccessExpr = isNameExpr; } public int isMethod() { return isNameExpr; } public void isMethod(int isParameter) { this.isFieldAccessExpr = isNameExpr; } public int isMethod() { return isNameExpr; } public void isMethod(int isParameter) { this.isFieldAccessExpr = isNameExpr; } public String isMethod() { return isNameExpr; } public void isMethod(String isParameter) { this.isFieldAccessExpr = isNameExpr; } public void isMethod(Entity_client isParameter) { this.isFieldAccessExpr = isNameExpr; } public Entity_client isMethod() { return isNameExpr; } public String isMethod() { return isNameExpr; } public void isMethod(String isParameter) { this.isFieldAccessExpr = isNameExpr; } public Boolean isMethod() { return this.isFieldAccessExpr; } public void isMethod(Boolean isParameter) { this.isFieldAccessExpr = isNameExpr; } }
true
e0f3047194177e3caa3f76e1ad8e44e9f9176cf5
Java
OGKotov/task3-expression_calculator
/src/main/java/com/epam/jwd35/kotov/task3/expression_calculator/entity/LexemeType.java
UTF-8
326
2.125
2
[]
no_license
/* * Java Web Development * JWD 35 * Oleg Kotov * Task3 * Information Handling * From 06-11-2021 to 11-11-2021 */ package com.epam.jwd35.kotov.task3.expression_calculator.entity; public enum LexemeType { LEFT_BRACKET, RIGHT_BRACKET, OP_PLUS, OP_MINUS, OP_MULTIPLY, OP_DIVIDE, NUMBER, EOF; }
true
845d6be46f4cee83e96f7cac31f09f5d199277e3
Java
simbest/simbest-api
/src/main/java/com/alipay/pojo/account/query/AccountPageQueryResult.java
UTF-8
1,759
1.835938
2
[ "Apache-2.0" ]
permissive
package com.alipay.pojo.account.query; import java.io.Serializable; import java.util.List; import com.quigley.moose.mapping.provider.annotation.XML; import com.quigley.moose.mapping.provider.annotation.XMLField; import com.quigley.moose.mapping.provider.annotation.XMLList; @XML(name = "account_page_query_result") public class AccountPageQueryResult implements Serializable { private static final long serialVersionUID = -5053327361316268453L; @XMLList(name = "account_log_list", elementName = "AccountQueryAccountLogVO") private List<AccountQueryAccountLogVO> accountQueryAccountLogVOList; @XMLField(name = "has_next_page") private String hasNextPage; @XMLField(name = "page_no") private String pageNo; @XMLField(name = "page_size") private String pageSize; public List<AccountQueryAccountLogVO> getAccountQueryAccountLogVOList() { return this.accountQueryAccountLogVOList; } public void setAccountQueryAccountLogVOList( List<AccountQueryAccountLogVO> accountQueryAccountLogVOList) { this.accountQueryAccountLogVOList = accountQueryAccountLogVOList; } public String getHasNextPage() { return this.hasNextPage; } public void setHasNextPage(String hasNextPage) { this.hasNextPage = hasNextPage; } public String getPageNo() { return this.pageNo; } public void setPageNo(String pageNo) { this.pageNo = pageNo; } public String getPageSize() { return this.pageSize; } public void setPageSize(String pageSize) { this.pageSize = pageSize; } @Override public String toString() { return "AccountPageQueryResult [accountQueryAccountLogVOList=" + this.accountQueryAccountLogVOList + ", hasNextPage=" + this.hasNextPage + ", pageNo=" + this.pageNo + ", pageSize=" + this.pageSize + "]"; } }
true
f0fcb783de8d4b3fe1bfb5d871307ce2e347b238
Java
jaiishankar/estools
/relestimation/src/main/java/edu/aspen/capstone/estimation/relative/resource/ProjectResourceController.java
UTF-8
2,492
1.953125
2
[]
no_license
/* * * * */ package edu.aspen.capstone.estimation.relative.resource; import edu.aspen.capstone.estimation.relative.domain.ProjectDO; import edu.aspen.capstone.estimation.relative.service.ProjectService; import edu.aspen.capstone.estimation.relative.utils.JSONResponseWrapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; /** * * @author jaiishankar */ @Controller public class ProjectResourceController { @Autowired private ProjectService service; @RequestMapping(method = RequestMethod.GET, value = "/projects/user/{id}", headers = "Accept=application/json") public @ResponseBody JSONResponseWrapper listProjectByUserId(@PathVariable Integer id) { return service.getProjectsByUserId(id); } @RequestMapping(method = RequestMethod.GET, value = "/projects/owner/{id}", headers = "Accept=application/json") public @ResponseBody JSONResponseWrapper listProjectByOwnerId(@PathVariable Integer id) { return service.getProjectsByOwner(id); } @RequestMapping(method = RequestMethod.GET, value = "/projects/{id}", headers = "Accept=application/json") public @ResponseBody JSONResponseWrapper listProjectById(@PathVariable Integer id) { return service.getProjectsById(id); } @RequestMapping(method = RequestMethod.GET, value = "/projects/both/{id}", headers = "Accept=application/json") public @ResponseBody JSONResponseWrapper listAllForThisUser(@PathVariable Integer id) { return service.getAllProjects(id); } @RequestMapping(method = RequestMethod.POST, value = "/projects", headers = "Accept=application/json") public @ResponseBody JSONResponseWrapper saveProject(@RequestBody ProjectDO prj) { return service.saveOrUpdateProject(prj); } @RequestMapping(method = RequestMethod.POST, value = "/projects/delete/{id}", headers = "Accept=application/json") public @ResponseBody JSONResponseWrapper deleteProject(@PathVariable Integer id) { return service.deleteProject(id); } }
true
7f60eab21768f07f4659f633e9e42059907bc093
Java
marceltoben/evandrix.github.com
/go/jgo/src/main/java/jgo/runtime/Slices.java
UTF-8
4,465
2.953125
3
[]
no_license
package jgo.runtime; import java.util.*; /** * Utility functions for slices. * * @author Harrison Klaperman */ public final class Slices { private Slices() { } public static <T> Slice<T> make(int len) { return new ObjSlice<T>((T[])new Object[len]); } public static <T> Slice<T> make(int len, int cap) { return new ObjSlice<T>((T[])new Object[cap], 0, len); } public static <T> Slice<T> fromArray(T[] arr) { return new ObjSlice<T>(arr); } public static <T> Slice<T> fromArrayLow(T[] arr, int low) { return new ObjSlice<T>(arr).slice(low, arr.length); } public static <T> Slice<T> fromArrayHigh(T[] arr, int high) { return new ObjSlice<T>(arr).slice(0, high); } public static <T> Slice<T> fromArray(T[] arr, int low, int high) { return new ObjSlice<T>(arr).slice(low, high); } public static Slice<Boolean> fromArray(boolean[] arr) { return new BoolSlice(arr); } public static Slice<Boolean> fromArrayLow(boolean[] arr, int low) { return new BoolSlice(arr).slice(low, arr.length); } public static Slice<Boolean> fromArrayHigh(boolean[] arr, int high) { return new BoolSlice(arr).slice(0, high); } public static Slice<Boolean> fromArray(boolean[] arr, int low, int high) { return new BoolSlice(arr).slice(low, high); } public static Slice<Long> fromArray(long[] arr) { return new LongSlice(arr); } public static Slice<Long> fromArrayLow(long[] arr, int low) { return new LongSlice(arr).slice(low, arr.length); } public static Slice<Long> fromArrayHigh(long[] arr, int high) { return new LongSlice(arr).slice(0, high); } public static Slice<Long> fromArray(long[] arr, int low, int high) { return new LongSlice(arr).slice(low, high); } public static Slice<Integer> fromArray(int[] arr) { return new IntSlice(arr); } public static Slice<Integer> fromArrayLow(int[] arr, int low) { return new IntSlice(arr).slice(low, arr.length); } public static Slice<Integer> fromArrayHigh(int[] arr, int high) { return new IntSlice(arr).slice(0, high); } public static Slice<Integer> fromArray(int[] arr, int low, int high) { return new IntSlice(arr).slice(low, high); } public static Slice<Short> fromArray(short[] arr) { return new ShortSlice(arr); } public static Slice<Short> fromArrayLow(short[] arr, int low) { return new ShortSlice(arr).slice(low, arr.length); } public static Slice<Short> fromArrayHigh(short[] arr, int high) { return new ShortSlice(arr).slice(0, high); } public static Slice<Short> fromArray(short[] arr, int low, int high) { return new ShortSlice(arr).slice(low, high); } public static Slice<Character> fromArray(char[] arr) { return new CharSlice(arr); } public static Slice<Character> fromArrayLow(char[] arr, int low) { return new CharSlice(arr).slice(low, arr.length); } public static Slice<Character> fromArrayHigh(char[] arr, int high) { return new CharSlice(arr).slice(0, high); } public static Slice<Character> fromArray(char[] arr, int low, int high) { return new CharSlice(arr).slice(low, high); } public static Slice<Byte> fromArray(byte[] arr) { return new ByteSlice(arr); } public static Slice<Byte> fromArrayLow(byte[] arr, int low) { return new ByteSlice(arr).slice(low, arr.length); } public static Slice<Byte> fromArrayHigh(byte[] arr, int high) { return new ByteSlice(arr).slice(0, high); } public static Slice<Byte> fromArray(byte[] arr, int low, int high) { return new ByteSlice(arr).slice(low, high); } public static Slice<Double> fromArray(double[] arr) { return new DoubleSlice(arr); } public static Slice<Double> fromArrayLow(double[] arr, int low) { return new DoubleSlice(arr).slice(low, arr.length); } public static Slice<Double> fromArrayHigh(double[] arr, int high) { return new DoubleSlice(arr).slice(0, high); } public static Slice<Double> fromArray(double[] arr, int low, int high) { return new DoubleSlice(arr).slice(low, high); } public static Slice<Float> fromArray(float[] arr) { return new FloatSlice(arr); } public static Slice<Float> fromArrayLow(float[] arr, int low) { return new FloatSlice(arr).slice(low, arr.length); } public static Slice<Float> fromArrayHigh(float[] arr, int high) { return new FloatSlice(arr).slice(0, high); } public static Slice<Float> fromArray(float[] arr, int low, int high) { return new FloatSlice(arr).slice(low, high); } }
true
2271ff3d8472714830c37efe234dfc3f98db1f9f
Java
NhamPhanDinh/math
/MathLogic/src/ydc/math/braintest/mathlogic/ultis/Untils.java
UTF-8
716
2.640625
3
[ "Apache-2.0" ]
permissive
package ydc.math.braintest.mathlogic.ultis; import android.app.Activity; import android.content.Context; import android.net.ConnectivityManager; import android.util.Log; public class Untils { /** * check connect internet * */ public static boolean checkInternetConnection(Activity activity) { ConnectivityManager conMgr = (ConnectivityManager) activity .getSystemService(Context.CONNECTIVITY_SERVICE); // ARE WE CONNECTED TO THE NET if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected()) { return true; } else { Log.v("Until", "Internet Connection Not Present"); return false; } } }
true
2b629b6f3a15ff8977295a846ffce53b1f587fd2
Java
alexbabalau/movie-manager-service
/src/test/java/service/delete/ReplyDeleteTest.java
UTF-8
2,449
2.015625
2
[]
no_license
package service.delete; import application.MovieManagerServiceApplication; import model.Reply; import model.Review; import org.springframework.test.context.ActiveProfiles; import repository.ReplyRepository; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.servlet.MockMvc; import javax.transaction.Transactional; import java.util.Optional; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest(classes = MovieManagerServiceApplication.class) @AutoConfigureMockMvc @TestPropertySource("classpath:application-test.properties") @ActiveProfiles("test") public class ReplyDeleteTest { @Autowired private MockMvc mockMvc; @Autowired private ReplyRepository replyRepository; @Test @Transactional public void reviewDeleteTest_StatusNoContent() throws Exception{ long countBefore = replyRepository.count(); mockMvc.perform(delete("/replies/1/user1") .header("authorization", "mockToken") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); Optional<Reply> retrievedReply = replyRepository.findById(1L); assertTrue(!retrievedReply.isPresent()); long countAfter = replyRepository.count(); assertTrue(countAfter == countBefore - 1); } @Test @Transactional public void reviewDeleteTest_StatusNotFound() throws Exception{ mockMvc.perform(delete("/replies/0/user1") .header("authorization", "mockToken") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } @Test @Transactional public void reviewDeleteTest_StatusForbidden() throws Exception{ mockMvc.perform(delete("/replies/1/user2") .header("authorization", "mockToken") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isForbidden()); } }
true
8a771cd7ba8596376479c9624a23e984aa06c217
Java
ssahla/tikape-harjoitus
/src/main/java/tikape/harjoitus/database/AnnosRaakaAineDao.java
UTF-8
6,098
2.3125
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 tikape.harjoitus.database; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import tikape.harjoitus.domain.AnnosRaakaAine; import tikape.harjoitus.domain.RaakaAine; public class AnnosRaakaAineDao implements Dao<AnnosRaakaAine, Integer> { private Tietokanta tk; public AnnosRaakaAineDao(Tietokanta tk) { this.tk = tk; } @Override public AnnosRaakaAine haeYksi(Integer key) throws SQLException { // ei toteutettu return null; } public Boolean raakaAineOnAnnoksessa(Integer aId, Integer rId) throws SQLException { Connection conn = tk.yhteys(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM AnnosRaakaAine " + "WHERE raaka_aine_id = ? AND annos_id = ?"); stmt.setInt(1, rId); stmt.setInt(2, aId); ResultSet res = stmt.executeQuery(); Boolean result = res.next(); res.close(); stmt.close(); conn.close(); return result; } @Override public List<AnnosRaakaAine> haeKaikki() throws SQLException { Connection conn = tk.yhteys(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM AnnosRaakaAine"); ResultSet res = stmt.executeQuery(); List<AnnosRaakaAine> AnnosRaakaAineet = new ArrayList<>(); while (res.next()) { Integer raakaAine_id = res.getInt("raaka_aine_id"); Integer annos_id = res.getInt("annos_id"); Integer jarjestys = res.getInt("jarjestys"); String maara = res.getString("maara"); String ohje = res.getString("ohje"); AnnosRaakaAineet.add(new AnnosRaakaAine(raakaAine_id, annos_id, jarjestys, maara, ohje, "")); } res.close(); stmt.close(); conn.close(); return AnnosRaakaAineet; } public List<AnnosRaakaAine> haeKaikkiAnnoksella(Integer annos_id) throws SQLException { Connection conn = tk.yhteys(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM AnnosRaakaAine" + " WHERE annos_id = ? ORDER BY jarjestys"); stmt.setInt(1, annos_id); ResultSet res = stmt.executeQuery(); List<AnnosRaakaAine> AnnosRaakaAineet = new ArrayList<>(); while (res.next()) { Integer raakaAine_id = res.getInt("raaka_aine_id"); Integer jarjestys = res.getInt("jarjestys"); String maara = res.getString("maara"); String ohje = res.getString("ohje"); AnnosRaakaAineet.add(new AnnosRaakaAine(annos_id, raakaAine_id, jarjestys, maara, ohje, "")); } res.close(); stmt.close(); conn.close(); return AnnosRaakaAineet; } public List<AnnosRaakaAine> haeKaikkiRaakaAineella(Integer raakaAine_id) throws SQLException { Connection conn = tk.yhteys(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM AnnosRaakaAine" + " WHERE raaka_aine_id = ?"); stmt.setInt(1, raakaAine_id); ResultSet res = stmt.executeQuery(); List<AnnosRaakaAine> AnnosRaakaAineet = new ArrayList<>(); while (res.next()) { Integer annos_id = res.getInt("annos_id"); Integer jarjestys = res.getInt("jarjestys"); String maara = res.getString("maara"); String ohje = res.getString("ohje"); AnnosRaakaAineet.add(new AnnosRaakaAine(annos_id, raakaAine_id, jarjestys, maara, ohje, "")); } res.close(); stmt.close(); conn.close(); return AnnosRaakaAineet; } public Integer viimeisinJarjestysAnnoksella(Integer annos_id) throws SQLException { // palauttaa suurimman järjestysnumeron annoksen raaka-aineista Connection conn = tk.yhteys(); PreparedStatement stmt = conn.prepareStatement("SELECT MAX(jarjestys) AS suurin FROM AnnosRaakaAine WHERE annos_id = ?"); stmt.setInt(1, annos_id); ResultSet res = stmt.executeQuery(); Integer suurin = 0; if (res.next()) { suurin = res.getInt("suurin"); } res.close(); stmt.close(); conn.close(); return suurin; } @Override public void poista(Integer key) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void poistaKaikkiAnnoksella(Integer annos_id) throws SQLException { Connection conn = tk.yhteys(); PreparedStatement stmt = conn.prepareStatement("DELETE FROM AnnosRaakaAine WHERE annos_id = ?"); stmt.setInt(1, annos_id); stmt.execute(); stmt.close(); conn.close(); } public void poistaKaikkiAnnoksellaJaRaakaAineella(Integer annos_id, Integer raakaAine_id) throws SQLException { Connection conn = tk.yhteys(); PreparedStatement stmt = conn.prepareStatement("DELETE FROM AnnosRaakaAine WHERE annos_id = ? " + "AND raaka_aine_id = ?"); stmt.setInt(1, annos_id); stmt.setInt(2, raakaAine_id); stmt.execute(); stmt.close(); conn.close(); } @Override public void tallenna(AnnosRaakaAine ar) throws SQLException { Connection conn = tk.yhteys(); PreparedStatement stmt = conn.prepareStatement("INSERT INTO AnnosRaakaAine " + "(raaka_aine_id, annos_id, jarjestys, maara, ohje) VALUES (?, ?, ?, ?, ?)"); stmt.setInt(1, ar.getRaakaAine_id()); stmt.setInt(2, ar.getAnnos_id()); stmt.setInt(3, ar.getJarjestys()); stmt.setString(4, ar.getMaara()); stmt.setString(5, ar.getOhje()); stmt.execute(); stmt.close(); conn.close(); } }
true
e3cff9a3f6c06bd6b68c7c1abab85b0216db315c
Java
miccgood55/BWM_GenInterface_1-1
/GenData/GenData/src/gen/GenUnitTrust.java
UTF-8
14,112
2.046875
2
[]
no_license
package src.gen; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import src.GenerateFile; import src.extend.Constants; import src.extend.GenFilesUtils; public class GenUnitTrust { private final static Map<Integer, String> FUND_CODE_MAP = new HashMap<Integer, String>(); private static int FUND_SEQ = 0, NO_OF_UH = 0, NO_OF_POSITION = 0, NO_OF_TRANSACTION = 0, NO_OF_UH_FILE = 0, NO_OF_POSITION_FILE = 0, NO_OF_TRANSACTION_FILE = 0; private static StringBuffer UH_SB = new StringBuffer(), POSITION_SB = new StringBuffer(), TRANSACTION_SB = new StringBuffer(); private final static String PATH_UH = Constants.DIR + Constants.DIR_UH; private final static String PATH_POS = Constants.DIR + Constants.DIR_UT_POS; private final static String PATH_TX= Constants.DIR + Constants.DIR_UT_TX; private final static String ISSUER_CODE = "BAY"; // Security Code = THMMF,THFI,FIFFI,FFICE,THEQ,FIFEQ,THMIX,FIFMIX,COMM,PROP public static void generateFundCode() throws IOException { String path = Constants.DIR + Constants.DIR_FUNDCODE; File logPath = new File(path); if(!logPath.exists()){ logPath.mkdirs(); } int noOfFile = 0; StringBuffer total = new StringBuffer(); for (int seq = 1; seq <= GenerateFile.NO_OF_FUND; seq++) { String fundCode = "FUND-BAY-" + String.format("%05d", seq); // String record = "||||||" + fundCode + "|||SEC-CAT-UNITTRUST|BAY" ; String record = ISSUER_CODE + "|"+fundCode+"|THMMF|||||||||THB" ; total.append(record).append(Constants.DEFAULT_LINE_SEPARATOR); FUND_CODE_MAP.put(seq, fundCode); if(seq%GenerateFile.LIMIT_FUND_PER_FILE == 0){ noOfFile++; File file = new File(path + Constants.FILE_NAME_FUNDCODE + noOfFile + ".txt"); GenFilesUtils.writeFile(file, total, true); } } System.out.println("Generate FundCode Done"); } public static void generateUnitholder() throws IOException { File logPath = new File(PATH_UH); if(!logPath.exists()){ logPath.mkdirs(); } for (int seq = 1; seq <= GenerateFile.NO_OF_CUSTOMER; seq++) { for (int i = 1; i <= GenerateFile.NO_OF_UH_PER_CIF; i++) { NO_OF_UH++; String cifCode = "P" + String.format("%06d", seq); String uh = "UH_" + cifCode + "_" + String.format("%02d", i); // String record = uh + "|||||0|" + cifCode; String record = uh + "|UH_NAME|UH_NAME_TH|0|" + cifCode + "|||||||||||" +"|BAY|00001|"+ISSUER_CODE+"|||"; UH_SB.append(record).append(Constants.DEFAULT_LINE_SEPARATOR); generateUnitTrustPosition(cifCode, uh); if(NO_OF_UH%GenerateFile.LIMIT_UH_PER_FILE == 0){ NO_OF_UH_FILE++; File file = new File(PATH_UH + Constants.FILE_NAME_UH + NO_OF_UH_FILE + ".txt"); GenFilesUtils.writeFile(file, UH_SB, true); } if(NO_OF_UH == GenerateFile.NO_OF_UH){ break; } } } if(UH_SB.length() > 0){ NO_OF_UH_FILE++; File file = new File(PATH_UH + Constants.FILE_NAME_UH + NO_OF_UH_FILE + ".txt"); GenFilesUtils.writeFile(file, UH_SB, true); } if(POSITION_SB.length() > 0){ NO_OF_POSITION_FILE++; File file = new File(PATH_POS + Constants.FILE_NAME_UT_POS + NO_OF_POSITION_FILE + "_" + GenerateFile.CURRENT_DATE_FORMAT + ".txt"); GenFilesUtils.writeFile(file, POSITION_SB, true); } if(TRANSACTION_SB.length() > 0){ NO_OF_TRANSACTION_FILE++; File file = new File(PATH_TX + Constants.FILE_NAME_UT_TX + "_" + NO_OF_TRANSACTION_FILE + ".txt"); GenFilesUtils.writeFile(file, TRANSACTION_SB, true); } System.out.println("Generate Unitholder Done"); } // public static void generateUnitTrustPosition(int records, int limit, int noOfUh, int noOfFund, int max) throws IOException { public static void generateUnitTrustPosition(String cifCode, String uh) throws IOException { File logPath = new File(PATH_POS); if(!logPath.exists()){ logPath.mkdirs(); } for (int j = 1; j <= GenerateFile.NO_OF_UT_POS_PER_UH; j++) { NO_OF_POSITION++; String fundCode = FUND_CODE_MAP.get( ( (FUND_SEQ++) % FUND_CODE_MAP.size() ) + 1); String record = GenerateFile.CURRENT_DATE_FORMAT + "|" + uh + "|" +ISSUER_CODE +"|"+fundCode+ "|3333.333|444.4444||||||"; // 1 As of Date Y Y วันที่ข้อมูล Y DATE 8 yyyyMMdd N // 2 Unit Holder No Y Y Unit Holder No Y STRING 20 ใช้ใน look up unitholder (Account) พิจารณาคู่�ับ Issuer Code �ละ Source N // 3 Issuer Code Y Y ชื่อย่อ บลจ Y STRING 20 ใช้ใน�าร look up หา unitholder �ละ Fund Code Y // 4 Fund Code Y Y ชื่อย่อ�องทุน Y STRING 50 Y // 5 Outstanding Units Y Y ยอดหน่วยสะสม Y BIGDECIMAL 23 22|6 N // 6 Market Value Y Y มูลค่าปัจจุบันของยอดหน่วยสะสม Y BIGDECIMAL 21 20|2 N // 7 MTM Date Y Y วันที่ของราคาที่ใช้ใน�ารคำนวณมูลค่า N DATE 8 yyyyMMdd วันที่ใช้ nav เมื่อ as of date ตรง�ับวันหยุดทำ�าร N // 8 Market Price Y Y ราคาตลาด N BIGDECIMAL 21 20|2 N // 9 Average Cost Y Y ต้นทุนเฉลี่ย N BIGDECIMAL 23 22|6 ต้นทุนเฉลี่ยที่ซื้อ �รณี LTF KSAM ไม่ส่งเพราะอาจผิด�ลต N // 10 Cost Y Y ต้นทุนคงเหลือ N BIGDECIMAL 21 20|2 N // 11 First Investment Date Y Y วันที่ลงทุนครั้ง�ร� N DATE 8 yyyyMMdd N // 12 Source D N Source Y STRING 20 ใช้ใน�าร look up หา unitholder N POSITION_SB.append(record).append(Constants.DEFAULT_LINE_SEPARATOR); generateUnitTrustTransaction(uh, fundCode); if(NO_OF_POSITION% (GenerateFile.LIMIT_UH_PER_FILE * 2) == 0){ NO_OF_POSITION_FILE++; File file = new File(PATH_POS + Constants.FILE_NAME_UT_POS + NO_OF_POSITION_FILE + "_" + GenerateFile.CURRENT_DATE_FORMAT + ".txt"); GenFilesUtils.writeFile(file, POSITION_SB, true); } } } public static void generateUnitTrustTransaction(String uh, String fundCode) throws IOException { File logPath = new File(PATH_TX); if(!logPath.exists()){ logPath.mkdirs(); } for (int tx = 1; tx <= GenerateFile.NO_OF_UT_TX_PER_POS; tx++) { NO_OF_TRANSACTION++; String txNo = "UT_TX_NO_" + String.format("%08d", NO_OF_TRANSACTION); // String record = "11.11||20150223|11.11||" + txNo + "||||||20150223|11.11||||||||" + fundCode + "|A|BUY|" + uh; String record = ISSUER_CODE + "|" + fundCode + "|" + uh + "|" + GenerateFile.CURRENT_DATE_FORMAT + "|" + GenerateFile.CURRENT_DATE_FORMAT + "|" + GenerateFile.CURRENT_DATE_FORMAT + "|BUY|BAY|00001|11.11|11.11|11.11|11.11||||"+txNo+"|||||||"; // 1 Issuer Code Y Y AIMC Code ex. KSAM Y STRING 20 Y // 2 Fund Code Y Y Fund Code ex. KFCASH Y STRING 50 Y // 3 Unit Holder No Y Y Unit Holder No Y STRING 20 Y // 4 Order Date Y Y วันที่ทำราย�าร Y DATE 8 yyyyMMdd N // 5 Allot Date Y Y วันที่จัดสรร(วันที่ของราคาที่ใช้ใน�ารจัดสรร) Y DATE 8 yyyyMMdd N // 6 Settle Date Y Y วันที่รับเงิน / วันที่จ่ายเงิน Y DATE 8 yyyyMMdd เฉพาะราย�ารขายให้ระบุวันที่ Settle Date = วันที่รับเงิน เช่น T+3 ส่วนราย�ารอื่นๆ ที่เหลือให้ระบุ Settle Date = AllotDate N // 7 Transaction Type Y Y Transaction Type : BUY, SELL,SWIN, SWOUT, TRIN, TROUT, XSWIN, XSWOUT Y STRING 20 ระบบ เ�็บ BUY=1, SELL = 2 , SWIN = 3, SWOUT = 4, TRIN = 5, TROUT = 6, XSWIN = 7, XSWOUT = 8 N // 8 Agent Code D=KS Y ชือย่อตัว�ทนขาย Y STRING 20 KS,BAY N // 9 Agent Branch Code Y Y รหัสสาขาตัว�ทนขาย Y STRING 20 N // 10 Allot Unit Y Y หน่วยที่ได้รับ�ารจัดสรร Y BIGDECIMAL 23 22|6 N // 11 Balance Unit Y Y ยอดหน่วยสะสมปัจจุบัน N BIGDECIMAL 23 22|6 N // 12 Price/Unit Y Y ราคาที่ใช้ใน�ารจัดสรร Y BIGDECIMAL 23 22|6 N // 13 Allot Cost Y Y จำนวนเงินที่ได้ใน�ารจัดสรร Unit * Price /Unit Y BIGDECIMAL 21 20|2 N // 14 Realized G/L Y Y Realized Gain/Loss �ำไร/ขาดทุนที่เ�ิดขึ้นจริง (Required สำหรับ Tx. Type ที่เป็น SELL, SO) ขี้น�ับประเภท�องทุน หา�เป็น LTF = FIFO ที่เหลือเป็น average N BIGDECIMAL 21 20|2 N // 15 Swin Allot Date Y Y as of date ของราย�ารสับเปลี่ยนเข้า [ไม่ใช่ MTM Date] // ส่ง field นี้มาเฉพาะตอนส่งราย�าร Switch out N DATE 8 yyyyMMdd N // 16 Switching Fund Code Y Y ชื่อย่อ�องทุนของราย�ารสับเปลี่ยนตรงข้าม // หา�เป็นราย�าร Switch-out ให้ระบ Switch-in Fund // หา�เป็นราย�าร Switch-in ให้ระบุ Switch-out Fund N STRING 50 N // 17 Ext TX No Y Y Transaction No of another system ( Reference No for cancel this transaction ) N STRING 50 N // 18 IC Code Y Y รหัส license ของพนั�งานผู้ทำราย�าร N STRING 20 N // 19 Sale Code Y Y รหัสพนั�งานผู้ทำราย�าร N STRING 20 N // 20 Referral Code Y Y รหัสพนั�งานผู้�นะนำ N STRING 20 N // 21 Sequence Y Y ลำดับที่ของราย�าร N STRING 15 N // 22 Status Y Y Status = N=New(unallot) D=Deleted transaction,A=Active transaction N STRING 10 N // 23 Remark Y Y �รณี Transfer บอ� unithlder ที่ reference N STRING 50 N // 24 Source D N Source Y STRING 20 N TRANSACTION_SB.append(record).append(Constants.DEFAULT_LINE_SEPARATOR); if(NO_OF_TRANSACTION%(GenerateFile.LIMIT_UH_PER_FILE * 2) == 0){ NO_OF_TRANSACTION_FILE++; File file = new File(PATH_TX + Constants.FILE_NAME_UT_TX + "_" + NO_OF_TRANSACTION_FILE + ".txt"); GenFilesUtils.writeFile(file, TRANSACTION_SB, true); } } } }
true
8ed5a2c100c5358e7ac5a8338fbd3cc0562be582
Java
Liplhello/project_68
/src/com/firstKind/String5_6.java
UTF-8
700
2.96875
3
[]
no_license
package com.firstKind; /** * Created by lpl on 2018/6/25. */ public class String5_6 { public static void main(String[] args) { String str = "Java技术学习班20070326"; String str1 = "MLDN JAVA"; String str2 = "Java技术学习班20070326 MLDN 老师"; String userCard = "110110154011113452"; System.out.println(str.substring(str.length()-8)); System.out.println(str1.replaceAll("JAVA", "J2EE")); System.out.println(str.charAt(8 - 1)); System.out.println(str.replace("0", "")); System.out.println(str2.replace(" ","")); System.out.println(userCard.substring(userCard.length()-12,userCard.length()-4)); } }
true
0f0930ba4850352f64ea4e039d65c9f74bc9aee8
Java
vikramtambe/hackerrank-test
/src/main/java/com/hackerrank/test/SolutionRepeatedString.java
UTF-8
2,656
3.671875
4
[]
no_license
package com.hackerrank.test; import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; /** * Lilah has a string, s , of lowercase English letters that she repeated infinitely many times. Given an integer, n , find and print the number of letter a's in the first n letters of Lilah's infinite string. For example, if the string s = 'abcac' and n = 10, the substring we consider is abcacabcac, the first 10 characters of her infinite string. There are 4 occurrences of a in the substring. Function Description Complete the repeatedString function in the editor below. It should return an integer representing the number of occurrences of a in the prefix of length n in the infinitely repeating string. repeatedString has the following parameter(s): s: a string to repeat n: the number of characters to consider Input Format The first line contains a single string, s. The second line contains an integer, n. Constraints 1 <= s <= 100 1 <= n <= 10^12 For of the test cases, . Output Format Print a single integer denoting the number of letter a's in the first letters of the infinite string created by repeating infinitely many times. Sample Input 0 aba 10 Sample Output 0 7 Explanation 0 The first letters of the infinite string are abaabaabaa. Because there are a's, we print on a new line. * @author vtambe * */ public class SolutionRepeatedString { // Complete the repeatedString function below. static long repeatedString(String s, long n) { long length = s.length(); long count_of_a=0; long temp=n%length; for(long i=0;i<length;++i) { System.out.println("i " + i + " temp "+ temp); if(i<temp && s.charAt((int)i)=='a') { ++count_of_a; } if(s.charAt((int)i)=='a') { count_of_a += (long)(n/length); } } return count_of_a; } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { //BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); String s = scanner.nextLine(); long n = scanner.nextLong(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); long result = repeatedString(s, n); System.out.println("No of repeatedString :" + result); //bufferedWriter.write(String.valueOf(result)); //bufferedWriter.newLine(); //bufferedWriter.close(); scanner.close(); } }
true
3cf90e9090925be0851dfd368c4fb83efe5fd8ae
Java
paramonov-yo/java_homeworks
/JavaSpring/src/main/java/com/JavaDevSpring/service/impl/BookServiceImpl.java
UTF-8
1,420
2.53125
3
[]
no_license
package com.JavaDevSpring.service.impl; import com.JavaDevSpring.model.Book; import com.JavaDevSpring.repository.BookRepository; import com.JavaDevSpring.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class BookServiceImpl implements BookService { public BookServiceImpl(BookRepository repository) { BookServiceImpl.repository = repository; } public BookRepository getRepository() { return repository; } public void setRepository(BookRepository repository) { BookServiceImpl.repository = repository; } @Autowired private static BookRepository repository; @Override public List<Book> getAll() { List<Book> bookList = repository.findAll(); for (Book book : bookList) { System.out.println(book.getBookName()); } return null; } @Override public Optional<Book> findById(int id) { return repository.findById(id); } @Override public Book save(Book book) { return repository.save(book); } @Override public Book update(int id, Book book) { return repository.save(book); } @Override public void delete(int id) { repository.findById(id).ifPresent(Book -> repository.delete(Book)); } }
true
adcba021d7919b3323c39851bf562a569e2dfbe5
Java
keerthivyas/90-days-program
/week3/PrintString5.java
UTF-8
611
3.703125
4
[]
no_license
package freeJava.week3; import java.util.Scanner; public class PrintString5 { public static void main(String[] args) { String[] arr = new String[5]; Scanner input = new Scanner(System.in); System.out.println("Enter elements : "); for (int i = 0; i <5; i++) { arr[i] = input.next(); } System.out.println("String with more than 5 characters : "); for (int i = 0; i <5; i++) { if (arr[i].length()>5) { System.out.println(arr[i]); } } } }
true
7ef43a15653f5668e07e2a9910ec543abdfe4a2f
Java
gruzilla/swag
/modelDrivenSwag/src-gen/swag/db/dao/MapDAO.java
UTF-8
1,749
2.703125
3
[]
no_license
package swag.db.dao; import javax.persistence.*; import swag.db.model.Map; public class MapDAO { private static EntityManagerFactory entityManagerFactory; private static EntityManager entityManager; public static void initializeEntityManagerFactory( EntityManagerFactory entityManagerFactory) { MapDAO.entityManagerFactory = entityManagerFactory; entityManager = entityManagerFactory.createEntityManager(); } public void delete(Map map) { try { entityManager.getTransaction().begin(); entityManager.remove(map); entityManager.getTransaction().commit(); } catch (RuntimeException e) { rollBackTransaction(entityManager); throw e; } } public Map get(Integer key) { Map map = entityManager.find(Map.class, key); return map; } public void persist(Map map) { entityManager.getTransaction().begin(); try { entityManager.persist(map); entityManager.getTransaction().commit(); } catch (RuntimeException e) { rollBackTransaction(entityManager); throw e; } } public Map update(Map map) { Map merged; entityManager.getTransaction().begin(); try { merged = entityManager.merge(map); entityManager.getTransaction().commit(); return merged; } catch (RuntimeException e) { rollBackTransaction(entityManager); throw e; } } public void refresh(Map map) { try { entityManager.refresh(map); } catch (RuntimeException e) { throw e; } } private void rollBackTransaction(EntityManager entityManager) { if (entityManager.getTransaction().isActive()) entityManager.getTransaction().rollback(); } public static void shutdown(EntityManager entityManager) { if (entityManager != null && entityManager.isOpen()) { entityManager.close(); } } }
true
58846473f1d8daf787a91da85a7f31a68b761c6c
Java
SaoriKaku/LaiCode
/Array/2D Array/1. Spiral Order Traverse I.Java
UTF-8
1,427
3.984375
4
[]
no_license
/* Traverse an N * N 2D array in spiral order clock-wise starting from the top left corner. Return the list of traversal sequence. Assumptions The 2D array is not null and has size of N * N where N >= 0 Examples { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} } the traversal sequence is [1, 2, 3, 6, 9, 8, 7, 4, 5] */ public class Solution { public List<Integer> spiral(int[][] matrix) { // Write your solution here List<Integer> result = new ArrayList<>(); int size = matrix.length; spiralHelper(matrix, 0, size, result); return result; } private void spiralHelper(int[][] matrix, int offset, int size, List<Integer> result) { // offset is the [x] and [y] coordinates of the upper-left corner of the box // size is the column & row number for the current matrix if(size == 0) { return; } if(size == 1) { result.add(matrix[offset][offset]); return; } // 1 2 for(int i = 0; i < size - 1; i++) { result.add(matrix[offset][offset + i]); } // 3 6 for(int i = 0; i < size - 1; i++) { result.add(matrix[offset + i][offset + size - 1]); } // 9 8 for(int i = size - 1; i >= 1; i--) { result.add(matrix[offset + size - 1][offset + i]); } // 7 4 for(int i = size - 1; i >= 1; i--) { result.add(matrix[offset + i][offset]); } spiralHelper(matrix, offset + 1, size - 2, result); } }
true
73f1430a1afb12055d98caf573fdafe27cac9ad2
Java
chen4778482/jjfw
/test/interfacetest/HttpUtil.java
UTF-8
7,108
2.328125
2
[]
no_license
package interfacetest; /** * @class IfsUtil * @Describtion ��������� * @Date 2011-09-15 * @Author zhouyouyi */ import java.io.IOException; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.DeleteMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.PutMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.params.HttpMethodParams; public class HttpUtil { public static final String XML_HEAD = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"; public static final String ENTER = "\r\n"; public static final String TYPE_XML = "text/xml"; public static final String ENCODE_DEFAULT = "UTF-8"; // 默认编码:UTF-8 // public static final String SERVERURL = "http://10.137.29.133:8080"; public static final String SERVERURL = "http://127.0.0.1:8089"; // public static final String SERVERURL="http://112.80.141.35:9999"; // public static final String SERVERURL="http://192.168.1.103:8080"; // public static final String SERVERURL="http://86.96.241.70:8000"; public static String AUTH = "c81ef0edea420a7e7196919bf8017b2fcbf9559cec7a87c7c2016baac85e70c6a9cb738434d21fa10e4fab6824221c583beb5a2052f33f83301d26e8c39c7e2aba92329ecb78e6d11c32e773b9ea3519"; // static // { // byte []b = AUTH.getBytes(); // AUTH = new String(Base64.encode(b)); // } /** * "bmdHYnJyYWJ8MXwxfDEzMzg3NjUyODMyMzl8QXVCY0xidE0xMzF5dG43aHliOGFoMElNeFV3VDJLUGJSMDNNR2x1ek1lMTB5QlU2bVlsb01HQTZfVGVDSVlsZUpWZzJMRmpiaDVJekZINk1xSjBhQllKSjZCbGF2bWRuOG5zbWhiSWRBYWc5WFJ0LldjRHE0cnFhU1hsSTQ3NktzNUJQMGlfWXFwQVJmNDBnN0I1YkpPVG4wT0kwTUFsR3JmWVI5WlouVnh3LQ==" * * @param url * QHL_aQdV|1|1|1338407076063| * CDhHS2aEBJfi67yBcrkCc9pdgUf4lp3bzXeU6K36DYM7F5MDm.ZZ5_VNVX.5 * yJ8j63Poldo3XHxqEGu9RvUrvlKMWYbNatc8uctvIZueDfYZGfPIhgF * .uCIs6ImacjfMHl_1eaiO12rJ9BIsVDIPZYrgJPTwkuazAqBlSwexhaQ- * get方式请求的地�? * @param auth * 鉴权用的�? * @return */ public static String getMethodRequest(String methodName, String url, String auth) { byte[] responseBody = null; // 构�?HttpClient的实�?�?? HttpClient httpClient = new HttpClient(); // 创建GET方法的实�?�?? GetMethod getMethod = new GetMethod(url); // 使用系统提供的默认的恢复策略 getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); getMethod.setRequestHeader("Authorization", auth); System.out.println(methodName + " requestUrl: " + ENTER + url); try { // 执行getMethod int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + getMethod.getStatusLine()); } // 读取内容 responseBody = getMethod.getResponseBody(); // 处理内容 String response = new String(responseBody); System.out .println(methodName + "responseDate: " + ENTER + response); } catch (HttpException e) { // 发生致命的异常,可能是协议不对或者返回的内容有问�? System.out.println("Please check your provided http address!"); e.printStackTrace(); } catch (IOException e) { // 发生网络异常 e.printStackTrace(); } finally { // 释放连接 getMethod.releaseConnection(); } return (new String(responseBody)); } /** * @throws IOException * @throws HttpException * */ public static String postMethodRequest(String methodName, String reqXml, String url, String auth) throws HttpException, IOException { // 构�?HttpClient的实�?�?? HttpClient httpClient = new HttpClient(); // 创建POST方法的实�?�?? PostMethod postMethod = new PostMethod(url); StringRequestEntity requestEntity = new StringRequestEntity( reqXml.toString(), TYPE_XML, ENCODE_DEFAULT); postMethod.setRequestEntity(requestEntity); postMethod.setRequestHeader("Authorization", auth); System.out.println(methodName + " requestDate: " + ENTER + url); int statusCode = httpClient.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + postMethod.getStatusLine()); } // 读取内容 byte[] responseBody = postMethod.getResponseBody(); // 处理内容 String response = new String(responseBody); System.out.println(methodName + "responseDate: " + ENTER + response); postMethod.releaseConnection(); return response; } /** * @throws IOException * @throws HttpException * */ public static String putMethodRequest(String methodName, String reqXml, String url, String auth) throws HttpException, IOException { // 构�?HttpClient的实�?�?? HttpClient httpClient = new HttpClient(); // 创建POST方法的实�?�?? PutMethod postMethod = new PutMethod(url); StringRequestEntity requestEntity = null; requestEntity = new StringRequestEntity(reqXml.toString(), TYPE_XML, ENCODE_DEFAULT); postMethod.setRequestEntity(requestEntity); postMethod.setRequestHeader("Authorization", auth); System.out.println(methodName + " requestDate: " + ENTER + url); int statusCode = httpClient.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + postMethod.getStatusLine()); } // 读取内容 byte[] responseBody = postMethod.getResponseBody(); // 处理内容 String response = new String(responseBody); System.out.println(methodName + "responseDate: " + ENTER + response); postMethod.releaseConnection(); return response; } /** * * @param url * delete方式请求的地�? * @param auth * 鉴权用的�? * @return */ public static String deleteMethodRequest(String methodName, String url, String auth) { byte[] responseBody = null; // 构�?HttpClient的实�?�?? HttpClient httpClient = new HttpClient(); // 创建GET方法的实�?�?? DeleteMethod delMethod = new DeleteMethod(url); // 使用系统提供的默认的恢复策略 delMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); delMethod.setRequestHeader("Authorization", auth); System.out.println(methodName + " requestUrl: " + ENTER + url); try { // 执行getMethod int statusCode = httpClient.executeMethod(delMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + delMethod.getStatusLine()); } // 读取内容 responseBody = delMethod.getResponseBody(); // 处理内容 String response = new String(responseBody); System.out .println(methodName + "responseDate: " + ENTER + response); } catch (HttpException e) { // 发生致命的异常,可能是协议不对或者返回的内容有问�? System.out.println("Please check your provided http address!"); e.printStackTrace(); } catch (IOException e) { // 发生网络异常 e.printStackTrace(); } finally { // 释放连接 delMethod.releaseConnection(); } return (new String(responseBody)); } }
true
3394563ec9841b9cef3c6c43630ede4b76f18bcf
Java
minhhoangtcu/Sortingcomparison
/src/sorting/algorithms/QuickSort.java
UTF-8
2,373
3.984375
4
[]
no_license
package sorting.algorithms; public class QuickSort<T extends Comparable<T>> extends SortingAlgorithm<T> { public QuickSort(T[] input) { super(); sort(input); sortingMethod = SortingMethod.QUICK; } @Override protected void sort(T[] input) { sort(input, 0, input.length-1); output = input; } private void sort(T[] input, int lo, int hi) { if (hi <= lo) return; int pivot = partition(input, lo, hi); sort(input, lo, pivot-1); sort(input, pivot+1, hi); } /** * <p>Partition the input array into a[lo..i-1], a[i], a[i+1..hi]<br></p> * <p>The program is going to keep a as a pivot. And, it will * run two pointer, one from the left, one from the right into the middle. While the pointers * do not cross each other, exchange variables that the left pointer found larger than the pivot, * and the right pointer found smaller than the pivot. <br></p> * <p>For the case of <b>[c, e, g, a, b]</b>, the pivot is going to be <b>c</b>. The left pointer will point to <b>e</b>, * and e is truly larger than <b>c</b>. The right pivot find <b>b</b>, which is lower than <b>c</b>. Exchange <b>e</b> with <b>b</b>. * After that, both the pointers will increase. The left find <b>g</b> and right find <b>a</b>, they both satisfy the * requirement. We make an exchange. Again, the pointers will increase; however, this time, * they cross each other. The loop is broken. The program put the pivot in the middle and return it.<br> * The resulting array is <b>[b, a, c, g, e]</b></p> * * @param input an array that we want to take partition * @param lo the lower bound of the array * @param hi the higher bound of the array * @return the index of the pivot */ private int partition(T[] input, int lo, int hi) { int i = lo, j = hi+1; // left and right pointers T v = input[lo]; while (true) { while (less(input[++i], v)) if (i == hi) break; while (less(v, input[--j])) if (j == lo) break; if (i >= j) // If the 2 pointers cross each other, then no other exchanges can be made. break; exchange(input, i, j); } exchange(input, lo, j); return j; } @Override public String getDescription() { return "Quicksort is a fast sorting algorithm, which is used not only for educational purposes, but widely applied in practice."; } }
true
d3bb73be35a27066403b49d6c90391e14d5a2303
Java
Pokesy/YZL-master
/tox/src/main/java/com/thinksky/fragment/CheckInFragment.java
UTF-8
7,525
1.882813
2
[]
no_license
package com.thinksky.fragment; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.thinksky.adapter.CheckInAdapter; import com.thinksky.info.CheckInfo; import com.thinksky.myview.MyListView; import com.thinksky.tox.R; import com.thinksky.utils.MyJson; import com.tox.BaseFunction; import com.tox.InfoHelper; import com.tox.WeiboApi; import org.kymjs.aframe.bitmap.KJBitmap; import java.util.ArrayList; import java.util.List; /** * A simple {@link Fragment} subclass. */ public class CheckInFragment extends Fragment implements View.OnClickListener { private RelativeLayout mCheckIn; private ImageView mReturn; private CheckInAdapter mCheckInAdapter = null; private Context context; private WeiboApi weiboApi = new WeiboApi(); private ProgressBar mProgressBar; private CheckInFragmentCallBack mCheckInFrsgmentCallBack; private KJBitmap kjBitmap; private View view; private List<CheckInfo> mList = new ArrayList<CheckInfo>(); private MyJson myJson = new MyJson(); private MyListView mListView; private TextView mCheckInfo, mToast, mTimeNow, mCheckInText; private LinearLayout mMyCheckInfoShow; private boolean firstLoadFlag = true; private CheckInfo myCheckInfo; public CheckInFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.activity_check_in, null); context = view.getContext(); kjBitmap = KJBitmap.create(); initView(); initRequest(); return view; } private void initView() { mCheckInText = (TextView) view.findViewById(R.id.checkIn_text); mListView = (MyListView) view.findViewById(R.id.CheckIn_List); mCheckInfo = (TextView) view.findViewById(R.id.MyCheckInfo); mTimeNow = (TextView) view.findViewById(R.id.CheckIn_TimeNow); mToast = (TextView) view.findViewById(R.id.CheckToast); mCheckIn = (RelativeLayout) view.findViewById(R.id.checkIn); mReturn = (ImageView) view.findViewById(R.id.Menu); mReturn.setOnClickListener(this); mCheckIn.setOnClickListener(this); mMyCheckInfoShow = (LinearLayout) view.findViewById(R.id.MyCheckInfoShow); mProgressBar = new ProgressBar(context); mCheckInAdapter = new CheckInAdapter(context, mList); mListView.setAdapter(mCheckInAdapter); mTimeNow.setText(BaseFunction.getTimeNow()); mListView.setonRefreshListener(new MyListView.OnRefreshListener() { @Override public void onRefresh() { weiboApi.setHandler(handler); weiboApi.getCheckRankDate(); } }); } private void initRequest() { weiboApi.setHandler(handler); weiboApi.getCheckRankDate(); if (BaseFunction.isLogin()) { Log.e(">>>>>>>", "已经登入"); //TODO 检查是否签到 WeiboApi weiboApi1 = new WeiboApi(); weiboApi1.setHandler(handlerMyCheckInfo); weiboApi1.getCheckInfo(); } } @Override public void onClick(View v) { int mID = v.getId(); switch (mID) { case R.id.Menu: getActivity().finish(); break; case R.id.checkIn: if (BaseFunction.isLogin()) { if (myCheckInfo != null && myCheckInfo.getIsChecked() == 0) { checkIn(); } } else { Toast.makeText(context, "未登陆", Toast.LENGTH_SHORT).show(); } break; default: break; } } Handler handlerMyCheckInfo = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 0) { String result = (String) msg.obj; myCheckInfo = myJson.getMyCheckInfo(result); mCheckInfo.setText("连签" + myCheckInfo.getCon_num() + "天,累签" + myCheckInfo.getTotal_num() + "天,超" + myCheckInfo.getOver_tare() + "的用户"); if (myCheckInfo.getIsChecked() == 1) { mCheckIn.setClickable(false); mToast.setText("今日已签到"); mCheckInText.setText("已签到"); } else { mToast.setText("今日未签到"); mCheckIn.setClickable(true); } mMyCheckInfoShow.setVisibility(View.VISIBLE); } else { InfoHelper.ShowMessageInfo(context, msg.what); } } }; private void checkIn() { if (BaseFunction.isLogin()) { WeiboApi weiboApi2 = new WeiboApi(); weiboApi2.setHandler(checkHandler); weiboApi2.CheckIn(); } else { Toast.makeText(context, "请先登陆", Toast.LENGTH_LONG).show(); } } Handler checkHandler = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 0) { String result = (String) msg.obj; CheckInfo checkInfo = myJson.getMyCheckInfo(result); mCheckInfo.setText("连签" + checkInfo.getCon_num() + "天,累签" + checkInfo.getTotal_num() + "天,超" + checkInfo.getOver_tare() + "的用户"); mCheckInfo.setVisibility(View.VISIBLE); mCheckInText.setText("已签到"); mToast.setText("签到成功"); mCheckIn.setClickable(false); firstLoadFlag = false; initRequest(); } else { InfoHelper.ShowMessageInfo(context, msg.what); /* Toast.makeText(mContext,"已经签到",Toast.LENGTH_LONG).show(); mCheckInText.setText("已签到"); mCheckIn.setClickable(false);*/ } } }; Handler handler = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 0) { mList.removeAll(mList); String result = (String) msg.obj; Log.d("输出签到信息>>>>>",result); List<CheckInfo> newList = myJson.getCheckRank(result); mListView.setVisibility(View.VISIBLE); for (CheckInfo info : newList) { mList.add(info); } } else { } mListView.onRefreshComplete(); mCheckInAdapter.notifyDataSetChanged(); } }; public void setCallBack(CheckInFragmentCallBack mCheckInFragmentCallBack) { this.mCheckInFrsgmentCallBack = mCheckInFragmentCallBack; } public interface CheckInFragmentCallBack { void callback(int flag); } }
true
d8ccd58712224980efee1be3528e4b960a7023bc
Java
gitzqs/edu-unioncenter
/src/main/java/com/zqs/model/course/CourseInfo.java
UTF-8
2,153
2.359375
2
[]
no_license
package com.zqs.model.course; import java.util.Date; import com.zqs.model.basics.REntity; /** * 课程概览信息 * * @author qiushi.zhou * @date 2017年7月3日 下午4:13:29 */ public class CourseInfo extends REntity{ private static final long serialVersionUID = 3072320582091905713L; /** 课程名称 */ private String name; /** 课程图片 */ private String img; /** 课程老师 */ private int teacherId; /** 节数 */ private int nodeNumber; /** 单价 */ private double unitPrice; /** 课程类型 */ private int categoryId; /** 级别 */ private int level; /** 开始时间 */ private Date beginTime; /** 结束时间 */ private Date endTime; /** 状态 */ private int status; /** 描述 */ private String description; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNodeNumber() { return nodeNumber; } public void setNodeNumber(int nodeNumber) { this.nodeNumber = nodeNumber; } public double getUnitPrice() { return unitPrice; } public void setUnitPrice(double unitPrice) { this.unitPrice = unitPrice; } public int getCategoryId() { return categoryId; } public void setCategoryId(int categoryId) { this.categoryId = categoryId; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public Date getBeginTime() { return beginTime; } public void setBeginTime(Date beginTime) { this.beginTime = beginTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public int getTeacherId() { return teacherId; } public void setTeacherId(int teacherId) { this.teacherId = teacherId; } }
true
f26f2210bb9f7f10aba05e6f81c8a3a3e6ce04b6
Java
kongyh/emart
/emart_services/item-service/src/test/java/com/fsd/emart/item/test/TestItemService.java
UTF-8
541
1.96875
2
[]
no_license
package com.fsd.emart.item.test; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import com.fsd.emart.item.entity.Item; import com.fsd.emart.item.service.ItemServiceImpl; public class TestItemService extends TestTemplate { @Autowired ItemServiceImpl itemService; @Test public void testGetItems() { List<Item> itemList = itemService.getItems(); for (Item item : itemList) { System.out.println(item.toString()); //Assert.assertSame // } } }
true
3ea5a0d79134c776a0bd0ccde768359b4d2354b5
Java
Finkky/sy-clappin
/src/main/java/cz/cvut/fit/culkajac/dp/dto/RoutableFileDTO.java
UTF-8
1,285
2.46875
2
[]
no_license
package cz.cvut.fit.culkajac.dp.dto; import java.util.Set; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import com.google.common.collect.Sets; public class RoutableFileDTO { private FileDTO message; private Set<String> destination; public RoutableFileDTO(FileDTO f) { this.message = f; this.destination = Sets.newHashSet(); } public FileDTO getMessage() { return this.message; } public Set<String> getDestination() { return this.destination; } public void setMessage(FileDTO message) { this.message = message; } public void setDestination(Set<String> destination) { this.destination = destination; } public void insertRoute(String routeName) { this.destination.add(routeName); } public boolean hasRoute(String routeName) { // return true; return this.destination.contains(routeName); } @Override public String toString() { return "RoutableFile"; //return ReflectionToStringBuilder.toString(this); } @Override public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } }
true
a2e3cb48f372fdcd5faccef32c8cf6be9c95d9db
Java
rgpolizeli/quarkus-app
/src/main/java/org/acme/controller/repositories/IPostoColetaRepository.java
UTF-8
273
2.015625
2
[]
no_license
package org.acme.controller.repositories; import org.acme.model.api.errors.InvalidPostoColetaError; import org.acme.model.entities.PostoColeta; public interface IPostoColetaRepository { public PostoColeta getPostoColetaById(Long id) throws InvalidPostoColetaError; }
true
3a6aab114297c6a8157496fe271c79dc5ea4097d
Java
AubreyNgoma/AutomationTesting
/InternalFormsConfiguration.java
UTF-8
9,373
1.914063
2
[]
no_license
package za.co.resbank.pages.Internal; import net.serenitybdd.core.annotations.findby.FindBy; import net.serenitybdd.core.pages.WebElementFacade; import net.thucydides.core.annotations.DefaultUrl; import net.thucydides.core.pages.PageObject; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Action; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; @DefaultUrl("http://localhost:4502/content/sarb-forms-web-interface/internal/form-config-all-forms.html") public class InternalFormsConfiguration extends PageObject { private final Logger LOGGER = LoggerFactory.getLogger(getClass()); private WebDriverWait wait; private Actions act; private List<WebElement> periodList; private List<WebElement> statusList; int index = 0; public static @FindBy(xpath = "//*[@id=\"navbarCollapse\"]/ul/li[2]/a") WebElementFacade FORMSCONFIGLINK; @FindBy(xpath = "//*[@id=\"btn-create-form-type\"]") WebElementFacade btnAddNewFormType; @FindBy(xpath = "//*[@id=\"btn-create-form-type-confirm\"]") WebElementFacade btnCreate; @FindBy(xpath = "//*[@id=\"btn-acknowledge-form-type-created\"]") WebElementFacade btnOk; @FindBy(xpath = "//*[@id=\"btn-create-form-type-cancel\"]") WebElementFacade btnCancel; @FindBy(xpath = "//*[@id=\"form-type-code\"]") WebElementFacade code; @FindBy(xpath = "//*[@id=\"form-type-title\"]") WebElementFacade title; @FindBy(xpath = "//*[@id=\"form-type-description\"]") WebElementFacade description; @FindBy(xpath = "//*[@id=\"aem-form-path\"]") WebElementFacade aemForm; public void clickFormsConfigurationLink(){ if(FORMSCONFIGLINK.isDisplayed()){ FORMSCONFIGLINK.click(); } } public boolean createNewFormType(String code, String title, String distributionType,String frequency, String action){ Select select = null; wait = new WebDriverWait(this.getDriver(), 30); act = new Actions(this.getDriver()); LOGGER.info("Creating new form type: "+code); WebElement distributionBox; WebElement frequencyBox; btnAddNewFormType.click(); if(action.equalsIgnoreCase("created")){ //create new formType this.code.type(code); this.title.type(title); description.type(title); aemForm.type(title); distributionBox = this.getDriver().findElement(By.xpath("//*[@id=\"distribution-type\"]")); select = new Select(distributionBox); select.selectByValue(distributionType); frequencyBox = this.getDriver().findElement(By.xpath("//*[@id=\"release-frequency\"]")); select = new Select(frequencyBox); select.selectByValue(frequency); if(btnCreate.isDisplayed()) { btnCreate.click(); }else { act.click(wait.until(ExpectedConditions.elementToBeClickable(btnCreate))); } if(btnOk.isDisplayed()){ btnOk.click(); return true; }else{ act.click(wait.until(ExpectedConditions.elementToBeClickable(btnOk))).build().perform(); return true; } }else if(action.equalsIgnoreCase("not_created")){ //cancel the process of creating a formType if(btnCancel.isDisplayed()) { btnCancel.click(); return true; } } return false; } // public boolean getFormTypeReleaseCount(String formType, String amount){ int index = 0; List<WebElement> formTypeList = getFormTypeList(); LOGGER.info("Found this amount of form types in the list "+formTypeList.size()); for(WebElement item:formTypeList){ index++; if(item.getText().contains(formType)){ String releaseCount = this.getDriver().findElement(By.xpath("/html/body/div/div[2]/div/div[1]/div/div/table/tbody/tr["+index+"]/td[5]")).getText(); LOGGER.info("Found Release Count "+releaseCount+" for "+formType); if(Integer.parseInt(releaseCount)==Integer.parseInt(amount)){ return true; }else if(amount.equalsIgnoreCase("more_than_one")&&Integer.parseInt(releaseCount)>1){ return true; } } } return false; } //check for form type in forms configuration public boolean checkFormType(String formType){ wait = new WebDriverWait(this.getDriver(), 30); act = new Actions(this.getDriver()); LOGGER.info("Going through table to see if "+formType+" has been created."); List<WebElement> formTypeList = getFormTypeList(); if(formType.isEmpty()) { if (formTypeList.isEmpty()) { return true; } }else { for (WebElement formTypes : formTypeList) { if (formTypes.getText().contains(formType)) { LOGGER.info("Found new created form Type: " + formTypes.getText()); return true; } } } return formTypeList.isEmpty(); } public boolean checkFormTypeByPropertyType(String formType, String propertyType, String propertyValue){ List<WebElement> propertyList = new ArrayList<>(); if(propertyType.contains("distribution")){ propertyList = this.getDriver().findElements(By.xpath("/html/body/div/div[2]/div/div[1]/div/div/table/tbody/tr/td[2]")); }else if(propertyType.contains("frequency")){ propertyList = this.getDriver().findElements(By.xpath("/html/body/div/div[2]/div/div[1]/div/div/table/tbody/tr/td[3]")); } for(WebElement item:propertyList){ if(item.getText().equals(propertyValue.toUpperCase())&&this.checkFormType(formType)){ return true; } } return false; } public boolean clickOnReleaseDetail(String periodValue, String statusValue){ for(WebElement period:periodList){ index++; for(WebElement status:statusList){ if(period.getText().equals(periodValue)&&status.getText().equals(statusValue)){ LOGGER.info("Attempting to click on Release detail for release "+periodValue); WebDriverWait wait = new WebDriverWait(this.getDriver(), 30); Actions act = new Actions(this.getDriver()); act.click(wait.until(ExpectedConditions.elementToBeClickable(this.getDriver().findElement(By.xpath("/html/body/div/div[2]/div/div[2]/table/tbody/tr["+index+"]/td[5]/a"))))).build().perform(); return true; } } } LOGGER.info("Attempting to click on Release detail for release "+periodValue+" but something is wrong by retrieving the index."); return false; } private List<WebElement> getPeriodList(){ WebElement element = this.getDriver().findElement(By.xpath("/html/body/div/div[3]")); act = new Actions(this.getDriver()); wait = new WebDriverWait(this.getDriver(),30); act.moveToElement(wait.until(ExpectedConditions.visibilityOf(element)),element.getLocation().getX(),element.getLocation().getY()).build().perform(); return this.getDriver().findElements(By.xpath("/html/body/div/div[2]/div/div[2]/table/tbody/tr/td[1]")); } private List<WebElement> getStatusList() { WebElement element = this.getDriver().findElement(By.xpath("/html/body/div/div[3]")); act = new Actions(this.getDriver()); wait = new WebDriverWait(this.getDriver(),30); act.moveToElement(wait.until(ExpectedConditions.visibilityOf(element)),element.getLocation().getX(),element.getLocation().getY()).build().perform(); return this.getDriver().findElements(By.xpath("/html/body/div/div[2]/div/div[2]/table/tbody/tr/td[2]")); } public List<WebElement> getFormTypeList(){ return this.getDriver().findElements(By.xpath("/html/body/div/div[2]/div/div[1]/div/div/table/tbody/tr/td[1]")); } public void clickReleaseDetail(int index){ act.click(wait.until(ExpectedConditions.elementToBeClickable(By.xpath("/html/body/div/div[2]/div/div[1]/div/div/table/tbody/tr["+index+"]/td[6]/a[1]")))).build().perform(); } public boolean checkNewCreatedRelease(String periodValue, String statusValue){ periodList = getPeriodList(); statusList = getStatusList(); for(WebElement period:periodList){ for(WebElement status:statusList){ if(period.getText().equals(periodValue)&&status.getText().equals(statusValue)){ return true; } } } return false; } }
true
1f9203c3f6a1f26a74b03fed0fdb94fff9f27da3
Java
DanielCY79/net
/src/main/java/com/daniel/other/Other3.java
UTF-8
1,154
3.671875
4
[]
no_license
package com.daniel.other; /** * [1, 2, 100, 4] 两个人,从两边取数,问获胜的人点数总和 * * @author Daniel Xia * @since 2019-07-03 20:36 */ public class Other3 { public int win(int[] nums) { if (nums == null || nums.length == 0) { return 0; } return Math.max( first(nums, 0, nums.length - 1), second(nums, 0, nums.length - 1) ); } public int first(int[] nums, int left, int right) { if (left == right) { return nums[left]; } return Math.max( nums[left] + second(nums, left + 1, right), nums[right] + second(nums, left, right - 1) ); } public int second(int[] nums, int left, int right) { if(left == right){ return 0; } return Math.min( first(nums, left + 1, right), first(nums, left, right - 1) ); } public static void main(String[] args) { int[] testArr= {1, 5, 2}; Other3 other3 = new Other3(); System.out.println(other3.win(testArr)); } }
true
b9cf003eb5f3039d67ba2139c17f2792e598713d
Java
BatriderD/uzao
/uzao/uzao/app/src/main/java/com/zhaotai/uzao/ui/designer/adapter/DesignerListAdapter.java
UTF-8
1,742
2.15625
2
[]
no_license
package com.zhaotai.uzao.ui.designer.adapter; import android.widget.ImageView; import android.widget.TextView; import com.chad.library.adapter.base.BaseViewHolder; import com.zhaotai.uzao.R; import com.zhaotai.uzao.api.ApiConstants; import com.zhaotai.uzao.base.BaseRecyclerAdapter; import com.zhaotai.uzao.bean.DesignerBean; import com.zhaotai.uzao.utils.GlideLoadImageUtil; import com.zhaotai.uzao.utils.transform.CircleTransform; /** * description: 设计师列表 * author : ZP * date: 2018/3/16 0016. */ public class DesignerListAdapter extends BaseRecyclerAdapter<DesignerBean, BaseViewHolder> { public DesignerListAdapter() { super(R.layout.item_designer_list); } @Override protected void convert(BaseViewHolder helper, DesignerBean item) { ImageView ivAvatar = helper.getView(R.id.iv_designer_avatar); GlideLoadImageUtil.load(mContext, ApiConstants.UZAOCHINA_IMAGE_HOST + item.avatar, ivAvatar, R.drawable.ic_default_head, R.drawable.ic_default_head, new CircleTransform(mContext)); //设计师名字 helper.setText(R.id.tv_nick_name, item.nickName); //作品数 //粉丝数 helper.setText(R.id.tv_designer_info, "粉丝:" + item.followCount + "\n作品数:" + String.valueOf(item.spuCount + item.materialCount)); TextView attention = helper.getView(R.id.tv_designer_attention); if (item.data == null || !"Y".equals(item.data.isFavorited)) { attention.setText("关注"); attention.setSelected(true); } else { attention.setText("已关注"); attention.setSelected(false); } helper.addOnClickListener(R.id.tv_designer_attention); } }
true
eb6c279c677018ce40a5cfb15373f0a6b29c2e97
Java
qq764813981/OASystem
/src/dao/impl/ProjectDaoImpl.java
UTF-8
339
1.703125
2
[]
no_license
package dao.impl; import dao.ProjectDao; import entity.Project; import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; import javax.annotation.Resource; /** * Created by 嘉诚 on 2016/8/29. */ @Repository("projectDao") public class ProjectDaoImpl extends BaseDaoImpl<Project> implements ProjectDao{ }
true
59c670a5d806a2c725c23ce6c98a7e78e14e9938
Java
feizhihui/Algorithms-in-Java
/POJ代码分类/easy/Main3331.java
UTF-8
909
3.0625
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package poj.easy; import java.math.BigInteger; import java.util.Scanner; /** * * 高精度阶乘问题 */ public class Main3331 { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int m=scan.nextInt(); while(m--!=0){ int k=scan.nextInt(); int t=scan.nextInt(); BigInteger sum=new BigInteger("1"); for(int i=2;i<=k;i++){ BigInteger bk=new BigInteger(i+""); sum=sum.multiply(bk); } String s=sum+""; int num=0; for(int i=0;i<s.length();i++){ if(s.charAt(i)==t+'0'){ num++; } } System.out.println(num); } } }
true
b7c6e92596927d5454488c2f422c8e2d78167e97
Java
nullsector12/inClass
/Cp2_Operator/src/chapter2_Op/TestOp4.java
UTF-8
1,000
4.03125
4
[]
no_license
package chapter2_Op; public class TestOp4 { public static void main(String[] args) { /*a= {{(25+5)+(36/4)}-72}*5, b= {{(25x5)+(36-4)}-71}/4, c=(128/4)*2 일 때 a>b>c 가 참이면 true 아니면 false를 출력하는 프로그램 작성 */ int a = (((25+5)+(36/4))-72)*5; // -165 int b = (((25*5)+(36-4))-71)/4; // 21 int c = (128/4)*2; // 64 boolean result = false; // 기본은 false // a가 b보다 크고 b가 c보다 큰 것이 모두 참이면 a는 당연히 c보다 크다 따라서 비교 할 필요 없이 a>b>c가 성립된다. ( a>c = SCE) if(a>b && b>c) { //a가 b보다 크고 b가 c보다 크다가 모두 참이면 System.out.println("a>b>c는 : " + !result); // rseult 앞에 !를 붙여 논리부정표시로 출력값을 true로 변경 }else { // 두 조건 중 하나라도 거짓이면 a>b>c는 성립하지 않음. System.out.println("a>b>c는 : " + result); // 기본값인 false 출력 } //결과는 거짓이 출력되야함 } }
true
8c0d6b23e82c2e9fd624c0d75812aa7a56f3f41d
Java
XingtaoZhou/test1
/tkmybatis/src/main/java/com/example/mapper/StudentMapper.java
UTF-8
494
1.773438
2
[]
no_license
package com.example.mapper; import com.example.entity.Student; import tk.mybatis.mapper.common.Mapper; import java.util.List; import java.util.Map; public interface StudentMapper extends Mapper<Student> { List<Student> select1(); List<Student> select6(String sclass, String ssex); List<Map<String, Object>> select11(); List<Map<String, Object>> selectAvgDegreeBySclass(String sclass); List<Map<String, Object>> select13(); List<Map<String, Object>> select14(); }
true
c599a18c69fe3acf5ef5074d46665b10464ae09f
Java
JoniMatias/Mufasa
/Mufasa/src/UserValidator.java
UTF-8
2,231
3.015625
3
[]
no_license
public class UserValidator { public CountryCodeList countryList; public UserValidator(CountryCodeList codeList) { countryList = codeList; } public boolean isUserValid(User user) throws UserValidationError { //if (!isNameValid(user.getFirstName())) return false; //if (!isNameValid(user.getLastName())) return false; if (!isUserNameValid(user)) return false; if (!isCountryValid(user)) return false; //if (!isPhoneNumberValid(user)) return false; return true; } public boolean isUserValidForBankAccount(User user) { return true; } private boolean isNameValid(String name) throws UserValidationError { if (name.matches("[a-zA-Z\\s]+")) { return true; } else { throw new UserValidationError("Names can only contain letters and spaces."); } } private boolean isUserNameValid(User user) throws UserValidationError { if (user.getUserName().length() > 15) { throw new UserValidationError("Username must be less than 15 characters."); } if (user.getUserName().length() - user.getUserName().replace("_", "").length() >= 2) { throw new UserValidationError("Username can only contain one underscore."); } return true; } private boolean isCountryValid(User user) throws UserValidationError { if (countryList.isCountryCodeValid(user.getCountryCode())) { return true; } else { throw new UserValidationError("Please select a country."); } } private boolean isPhoneNumberValid(User user) throws UserValidationError { if (user.getPhoneNumber().matches("[0-9\\s]+")) { return true; } else { throw new UserValidationError("Names can only contain letters and spaces."); } } private boolean isAddressValid(User user) throws UserValidationError { Address address = user.getBankingData().getAddress(); if (address.getStreetAddress().matches("[a-zA-Z0-9\\s]+") && address.getCity().matches("[a-zA-Z\\s]+") && address.getPostalCode().matches("[0-9-]+") && countryList.isCountryCodeValid(address.getCountry())) { return true; } else { throw new UserValidationError("Address details are wrong."); } } }
true
daf1be008050b63669a2f149628e70fe69d61e99
Java
xushjie1987/appd-analytics
/analytics-shared-rest/src/main/java/com/appdynamics/analytics/shared/rest/client/utils/HttpRequestFactory.java
UTF-8
6,873
2.140625
2
[]
no_license
/* */ package com.appdynamics.analytics.shared.rest.client.utils; /* */ /* */ import com.appdynamics.analytics.shared.rest.exceptions.ClientException; /* */ import com.fasterxml.jackson.databind.ObjectMapper; /* */ import com.google.common.base.Strings; /* */ import com.google.common.base.Throwables; /* */ import java.beans.ConstructorProperties; /* */ import java.net.SocketException; /* */ import java.net.URI; /* */ import java.net.URISyntaxException; /* */ import java.util.concurrent.TimeUnit; /* */ import org.apache.http.NoHttpResponseException; /* */ import org.apache.http.client.config.RequestConfig; /* */ import org.apache.http.client.config.RequestConfig.Builder; /* */ import org.apache.http.client.methods.HttpDelete; /* */ import org.apache.http.client.methods.HttpGet; /* */ import org.apache.http.client.methods.HttpPatch; /* */ import org.apache.http.client.methods.HttpPost; /* */ import org.apache.http.client.methods.HttpPut; /* */ import org.apache.http.impl.client.CloseableHttpClient; /* */ import org.apache.http.impl.client.HttpClientBuilder; /* */ import org.apache.http.impl.client.HttpClients; /* */ import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; /* */ /* */ /* */ public class HttpRequestFactory /* */ { /* */ @ConstructorProperties({"mapper", "client", "baseUri"}) /* */ public HttpRequestFactory(ObjectMapper mapper, CloseableHttpClient client, URI baseUri) /* */ { /* 31 */ this.mapper = mapper;this.client = client;this.baseUri = baseUri; /* */ } /* */ /* 34 */ private static final ObjectMapper MAPPER = new ObjectMapper(); /* */ /* */ /* */ private final ObjectMapper mapper; /* */ /* */ /* */ private final CloseableHttpClient client; /* */ /* */ private final URI baseUri; /* */ /* */ /* */ public static <T> T retryWithRequestFactory(HttpRequestExecutor<T> executor, CloseableHttpClient httpClient, String url, int maxRetries) /* */ { /* 47 */ int attempt = 1; /* */ /* 49 */ Exception clientException = null; /* 50 */ for (; attempt <= maxRetries; attempt++) { /* 51 */ HttpRequestFactory requestFactory = buildRequestFactory(url, httpClient); /* */ try { /* 53 */ return (T)executor.execute(requestFactory); /* */ } catch (ClientException e) { /* 55 */ clientException = e; /* 56 */ if (((e.getCause() instanceof SocketException)) || (!(e.getCause() instanceof NoHttpResponseException))) /* */ { /* */ /* 59 */ throw Throwables.propagate(e); } /* */ } /* */ } /* 62 */ String msg = "Failed after [" + maxRetries + "] retries" + (clientException != null ? " with exception " + clientException.getMessage() : ""); /* */ /* 64 */ if (clientException != null) { /* 65 */ throw new IllegalStateException(msg, clientException); /* */ } /* 67 */ throw new IllegalStateException(msg); /* */ } /* */ /* */ public static HttpRequestFactory buildRequestFactory(String uriString, CloseableHttpClient httpClient) /* */ { /* */ URI uri; /* */ try { /* 74 */ uri = new URI(uriString); /* */ } catch (URISyntaxException e) { /* 76 */ throw Throwables.propagate(e); /* */ } /* 78 */ if (((!uri.getScheme().equalsIgnoreCase("http")) && (!uri.getScheme().equalsIgnoreCase("https"))) || (Strings.isNullOrEmpty(uri.getHost()))) /* */ { /* 80 */ throw new IllegalArgumentException("Invalid uri: " + uri); /* */ } /* 82 */ return new HttpRequestFactory(MAPPER, httpClient, uri); /* */ } /* */ /* */ public static CloseableHttpClient buildHttpClient(long timeout, TimeUnit timeoutUnit) { /* 86 */ RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout((int)TimeUnit.MILLISECONDS.convert(timeout, timeoutUnit)).build(); /* */ /* */ /* */ /* */ /* 91 */ PoolingHttpClientConnectionManager cManager = new PoolingHttpClientConnectionManager(); /* 92 */ cManager.setDefaultMaxPerRoute(20); /* 93 */ cManager.setMaxTotal(200); /* */ /* 95 */ return HttpClients.custom().setDefaultRequestConfig(requestConfig).setConnectionManager(cManager).build(); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public HttpEntityEnclosingRequestBuilder post() /* */ { /* 106 */ return (HttpEntityEnclosingRequestBuilder)((HttpEntityEnclosingRequestBuilder)((HttpEntityEnclosingRequestBuilder)new HttpEntityEnclosingRequestBuilder(new HttpPost()).setUri(this.baseUri)).using(this.mapper)).using(this.client); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public HttpEntityEnclosingRequestBuilder patch() /* */ { /* 117 */ return (HttpEntityEnclosingRequestBuilder)((HttpEntityEnclosingRequestBuilder)((HttpEntityEnclosingRequestBuilder)new HttpEntityEnclosingRequestBuilder(new HttpPatch()).setUri(this.baseUri)).using(this.mapper)).using(this.client); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public HttpEntityEnclosingRequestBuilder put() /* */ { /* 128 */ return (HttpEntityEnclosingRequestBuilder)((HttpEntityEnclosingRequestBuilder)((HttpEntityEnclosingRequestBuilder)new HttpEntityEnclosingRequestBuilder(new HttpPut()).setUri(this.baseUri)).using(this.mapper)).using(this.client); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public HttpRequestBuilder get() /* */ { /* 139 */ return (HttpRequestBuilder)((HttpRequestBuilder)((HttpRequestBuilder)new HttpRequestBuilder(new HttpGet()).setUri(this.baseUri)).using(this.mapper)).using(this.client); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public HttpRequestBuilder delete() /* */ { /* 150 */ return (HttpRequestBuilder)((HttpRequestBuilder)((HttpRequestBuilder)new HttpRequestBuilder(new HttpDelete()).setUri(this.baseUri)).using(this.mapper)).using(this.client); /* */ } /* */ /* */ public static abstract interface HttpRequestExecutor<T> /* */ { /* */ public abstract T execute(HttpRequestFactory paramHttpRequestFactory); /* */ } /* */ } /* Location: /Users/gchen/Downloads/AppDynamics/events-service/lib/analytics-shared-rest.jar!/com/appdynamics/analytics/shared/rest/client/utils/HttpRequestFactory.class * Java compiler version: 7 (51.0) * JD-Core Version: 0.7.1 */
true
a8e7bd6b899bdd2f0a691708574bf12260a7a893
Java
chulicaoli/Algorithm
/test/src/algorithm/kdTree/Iterator.java
UTF-8
299
2.484375
2
[]
no_license
package algorithm.kdTree; import java.io.Serializable; /**抽象迭代器或遍历器接口*/ public interface Iterator<S> extends java.util.Iterator<S> , Serializable { /**返回前一个元素*/ public S prior(); /**判断是否存在前一个元素*/ public boolean hasPrior(); }
true
2260b2411f80f1919c6af8d5b6fb155fb091cb93
Java
fakhethazem/exercice1
/src/com/company/design/bridge/Rectangle.java
UTF-8
268
2.8125
3
[]
no_license
package com.company.design.bridge; public class Rectangle extends Shape { public Rectangle(Color col){ super(col); } @Override public void applay() { System.out.println("la rectangle de couleur :"); col.applycolor(); } }
true
17b8415cfc48534524d18173a5b8f14d8d5ae973
Java
a-malyshev/CheckConnectionEmulator
/src/test/java/com/malyshev/SupervisorTests.java
UTF-8
1,394
2.609375
3
[]
no_license
package com.malyshev; import com.malyshev.metrics.Timer; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Random; public class SupervisorTests { private final int NUMBER_OF_DEVICES = 1000; private Timer timer; private List<String> devices; private InteractionService interactionService; private Supervisor supervisor; @Before public void creatingDeviceList() { initializingInstances(); devices = new ArrayList<>(NUMBER_OF_DEVICES); timer.start(); Random randomValueForAddress = new Random(); for (int i = 0; i < NUMBER_OF_DEVICES; i++) { devices.add(String.format("%d.%d.%d.%d", randomValueForAddress.nextInt(256), randomValueForAddress.nextInt(256), randomValueForAddress.nextInt(256), randomValueForAddress.nextInt(256))); } System.out.println("list of devices is ready"); timer.stop(); } private void initializingInstances() { System.out.println("============ SetUp =============="); interactionService = new MockInteractionService(3); supervisor = new ThreadSupervisor(interactionService, NUMBER_OF_DEVICES); timer = new Timer(); } @Test public void sendToDevice() throws InterruptedException { supervisor.checkConnectionFor(devices); } }
true
e0d61b9461668229108d220abb3acf05a8e46882
Java
james1106/open-cloud
/opencloud-app/opencloud-admin-provider/src/main/java/com/github/lyd/admin/provider/controller/AdminController.java
UTF-8
4,521
1.984375
2
[ "MIT" ]
permissive
package com.github.lyd.admin.provider.controller; import com.github.lyd.common.configuration.CommonProperties; import com.github.lyd.common.http.OpenRestTemplate; import com.github.lyd.common.model.ResultBody; import com.github.lyd.common.utils.DateUtils; import com.github.lyd.common.utils.RandomValueUtils; import com.github.lyd.common.utils.SignatureUtils; import com.github.lyd.common.utils.WebUtils; import com.google.common.collect.Maps; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.util.Map; /** * @author liuyadu */ @Api(tags = "运营后台开放接口") @RestController public class AdminController { @Autowired private OpenRestTemplate openRestTemplate; @Autowired private ResourceServerProperties resourceServerProperties; @Autowired private CommonProperties commonProperties; /** * 获取用户访问令牌 * 基于oauth2密码模式登录 * * @param username * @param password * @return access_token */ @ApiOperation(value = "获取用户访问令牌", notes = "基于oauth2密码模式登录,无需签名,返回access_token") @ApiImplicitParams({ @ApiImplicitParam(name = "username", required = true, value = "登录名", paramType = "form"), @ApiImplicitParam(name = "password", required = true, value = "登录密码", paramType = "form") }) @PostMapping("/login/token") public Object getLoginToken(@RequestParam String username, @RequestParam String password, @RequestHeader HttpHeaders headers) { // 使用oauth2密码模式登录. MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>(); postParameters.add("username", username); postParameters.add("password", password); postParameters.add("client_id", resourceServerProperties.getClientId()); postParameters.add("client_secret", resourceServerProperties.getClientSecret()); postParameters.add("grant_type", "password"); // 使用客户端的请求头,发起请求 headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); // 强制移除 原来的请求头,防止token失效 headers.remove(HttpHeaders.AUTHORIZATION); HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity(postParameters, headers); Map result = openRestTemplate.postForObject(commonProperties.getAccessTokenUri(), request, Map.class); if (result.containsKey("access_token")) { return ResultBody.success(result); } else { return result; } } /** * 参数签名 * * @param * @return */ @ApiOperation(value = "内部应用请求签名", notes = "仅限系统内部调用") @ApiImplicitParams({ @ApiImplicitParam(name = "params1", value = "参数1", paramType = "form"), @ApiImplicitParam(name = "params2", value = "参数2", paramType = "form"), @ApiImplicitParam(name = "paramsN", value = "参数...", paramType = "form"), }) @PostMapping(value = "/sign") public ResultBody sign(HttpServletRequest request) { Map params = WebUtils.getParameterMap(request); Map appMap = Maps.newHashMap(); appMap.put("clientId", resourceServerProperties.getClientId()); appMap.put("nonce", RandomValueUtils.uuid().substring(0, 16)); appMap.put("timestamp", DateUtils.getTimestampStr()); appMap.put("signType", "SHA256"); params.putAll(appMap); String sign = SignatureUtils.getSign(params, resourceServerProperties.getClientSecret()); appMap.put("sign", sign); return ResultBody.success(appMap); } }
true
a0780dc490a1ff74b9f52124fc58482c3894c6a1
Java
18645956947/text
/src/zhx/day20190128/Solution.java
WINDOWS-1252
584
2.78125
3
[]
no_license
package zhx.day20190128; import java.awt.geom.Ellipse2D; import javax.imageio.ImageTypeSpecifier; /** * @author lenovo * @date 201912810:43:07 * @Description: */ /* The isBadVersion API is defined in the parent class VersionControl. boolean isBadVersion(int version); */ public class Solution extends VersionControl { public int firstBadVersion(int n) { int l = 1; int mid = 0; int r = n; while(l<r){ mid = l + (r-l)/2; if(isBadVersion(mid)){ r = mid; } else{ l = mid+1; } } return r; } }
true
bf4fcdb7597a36d5d8f160a9650f5258753c5ceb
Java
redtroy/sxj-src
/supervisor-parent/supervisor-tasks/src/main/java/com/sxj/supervisor/model/tasks/WindDoorModel.java
UTF-8
690
2.015625
2
[]
no_license
package com.sxj.supervisor.model.tasks; import com.sxj.supervisor.entity.gather.WindDoorEntity; public class WindDoorModel extends WindDoorEntity { /** * */ private static final long serialVersionUID = -6646912373367372232L; private String starDate; private String endDate; public String getStarDate() { return starDate; } public void setStarDate(String starDate) { this.starDate = starDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } }
true
764102f207c6c519420674fdca67770b2c2a57b7
Java
ForomePlatform/Anfisa-Annotations
/annotation-service/src/main/java/org/forome/annotation/utils/ZygosityUtils.java
UTF-8
2,000
2.5
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2020. Vladimir Ulitin, Partners Healthcare and members of Forome Association * * Developed by Vladimir Ulitin and Michael Bouzinier * * 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 org.forome.annotation.utils; import org.forome.annotation.struct.Allele; import java.util.List; public class ZygosityUtils { /** * Most of chromosomes for human are pairwise, so a mutation/variant applying to a sample has one of the following states: * Zygosity 0: variant is absent * Zygosity 1: variant is heterozygous, it presents on one chromosome copy * Zygosity 2: variant is homozygous, it presents on both copies of chromosome * <p> * Males have chromosomes X and Y in one copies, so a mutation/variant on these chromosomes for male sample has one of the following states: * Zygosity 0: variant is absent * Zygosity 2: variant is hemozygous, it does present on single copy of chromosome * * @param alt * @param genotypeAlleles * @return * @see <a href="https://foromeplatform.github.io/anfisa/zygosity.html">https://foromeplatform.github.io/anfisa/zygosity.html</a> */ public static int getGenotypeZygosity(Allele alt, List<Allele> genotypeAlleles) { if (genotypeAlleles.size() == 1) { //Haploid return (genotypeAlleles.get(0).equalsIgnoreConservative(alt)) ? 2 : 0; } else { long count = genotypeAlleles.stream() .filter(allele -> allele.equalsIgnoreConservative(alt)) .count(); return (count > 2L) ? 2 : (int) count; } } }
true
a0df3fbc19a2e00542eb7b5dbb3bd2aa109df5ce
Java
Kobyrisko/VEFCRM
/src/com/aleykoteretpro/packages/TransDAO.java
UTF-8
4,732
2.75
3
[]
no_license
package com.aleykoteretpro.packages; import java.util.Iterator; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; public class TransDAO implements ITransDAO { /**Data access object. * Provides access to the data base */ private SessionFactory factory; public static TransDAO instance; public static TransDAO getInstance() { if (instance == null) instance = new TransDAO(); return instance; } private TransDAO() { factory = new AnnotationConfiguration().configure() .buildSessionFactory(); } @Override public List<Trans> getTrans() throws MyExceptions { /**Return a list of all Trans currently in the data base. * @exception MyExceptions occurs when the server fails to open a session */ Session session=null; try { //creating factory for getting sessions SessionFactory factory = new AnnotationConfiguration().configure().buildSessionFactory(); //creating a new session for adding products session = factory.openSession(); session.beginTransaction(); List<Trans> transList = session.createQuery("from Trans").list(); System.out.println(transList.size()); return transList; } catch(HibernateException ce) { if (session != null) session.getTransaction().rollback(); throw new MyExceptions("failure in getting Translators List",ce); } finally { session.close(); } } @Override public Boolean addTrans(Trans tr) throws MyExceptions { /**Update a Trans in the data base. * @param cl the Trans entity to update. * @exception MyExceptions occurs when the server fails to open a session */ Session session=null; try { //creating factory for getting sessions SessionFactory factory = new AnnotationConfiguration().configure().buildSessionFactory(); //creating a new session for adding products session = factory.openSession(); session.beginTransaction(); session.save(tr); session.beginTransaction().commit(); return true; } catch(HibernateException ce) { if (session != null) session.getTransaction().rollback(); throw new MyExceptions("failure in adding new Translator",ce); } finally { session.close(); } } @Override public Boolean deleteTrans(Trans tr) throws MyExceptions { /**Update a Trans in the data base. * @param cl the Trans entity to update. * @exception MyExceptions occurs when the server fails to open a session */ Session session=null; try { //creating factory for getting sessions SessionFactory factory = new AnnotationConfiguration().configure().buildSessionFactory(); //creating a new session for adding products session = factory.openSession(); session.beginTransaction(); session.delete(tr); session.beginTransaction().commit(); return true; } catch(HibernateException ce) { if (session != null) session.getTransaction().rollback(); throw new MyExceptions("failure in deleting Translator",ce); } finally { session.close(); } } @Override public Boolean updateTrans(Trans tr) throws MyExceptions { /**Update a Trans in the data base. * @param cl the Trans entity to update. * @exception MyExceptions occurs when the server fails to open a session */ Session session= null; try { //creating factory for getting sessions SessionFactory factory = new AnnotationConfiguration().configure().buildSessionFactory(); //creating a new session for adding products session = factory.openSession(); List<Trans> transList= getTrans(); System.out.println(transList.size()); Iterator<Trans> i = transList.iterator(); Trans trans3= new Trans(); while(i.hasNext()) { Trans trans2= i.next(); if(tr.getId()==trans2.getId()) trans3=trans2; } if(!tr.getFirstName().equals("")) trans3.setFirstName(tr.getFirstName()); if(!tr.getLastName().equals("")) trans3.setLastName(tr.getLastName()); if(!tr.getPhone().equals("")) trans3.setPhone(tr.getPhone()); if(!tr.getEmail().equals("")) trans3.setEmail(tr.getEmail()); if(!tr.getAdress().equals("")) trans3.setAdress(tr.getAdress()); if(tr.getTransPrice()!=0) trans3.setTransPrice((tr.getTransPrice())); if(!tr.getTransCode().equals("")) trans3.setTransCode(tr.getTransCode()); if(!tr.getLanguages().equals("")) trans3.setLanguages(tr.getLanguages()); session.update(trans3); session.beginTransaction().commit(); return true; } catch(HibernateException ce) { if (session != null) session.getTransaction().rollback(); throw new MyExceptions("failure in updating new Translator",ce); } finally { session.close(); } } }
true
eab827c9852824a788e176cda5dad8de143a614b
Java
mathwiz/JavaTDD
/src/main/java/littlejava/Radish.java
UTF-8
465
2.859375
3
[]
no_license
package littlejava; /** * Created by Yohan on 1/19/14. */ public class Radish extends KebabD { KebabD k; public Radish(KebabD k) { this.k = k; } @Override public boolean isVeggie() { return k.isVeggie(); } @Override public Object whatHolder() { return k.whatHolder(); } @Override public String toString() { return "Radish{" + "k=" + k + '}'; } }
true
faee48623356917bbf9b2af79130a0c8b815c2f7
Java
brokersolutions/bs-common
/src/main/java/bs/common/util/JsonUtil.java
UTF-8
4,438
2.59375
3
[]
no_license
package bs.common.util; import java.io.IOException; import java.io.Serializable; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import lombok.extern.slf4j.Slf4j; /** * Utility which is up to transform json2object or Object2json * @author Maikel Guerra Ferrer mguerra@softixx.mx * */ @Slf4j public class JsonUtil implements Serializable { private static final long serialVersionUID = 7284025549866452865L; private JsonUtil() { throw new IllegalStateException("Utility class"); } public static boolean isJSONValid(String jsonInString) { try { final ObjectMapper mapper = new ObjectMapper(); mapper.readTree(jsonInString); return true; } catch (IOException e) { log.error("UJson#isJSONValid error {}", e.getMessage()); } return false; } public static String serialize(final Object object) { try { ObjectMapper objMapper = new ObjectMapper(); objMapper.enable(SerializationFeature.INDENT_OUTPUT); objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); StringWriter sw = new StringWriter(); objMapper.writeValue(sw, object); return sw.toString(); } catch (Exception e) { log.error("UJson#serialize error {}", e.getMessage()); } return null; } public static String serialize(final Object object, final boolean indent) { try { ObjectMapper objMapper = new ObjectMapper(); if (indent == true) { objMapper.enable(SerializationFeature.INDENT_OUTPUT); objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); } StringWriter stringWriter = new StringWriter(); objMapper.writeValue(stringWriter, object); return stringWriter.toString(); } catch (Exception e) { log.error("UJson#serialize error {}", e.getMessage()); } return null; } public static <T> T jsonToObject(final String content, final Class<T> clazz) { T obj = null; try { ObjectMapper objMapper = new ObjectMapper(); obj = objMapper.readValue(content, clazz); } catch (Exception e) { log.error("UJson#jsonToObject error {}", e.getMessage()); } return obj; } public static <T> List<T> jsonToList(String content, Class<T> clazz) { try { ObjectMapper mapper = new ObjectMapper(); List<T> list = mapper.readValue(content, mapper.getTypeFactory().constructCollectionType(List.class, clazz)); //##### Otras variante //List<T> list = Arrays.asList(mapper.readValue(content, clazz)); //List<T> list = mapper.readValue(content, new TypeReference<List<T>>(){}); return list; } catch (Exception e) { log.error("UJson#jsonToList error {}", e.getMessage()); } return new ArrayList<T>(); } @SuppressWarnings({ "rawtypes", "unchecked" }) public static <T> T jsonToObjectArray(String content) throws JsonParseException, JsonMappingException, IOException { T obj = null; try { ObjectMapper mapper = new ObjectMapper(); obj = (T) mapper.readValue(content, new TypeReference<List>() {}); } catch (Exception e) { log.error("UJson#jsonToObjectArray error {}", e.getMessage()); } return obj; } public static <T> T jsonToObjectArray(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException { T obj = null; try { ObjectMapper mapper = new ObjectMapper(); mapper = new ObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); obj = mapper.readValue(content, mapper.getTypeFactory().constructCollectionType(List.class, clazz)); } catch (Exception e) { log.error("UJson#jsonToObjectArray error {}", e.getMessage()); } return obj; } }
true
e3e9ff48c35bd0d57a85b4e98a3a27a7445abcfc
Java
SagenApp/MySQL-UTILS
/src/main/java/app/sagen/mysqlutils/callback/MySQLUpdateCallback.java
UTF-8
700
1.632813
2
[]
no_license
/*----------------------------------------------------------------------------- - Copyright (C) BlueLapiz.net - All Rights Reserved - - Unauthorized copying of this file, via any medium is strictly prohibited - - Proprietary and confidential - - Written by Alexander Sagen <alexmsagen@gmail.com> - -----------------------------------------------------------------------------*/ package app.sagen.mysqlutils.callback; import app.sagen.mysqlutils.MySQLExceptionType; public interface MySQLUpdateCallback { void success(int rowsAffected); void failure(MySQLExceptionType exceptionType, String errorMessage); }
true
32d5d57f906b4b2e0d664206baa00aa131c10b27
Java
tablesheep233/leetcode
/src/org/table/swordfingeroffer/ConstructArr_66.java
UTF-8
994
3.546875
4
[]
no_license
package org.table.swordfingeroffer; /** * 给定一个数组 A[0,1,…,n-1],请构建一个数组 B[0,1,…,n-1],其中B[i] 的值是数组 A 中除了下标 i 以外的元素的积, * 即B[i]=A[0]×A[1]×…×A[i-1]×A[i+1]×…×A[n-1]。不能使用除法。 * */ public class ConstructArr_66 { //每个元素左边的乘积与右边的乘积 public int[] constructArr(int[] a) { if(a == null) { return null; } int length = a.length; int[] b = new int[length]; for (int i = 0, p = 1; i < length; p *= a[i++]) { b[i] = p; } for (int i = length - 1, p = 1; i >= 0; p *= a[i--]) { b[i] *= p; } return b; } public static void main(String[] args) { ConstructArr_66 constructArr_66 = new ConstructArr_66(); int[] array = {1,3,9,7,2}; for (int i : constructArr_66.constructArr(array)) { System.out.println(i); } } }
true
92a0fcdfd5adb5c48d26f225a08aab7449a0d8fe
Java
mcanoy/quarkus-ex
/src/main/java/com/mcanoy/Version.java
UTF-8
721
2.1875
2
[]
no_license
package com.mcanoy; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.eclipse.microprofile.metrics.annotation.Counted; import org.eclipse.microprofile.metrics.annotation.Timed; @Path("/version") public class Version { @ConfigProperty(name = "com.mcanoy.version") String version; @GET @Produces(MediaType.APPLICATION_JSON) @Counted(name="versionCounter") @Timed(name="versionTimer") public String version(@QueryParam(value="greetings") String greetings) { return String.format("{\"version\": \"%s\"}", version); } }
true
4f069d90b19dd84325ed80e6d56c9701cd8b0932
Java
zhaohongbogit/androidNetty
/app/src/main/java/com/cclx/mobile/hb_connect/net/SocketService.java
UTF-8
834
2.234375
2
[]
no_license
package com.cclx.mobile.hb_connect.net; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; public class SocketService extends Service { @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); new Thread(new Runnable() { @Override public void run() { try { startService(); } catch (Exception e) { Log.e("SocketService", "启动socket服务器异常", e); } } }).start(); } private void startService() throws Exception { new DiscardServer(12345).run(); } }
true
b2750777600df6d0e900380ef9e87963cc5c67e8
Java
sollunna/leetcode-practice
/src/crackingcode/Easy0206.java
UTF-8
1,779
3.921875
4
[]
no_license
package crackingcode; import org.junit.Test; /** * 编写一个函数,检查输入的链表是否是回文的。 * * 示例 1: * 输入: 1->2 * 输出: false * 示例 2: * 输入: 1->2->2->1 * 输出: true *   * 进阶: * 你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题? * * 思路:快慢指针,快走两步慢走一步,链表长度为奇数,慢指针指向最中间,偶数指向后半段开头 * O(1)空间复杂度实现:遍历前半段时,让每个元素指向都相反,则完成了反转 * 常规思路从中间开始将后半段入栈,在一个个弹出来后前半段比较,空间复杂度O(n) */ public class Easy0206 { public boolean isPalindrome(ListNode head) { ListNode slow = head, fast = head; ListNode rev = null;//前半段反转后的头结点 while (fast != null && fast.next != null) { ListNode tmp = slow; slow = slow.next; fast = fast.next.next; tmp.next = rev;//指针转向 rev = tmp;//头往后移 } /*通过fast状态判断链表长度奇偶性 * fast != null证明长度为奇数,此时slow指向正中间那个元素,所以往后移动一位*/ if (fast != null) slow = slow.next; /*此时链表rev是前半段反转后的结果,比较即可*/ while (slow != null) { if (rev.val != slow.val) return false; slow = slow.next; rev = rev.next; } return true; } public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } @Test public void test1() { ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(3); head.next.next.next = new ListNode(2); head.next.next.next.next = new ListNode(1); System.out.println(isPalindrome(head)); } }
true
8e87e2a484953c1241d6fcc4d941f4305e5bf224
Java
AshkIza/AlgorithmsAndSystemDesign
/src/main/java/leetcode/Strings/myAtoi.java
UTF-8
1,623
3.65625
4
[]
no_license
package leetcode.Strings; public class myAtoi { public static int myAtoi(String s) { if(s.length() == 0) return 0; long result = 0; int index = 0; while(index < s.length() && s.charAt(index) == ' '){//ignore whitespaces index++; } if(index > s.length()-1) return 0;//reached end of string char ch = s.charAt(index); if(ch=='+' || ch=='-' || isAnumber(ch)){ int sign = ch=='-' ? -1 : 1 ; if(ch=='+' || ch=='-'){ index++; } //long overflow is possible too, so return imediatly when int overflow while(index < s.length() && isAnumber(s.charAt(index))){ long i = (long) s.charAt(index) - '0'; result = result * 10 + i; if(result > Integer.MAX_VALUE){//if int overflow return imediatly result *= sign; result = (result >= Integer.MAX_VALUE) ? Integer.MAX_VALUE : Integer.MIN_VALUE; return (int) result; } index++; } result *= sign; return (int) result; } return 0; } private static boolean isAnumber(char ch){ return ch>='0' && ch<='9'; } public static void main(String[] args) { System.out.println(myAtoi("9223372036854775808"));//Long overflow System.out.println("Long overflow -> Long.MAX_VALUE =" + Long.MAX_VALUE); System.out.print("Long.MAX_VALUE + 1 --overflow--> " + (Long.MAX_VALUE + 1)); } }
true
a5d67a2a340ffe2bc30c7378d48c67c64703ce8c
Java
acgatea/Java-compiler
/target/test-classes/a5/J1_sideeffect7.java
UTF-8
435
1.976563
2
[]
no_license
// CODE_GENERATION public class J1_sideeffect7 { public J1_sideeffect7() {} protected int g; public static int test() { return new J1_sideeffect7().test2(); } public int test2() { g=1; boolean b7 = (f(1)==2 || 10/0<10); int r7 = String.valueOf(b7).charAt(0); return r7 + 7; } public int f(int x) { g=g+1; return x*g; } }
true
6b8e8a21f0c65264571bd405e58fa7a8e29d82e3
Java
mannguyen1411/PlayMusicDuAn1
/app/src/main/java/com/example/duan1/playmusicduan1/FeedbackActivity.java
UTF-8
2,648
1.929688
2
[]
no_license
package com.example.duan1.playmusicduan1; import android.app.ProgressDialog; import android.graphics.Bitmap; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; import android.widget.Toast; public class FeedbackActivity extends AppCompatActivity { String url; WebView webViewFeedback; ProgressDialog progressDialogFeedback; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_feedback); webViewFeedback = (WebView) findViewById(R.id.webviewFeedback); url = "https://docs.google.com/forms/d/1Yh85fzDqke8eoFxyEIkWJcmiJheRjUY7gLJSokt7-FE"; webViewFeedback.loadUrl(url); WebSettings webSettingsFeedback = webViewFeedback.getSettings(); webSettingsFeedback.setJavaScriptEnabled(true); webSettingsFeedback.setBuiltInZoomControls(true); webSettingsFeedback.setAppCacheEnabled(true); webSettingsFeedback.setDisplayZoomControls(true); progressDialogFeedback = new ProgressDialog(FeedbackActivity.this); webViewFeedback.setWebViewClient(new WebViewClient(){ @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { try {progressDialogFeedback.setTitle("Please wait !!!"); progressDialogFeedback.setMessage("Process loading ..."); progressDialogFeedback.setIndeterminate(true); progressDialogFeedback.setCancelable(true); progressDialogFeedback.setCanceledOnTouchOutside(true); progressDialogFeedback.show();}catch (Exception e){} } @Override public void onPageFinished(WebView view, String url) { try {progressDialogFeedback.dismiss();}catch (Exception e){} } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_option_reload,menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.opt_reload: webViewFeedback.reload(); break; } return super.onOptionsItemSelected(item); } }
true
845aa9c36429f6af1daa70de1d6a2b22cb7debd0
Java
geeeeet/weixin-server
/weixin-controller/src/main/java/pers/lrf/weixinserver/controller/weixintest/ExampleController.java
UTF-8
1,000
1.921875
2
[]
no_license
package pers.lrf.weixinserver.controller.weixintest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import pers.lrf.weixinserver.controller.BaseController; import pers.lrf.weixinserver.service.interfaces.IExample; import java.util.HashMap; import java.util.Map; /** * @author lirufeng * @date 2019/10/16 9:26 **/ @RestController @CrossOrigin @RequestMapping("example") public class ExampleController extends BaseController { @Autowired private IExample iExample; @RequestMapping("test") public Object test() { ResultJson resultJson = new ResultJson<>(); resultJson.setMsg("查询成功!"); Map<String,String> map = new HashMap<>(); map.put("name",iExample.getAuthorName()); resultJson.setRt(map); return resultJson; } }
true
061b385ccf0836945b2b1715a423d35e4c58120d
Java
aleffilus/tddestudy
/projectteste/src/test/java/br/com/projectteste/CalculadoraDeSalarioTest.java
UTF-8
1,418
2.5
2
[ "Apache-2.0" ]
permissive
package br.com.projectteste; import br.com.projectteste.domain.CalculadoraDeSalario; import br.com.projectteste.domain.Cargo; import br.com.projectteste.domain.Funcionario; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; /** * Created by Alessandro on 08/05/2017. */ public class CalculadoraDeSalarioTest { private final CalculadoraDeSalario calculadoraDeSalario = new CalculadoraDeSalario(); private final float delta = 0.00001f; @Test public void deveCalcularSalarioParaDesenvolvedoresComSalarioAbaixoDoLimite () { Funcionario desenvolvedor = new Funcionario("Mauricio", 1500.0, Cargo.DESENVOLVEDOR); double salario = calculadoraDeSalario.calculaSalario(desenvolvedor); assertEquals(1500.0 * 0.9, salario, delta); } @Test public void deveCalcularSalarioParaDesenvolvedoresComSalarioAcimaDoLimite () { Funcionario desenvolvedor = new Funcionario("Alessandro", 4000.0, Cargo.DESENVOLVEDOR); double salario = calculadoraDeSalario.calculaSalario(desenvolvedor); assertEquals(4000* 0.8, salario, delta); } @Test public void deveCalcularSalarioParaDBAsComSalarioAbaixoDoLimite () { Funcionario dba = new Funcionario("Alessandro", 500.0, Cargo.DBA); double salario = calculadoraDeSalario.calculaSalario(dba); assertEquals(500.0 * 0.85, salario, delta); } }
true
bd888d305573b989d0548b5ee9ef5fbc987a612f
Java
astock1229/main
/src/main/java/seedu/address/ui/TaskDetailsPane.java
UTF-8
2,149
2.734375
3
[ "MIT" ]
permissive
package seedu.address.ui; import java.util.logging.Logger; import com.google.common.eventbus.Subscribe; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Region; import seedu.address.commons.core.LogsCenter; import seedu.address.commons.events.ui.TaskPanelDeselectionEvent; import seedu.address.commons.events.ui.TaskPanelSelectionChangedEvent; import seedu.address.model.task.Task; /** * The Task Detail Panel of the App. */ public class TaskDetailsPane extends UiPart<Region> { private static final String FXML = "TaskDetailsPane.fxml"; private final Logger logger = LogsCenter.getLogger(getClass()); @FXML private HBox cardPane; @FXML private Label name; @FXML private Label startDateTime; @FXML private Label endDateTime; @FXML private FlowPane tags; public TaskDetailsPane() { super(FXML); // To prevent triggering events for typing inside the loaded detail screen. getRoot().setOnKeyPressed(Event::consume); registerAsAnEventHandler(this); } @Subscribe private void handleTaskPanelSelectionChangedEvent(TaskPanelSelectionChangedEvent event) { logger.info(LogsCenter.getEventHandlingLogMessage(event)); Task task = event.getNewSelection(); name.setText(task.getName().toString()); startDateTime.setText("Starting from: " + task.getStartDateTime().getDate()); endDateTime.setText("Due by: " + task.getEndDateTime().toString()); // Clear existing list of tags before populating with new tags tags.getChildren().clear(); task.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName))); } @Subscribe private void handleTaskPanelDeselectionEvent(TaskPanelDeselectionEvent event) { logger.info(LogsCenter.getEventHandlingLogMessage(event)); // Clear details pane name.setText(""); startDateTime.setText(""); endDateTime.setText(""); tags.getChildren().clear(); } }
true
69b807ac5eeb705c7c57d4b555c210e9f51489ac
Java
lc522108813/tradecoin
/src/main/java/com/coins/tradecoin/enums/RequestType.java
UTF-8
543
2.546875
3
[]
no_license
package com.coins.tradecoin.enums; public enum RequestType { GET(1,"GET"), POST(2,"POST"), ; private RequestType(Integer type, String name) { this.type = type; this.name = name; } private Integer type; private String name; public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
true
3ccf25f493e858b5518cb40f9aa9c05113406fd2
Java
mihaelacalin/studio
/workspace/MyBatisAnnotation/src/mc/CommentoMapper.java
UTF-8
1,052
2.21875
2
[]
no_license
package mc; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; public interface CommentoMapper { @Insert("create table Commento(id INTEGER PRIMARY KEY,authorId INTEGER NOT NULL, postId INTEGER NOT NULL,text VARCHAR(50) NOT NULL)") void createCommentoTable(); @Insert("insert into Commento(id,authorId,postId,text) values( #{id}, #{authorId}, #{postId},#{text})") void insertCommento(Commento commento); @Delete("DELETE FROM Commento WHERE id = #{id}") void deleteCommento(Long id); @Select("SELECT * FROM Commento WHERE id = #{id}") Commento selectCommento(Long id); @Select("SELECT * FROM Commento") List<Commento> selectAllComments(); @Select("SELECT * FROM Commento,Autore WHERE Commento.authorId=Autore.id AND Autore.id=#{id} ") List<Commento> selectAllCommentsOfAuthor(Long id); @Select("SELECT * FROM Commento,Post WHERE Commento.postId=Post.id AND Post.id=#{id}") List<Commento> selectAllCommentsOfPost(Long id); }
true
07b188cf7bdd270b2fc5337cb92daec39f2d8f2d
Java
piwicode/diplomacy-strategy-editor
/src/diplo/visu/Frame.java
UTF-8
4,418
2.40625
2
[]
no_license
package diplo.visu; import java.awt.event.*; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.geom.*; import diplo.framework.*; import diplo.meta.MetaGame; import java.util.List; public class Frame extends GraphicalComponent implements ComponentListener { final Root root; boolean inDrag = false; Point2D Center = new Point2D.Double(); Frame(Root root, MetaGame g, double w, double h) { if (root == null) { throw new IllegalArgumentException(); } this.root = root; after.scale(.1, .1); setSize(root.getPannelWidth(), root.getPannelHeight()); root.addComponentListener(this); } // Set the size of mouse interception area void setSize(double w, double h) { shape = new Rectangle2D.Double(0., 0., w, h); } // ComponentListener::componentHidden public void componentHidden(ComponentEvent e) { } // ComponentListener::componentMoved public void componentMoved(ComponentEvent e) { } // ComponentListener::componentResized public void componentResized(ComponentEvent e) { Component c = e.getComponent(); setSize(c.getWidth(), c.getHeight()); } // ComponentListener::componentShown public void componentShown(ComponentEvent e) { } public void doReframeOn(Point2D center, double w, double h) { System.out.println("coord:" + center.getX() + "," + center.getY()); double hmin = 65; double hmax = 5; double wmin = 5; double wmax = 5; double ww = ((Rectangle2D) shape).getWidth() - wmin - wmax; double wh = ((Rectangle2D) shape).getHeight() - hmin - hmax; double ratio = 1; if (w / h > ww / wh) { ratio = ww / w; } else { ratio = wh / h; } AffineTransform t = new AffineTransform(); t.setToTranslation(-center.getX(), -center.getY()); after.preConcatenate(t); t.setToScale(ratio, ratio); after.preConcatenate(t); t.setToTranslation(wmin + ww * .5, hmin + wh * .5); after.preConcatenate(t); } @Override public boolean onPress(int button, int modifiers, PickPath path, Point2D point) { if (button == MouseEvent.BUTTON2 || button == MouseEvent.BUTTON3) { inDrag = true; return true; } else { return false; } } ; @Override public void onDrag(int button, int modifiers, PickPath me, List<PickPath> path, Point2D point, Point2D move) { if (button == MouseEvent.BUTTON2 || button == MouseEvent.BUTTON3) { Point2D pt = move; //*pt = me.getTransform().deltaTransform(move, pt); if (button == MouseEvent.BUTTON2) { final AffineTransform t = new AffineTransform(); t.translate(pt.getX(), pt.getY()); t.concatenate(after); after.setTransform(t); } if (button == MouseEvent.BUTTON3) { double s = Math.exp(pt.getY() / 100.); final AffineTransform t = new AffineTransform(); t.translate(root.getPannelWidth() * .5, root.getPannelHeight() * .5); t.scale(s, s); t.translate(-root.getPannelWidth() / 2., -root.getPannelHeight() / 2.); t.concatenate(after); after.setTransform(t); } root.querryRedraw(); } } @Override public void onRelease(int button, int modifiers, List<PickPath> path, Point2D point) { if (button == MouseEvent.BUTTON2 || button == MouseEvent.BUTTON3) { inDrag = false; queryRedraw(); } } public void queryRedraw() { root.querryRedraw(); } public void Draw(Graphics2D gfx, AffineTransform t2D) { if (inDrag) { gfx.translate(((Rectangle2D.Double) shape).getWidth() / 2., ((Rectangle2D.Double) shape).getHeight() / 2.); gfx.drawLine(0, 10, 0, 20); gfx.drawLine(0, -10, 0, -20); gfx.drawLine(10, 0, 20, 0); gfx.drawLine(-10, 0, -20, 0); } } }
true
f7294fefb7eaeead1d7a5340180e413f96f906dd
Java
rodrigobitdelima/Auditeste-Web-Automation
/src/test/java/pageFactory/HomePage.java
UTF-8
1,474
2.234375
2
[ "MIT" ]
permissive
package pageFactory; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class HomePage { WebDriver driver; @FindBy(xpath = "//*[@id=\"sgpb-popup-dialog-main-div-wrapper\"]/div/img") WebElement contactPopupCloseBtn; @FindBy(xpath = "//*[@id=\"rodape-faixa-preta\"]/div[2]/div/div/div[1]/a") WebElement requestBudgetBtn; @FindBy(id = "menu-item-290") WebElement servicesMenuBtn; public HomePage(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); } public void closeWelcomeContactPopup() { contactPopupCloseBtn.click(); } public void requestBudget() { requestBudgetBtn.click(); } public void accessMenu(String menuName) { driver.findElement(By.xpath("//li/a[contains(.,'" + menuName + "')]")).click(); } public void accessServicePage(String service) throws InterruptedException { openServicesSubmenu(); driver.findElement(By.xpath("//ul/li/a[contains(.,'" + service + "')]")).click(); } public boolean isBrowserAtPage(String pageTitle) { return driver.getPageSource().contains("//" + pageTitle); } private void openServicesSubmenu() throws InterruptedException { servicesMenuBtn.click(); Thread.sleep(1000L); } }
true
899f48158eb6bc74914aaa6de93c4ab1c14ee3b3
Java
211806230/ReadC
/StringUtil.java
UTF-8
526
3
3
[]
no_license
package ReadClockIn.www.Others; /** * 字符串工具类 */ public class StringUtil { //判断是否为空 public static boolean isEmpty(String str) { if (str == null || "".equals ( str.trim () )) { return true; } else { return false; } } //判断是否不为空 public static boolean isNotEmpty(String str) { if (str != null || !"".equals ( str.trim () )) { return true; } else { return false; } } }
true
557a06383d55fe65fad29ac5ca015304159d94ce
Java
CSC3054-Group/GroupProject
/app/src/main/java/com/groupwork/activity/SocketClass.java
UTF-8
8,635
2.421875
2
[]
no_license
package com.groupwork.activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.groupwork.R; import com.groupwork.urlContrans.UrlConfig; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; /** * Created by admin on 2017/3/31. */ public class SocketClass extends AppCompatActivity { private EditText editText; private Button socket_bt; private TextView textView; Handler handler = new Handler() { @Override public void handleMessage(Message msg) { String text = msg.obj.toString(); textView.setText(text); } }; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.socket_test); editText = (EditText) findViewById(R.id.edit_userID); socket_bt = (Button) findViewById(R.id.bt_forename); textView = (TextView) findViewById(R.id.text_forename); socket_bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String id_number = editText.getText().toString(); new Thread(new Runnable() { @Override public void run() { // open thread to process network access request and response Socket socket = null; try { socket = new Socket(UrlConfig.Socket_IP, UrlConfig.Socket_PORT); //Output data to Server OutputStream out = socket.getOutputStream(); PrintWriter pw = new PrintWriter(out); //Input sql sentence which you want to execute String sqlString = "select tbl_restaurants.restId,resLocation,tbl_restaurants.resName," + "AVG(revStarRating),resType from tbl_restaurants,tbl_restype,tbl_reviews " + "where tbl_restaurants.restId=tbl_reviews.restId " + "and tbl_restaurants.resTypeId=tbl_restype.resTypeId " + "GROUP BY tbl_restaurants.restId"; pw.write(sqlString); pw.flush(); socket.shutdownOutput(); Log.d("Test", "transport successfully"); //get response from server InputStream is = socket.getInputStream(); InputStreamReader isr =new InputStreamReader(is); BufferedReader br =new BufferedReader(isr); String info = ""; String line = null; while((line=br.readLine())!=null){ info = info + line; } //socket.shutdownInput(); Log.d("Test", info); /** * Json analyse * [ { "Email": "gcunningham12@qub.ac.uk", "UserId": "1", "Forename": "Gerard", "Title": "Mr", "UserPassword": "password123", "Middlename": "Anthony", "Surname": "Cunningham", "Postcode": "BT344HR", "SecurityQuestion": "Place Of Birth", "SecurityAnswer": "Newry" }, { "Email": "jmccully03@qub.ac.uk", "UserId": "6", "Forename": "Jamie", "Title": "Mr", "UserPassword": "password123", "Middlename": "Ryan ", "Surname": "McCully", "Postcode": "BT455HR", "SecurityQuestion": "Place Of Birth", "SecurityAnswer": "Belfast" }, { "Email": "hwilson20@qub.ac.uk", "UserId": "7", "Forename": "Harry ", "Title": "Mr", "UserPassword": "password123", "Middlename": "Jamie", "Surname": "Wilson", "Postcode": "BT367RD", "SecurityQuestion": "Place Of Birth", "SecurityAnswer": "Belfast" }, { "Email": "l@qub.ac.uk", "UserId": "8", "Forename": "Jianyu", "Title": "Mr ", "UserPassword": "password123", "Middlename": "R", "Surname": "Li", "Postcode": "BT321SE", "SecurityQuestion": "Place Of Birth", "SecurityAnswer": "Belfast" }, { "Email": "r@qub.ac.uk", "UserId": "9", "Forename": "Lei", "Title": "Mr ", "UserPassword": "password123", "Middlename": "R", "Surname": "Tong", "Postcode": "BT321RS", "SecurityQuestion": "Place Of Birth", "SecurityAnswer": "Belfast" } ] * * */ JSONArray array= new JSONArray(info); for(int i=0;i<array.length();i++){ JSONObject object=array.getJSONObject(i); String Email=object.getString("Email"); int UserId=object.getInt("UserId"); String ForeName=object.getString("Forename"); String Title=object.getString("Title"); String Middlename=object.getString("Middlename"); String Surname=object.getString("Surname"); Log.d("Test2",Email+" "+UserId+" "+ForeName+" "+Title+" "+ Middlename+" "+Surname); //Log.d("Test2",Email+); } Log.d("Test2","successful"); //Set result to textview Message message =Message.obtain(); message.obj = info; message.what = 1; // obj and what is similar as value-key handler.sendMessage(message);// send message to handler } catch (Exception e) { } finally { try { if(socket!=null){ socket.close(); } socket.shutdownInput(); } catch (IOException e) { e.printStackTrace(); } } } }).start(); } }); } }
true
b0f2cf7d71843f25390f6f2e8ac45934ec4639e6
Java
lvfaqiang/Multi-Image-Selector
/app/src/main/java/com/lvfq/multiimage_master/impl/IDeletePicCallback.java
UTF-8
213
1.679688
2
[]
no_license
package com.lvfq.multiimage_master.impl; /** * IDeletePicCallback * * @author lvfq * @date 2017/4/5 上午9:20 * @mainFunction : */ public interface IDeletePicCallback { void callBack(int position); }
true
27aa1ed3c1c51ae41e55f32c0c56f9474117cb4c
Java
KRHwangSeonWoo/kw_infosci_board_project01
/src/bFrontController/BFrontController.java
UTF-8
4,241
2.140625
2
[]
no_license
package bFrontController; import java.io.IOException; import javax.servlet.RequestDispatcher; 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 bCommand.BCommand; import bCommand.BContent_viewCommand; import bCommand.BMainCommand; import bCommand.BReplyDeleteCommand; import bCommand.BReplyModifyCommand; import bCommand.BWriteCommand; import bCommand.BWriteReplyCommand; import bCommand.BBoardDeleteCommand; import bCommand.BBoardModifyCommand; /** * Servlet implementation class BFrontController */ @WebServlet("*.do") public class BFrontController extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public BFrontController() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("doGet"); actionDo(request,response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("doPost"); actionDo(request,response); } private void actionDo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ System.out.println("actionDo"); request.setCharacterEncoding("EUC-KR"); String movePage=null; BCommand bCommand=null; String uri=request.getRequestURI(); String conpath= request.getContextPath(); String com= uri.substring(conpath.length()); if(com.equals("/write.do")) { bCommand=new BWriteCommand(); bCommand.play(request, response); movePage="main.do"; } else if(com.equals("/main.do")) { bCommand=new BMainCommand(); bCommand.play(request,response); movePage="main.jsp"; } else if(com.equals("/content_view.do")) { bCommand=new BContent_viewCommand(); bCommand.play(request,response); movePage="content_view.jsp"; } else if(com.equals("/boardModify.do")) { bCommand=new BBoardModifyCommand(); bCommand.play(request, response); movePage="main.do"; } else if(com.equals("/boardDelete.do")) { bCommand=new BBoardDeleteCommand(); bCommand.play(request,response); movePage="main.do"; } else if(com.equals("/writeReply.do")) { bCommand=new BWriteReplyCommand(); bCommand.play(request,response); movePage="content_view.do"; } else if(com.equals("/replyModify.do")) { bCommand=new BReplyModifyCommand(); bCommand.play(request,response); movePage="content_view.do"; } else if(com.equals("/replyDelete.do")) { bCommand=new BReplyDeleteCommand(); bCommand.play(request, response); movePage="content_view.do"; } else if(com.equals("/write_page_jsp.do")) { movePage="write_page.jsp"; } else if(com.equals("/login_jsp.do")) { movePage="login.jsp"; } else if(com.equals("/boardModify_jsp.do")) { movePage="boardModify.jsp"; } else if(com.equals("/boardDelete_jsp.do")) { movePage="boardDelete.jsp"; } else if(com.equals("/joinAfter_jsp.do")) { movePage="joinAfter.jsp"; } else if(com.equals("/infoModify_jsp.do")) { movePage="infoModify.jsp"; } else if(com.equals("/loginAfter_jsp.do")) { movePage="loginAfter.jsp"; } else if(com.equals("/infoModifyAfter_jsp.do")) { movePage="infoModifyAfter.jsp"; } else if(com.equals("/login_jsp.do")) { movePage="login.jsp"; } else if(com.equals("/replyModify_jsp.do")) { movePage="replyModify.jsp"; } else if(com.equals("/replyDelete_jsp.do")) { movePage="replyDelete.jsp"; } RequestDispatcher dispatcher = request.getRequestDispatcher(movePage); dispatcher.forward(request, response); } }
true
38fd68738f9bae6a5cf3eac457baafc757f81844
Java
bondareko/trezor-android
/cgcmn-liban/src/main/java/com/circlegate/liban/utils/ActivityUtils.java
UTF-8
2,739
1.976563
2
[]
no_license
package com.circlegate.liban.utils; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Parcelable; import android.speech.RecognizerIntent; import android.text.TextUtils; import android.widget.Toast; import com.circlegate.liban.R; import com.circlegate.liban.base.CommonClasses.IGlobalContext; import java.util.List; import java.util.Locale; public class ActivityUtils { private static final String ACTIVITY_RESULT_PARCELABLE = ActivityUtils.class.getName() + "." + "ACTIVITY_RESULT_PARCELABLE"; public static void setResultParcelable(Activity activity, int resultCode, Parcelable data) { Intent intent = new Intent(); intent.putExtra(ACTIVITY_RESULT_PARCELABLE, data); activity.setResult(resultCode, intent); } public static <T extends Parcelable> T getResultParcelable(Intent resultData) { return resultData != null ? resultData.<T>getParcelableExtra(ACTIVITY_RESULT_PARCELABLE) : null; } public static void showSpeechRecognitionActivity(Activity activity, String msg) { showSpeechRecognitionActivity(activity, msg, null); } public static void showSpeechRecognitionActivity(Activity activity, String msg, Locale optLocale) { PackageManager pm = activity.getPackageManager(); List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0); if (activities.size() == 0) { Toast.makeText(activity, R.string.voice_recognition_not_available, Toast.LENGTH_LONG).show(); } else { Intent itVoiceRec = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); itVoiceRec.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); itVoiceRec.putExtra(RecognizerIntent.EXTRA_PROMPT, msg); // Na Android Wear zmena jazyka mozna nefunguje :( (prosinec 2014) if (optLocale != null) { String lang = optLocale.getLanguage(); if (!TextUtils.isEmpty(lang)) { String country = optLocale.getCountry(); //Toast.makeText(activity, lang + "-" + country, Toast.LENGTH_SHORT).show(); itVoiceRec.putExtra(RecognizerIntent.EXTRA_LANGUAGE, lang + (!TextUtils.isEmpty(country) ? ("-" + country) : "")); itVoiceRec.putExtra("android.speech.extra.EXTRA_ADDITIONAL_LANGUAGES", new String[]{ lang }); } } activity.startActivityForResult(itVoiceRec, IGlobalContext.RQC_SPEECH_RECOGNITION); } } }
true
e61a0fa015848c5246c38a6d59e0a6531c1ae75b
Java
bcy569/SWD4TA020-3008
/Bookstore/src/main/java/fi/bcy569/domain_class_pojo_orm/Category.java
UTF-8
1,053
2.6875
3
[ "MIT" ]
permissive
package fi.bcy569.domain_class_pojo_orm; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; @Entity // ORM map into DB table @Table @Data // Lombok for constructors, getters and setters public class Category { @OnDelete(action = OnDeleteAction.NO_ACTION) @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; private String name; @JsonIgnore // Otherwise it will be endless looping with linked mapping @OneToMany(cascade = CascadeType.ALL, mappedBy = "category") private List<Book> books; // public List<Book> getBooks() { // return books; // } // // public void setBooks(List<Book> books) { // this.books = books; // } }
true
aa3c416d89375233f0d485428b67ac09022cbb5e
Java
kh4904/SteadyTurtle
/src/main/java/com/spring/ex/dto/BoardDTO.java
UTF-8
1,435
2.640625
3
[]
no_license
package com.spring.ex.dto; public class BoardDTO { // 작성자 private String mName; // 게시글 번호 private String bNum; // 게시글 메인제목 private String bTitle; // 게시글 내용 private String bNote; // 게시글 날짜 private String bDate; // 게시글 카테고리 private String bCate; // 게시글 답변내용 private String bReply; public String getmName() { return mName; } public void setmName(String mName) { this.mName = mName; } public String getbNum() { return bNum; } public void setbNum(String bNum) { this.bNum = bNum; } public String getbTitle() { return bTitle; } public void setbTitle(String bTitle) { this.bTitle = bTitle; } public String getbNote() { return bNote; } public void setbNote(String bNote) { this.bNote = bNote; } public String getbDate() { return bDate; } public void setbDate(String bDate) { this.bDate = bDate; } public String getbCate() { return bCate; } public void setbCate(String bCate) { this.bCate = bCate; } public String getbReply() { return bReply; } public void setbReply(String bReply) { this.bReply = bReply; } @Override public String toString() { return "BoardDTO [mName=" + mName + ",bNum=" + bNum + ", bTitle=" + bTitle + ", bCate=" + bCate + ", bNote=" + bNote + ", bDate=" + bDate + ", bReply=" + bReply + "]"; } }
true
806059b5a83cc864562b16252e999ff9478a4d3d
Java
mattia-marchesini-unibo/oop20-bang
/src/model/states/PlayCardState.java
UTF-8
2,717
2.578125
3
[]
no_license
package model.states; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import libs.Pair; import model.GameStateMachine; import model.Player; import model.Table; import model.Table.Message; import model.card.Card; import model.card.Color; import model.effects.Weapon; public class PlayCardState implements State { private Card playedCard; private GameStateMachine gsMachine; private Map<Message, Pair<Runnable, String>> tableMsgMap = new HashMap<>( Map.of(Message.CHOOSE_CARD, new Pair<>((Runnable) () -> { gsMachine.getTable().getChooseCardsObservable().addObserver(() -> { gsMachine.setCurrentState(new CheckDeadPlayersState()); gsMachine.go(); }); }, "chooseCard"), Message.CHOOSE_PLAYER, new Pair<>((Runnable) () -> { gsMachine.getTable().getChoosePlayerObservable().addObserver(() -> { gsMachine.setCurrentState(new CheckDeadPlayersState()); gsMachine.go(); }); }, "choosePlayer"), Message.CHOOSE_PLAYER_WITH_DISTANCE, new Pair<>((Runnable) () -> { gsMachine.getTable().getChoosePlayerObservable().addObserver(() -> { gsMachine.setCurrentState(new CheckDeadPlayersState()); gsMachine.go(); }); }, "choosePlayerDistance"))); public PlayCardState(Card playedCard) { this.playedCard = playedCard; } @Override public void handle(final GameStateMachine gsMachine) { this.gsMachine = gsMachine; Table table = gsMachine.getTable(); playedCard.getEffect().useEffect(table); Player current = gsMachine.getTable().getCurrentPlayer(); Set<Card> active = current.getActiveCards(); Message msg = table.getMessage(); table.setMessage(null); // if card is blue and is not prison if (playedCard.getColor().equals(Color.BLUE) && !playedCard.getRealName().equals("jail")) { // if card is not already in blue active cards if (current.getActiveCardsByName(playedCard.getRealName()).isEmpty()) { // if there's already a weapon then remove it if (playedCard.getClass().equals(Weapon.class)) { Optional<Card> optWeapon = active.stream() .filter(c -> c.getEffect().getClass().equals(Weapon.class)).findFirst(); if (!optWeapon.isEmpty()) { current.removeActiveCard(optWeapon.get()); } } // then add card current.addActiveCard(playedCard); } } if (this.tableMsgMap.containsKey(msg)) { var pair = this.tableMsgMap.get(msg); pair.getX().run(); table.getCurrentPlayer().removeCard(playedCard); gsMachine.setMessage(pair.getY()); } else { table.getCurrentPlayer().removeCard(playedCard); gsMachine.setMessage("playedCard"); gsMachine.setCurrentState(new CheckDeadPlayersState()); gsMachine.go(); } } }
true
07591d6636a040bde1974014cc8e906959e15903
Java
bullshitprojects/java-SistemaHospitalario
/Entidades/ConsumoMedicamento.java
UTF-8
362
2.25
2
[]
no_license
package Entidades; import java.util.Date; /** * * @author juliocanizalez */ public class ConsumoMedicamento extends Medicamento{ protected Date fechaDeConsumo; public Date getFechaDeConsumo() { return fechaDeConsumo; } public void setFechaDeConsumo(Date fechaDeConsumo) { this.fechaDeConsumo = fechaDeConsumo; } }
true
868a1189829ea50cd42804e2c6e7abc7abf8065d
Java
jankovicdragan/flight-advisor-app
/src/main/java/com/jankovicd/flightadvisor/auth/jwt/JwtPropertiesProvider.java
UTF-8
536
2.03125
2
[]
no_license
package com.jankovicd.flightadvisor.auth.jwt; import javax.crypto.SecretKey; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import io.jsonwebtoken.security.Keys; @Component public class JwtPropertiesProvider { @Value("${jwt.secret}") private String secretKey; @Value("${jwt.cookie.name}") private String cookieName; public SecretKey getSecretKey() { return Keys.hmacShaKeyFor(secretKey.getBytes()); } public String getCookieName() { return cookieName; } }
true
2e021d16fbb0d60499bea9a1d02ea156f74d769c
Java
liuhaosource/OppoFramework
/A1_7_1_1/src/main/java/com/android/server/wifi/hotspot2/pps/DomainMatcher.java
UTF-8
10,718
1.890625
2
[]
no_license
package com.android.server.wifi.hotspot2.pps; import com.android.server.wifi.hotspot2.Utils; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; /* JADX ERROR: NullPointerException in pass: ReSugarCode java.lang.NullPointerException at jadx.core.dex.visitors.ReSugarCode.initClsEnumMap(ReSugarCode.java:159) at jadx.core.dex.visitors.ReSugarCode.visit(ReSugarCode.java:44) at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:12) at jadx.core.ProcessClass.process(ProcessClass.java:32) at jadx.core.ProcessClass.lambda$processDependencies$0(ProcessClass.java:51) at java.lang.Iterable.forEach(Iterable.java:75) at jadx.core.ProcessClass.processDependencies(ProcessClass.java:51) at jadx.core.ProcessClass.process(ProcessClass.java:37) at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:292) at jadx.api.JavaClass.decompile(JavaClass.java:62) at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200) */ /* JADX ERROR: NullPointerException in pass: ExtractFieldInit java.lang.NullPointerException at jadx.core.dex.visitors.ExtractFieldInit.checkStaticFieldsInit(ExtractFieldInit.java:58) at jadx.core.dex.visitors.ExtractFieldInit.visit(ExtractFieldInit.java:44) at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:12) at jadx.core.ProcessClass.process(ProcessClass.java:32) at jadx.core.ProcessClass.lambda$processDependencies$0(ProcessClass.java:51) at java.lang.Iterable.forEach(Iterable.java:75) at jadx.core.ProcessClass.processDependencies(ProcessClass.java:51) at jadx.core.ProcessClass.process(ProcessClass.java:37) at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:292) at jadx.api.JavaClass.decompile(JavaClass.java:62) at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200) */ public class DomainMatcher { private static final String[] TestDomains = null; private final Label mRoot; private static class Label { private final Match mMatch; private final Map<String, Label> mSubDomains; /* synthetic */ Label(Match match, Label label) { this(match); } private Label(Match match) { this.mMatch = match; this.mSubDomains = match == Match.None ? new HashMap() : null; } private void addDomain(Iterator<String> labels, Match match) { String labelName = (String) labels.next(); if (labels.hasNext()) { Label subLabel = new Label(Match.None); this.mSubDomains.put(labelName, subLabel); subLabel.addDomain(labels, match); return; } this.mSubDomains.put(labelName, new Label(match)); } private Label getSubLabel(String labelString) { return (Label) this.mSubDomains.get(labelString); } public Match getMatch() { return this.mMatch; } private void toString(StringBuilder sb) { if (this.mSubDomains != null) { sb.append(".{"); for (Entry<String, Label> entry : this.mSubDomains.entrySet()) { sb.append((String) entry.getKey()); ((Label) entry.getValue()).toString(sb); } sb.append('}'); return; } sb.append('=').append(this.mMatch); } public String toString() { StringBuilder sb = new StringBuilder(); toString(sb); return sb.toString(); } } /* JADX ERROR: NullPointerException in pass: EnumVisitor java.lang.NullPointerException at jadx.core.dex.visitors.EnumVisitor.visit(EnumVisitor.java:102) at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:12) at jadx.core.dex.visitors.DepthTraversal.lambda$visit$0(DepthTraversal.java:13) at java.util.ArrayList.forEach(ArrayList.java:1251) at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:13) at jadx.core.ProcessClass.process(ProcessClass.java:32) at jadx.core.ProcessClass.lambda$processDependencies$0(ProcessClass.java:51) at java.lang.Iterable.forEach(Iterable.java:75) at jadx.core.ProcessClass.processDependencies(ProcessClass.java:51) at jadx.core.ProcessClass.process(ProcessClass.java:37) at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:292) at jadx.api.JavaClass.decompile(JavaClass.java:62) at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200) */ public enum Match { ; /* JADX ERROR: Method load error jadx.core.utils.exceptions.DecodeException: Load method exception: bogus opcode: 0073 in method: com.android.server.wifi.hotspot2.pps.DomainMatcher.Match.<clinit>():void, dex: at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:118) at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:248) at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:254) at jadx.core.ProcessClass.process(ProcessClass.java:29) at jadx.core.ProcessClass.lambda$processDependencies$0(ProcessClass.java:51) at java.lang.Iterable.forEach(Iterable.java:75) at jadx.core.ProcessClass.processDependencies(ProcessClass.java:51) at jadx.core.ProcessClass.process(ProcessClass.java:37) at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:292) at jadx.api.JavaClass.decompile(JavaClass.java:62) at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200) Caused by: java.lang.IllegalArgumentException: bogus opcode: 0073 at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1227) at com.android.dx.io.OpcodeInfo.getName(OpcodeInfo.java:1234) at jadx.core.dex.instructions.InsnDecoder.decode(InsnDecoder.java:581) at jadx.core.dex.instructions.InsnDecoder.process(InsnDecoder.java:74) at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:104) ... 10 more */ static { /* // Can't load method instructions: Load method exception: bogus opcode: 0073 in method: com.android.server.wifi.hotspot2.pps.DomainMatcher.Match.<clinit>():void, dex: */ throw new UnsupportedOperationException("Method not decompiled: com.android.server.wifi.hotspot2.pps.DomainMatcher.Match.<clinit>():void"); } } /* JADX ERROR: Method load error jadx.core.utils.exceptions.DecodeException: Load method exception: bogus opcode: 0073 in method: com.android.server.wifi.hotspot2.pps.DomainMatcher.<clinit>():void, dex: at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:118) at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:248) at jadx.core.ProcessClass.process(ProcessClass.java:29) at jadx.core.ProcessClass.lambda$processDependencies$0(ProcessClass.java:51) at java.lang.Iterable.forEach(Iterable.java:75) at jadx.core.ProcessClass.processDependencies(ProcessClass.java:51) at jadx.core.ProcessClass.process(ProcessClass.java:37) at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:292) at jadx.api.JavaClass.decompile(JavaClass.java:62) at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200) Caused by: java.lang.IllegalArgumentException: bogus opcode: 0073 at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1227) at com.android.dx.io.OpcodeInfo.getName(OpcodeInfo.java:1234) at jadx.core.dex.instructions.InsnDecoder.decode(InsnDecoder.java:581) at jadx.core.dex.instructions.InsnDecoder.process(InsnDecoder.java:74) at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:104) ... 9 more */ static { /* // Can't load method instructions: Load method exception: bogus opcode: 0073 in method: com.android.server.wifi.hotspot2.pps.DomainMatcher.<clinit>():void, dex: */ throw new UnsupportedOperationException("Method not decompiled: com.android.server.wifi.hotspot2.pps.DomainMatcher.<clinit>():void"); } public DomainMatcher(List<String> primary, List<List<String>> secondary) { this.mRoot = new Label(Match.None, null); for (List<String> secondaryLabel : secondary) { this.mRoot.addDomain(secondaryLabel.iterator(), Match.Secondary); } this.mRoot.addDomain(primary.iterator(), Match.Primary); } public Match isSubDomain(List<String> domain) { Label label = this.mRoot; for (String labelString : domain) { label = label.getSubLabel(labelString); if (label == null) { return Match.None; } if (label.getMatch() != Match.None) { return label.getMatch(); } } return Match.None; } public static boolean arg2SubdomainOfArg1(List<String> arg1, List<String> arg2) { if (arg2.size() < arg1.size()) { return false; } Iterator<String> l2 = arg2.iterator(); for (String equals : arg1) { if (!equals.equals(l2.next())) { return false; } } return true; } public String toString() { return "Domain matcher " + this.mRoot; } public static void main(String[] args) { String domain; int i = 0; DomainMatcher dm1 = new DomainMatcher(Utils.splitDomain("android.google.com"), Collections.emptyList()); for (String domain2 : TestDomains) { System.out.println(domain2 + ": " + dm1.isSubDomain(Utils.splitDomain(domain2))); } List<List<String>> secondaries = new ArrayList(); secondaries.add(Utils.splitDomain("apple.com")); secondaries.add(Utils.splitDomain("net")); DomainMatcher dm2 = new DomainMatcher(Utils.splitDomain("android.google.com"), secondaries); String[] strArr = TestDomains; int length = strArr.length; while (i < length) { domain2 = strArr[i]; System.out.println(domain2 + ": " + dm2.isSubDomain(Utils.splitDomain(domain2))); i++; } } }
true
3f8519b56b28db342bff9ed2d54a2f8ee6fcda7d
Java
P79N6A/icse_20_user_study
/methods/Method_8072.java
UTF-8
1,379
2.109375
2
[]
no_license
public void setPhotoEntry(MediaController.PhotoEntry entry,boolean needCheckShow,boolean last){ pressed=false; photoEntry=entry; isLast=last; if (photoEntry.isVideo) { imageView.setOrientation(0,true); videoInfoContainer.setVisibility(VISIBLE); int minutes=photoEntry.duration / 60; int seconds=photoEntry.duration - minutes * 60; videoTextView.setText(String.format("%d:%02d",minutes,seconds)); } else { videoInfoContainer.setVisibility(INVISIBLE); } if (photoEntry.thumbPath != null) { imageView.setImage(photoEntry.thumbPath,null,getResources().getDrawable(R.drawable.nophotos)); } else if (photoEntry.path != null) { if (photoEntry.isVideo) { imageView.setImage("vthumb://" + photoEntry.imageId + ":" + photoEntry.path,null,getResources().getDrawable(R.drawable.nophotos)); } else { imageView.setOrientation(photoEntry.orientation,true); imageView.setImage("thumb://" + photoEntry.imageId + ":" + photoEntry.path,null,getResources().getDrawable(R.drawable.nophotos)); } } else { imageView.setImageResource(R.drawable.nophotos); } boolean showing=needCheckShow && PhotoViewer.isShowingImage(photoEntry.path); imageView.getImageReceiver().setVisible(!showing,true); checkBox.setAlpha(showing ? 0.0f : 1.0f); videoInfoContainer.setAlpha(showing ? 0.0f : 1.0f); requestLayout(); }
true
5eed649da84369fbe9e9214c50674b8a8f5cd62b
Java
sawtor/LinkerConfigRefactor
/src/com/taylor/stb/STBDataManager.java
UTF-8
11,512
2.109375
2
[]
no_license
package com.taylor.stb; import android.content.Context; import android.os.Handler; import android.util.Log; import com.tvezu.localdb.LocalDBManager; import com.tvezu.restclient.AsyncRESTClient; import com.tvezu.restclient.RESTException; import com.tvezu.urc.restclient.*; import java.util.*; /** * Created by Taylor on 14-7-21. * Manage spinner's data. */ public class STBDataManager implements AsyncRESTClient.OnErrorListener,AsyncRESTClient.OnResponseListener{ private static final String TAG = Constant.TAG; private Context mContext; private DataListener mDataListener; private AsyncUrcClient mUrcClient; private LocalDBManager mLocalDBManager; private ContentType mRequestContent = ContentType.BAIDU_LOCATION; private Location mBaiduProvince,mBaiduCity; public Location mDefaultProvince,mDefaultCity; private List<Location> mAllProvince; private Map<String,List<SetTopBox>> mSTBMap; private Location mProvince,mCity; private Operator mOperator; private UrcObject mBrand; private SetTopBox mSetTopBox; private static final int MAX_REQUEST_TIMES = 3 ; private int requestTimes = 0 ; public void setProvince(Location province){ mProvince = province; } public void setCity(Location city){ mCity = city; mOperator = null; } public void setOperator(Operator operator){ mOperator = operator; } public void setBrand(UrcObject brand){ mBrand = brand; } public void setSetTopBox(SetTopBox setTopBox){ mSetTopBox = setTopBox; afterSTBSelected(); } public Location getProvince(){ return mProvince; } public Location getCity(){ return mCity; } public Operator getOperator(){ return mOperator; } public UrcObject getBrand(){ return mBrand; } public SetTopBox getSetTopBox(){ return mSetTopBox; } public STBDataManager(Context context){ this.mContext = context; mUrcClient = new AsyncUrcClient(mContext,new Handler()); mLocalDBManager = LocalDBManager.getInstance(mContext); } public void setDataListener(DataListener listener){ this.mDataListener = listener; Log.d(TAG,mDataListener != null ? "非空" : "空\n"); } /** * get user location by baidu city code. * * @param cityCode use wifi/IP query location in baidu service. * */ /* */ private void getLocationByCityCode(int cityCode){ //DEBUG cityCode = 131; mRequestContent = ContentType.BAIDU_LOCATION; mUrcClient.requestLocationByBaiduCityCode(cityCode,this,this); } /** * Query all province. */ private void queryAllProvince(){ mUrcClient.requestProvinceList(this,this); } /** * Query city by selected province. * @param province */ private void queryCityByProvince(Location province){ mUrcClient.requestSublocationList(province,this,this); } /** * Query operator by select city * @param city */ private void queryOperatorByCity(Location city){ mUrcClient.requestOperatorListByLocation(city,this,this); } private void querySTBByOperator(){ mUrcClient.requestSetTopBoxListByOperator(mOperator,this,this); } private void querySTBByBrand(){ List<SetTopBox> setTopBoxes = mSTBMap.get(mBrand.getName()); mDataListener.onQuerySucceed(setTopBoxes); } public void afterSTBSelected(){ mUrcClient.requestPidMappingByOperator(mOperator, new AsyncRESTClient.OnResponseListener() { @Override public void onResponse(Object response) { if (response!=null){ List<PidMapping> pidMapping = ((ListResult<PidMapping>)response).list; mLocalDBManager.updatePidsToLocalDB(pidMapping); Log.d(TAG,"Updated pids to local db."); } } },new AsyncRESTClient.OnErrorListener() { @Override public void onError(RESTException e) { Log.d(TAG,"request pid mapping by operator error!",e); } }); mUrcClient.requestIRCodeListBySetTopBox(mSetTopBox,new AsyncRESTClient.OnResponseListener() { @Override public void onResponse(Object response) { List<Key> keys = ((ListResult<Key>)response).list; mLocalDBManager.updateKeysToLocalDB(keys); Log.d(TAG,"Updated keys to local db."); } }, new AsyncRESTClient.OnErrorListener() { @Override public void onError(RESTException e) { Log.d(TAG,"request keys error!",e); } }); } /** * Comparing baidu location with list,if they same, use that location as the default value. * @param list */ public void setDefaultLocation(List<Location> list){ if (mRequestContent == ContentType.PROVINCE){ if (mBaiduProvince != null && list != null){ for (Location location : list){ if (location.equals(mBaiduProvince)){ mDefaultProvince = location; requestData(ContentType.CITY); Log.d(TAG,"Set default province :" + mDefaultProvince.getName()); } } } } if (mRequestContent == ContentType.CITY){ if (mBaiduCity != null){ for (Location location : list){ if (location.equals(mBaiduCity)){ mDefaultCity = location; Log.d(TAG,"Set default city : " + mDefaultCity.getName()); } } } } } public void formatSTB(List<SetTopBox> setTopBoxes){ Log.d(TAG,"Format STB data."); // List<Map<String,List<SetTopBox>>> stbDate = new ArrayList<Map<String, List<SetTopBox>>>(); mSTBMap = new HashMap<String,List<SetTopBox>>() ; for (int i = 0 ; i < setTopBoxes.size() ; i ++ ){ SetTopBox stb = setTopBoxes.get(i); String brand = stb.getBrand(); if (mSTBMap.get(brand) == null){ List<SetTopBox> modelList = new ArrayList<SetTopBox>(); modelList.add(stb); mSTBMap.put(brand, modelList); }else { List<SetTopBox> modelList = mSTBMap.get(brand); modelList.add(stb); } } Set<String> set = mSTBMap.keySet(); List<UrcObject> brandList = new ArrayList<UrcObject>(); for(String s : set) { UrcObject brand = new UrcObject(); brand.setName(s); brandList.add(brand); } mDataListener.onQuerySucceed(brandList); } @Override public void onError(RESTException e) { if (requestTimes < MAX_REQUEST_TIMES){ requestData(mRequestContent); Log.d(TAG,"Sll request error times = " + requestTimes,e) ; }else { Log.d(TAG,"Give up request"); } } public void requestData(ContentType type){ Log.d(TAG,"spinner request data with " + type.name()); if (mRequestContent == type){ requestTimes += 1; }else { requestTimes = 0; } mRequestContent = type; switch (type){ case BAIDU_LOCATION: getLocationByCityCode(131); case PROVINCE: if(mAllProvince != null && mAllProvince.size() == 31){ Log.d(TAG,"return mAllProvince" + mAllProvince.size()); mDataListener.onQuerySucceed(mAllProvince); break; } queryAllProvince(); break; case CITY: queryCityByProvince(mProvince); break; case OPERATOR: queryOperatorByCity(mCity); break; case STB_BRAND: querySTBByOperator(); break; case STB_MODEL: querySTBByBrand(); } } /** * All response in sll service show here. * @param response */ @Override public void onResponse(Object response) { if (response == null){ if (requestTimes <= MAX_REQUEST_TIMES){ onError(new RESTException(-444)); Log.d(TAG, "Response is null"); return; }else { requestTimes = 0 ; return; } } Log.d(TAG,"Content Type : " + mRequestContent.name()); switch (mRequestContent){ case BAIDU_LOCATION: List<Location> result = ((ListResult<Location>)response).list; if (result != null && result.size() > 0){ if (result.size() >= 1){ // Means there is maybe only have province in result. No city. mBaiduProvince = result.get(0); } if (result.size() >= 2){ mBaiduCity = result.get(1); } Log.d(TAG,"Province:" + (mBaiduProvince != null ? mBaiduProvince.getName() : "Empty") + "City:" + (mBaiduCity != null ? mBaiduCity.getName() : "Empty")); requestData(ContentType.PROVINCE); if (mBaiduCity == null && mBaiduProvince == null){ requestData(ContentType.PROVINCE); } } break; case PROVINCE: mAllProvince = ((ListResult<Location>)response).list; for (Location location : mAllProvince){ Log.d(TAG,"Requested Province List " + location.getName()); } mAllProvince.remove(mAllProvince.size()-1); mAllProvince.remove(mAllProvince.size()-1); mAllProvince.remove(mAllProvince.size()-1); if (mDefaultProvince == null) { setDefaultLocation(mAllProvince); } mDataListener.onQuerySucceed(mAllProvince); break; case CITY: List<Location> cityResult = ((ListResult<Location>)response).list; if (mDefaultCity == null){ setDefaultLocation(cityResult); } mDataListener.onQuerySucceed(cityResult); break; case OPERATOR: List<Operator> operators = ((ListResult<Operator>)response).list; mDataListener.onQuerySucceed(operators); break; case STB_BRAND: Log.d(TAG,"Response : STB brand."); List<SetTopBox> setTopBoxes = ((ListResult<SetTopBox>)response).list; Log.d(TAG,"List result + " + setTopBoxes.toString()); formatSTB(setTopBoxes); break; case STB_MODEL: break; default:break; } } public enum ContentType { BAIDU_LOCATION, PROVINCE, CITY, DISTRACT, OPERATOR, STB_BRAND, STB_MODEL; } }
true
55c58ba234d71b4d2280e797b6ffd668b841c4f0
Java
JavaTool/DataPlatform
/src/dataplatform/cache/lazy/hash/DayRefreshLazyHash.java
UTF-8
489
2.234375
2
[]
no_license
package dataplatform.cache.lazy.hash; import static dataplatform.util.DateUtil.getMilliSecondStartOfDayRefresh; import dataplatform.cache.manager.ICachePlatform; public class DayRefreshLazyHash<F, V> extends ExpireLazyHash<F, V> { public DayRefreshLazyHash(ICachePlatform cachePlatform, Class<F> fclz, Class<V> vclz, String preKey) { super(cachePlatform, fclz, vclz, preKey); } @Override protected long getExpireTime(V value) { return getMilliSecondStartOfDayRefresh(); } }
true
9b0fb087a19e2fe43239338d4c6e1d0d4346a5aa
Java
Prashant203/dr_auto
/app/src/main/java/com/example/dr_auto/Login/Register_1.java
UTF-8
3,918
1.976563
2
[]
no_license
package com.example.dr_auto.Login; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.databinding.DataBindingUtil; import com.example.dr_auto.R; import com.example.dr_auto.databinding.ActivityRegister1Binding; import com.google.firebase.FirebaseException; import com.google.firebase.auth.PhoneAuthCredential; import com.google.firebase.auth.PhoneAuthProvider; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.concurrent.TimeUnit; public class Register_1 extends AppCompatActivity { ActivityRegister1Binding binding; FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance(); DatabaseReference databaseReference; private static final int TIME_DELAY = 2000; private static long back_pressed; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_register_1); String uid = getIntent().getStringExtra("uid"); System.out.println("---------------" + uid); databaseReference = firebaseDatabase.getReference("Users"); System.out.println(); databaseReference.child(uid).addValueEventListener(new ValueEventListener() { @SuppressLint("SetTextI18n") @Override public void onDataChange(@NonNull DataSnapshot snapshot) { String phone = snapshot.child("phone").getValue(String.class); binding.phoneNumber.setText(phone.substring(4)); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); binding.buttonVerifyPhone.setOnClickListener(v -> loginUser()); binding.CreateNew.setOnClickListener(v -> startActivity(new Intent(Register_1.this, Login.class))); } private void loginUser() { PhoneAuthProvider.getInstance().verifyPhoneNumber("+91" + binding.phoneNumber.getText().toString(), 30L, TimeUnit.SECONDS, Register_1.this, new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) { } @Override public void onCodeSent(@NonNull String VerificationId, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) { // Intent intent = new Intent(getApplicationContext(), OTP2.class); intent.putExtra("Mobile", binding.phoneNumber.getText().toString()); intent.putExtra("VerificationId", VerificationId); startActivity(intent); } @Override public void onVerificationFailed(@NonNull FirebaseException e) { binding.buttonVerifyPhone.setVisibility(View.VISIBLE); Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } @Override public void onBackPressed() { if (back_pressed + TIME_DELAY > System.currentTimeMillis()) { super.onBackPressed(); } else { Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show(); } back_pressed = System.currentTimeMillis(); } }
true
007f8d29683841de5811c34b950d9e1e5983e60f
Java
ontop/ontop
/engine/reformulation/core/src/main/java/it/unibz/inf/ontop/answering/reformulation/rewriting/impl/DummyRewriter.java
UTF-8
7,545
1.796875
2
[ "CC-BY-4.0", "Apache-2.0" ]
permissive
package it.unibz.inf.ontop.answering.reformulation.rewriting.impl; /* * #%L * ontop-reformulation-core * %% * Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano * %% * 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. * #L% */ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.inject.Inject; import com.google.inject.Provider; import it.unibz.inf.ontop.answering.reformulation.rewriting.QueryRewriter; import it.unibz.inf.ontop.constraints.impl.FullLinearInclusionDependenciesImpl; import it.unibz.inf.ontop.injection.IntermediateQueryFactory; import it.unibz.inf.ontop.iq.IQ; import it.unibz.inf.ontop.iq.IQTree; import it.unibz.inf.ontop.iq.exception.EmptyQueryException; import it.unibz.inf.ontop.iq.node.IntensionalDataNode; import it.unibz.inf.ontop.model.atom.AtomFactory; import it.unibz.inf.ontop.model.atom.AtomPredicate; import it.unibz.inf.ontop.model.atom.DataAtom; import it.unibz.inf.ontop.model.atom.RDFAtomPredicate; import it.unibz.inf.ontop.model.term.TermFactory; import it.unibz.inf.ontop.model.term.Variable; import it.unibz.inf.ontop.model.term.VariableOrGroundTerm; import it.unibz.inf.ontop.spec.ontology.*; import it.unibz.inf.ontop.utils.CoreUtilsFactory; import it.unibz.inf.ontop.utils.ImmutableCollectors; import java.util.*; import java.util.function.Function; /*** * A query rewriter that used Sigma ABox dependencies to optimise BGPs. * */ public class DummyRewriter implements QueryRewriter { private FullLinearInclusionDependenciesImpl<RDFAtomPredicate> sigma; protected final IntermediateQueryFactory iqFactory; protected final AtomFactory atomFactory; protected final TermFactory termFactory; protected final CoreUtilsFactory coreUtilsFactory; @Inject protected DummyRewriter(IntermediateQueryFactory iqFactory, AtomFactory atomFactory, TermFactory termFactory, CoreUtilsFactory coreUtilsFactory) { this.iqFactory = iqFactory; this.atomFactory = atomFactory; this.termFactory = termFactory; this.coreUtilsFactory = coreUtilsFactory; } @Override public void setTBox(ClassifiedTBox reasoner) { FullLinearInclusionDependenciesImpl.Builder<RDFAtomPredicate> builder = FullLinearInclusionDependenciesImpl.builder(coreUtilsFactory, atomFactory); Variable x = termFactory.getVariable("x"); Variable y = termFactory.getVariable("y"); traverseDAG(reasoner.objectPropertiesDAG(), p -> !p.isInverse(), ope -> getAtom(x, ope, y), builder); traverseDAG(reasoner.dataPropertiesDAG(), p -> true, dpe -> getAtom(x, dpe, y), builder); // the head will have no existential variables traverseDAG(reasoner.classesDAG(), c -> (c instanceof OClass), c -> getAtom(c, x, () -> y), builder); sigma = builder.build(); } protected FullLinearInclusionDependenciesImpl<RDFAtomPredicate> getSigma() { return sigma; } /* optimise with Sigma ABox dependencies */ @Override public IQ rewrite(IQ query) throws EmptyQueryException { return iqFactory.createIQ(query.getProjectionAtom(), query.getTree().acceptTransformer(new BasicGraphPatternTransformer(iqFactory) { @Override protected ImmutableList<IQTree> transformBGP(ImmutableList<IntensionalDataNode> bgp) { return removeRedundantAtoms(bgp); } })); } private ImmutableList<IQTree> removeRedundantAtoms(ImmutableList<IntensionalDataNode> bgp) { ArrayList<IntensionalDataNode> list = new ArrayList<>(bgp); // mutable copy // this loop has to remain sequential (no streams) for (int i = 0; i < list.size(); i++) { DataAtom<RDFAtomPredicate> atom = (DataAtom)list.get(i).getProjectionAtom(); ImmutableSet<DataAtom<RDFAtomPredicate>> derived = sigma.chaseAtom(atom); for (int j = 0; j < list.size(); j++) { DataAtom<AtomPredicate> curr = list.get(j).getProjectionAtom(); if (j != i && derived.contains(curr)) { ImmutableSet<Variable> variables = list.stream() .map(IntensionalDataNode::getProjectionAtom) .filter(a -> (a != curr)) .flatMap(a -> a.getVariables().stream()) .collect(ImmutableCollectors.toSet()); // atom to be removed cannot contain a variable occurring nowhere else if (variables.containsAll(curr.getVariables())) { list.remove(j); j--; if (j < i) // removing in front of the atom i--; // shift the atom position too } } } } return ImmutableList.copyOf(list); } private static <T> void traverseDAG(EquivalencesDAG<T> dag, java.util.function.Predicate<T> filter, Function<T, DataAtom<RDFAtomPredicate>> translate, FullLinearInclusionDependenciesImpl.Builder<RDFAtomPredicate> builder) { for (Equivalences<T> node : dag) for (Equivalences<T> subNode : dag.getSub(node)) for (T sub : subNode) for (T e : node) if (e != sub && filter.test(e)) { DataAtom<RDFAtomPredicate> head = translate.apply(e); DataAtom<RDFAtomPredicate> body = translate.apply(sub); builder.add(head, body); } } protected DataAtom<RDFAtomPredicate> getAtom(ClassExpression ce, VariableOrGroundTerm x, Provider<VariableOrGroundTerm> y) { if (ce instanceof OClass) { return getAtom(x, (OClass) ce); } else if (ce instanceof ObjectSomeValuesFrom) { return getAtom(x, ((ObjectSomeValuesFrom) ce).getProperty(), y.get()); } else { return getAtom(x, ((DataSomeValuesFrom) ce).getProperty(), y.get()); } } protected <T extends AtomPredicate> DataAtom<T> getAtom(VariableOrGroundTerm t1, ObjectPropertyExpression property, VariableOrGroundTerm t2) { return property.isInverse() ? (DataAtom)atomFactory.getIntensionalTripleAtom(t2, property.getIRI(), t1) : (DataAtom)atomFactory.getIntensionalTripleAtom(t1, property.getIRI(), t2); } protected <T extends AtomPredicate> DataAtom<T> getAtom(VariableOrGroundTerm t1, DataPropertyExpression property, VariableOrGroundTerm t2) { return (DataAtom)atomFactory.getIntensionalTripleAtom(t1, property.getIRI(), t2); } protected <T extends AtomPredicate> DataAtom<T> getAtom(VariableOrGroundTerm t, OClass oc) { return (DataAtom)atomFactory.getIntensionalTripleAtom(t, oc.getIRI()); } }
true
6d1ca6000c6684b4d9ffefba7319658bdc003895
Java
Jioji1321/bankWeb
/src/java/cn/com/ultrawise/bank/bnk/dao/hibernate/BnkBankDaoHibernate.java
UTF-8
1,288
2.375
2
[]
no_license
package cn.com.ultrawise.bank.bnk.dao.hibernate; import java.util.ArrayList; import java.util.List; import cn.com.ultrawise.bank.bnk.dao.BnkBankDao; import cn.com.ultrawise.bank.bnk.model.BnkBank; import cn.com.ultrawise.bank.dao.hibernate.BaseDaoHibernate; /** * @author zhouxing email:admin@zhouxing.org * */ public class BnkBankDaoHibernate extends BaseDaoHibernate implements BnkBankDao { public List<BnkBank> listBnkBank() { // TODO Auto-generated method stub return getHibernateTemplate().loadAll(BnkBank.class); } public void addBnkBank(BnkBank bnkBank) { // TODO Auto-generated method stub getHibernateTemplate().saveOrUpdate(bnkBank); } public BnkBank queryBnkBank(String bnkId, String bnkCode) { // TODO Auto-generated method stub String hql = "from cn.com.ultrawise.bank.bnk.model.BnkBank bnk"; String whereClause = ""; List<String> whereParam = new ArrayList<String>(); if(!"".equals(bnkId)){ whereClause += " where bnk.bnkBankId=?"; whereParam.add(bnkId); } if(!"".equals(bnkCode)){ whereClause += whereClause.length()>0? " and bnk.bnkCode=?":" where bnk.bnkCode=?"; whereParam.add(bnkCode); } hql += whereClause; BnkBank bnkBank = (BnkBank)getHibernateTemplate() .find(hql, whereParam).get(0); return bnkBank; } }
true
288d0569b1da0acba8f37f1845ba197fdf4fdcf9
Java
qinxiangyangnet/design
/src/main/java/com/yangyue/design/template/example2/NomalLogin.java
UTF-8
813
2.625
3
[]
no_license
package com.yangyue.design.template.example2; /** * @program: design * @description: * @author: yueyang * @create: 2020-02-29 10:15 **/ public class NomalLogin { public boolean login(LoginModel loginModel) { UserModel userModel = this.findUserByUserId(loginModel.getUserId()); if(userModel!=null){ if(userModel.getPwd().equals(loginModel.getPwd())&&loginModel.getUserId().equals(userModel.getUserId())){ return true; } } return false; } private UserModel findUserByUserId(String userId) { UserModel userModel = new UserModel(); userModel.setUserId(userId); userModel.setName("test"); userModel.setPwd("test"); userModel.setUuid("User001"); return userModel; } }
true
9c3fa8b1368de8c63d01a3f9e4aec660266c49b2
Java
sub-rat/AndroidTrainingAll
/src/com/gdg/androidtraining/database/DatabaseActivity.java
UTF-8
4,870
2.484375
2
[]
no_license
package com.gdg.androidtraining.database; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import com.gdg.androidtraining.R; import com.gdg.androidtraining.Student; public class DatabaseActivity extends Activity { DataBaseHandler dh; BaseAdapter adapter; List<Student> studentList; boolean showPhone; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_database); dh = new DataBaseHandler(getApplicationContext()); studentList = dh.getAllStudents(); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); showPhone = sharedPreferences.getBoolean("CheckBox_Value", false); adapter = new ArrayAdapter<Student>(this, android.R.layout.simple_list_item_1, studentList){ @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null){ convertView = getLayoutInflater().inflate(R.layout.row_student, null); } Student s = studentList.get(position); TextView name = (TextView) convertView.findViewById(R.id.txt_name); name.setText(s.getName()); TextView address = (TextView) convertView.findViewById(R.id.txt_address); address.setText(s.getAddress()); if(showPhone){ TextView phone = (TextView) convertView.findViewById(R.id.txt_phone); phone.setVisibility(View.VISIBLE); phone.setText(s.getPhone()); } return convertView; } }; ListView list = (ListView) findViewById(R.id.list); list.setAdapter(adapter); list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { showDetails(studentList.get(position)); } }); list.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) { showOptions(studentList.get(position)); return true; } }); } protected void showOptions(final Student student) { final String options[] = new String[]{"Delete"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(student.getName()) .setItems(options, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { toast(options[which] + " clicked"); Student stud = studentList.remove(which); dh.deleteStudent(stud); adapter.notifyDataSetChanged(); } }) .setPositiveButton("Dismiss", null) .create().show(); } protected void toast(String string) { Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT).show(); } protected void showDetails(Student student) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(student.getName()) .setMessage("Address : " + student.getAddress() + "\nPhone : " + student.getPhone()) .setPositiveButton("Dismiss", null) .create().show(); } public void addUser(View view) { AlertDialog.Builder builder = new AlertDialog.Builder(this); final View custom = getLayoutInflater().inflate(R.layout.dialog_add_user, null); builder.setView(custom) .setPositiveButton("Save", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { EditText name = (EditText) custom.findViewById(R.id.txt_name); EditText phone = (EditText) custom.findViewById(R.id.txt_phone); EditText address = (EditText) custom.findViewById(R.id.txt_address); Student st = new Student(0, name.getText().toString(), null, phone.getText().toString(), address.getText().toString()); if(st.getName().length() > 0){ Student stud = dh.addStudent(st); studentList.add(stud); adapter.notifyDataSetChanged(); toast("Saved data"); } else{ toast("Name empty"); } } }) .setNegativeButton("Cancel", null) .create().show(); } public void deleteFirstUser(View view) { if (studentList.size() > 0) { Student st = studentList.remove(0); dh.deleteStudent(st); adapter.notifyDataSetChanged(); toast("First data deleted"); } } }
true
aca2c452d3e130ec6cec39f6d78c21953576d6ee
Java
P79N6A/icse_20_user_study
/methods/Method_1001646.java
UTF-8
550
2.828125
3
[]
no_license
private Line2D.Double change(Line2D.Double line,Point2D p1,Point2D p2){ if (line.getP1().equals(p1) == false && line.getP2().equals(p2) == false) { return line; } final double dx=line.x2 - line.x1; final double dy=line.y2 - line.y1; if (line.getP1().equals(p1)) { p1=new Point2D.Double(line.x1 + dx / 10,line.y1 + dy / 10); } else { p1=line.getP1(); } if (line.getP2().equals(p2)) { p2=new Point2D.Double(line.x2 - dx / 10,line.y2 - dy / 10); } else { p2=line.getP2(); } return new Line2D.Double(p1,p2); }
true
be7fd46426e1dfc695209fb365202ad3b14d050e
Java
naveenanimation20/DecSessionSeleniumCode
/src/main/java/WebDriverSessions/TitleSync.java
UTF-8
1,213
2.265625
2
[]
no_license
package WebDriverSessions; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class TitleSync { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "/Users/NaveenKhunteta/Downloads/chromedriver"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS); //driver.manage().timeouts().implicitlyWait(200, TimeUnit.SECONDS); driver.get("https://app.hubspot.com/login"); System.out.println("before login, page title is: "+ driver.getTitle()); driver.findElement(By.id("username")).sendKeys("naveenanimation20@gmail.com"); driver.findElement(By.id("password")).sendKeys("Test@1234"); driver.findElement(By.id("loginBtn")).click(); //Thread.sleep(10000); WebDriverWait wait = new WebDriverWait(driver,20); wait.until(ExpectedConditions.titleContains("Reports dashboard")); System.out.println("after login, page title is: "+ driver.getTitle()); } }
true
07ed82b35994c3e7fd890627c08b51a86150f0b2
Java
williamtanws/beanframework
/bin/modules/backoffice/src/main/java/com/beanframework/backoffice/config/BackofficeConfig.java
UTF-8
887
2.015625
2
[ "MIT" ]
permissive
package com.beanframework.backoffice.config; import javax.servlet.ServletContext; import javax.servlet.ServletRegistration; import org.springframework.context.annotation.Configuration; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.XmlWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; @Configuration public class BackofficeConfig implements WebApplicationInitializer { @Override public void onStartup(ServletContext container) { XmlWebApplicationContext context = new XmlWebApplicationContext(); context.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml"); ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(context)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); } }
true
3aa8070ca367e2c480603d955d7d9b52ceb4e471
Java
bibikar/hacktx16
/src/hacktx16/PlayState.java
UTF-8
1,939
2.71875
3
[]
no_license
package hacktx16; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import hacktx16.entity.Player; import hacktx16.map.Camera; import hacktx16.map.Map; import hacktx16.map.Platform; import hacktx16.map.PlatformLoader; public class PlayState extends GameState { Dimension dimension; Player player; Camera camera; Map map; public PlayState(GameStateManager gameStateManager, Dimension dimension) { // TODO Auto-generated constructor stub super(gameStateManager); this.dimension = dimension; } @Override public void init() { camera = new Camera(0, 0, dimension.getWidth(), dimension.getHeight()); map = new Map(dimension.getWidth() * 3, dimension.getHeight()); map.getPlatforms().addAll(PlatformLoader.loadTestPlatforms()); player = new Player(map, 1, "Player", 100, 10, 50, 50, 0, 0); map.setCamera(camera); camera.setMap(map); } @Override public void update() { // TODO Auto-generated method stub handleInput(); map.tickAll(); player.tick(); camera.moveToPlayer(player.getxPos(), player.getyPos()); System.out.printf("Camera (%f, %f)\n", camera.getLocation()[0], camera.getLocation()[1]); } @Override public void draw(Graphics2D g) { // TODO Auto-generated method stub g.setColor(Color.WHITE); g.fillRect(0, 0, (int)dimension.getWidth(), (int)dimension.getHeight()); g.setColor(Color.BLACK); map.draw(g); player.draw(g, camera); } @Override public void handleInput() { // TODO Auto-generated method stub if(Keys.isPressed(Keys.ESCAPE)) { gsm.setPaused(true); } if (!Keys.isDown(Keys.A)) { player.setxVel(0); } if (!Keys.isDown(Keys.D)) { player.setxVel(0); } if (Keys.isDown(Keys.A)) { player.setxVel(-2); System.out.println("test"); } if (Keys.isDown(Keys.D)) { player.setxVel(2); System.out.println("test2"); } } }
true
28099103b94de1d5f07eea2c33373729c92230a2
Java
stephen-gao/reimuBlog
/src/main/java/com/reimu/service/impl/CategoryServiceImpl.java
UTF-8
909
1.953125
2
[]
no_license
package com.reimu.service.impl; import com.reimu.entity.Category; import com.reimu.dao.CategoryMapper; import com.reimu.service.ICategoryService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.reimu.utils.ShortIdUtil; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; /** * <p> * 服务实现类 * </p> * * @author gaosheng * @since 2019-10-28 */ @Service public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService { @Value("${default.url}") private String defaultUrl; @Value("${default.category}") private String categoryUrl; @Override public void add(Category category) { category.setId(ShortIdUtil.getUUID_8()); category.setUrl(defaultUrl+categoryUrl+category.getId()); baseMapper.insert(category); } }
true
4be6261c214943189c786b20ff783a58734a346c
Java
cloudwebsoft/ywoa
/c-common/src/main/java/com/cloudwebsoft/framework/security/ProtectFormConfig.java
UTF-8
4,402
2.3125
2
[]
no_license
package com.cloudwebsoft.framework.security; import cn.js.fan.cache.jcs.RMCache; import cn.js.fan.util.StrUtil; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.jdom.Document; import org.jdom.Element; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLDecoder; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Vector; /** * */ public class ProtectFormConfig { RMCache rmCache; private final String group = "CONFIG_PRORECT_FORM"; private final String ALLUNIT = "ALLUNIT"; private static Logger logger; private final String FILENAME = "config_protect_form.xml"; private static Document doc = null; private static Element root = null; private static String xmlPath; private static boolean isInited = false; private static URL confURL; public ProtectFormConfig() { rmCache = RMCache.getInstance(); logger = Logger.getLogger(this.getClass().getName()); confURL = getClass().getResource("/" + FILENAME); } public static void init() { if (!isInited) { // xmlPath = confURL.getPath(); // 如果有空格,会转换为%20 xmlPath = confURL.getFile(); try { xmlPath = URLDecoder.decode(xmlPath, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } SAXBuilder sb = new SAXBuilder(); try { FileInputStream fin = new FileInputStream(xmlPath); doc = sb.build(fin); root = doc.getRootElement(); fin.close(); isInited = true; } catch (org.jdom.JDOMException e) { logger.error(e.getMessage()); } catch (java.io.IOException e) { logger.error(e.getMessage()); } } } public Element getRootElement() { return root; } public void reload() { isInited = false; try { rmCache.invalidateGroup(group); } catch (Exception e) { logger.error(e.getMessage()); } } /** * 取得所有的规则 * @return */ public Vector<ProtectFormUnit> getAllUnit() { Vector<ProtectFormUnit> v = null; try { v = (Vector<ProtectFormUnit>) rmCache.getFromGroup(ALLUNIT, group); } catch (Exception e) { logger.error(e.getMessage()); } if (v==null) { v = new Vector<ProtectFormUnit>(); init(); List list = root.getChildren(); if (list != null) { Iterator ir = list.iterator(); while (ir.hasNext()) { Element child = (Element) ir.next(); int type = StrUtil.toInt(child.getAttributeValue("type"), ProtectUnit.TYPE_INCLUDE); String formCode = child.getChildText("formCode"); String fields = child.getChildText("fields"); List<String> fieldsAry = Arrays.asList(StringUtils.split(fields, ",")); ProtectFormUnit protectFormUnit = new ProtectFormUnit(); protectFormUnit.setFormCode(formCode); protectFormUnit.setFields(fieldsAry); protectFormUnit.setType(type); v.addElement(protectFormUnit); } try { rmCache.putInGroup(ALLUNIT, group, v); } catch (Exception e) { logger.error("getAllDeskTopUnit:" + e.getMessage()); } } } return v; } public void writemodify() { String indent = " "; Format format = Format.getPrettyFormat(); format.setIndent(indent); format.setEncoding("utf-8"); XMLOutputter outp = new XMLOutputter(format); try { FileOutputStream fout = new FileOutputStream(xmlPath); outp.output(doc, fout); fout.close(); } catch (java.io.IOException e) {} } }
true
394c7e25cde9c98179fdb3e8a1074e32e9c67a17
Java
kmilo9999/CS1971
/src/fxengine/PathFinding/NodeComparator.java
UTF-8
223
2
2
[]
no_license
package fxengine.PathFinding; import java.util.Comparator; public class NodeComparator implements Comparable<Node>{ @Override public int compareTo(Node o) { // TODO Auto-generated method stub return 0; } }
true
5856b19a5757056a9037566b40ae8891b7fd033d
Java
l1ghtsword/developer-exercise
/src/main/java/ca/braelor/l1ghtsword/assignment/events/PlayerCookingEvent.java
UTF-8
689
2.65625
3
[]
no_license
package ca.braelor.l1ghtsword.assignment.events; import ca.braelor.l1ghtsword.assignment.model.enums.Item; import net.gameslabs.api.Player; import net.gameslabs.api.PlayerEvent; /** * Event used to request an item be cooked by player. * This event will not inform player success of failure, that is * managed by CookingComponent listeners, which will also cancel this event * * Only provides player and item, one way response to listener */ public class PlayerCookingEvent extends PlayerEvent { private final Item i; public PlayerCookingEvent(Player player, Item item) { super(player); this.i = item; } public Item getItem() { return this.i; } }
true
beeb4393107009561082d1a52fccfdb99dd6924b
Java
katayohe/fhir-java-lambda
/src/main/java/example/pojo/patient/Meta.java
UTF-8
863
2.125
2
[]
no_license
package example.pojo.patient; import java.util.List; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Meta { @SerializedName("versionId") @Expose private String versionId; @SerializedName("tag") @Expose private List<Tag> tag = null; @SerializedName("lastUpdated") @Expose private String lastUpdated; public String getVersionId() { return versionId; } public void setVersionId(String versionId) { this.versionId = versionId; } public List<Tag> getTag() { return tag; } public void setTag(List<Tag> tag) { this.tag = tag; } public String getLastUpdated() { return lastUpdated; } public void setLastUpdated(String lastUpdated) { this.lastUpdated = lastUpdated; } }
true
ae11a3f41fe0e4eccf1c1211c8798f6fa3fc57ea
Java
aa215166671/Ywg
/app/src/main/java/com/kyun/android/baisibudejie/pro/essense/view/essence_all/BB_file/adapter/JianZhiHolder.java
UTF-8
797
1.953125
2
[ "Apache-2.0" ]
permissive
package com.kyun.android.baisibudejie.pro.essense.view.essence_all.BB_file.adapter; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.kyun.android.baisibudejie.R; import com.kyun.android.baisibudejie.pro.essense.view.essence_all.BB_file.listener.MyItemClickListener; class JianZhiHolder extends RecyclerView.ViewHolder implements MyItemClickListener { TextView mTextView; ImageView mImg; public JianZhiHolder(View itemView) { super(itemView); mTextView = (TextView) itemView.findViewById( R.id.jianzhi_neirong); mImg = (ImageView)itemView.findViewById(R.id.jianzhi_tupian); } @Override public void onItemClick(View view, int postion) { } }
true