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
c1d06430bb05134e5236023ed01478134224c7bf
Java
USTBlzg10/-offer
/src/main/java/leetcodeTest/JavaVersion/RomanToInt_13.java
UTF-8
1,830
3.4375
3
[]
no_license
package leetcodeTest.JavaVersion; import java.util.HashMap; import java.util.Map; /** * @author LiuZhiguo * @date 2019/11/12 10:39 */ public class RomanToInt_13 { public int romanToInt(String s){ /*方法一 Map<String, Integer> map = new HashMap<String, Integer>(); map.put("I",1); map.put("IV",4); map.put("V",5); map.put("IX",9); map.put("X",10); map.put("XL",40); map.put("L",50); map.put("XC",90); map.put("C",100); map.put("CD",400); map.put("D",500); map.put("CM",900); map.put("M",1000); int res = 0; for (int i=0;i<s.length();){ if (i+1 <s.length() && map.containsKey(s.substring(i,i+2))){ res += map.get(s.substring(i,i+2)); i += 2; }else { res += map.get(s.substring(i,i+1)); i += 1; } } return res;*/ int res =0; int preNum = getValue(s.charAt(0)); for (int i=1;i<s.length();i++) { int num = getValue(s.charAt(i)); if (preNum < num) res -=preNum; else res += preNum; preNum = num; } res += preNum; return res; } private int getValue(char ch) { switch(ch) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; default: return 0; } } public static void main(String[] args){ RomanToInt_13 romanToInt_13 = new RomanToInt_13(); System.out.println(romanToInt_13.romanToInt("LVIII")); } }
true
d6843764bcfe06e85cf69f3f82e909641fd26378
Java
contactashish94/BasicJava
/src/com/ashish/interview/warmUpChallenge/ex2/Solution.java
UTF-8
1,615
3.234375
3
[]
no_license
package com.ashish.interview.warmUpChallenge.ex2; import java.io.*; import java.util.HashMap; import java.util.Scanner; public class Solution { public static void main(String[] args) throws IOException { //BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); //BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); //int steps = Integer.parseInt(bufferedReader.readLine().trim()); //String path = bufferedReader.readLine(); //int result = Result.countingValleys(steps, path); // bufferedWriter.write(String.valueOf(result)); //bufferedWriter.newLine(); //bufferedReader.close(); //bufferedWriter.close(); Scanner sc = new Scanner(System.in); int tesctCase = Integer.parseInt(sc.nextLine()); int n = tesctCase; String str=null; if (tesctCase > 0){ str = sc.next(); } if(str!=null){ int result = Result.countingValleys(tesctCase, str); } } } class Result{ public static int countingValleys(int n, String path){ HashMap<Character,Integer> map = new HashMap<>(); map.put('U',1); map.put('D',-1); char[] ch = path.toUpperCase().toCharArray(); int level =0; int valleyCount =0; for (char step : ch) { level += map.get(step); if(level==0 && step=='U'){ valleyCount++; } } System.out.println(valleyCount); return valleyCount; } }
true
57c161165161bf99767c2bf792d7dfb71aa48eb5
Java
john821216/job_interview
/src/Leetcode/_198.java
UTF-8
998
3.109375
3
[]
no_license
package Leetcode; public class _198 { public int rob(int[] nums) { int[] dp = new int[nums.length]; int max = 0; for (int i = 0; i < nums.length; i++) { dp[i] = nums[i]; if (dp[i] > max) { max = dp[i]; } } for (int i = 0; i < nums.length; i++) { int maxJval = 0; for (int j = 0; j < i - 1; j++) { if (dp[j] > maxJval) { maxJval = dp[j]; } } dp[i] = maxJval + dp[i]; if (dp[i] > max) { max = dp[i]; } } return max; } public int rob2(int[] num) { int[][] dp = new int[num.length + 1][2]; for (int i = 1; i <= num.length; i++) { dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]); dp[i][1] = num[i - 1] + dp[i - 1][0]; } return Math.max(dp[num.length][0], dp[num.length][1]); } public int rob3(int[] num) { int prevNo = 0; int prevYes = 0; for (int i = 0; i < num.length; i++) { int temp = prevNo; prevNo = Math.max(prevNo, prevYes); prevYes = num[i] + temp; } return Math.max(prevNo, prevYes); } }
true
fdee50100e9fa27d32bbdc853ef4b6cf6b6d2004
Java
dginovker/RS-2009-317
/Client/src/main/java/com/runescape/chat/MessageType.java
UTF-8
3,680
2.78125
3
[]
no_license
package com.runescape.chat; import com.runescape.Game; import com.runescape.GameShell; import com.runescape.util.StringUtility; /** * Represents a type of message to show the player. * * @author <a href="http://Gielinor.org">Gielinor</a> */ public enum MessageType { GAME_MESSAGE(0), CONSOLE(0) { @Override public void sendMessage(Game game, String gameMessage, int filterType) { GameShell.getConsole().printMessage(gameMessage.replaceAll(":console:", ""), 0); } }, TRADE_REQ(4) { @Override public void sendMessage(Game game, String gameMessage, int filterType) { String playerName = gameMessage.substring(0, gameMessage.indexOf(":")); long playerNameLong = StringUtility.encodeBase37(playerName); boolean canSendTrade = false; for (int index = 0; index < game.getIgnoreCount(); index++) { if (game.getIgnores()[index] != playerNameLong) { continue; } canSendTrade = true; } if (!canSendTrade) { game.pushMessage("wishes to trade with you.", getType(), playerName); } } }, DUEL_REQ(8) { @Override public void sendMessage(Game game, String gameMessage, int filterType) { String playerName = gameMessage.substring(0, gameMessage.indexOf(":")); long l18 = StringUtility.encodeBase37(playerName); boolean canSendDuel = false; for (int k27 = 0; k27 < game.getIgnoreCount(); k27++) { if (game.getIgnores()[k27] != l18) { continue; } canSendDuel = true; } if (!canSendDuel) { game.pushMessage("wishes to duel with you.", getType(), playerName); } } }, // CLAN_REQ(17) { // @Override // public void sendMessage(Game game, String gameMessage, int filterType) { // String playerName = gameMessage.substring(0, gameMessage.indexOf(":")); // long l18 = StringUtility.encodeBase37(playerName); // boolean canSendChallenge = false; // for (int k27 = 0; k27 < game.getIgnoreCount(); k27++) { // if (game.getIgnores()[k27] != l18) { // continue; // } // canSendChallenge = true; // // } // if (!canSendChallenge) { // game.pushMessage("wishes to challenge your clan to a Clan War.", getType(), playerName); // } // } // }, ; /** * The type of message to send. */ private final int type; /** * Constructs a new message type. * * @param type The type of message to send. */ MessageType(int type) { this.type = type; } /** * Gets the type of message to send. * * @return The type. */ public int getType() { return type; } /** * The action to preform with the message. * * @param client The client. * @param gameMessage The message. */ public void sendMessage(Game client, String gameMessage, int filterType) { client.pushMessage(gameMessage.replaceAll(":" + getName() + ":", ""), type, -1, filterType); } /** * Gets the name to search for. * * @return The name. */ public String getName() { return name().replaceAll("_", "").toLowerCase(); } }
true
f13b823ff12ea862c3372660e996710f7ebe8c8b
Java
TheWizard91/Album_base_source_from_JADX
/sources/androidx/recyclerview/selection/PointerDragEventInterceptor.java
UTF-8
1,603
2
2
[]
no_license
package androidx.recyclerview.selection; import android.view.MotionEvent; import androidx.core.util.Preconditions; import androidx.recyclerview.widget.RecyclerView; final class PointerDragEventInterceptor implements RecyclerView.OnItemTouchListener { private RecyclerView.OnItemTouchListener mDelegate; private final OnDragInitiatedListener mDragListener; private final ItemDetailsLookup<?> mEventDetailsLookup; PointerDragEventInterceptor(ItemDetailsLookup<?> eventDetailsLookup, OnDragInitiatedListener dragListener, RecyclerView.OnItemTouchListener delegate) { boolean z = true; Preconditions.checkArgument(eventDetailsLookup != null); Preconditions.checkArgument(dragListener == null ? false : z); this.mEventDetailsLookup = eventDetailsLookup; this.mDragListener = dragListener; if (delegate != null) { this.mDelegate = delegate; } else { this.mDelegate = new DummyOnItemTouchListener(); } } public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { if (!MotionEvents.isPointerDragEvent(e) || !this.mEventDetailsLookup.inItemDragRegion(e)) { return this.mDelegate.onInterceptTouchEvent(rv, e); } return this.mDragListener.onDragInitiated(e); } public void onTouchEvent(RecyclerView rv, MotionEvent e) { this.mDelegate.onTouchEvent(rv, e); } public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { this.mDelegate.onRequestDisallowInterceptTouchEvent(disallowIntercept); } }
true
d4dba1de8e660ed11575911f5691d90d55e886b3
Java
kfulton121/uml-editor
/src/App.java
UTF-8
522
2.421875
2
[]
no_license
import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; public class App extends Application { @Override public void start(Stage primaryStage) { primaryStage.setTitle("UML Editor - fiVe"); Controller controller = new Controller(); Scene scene = new Scene(controller.ui, 1200, 800); scene.getStylesheets().add("style.css"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
true
b574b254630103e9e4f937d7ff1e9de115d83fa1
Java
zyinn/Repo
/FRT_Repopledge/src/main/java/com/finruntech/frt/fits/pledge/service/FitsAccPortfolioSecuService.java
UTF-8
1,648
2.1875
2
[]
no_license
package com.finruntech.frt.fits.pledge.service; import com.finruntech.frt.fits.pledge.model.FitsAccPortfolioSecuEntity; import com.finruntech.frt.fits.pledge.repository.FitsAccPortfolioSecuMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; /** * 投资组合查询 * Created by yinan.zhang on 2018/1/2. */ @Service public class FitsAccPortfolioSecuService { @Autowired private FitsAccPortfolioSecuMapper fitsAccPortfolioSecuMapper; /** * 根据账户类型、对应组合资金账户查询投资组合 * @param psAcctClass 账户类型 * @param psCashNum 对应组合资金账户 * @return FitsAccPortfolioSecuEntity */ public FitsAccPortfolioSecuEntity findFirstByPsAcctClassAndPsCashNum(String psAcctClass,String psCashNum){ Map<String,String> map = new HashMap<>(); map.put("psAcctClass",psAcctClass); map.put("psCashNum",psCashNum); return fitsAccPortfolioSecuMapper.findAccPSecuEnityByAcctClassAndCashNum(map); } /** * 根据组合证券账户、对应组合资金账户查询投资组合 * @param psAcctNum 组合证券账户 * @param psCashNum 对应组合资金账户 * @return */ public FitsAccPortfolioSecuEntity findFirstByPsAcctNumAndPsCashNum(String psAcctNum,String psCashNum){ Map<String,String> map = new HashMap<>(); map.put("psAcctNum",psAcctNum); map.put("psCashNum",psCashNum); return fitsAccPortfolioSecuMapper.findAccPSecuEnityByCashNumAndSecuNum(map); } }
true
2320cb6b7a43d3a1de2f6f1413cd52d25979dab9
Java
subramaniansrm/rta
/src/main/java/com/srm/rta/validation/WidgetValidation.java
UTF-8
4,973
2.21875
2
[]
no_license
package com.srm.rta.validation; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.srm.coreframework.config.UserMessages; import com.srm.coreframework.constants.ControlNameConstants; import com.srm.coreframework.util.CommonConstant; import com.srm.rta.vo.WidgetVO; /** * WidgetValidation.java * * This class is a Validation class for the Widget values. * * @author manoj */ @Component public class WidgetValidation { @Autowired private UserMessages userMessagesProperties; /** * This method is used to check whether any of the data is empty or null * * * @param WidgetVo * widgetVo * @return CommonConstants CommonConstants.VALIDATION_SUCCESS */ public String validateCreate(WidgetVO widgetVo) { boolean result; for (String field : widgetVo.getScreenFieldDisplayVoList()) { if (ControlNameConstants.WIDGETS_INDEX.equals(field)) { result = validateIndex(widgetVo.getWidgetIndex()); if (result == false) { return userMessagesProperties.getWidget_validation_widgetIndex(); } } if (ControlNameConstants.WIDGETS_TITLE.equals(field)) { result = validateTitle(widgetVo.getWidgetTitle().trim()); if (result == false) { return userMessagesProperties.getWidget_validation_widgetTitle(); } if (widgetVo.getWidgetTitle().length() > 50) { return userMessagesProperties.getWidget_validation_widgetTitle(); } } if (ControlNameConstants.WIDGETS_STATUS.equals(field)) { result = validateActive(widgetVo.isWidgetIsActive()); if (result == false) { return userMessagesProperties.getWidget_validation_widgetIsActive(); } } } return CommonConstant.VALIDATION_SUCCESS; } /** * This method is used to check whether any of the data is empty or null * * * @param WidgetVo * widgetVo * @return CommonConstants CommonConstants.VALIDATION_SUCCESS */ public String validateUpdate(WidgetVO widgetVo) { boolean result; for (String field : widgetVo.getScreenFieldDisplayVoList()) { if (ControlNameConstants.WIDGETS_CODE.equals(field)) { result = validateCode(widgetVo.getWidgetCode()); if (result == false) { return userMessagesProperties.getWidget_validation_widgetCode(); } if (widgetVo.getWidgetCode().length() > 10) { return userMessagesProperties.getWidget_validation_widgetCode(); } } if (ControlNameConstants.WIDGETS_INDEX.equals(field)) { result = validateIndex(widgetVo.getWidgetIndex()); if (result == false) { return userMessagesProperties.getWidget_validation_widgetIndex(); } } if (ControlNameConstants.WIDGETS_TITLE.equals(field)) { result = validateTitle(widgetVo.getWidgetTitle().trim()); if (result == false) { return userMessagesProperties.getWidget_validation_widgetTitle(); } if (widgetVo.getWidgetTitle().length() > 50) { return userMessagesProperties.getWidget_validation_widgetTitle(); } } } result = validateId(widgetVo.getWidgetId()); if (result == false) { return userMessagesProperties.getWidget_validation_widgetId(); } return CommonConstant.VALIDATION_SUCCESS; } /** * This method is used to check whether the list of widgetId are present or * not. * * @param WidgetVo * widgetVo * @return CommonConstants CommonConstants.VALIDATION_SUCCESS */ public String validateDelete(WidgetVO widgetVo) { List<Integer> widgetIdList = widgetVo.getWidgetsIdList(); if ((widgetIdList == null) || (widgetIdList.size() == 0)) { return userMessagesProperties.getWidget_validation_deleteIdList(); } return CommonConstant.VALIDATION_SUCCESS; } /** * This method is used to check whether the widgetId is present or not. * * @param WidgetVo * widgetVo * @return CommonConstants CommonConstants.VALIDATION_SUCCESS */ public String validateLoad(WidgetVO widgetVo) { boolean result = validateId(widgetVo.getWidgetId()); if (result == false) { return userMessagesProperties.getWidget_validation_widgetId(); } return CommonConstant.VALIDATION_SUCCESS; } private boolean validateId(Integer id) { if (id == 0) { return false; } return true; } public static boolean validateCode(String input) { String field = input; String pattern = "^.*(?=.*[/|`~!(){}_,\"'*?:;<>,@#$%^&+=-]).*$"; if (input == null || input.isEmpty()) { return false; } else if (field.matches(pattern)) { return false; } else { return true; } } private boolean validateIndex(int index) { if (index == 0) { return false; } return true; } public static boolean validateTitle(String input) { if (input == null || input.isEmpty()) { return false; } else { return true; } } private boolean validateActive(boolean flashNewsIsActive) { if (true == flashNewsIsActive) { return true; } return false; } }
true
d0920b50ab30c7f35a085b9b691e0398d1d9cc50
Java
j7arsen/mvpretrofitdagger
/app/src/main/java/j7arsen/com/dagger/main/newtest/view/NewTestActivity.java
UTF-8
2,285
2.09375
2
[]
no_license
package j7arsen.com.dagger.main.newtest.view; import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import javax.inject.Inject; import j7arsen.com.dagger.R; import j7arsen.com.dagger.app.TestApplication; import j7arsen.com.dagger.base.BaseContainerActivity; import j7arsen.com.dagger.base.BaseFragment; import j7arsen.com.dagger.di.component.AppComponent; import j7arsen.com.dagger.main.newtest.DaggerNewTestComponent; import j7arsen.com.dagger.main.newtest.INewTestContract; import j7arsen.com.dagger.main.newtest.module.NewTestModule; /** * Created by arsen on 15.12.16. */ public class NewTestActivity extends BaseContainerActivity { @Inject INewTestContract.Presenter mPresenter; private NewTestFragment mTestFragment; public static void startActivity(Activity activity) { Intent intent = new Intent(activity, NewTestActivity.class); activity.startActivity(intent); } public static void startActivity(Fragment fragment, Activity activity) { Intent intent = new Intent(activity, NewTestActivity.class); fragment.startActivity(intent); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mTestFragment = getFragment(); setupComponent(); if(savedInstanceState == null) { openFragment(); } } @Override public void setupComponent() { DaggerNewTestComponent.builder().appComponent((AppComponent) TestApplication.get(TestApplication.mInstance).component()).newTestModule(new NewTestModule(mTestFragment)).build().inject(this); } @Override protected void openFragment() { getFragmentManager().beginTransaction().replace(R.id.container, mTestFragment).commit(); } private NewTestFragment getFragment() { BaseFragment baseFragment = getCurrentFragment(); if(baseFragment != null){ return (NewTestFragment) baseFragment; }else{ return NewTestFragment.newInstance(); } } @Override protected void onDestroy() { super.onDestroy(); mPresenter.onDestroy(); } }
true
6d6a9b845a6347230201de8e3970d9e02eafcba4
Java
xingganfengxing/java-platform
/module/module-security/src/main/java/com/whenling/module/security/shiro/RetryLimitMd5CredentialsMatcher.java
UTF-8
2,023
2.4375
2
[ "Apache-2.0" ]
permissive
package com.whenling.module.security.shiro; import java.util.concurrent.atomic.AtomicInteger; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.ExcessiveAttemptsException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.cache.Cache; import org.apache.shiro.cache.CacheManager; import org.apache.shiro.crypto.hash.Hash; import org.apache.shiro.crypto.hash.Md5Hash; /** * hash认证匹配 * * @作者 孔祥溪 * @博客 http://ken.whenling.com * @创建时间 2016年3月1日 下午7:08:02 */ public class RetryLimitMd5CredentialsMatcher extends HashedCredentialsMatcher { private Integer maxRetryCount; private Cache<String, AtomicInteger> passwordRetryCache; public RetryLimitMd5CredentialsMatcher(CacheManager cacheManager, Integer maxRetryCount) { passwordRetryCache = cacheManager.getCache("password_retry"); this.maxRetryCount = maxRetryCount; setHashAlgorithmName(Md5Hash.ALGORITHM_NAME); } @Override public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { if (token instanceof UsernamePasswordToken) { String username = ((UsernamePasswordToken) token).getUsername(); AtomicInteger retryCount = passwordRetryCache.get(username); if (retryCount == null) { retryCount = new AtomicInteger(0); passwordRetryCache.put(username, retryCount); } if (retryCount.incrementAndGet() > maxRetryCount) { throw new ExcessiveAttemptsException(); } boolean matched = super.doCredentialsMatch(token, info); if (matched) { passwordRetryCache.remove(username); } return matched; } return super.doCredentialsMatch(token, info); } public Hash hashProvidedCredentials(Object credentials, Object salt) { return super.hashProvidedCredentials(credentials, salt, getHashIterations()); } }
true
7902a9ec3b14fa1e72650dc0012c1d70673b192f
Java
niuapp/RedBaByTest_1
/src/com/itheima/redbaby/fragment/ClassFragment.java
UTF-8
3,101
2.296875
2
[]
no_license
package com.itheima.redbaby.fragment; import java.util.ArrayList; import java.util.List; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import com.itheima.redbaby.R; import com.itheima.redbaby.activity.BaseActivity; import com.itheima.redbaby.activity.ClassActivity_2; import com.itheima.redbaby.adapter.MyTextAdapter; import com.itheima.redbaby.domain.MyCategory; import com.itheima.redbaby.myutils.GetDataByNet; import com.itheima.redbaby.myutils.OtherUtils; import com.itheima.redbaby.parser.CategoryParser; /** * 分类搜索 * @author Administrator */ public class ClassFragment extends BaseFragment { private ListView listView; //总集合 private List<MyCategory> allData; //一级,二级,三级 private List<MyCategory> categories_1; private List<MyCategory> categories_2; private List<MyCategory> categories_3; @Override public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.class_activity, null); listView = (ListView) view.findViewById(R.id.include_list); return view; } @Override public void initData() { //请求数据后根据 自己的id分成三个集合, 把集合存到 Base中(二三级都是Activity 所以用context存到BaseActivity), //一级页面点击时 传自己的id 在二级页面接收id 在对应集合中查(结果展示),三级同样 //获取数据 GetDataByNet.getDataByNet(context, "category", null, new CategoryParser(), new GetDataByNet.OnSetDataListener() { @Override public void setData(Object data) { allData = (List<MyCategory>) data; categories_1 = new ArrayList<MyCategory>(); categories_2 = new ArrayList<MyCategory>(); categories_3 = new ArrayList<MyCategory>(); for (MyCategory mc : allData) { //判断id的长度分 3 5 7 if (3 == mc.getId().length()) { categories_1.add(mc); }else if (5 == mc.getId().length()) { categories_2.add(mc); }else if (7 == mc.getId().length()) { categories_3.add(mc); } } //给BaseActivity中保存 只保存 2 3 ((BaseActivity)context).BA_categories_2 = categories_2; ((BaseActivity)context).BA_categories_3 = categories_3; //设置当前页数据 listView.setAdapter(new MyTextAdapter(context, OtherUtils.toStringList(categories_1))); } }); //ListView的条目点击事件 跳二级页面,带自己id listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //二级 Intent intent = new Intent(context, ClassActivity_2.class); intent.putExtra("categoryId", categories_1.get(position).getId()); intent.putExtra("categoryName", categories_1.get(position).getName()); startActivity(intent); showChangeAnim(); } }); } }
true
8cad81dd3d3339cd37dd5ca07748908d1ff367bd
Java
cybernetics/mapstruct
/processor/src/test/java/org/mapstruct/ap/test/conversion/nativetypes/CharConversionTest.java
UTF-8
2,210
1.960938
2
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
/** * Copyright 2012-2016 Gunnar Morling (http://www.gunnarmorling.de/) * and/or other contributors as indicated by the @authors tag. See the * copyright.txt file in the distribution for a full listing of all * contributors. * * 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.mapstruct.ap.test.conversion.nativetypes; import static org.fest.assertions.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.mapstruct.ap.testutil.IssueKey; import org.mapstruct.ap.testutil.WithClasses; import org.mapstruct.ap.testutil.runner.AnnotationProcessorTestRunner; @WithClasses({ CharSource.class, CharTarget.class, CharMapper.class }) @RunWith(AnnotationProcessorTestRunner.class) public class CharConversionTest { @Test public void shouldApplyCharConversion() { CharSource source = new CharSource(); source.setC( 'G' ); CharTarget target = CharMapper.INSTANCE.sourceToTarget( source ); assertThat( target ).isNotNull(); assertThat( target.getC() ).isEqualTo( Character.valueOf( 'G' ) ); } @Test public void shouldApplyReverseCharConversion() { CharTarget target = new CharTarget(); target.setC( Character.valueOf( 'G' ) ); CharSource source = CharMapper.INSTANCE.targetToSource( target ); assertThat( source ).isNotNull(); assertThat( source.getC() ).isEqualTo( 'G' ); } @Test @IssueKey( "229" ) public void wrapperToPrimitveIsNullSafe() { CharTarget target = new CharTarget(); CharSource source = CharMapper.INSTANCE.targetToSource( target ); assertThat( source ).isNotNull(); } }
true
2d5e867a10afdfe1f76134e16d9768f6c24d3514
Java
Oiwane/Code-Smell-Checker-Beta
/src/main/java/ui/refactoring/replaceTempWithQuery/MyTempWithQueryHandler.java
UTF-8
767
1.84375
2
[ "Apache-2.0" ]
permissive
package ui.refactoring.replaceTempWithQuery; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.refactoring.tempWithQuery.TempWithQueryHandler; import org.jetbrains.annotations.NotNull; public class MyTempWithQueryHandler { private final TempWithQueryHandler handler; private final boolean isTest; public MyTempWithQueryHandler(boolean isTest) { handler = new TempWithQueryHandler(); this.isTest = isTest; } public void invoke(@NotNull Project project, @NotNull PsiElement[] elements, DataContext dataContext) { if (!isTest) handler.invoke(project, elements, dataContext); } }
true
6066032450207594637b7f3d1fb75a90685bed73
Java
veeraBhavani/sampath-class-code
/Jun2015/src/edu/wbqa/entities/usages/AccountTest.java
UTF-8
377
2.703125
3
[]
no_license
package edu.wbqa.entities.usages; import edu.wbqa.entities.*; public class AccountTest { public static void main(String[] args) { Account a1 = new Account(); a1.deposit(50); System.out.println(a1.getAccountBalance()); Account a2 = new Account(); Account a3 = new Account(); a1.withdraw(80); a2.deposit(20); a3.deposit(60); } }
true
f94451b039e111a01526c9ab3d88f7408f0a6942
Java
piaoking/ticket_king
/src/main/java/com/ticket/demo_ticketking/mapper/SeatMapper.java
UTF-8
335
1.929688
2
[]
no_license
package com.ticket.demo_ticketking.mapper; import com.ticket.demo_ticketking.po.TbPlace; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Component; @Mapper @Component public interface SeatMapper { TbPlace querySeat(@Param("placeId") long placeId); }
true
70ce608eb3d82f663e293c3b4a91d24b02674c43
Java
wjdekdns0808/Cookie_app-android-
/app/src/main/java/com/example/team_project_cookie/Realtime_base_edit.java
UTF-8
781
2.171875
2
[]
no_license
package com.example.team_project_cookie; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.HashMap; public class Realtime_base_edit { FirebaseDatabase database; DatabaseReference databaseReference; Realtime_base_edit(){ } void upload_data(String db_path, String value) { database = FirebaseDatabase.getInstance(); DatabaseReference databaseReference = database.getReference(db_path); databaseReference.setValue(value); } void delete_data(String db_path,String value){ database = FirebaseDatabase.getInstance(); databaseReference = database.getReference(db_path); databaseReference.child(value).removeValue(); } }
true
fd8f9cfd25d0ae22b6ea05f9ab3ce4e4570ae483
Java
libgdx/libgdx
/gdx/src/com/badlogic/gdx/net/HttpRequestBuilder.java
UTF-8
5,518
2.265625
2
[ "Apache-2.0", "LicenseRef-scancode-other-copyleft", "CC-BY-SA-3.0", "LicenseRef-scancode-proprietary-license" ]
permissive
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.net; import java.io.InputStream; import java.util.Map; import com.badlogic.gdx.Net.HttpRequest; import com.badlogic.gdx.utils.Base64Coder; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.Pools; /** A builder for {@link HttpRequest}s. * * Make sure to call {@link #newRequest()} first, then set the request up and obtain it via {@link #build()} when you are done. * * It also offers a few utility methods to deal with content encoding and HTTP headers. * * @author Daniel Holderbaum */ public class HttpRequestBuilder { /** Will be added as a prefix to each URL when {@link #url(String)} is called. Empty by default. */ public static String baseUrl = ""; /** Will be set for each new HttpRequest. By default set to {@code 1000}. Can be overwritten via {@link #timeout(int)}. */ public static int defaultTimeout = 1000; /** Will be used for the object serialization in case {@link #jsonContent(Object)} is called. */ public static Json json = new Json(); private HttpRequest httpRequest; /** Initializes the builder and sets it up to build a new {@link HttpRequest} . */ public HttpRequestBuilder newRequest () { if (httpRequest != null) { throw new IllegalStateException("A new request has already been started. Call HttpRequestBuilder.build() first."); } httpRequest = Pools.obtain(HttpRequest.class); httpRequest.setTimeOut(defaultTimeout); return this; } /** @see HttpRequest#setMethod(String) */ public HttpRequestBuilder method (String httpMethod) { validate(); httpRequest.setMethod(httpMethod); return this; } /** The {@link #baseUrl} will automatically be added as a prefix to the given URL. * * @see HttpRequest#setUrl(String) */ public HttpRequestBuilder url (String url) { validate(); httpRequest.setUrl(baseUrl + url); return this; } /** If this method is not called, the {@link #defaultTimeout} will be used. * * @see HttpRequest#setTimeOut(int) */ public HttpRequestBuilder timeout (int timeOut) { validate(); httpRequest.setTimeOut(timeOut); return this; } /** @see HttpRequest#setFollowRedirects(boolean) */ public HttpRequestBuilder followRedirects (boolean followRedirects) { validate(); httpRequest.setFollowRedirects(followRedirects); return this; } /** @see HttpRequest#setIncludeCredentials(boolean) */ public HttpRequestBuilder includeCredentials (boolean includeCredentials) { validate(); httpRequest.setIncludeCredentials(includeCredentials); return this; } /** @see HttpRequest#setHeader(String, String) */ public HttpRequestBuilder header (String name, String value) { validate(); httpRequest.setHeader(name, value); return this; } /** @see HttpRequest#setContent(String) */ public HttpRequestBuilder content (String content) { validate(); httpRequest.setContent(content); return this; } /** @see HttpRequest#setContent(java.io.InputStream, long) */ public HttpRequestBuilder content (InputStream contentStream, long contentLength) { validate(); httpRequest.setContent(contentStream, contentLength); return this; } /** Sets the correct {@code ContentType} and encodes the given parameter map, then sets it as the content. */ public HttpRequestBuilder formEncodedContent (Map<String, String> content) { validate(); httpRequest.setHeader(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded"); String formEncodedContent = HttpParametersUtils.convertHttpParameters(content); httpRequest.setContent(formEncodedContent); return this; } /** Sets the correct {@code ContentType} and encodes the given content object via {@link #json}, then sets it as the * content. */ public HttpRequestBuilder jsonContent (Object content) { validate(); httpRequest.setHeader(HttpRequestHeader.ContentType, "application/json"); String jsonContent = json.toJson(content); httpRequest.setContent(jsonContent); return this; } /** Sets the {@code Authorization} header via the Base64 encoded username and password. */ public HttpRequestBuilder basicAuthentication (String username, String password) { validate(); httpRequest.setHeader(HttpRequestHeader.Authorization, "Basic " + Base64Coder.encodeString(username + ":" + password)); return this; } /** Returns the {@link HttpRequest} that has been setup by this builder so far. After using the request, it should be returned * to the pool via {@code Pools.free(request)}. */ public HttpRequest build () { validate(); HttpRequest request = httpRequest; httpRequest = null; return request; } private void validate () { if (httpRequest == null) { throw new IllegalStateException("A new request has not been started yet. Call HttpRequestBuilder.newRequest() first."); } } }
true
540686df498a5421458b3ec7aea3f3d0f21c0a05
Java
saguaro88/ForumProject
/src/main/java/com/javaee/projectFroum/projectForum/dto/TopicMapper.java
UTF-8
1,599
2.140625
2
[]
no_license
package com.javaee.projectFroum.projectForum.dto; import com.javaee.projectFroum.projectForum.models.Post; import com.javaee.projectFroum.projectForum.models.Topic; import com.javaee.projectFroum.projectForum.services.PostServiceImpl; import com.javaee.projectFroum.projectForum.services.UserServiceImpl; import com.javaee.projectFroum.projectForum.services.interfaces.PostService; import com.javaee.projectFroum.projectForum.services.interfaces.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import java.text.ParseException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; @Controller public class TopicMapper { private static PostServiceImpl postService; private static UserServiceImpl userService; @Autowired public TopicMapper(PostServiceImpl postService, UserServiceImpl userService){ TopicMapper.postService = postService; TopicMapper.userService = userService; } public static Topic toTopic(TopicDto topicDto) throws ParseException { Topic topic = new Topic(); topic.setTitle(topicDto.getTitle()); topic.setUser(userService.findByUsername(topicDto.getUsername())); Post post = new Post(); post.setContent(topicDto.getFirstPostContent()); post.setUser(userService.findByUsername(topicDto.getUsername())); postService.addPost(post); Set<Post> posts = new HashSet<>(); posts.add(post); topic.setPosts(posts); return topic; } }
true
c31743c55fb209a12137670ca6088cb22681cb64
Java
jstashk/doc-search
/doc-search-server/src/main/java/org/ystashko/docsearch/controller/DocumentsController.java
UTF-8
1,000
2.015625
2
[]
no_license
package org.ystashko.docsearch.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.ystashko.docsearch.model.ResponseWrapper; import org.ystashko.docsearch.service.DocumentIndex; import org.ystashko.docsearch.model.Document; import java.util.List; @RestController @RequestMapping("/documents") public class DocumentsController { @Autowired DocumentIndex documentIndex; @GetMapping public ResponseWrapper<Document> getDocumentsByKeys(@RequestParam List<String> keys){ return new ResponseWrapper<>(documentIndex.getDocuments(keys)); } @PutMapping public void putDocument(@RequestBody List<Document> documents){ documentIndex.putDocuments(documents); } @GetMapping("/search") public ResponseWrapper<String> searchForDocuments(@RequestParam List<String> tokens) { return new ResponseWrapper<>(documentIndex.findDocumentsContaining(tokens)); } }
true
f100a35e95b6964cc9930c5ab921a608ab28e3ca
Java
TwoToneEddy/uniBackup
/Sep 2014/Advanced OO/Week 2/FourPlay/src/fourplay/ColomnPanel.java
UTF-8
2,968
2.90625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package fourplay; import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; /** * * @author Lee Hudson 09092543 * This class is a specialised JPanel that displays a single colomn of * the board. It handles all clicking events associated with it. * */ public class ColomnPanel extends JPanel implements MouseListener { private Dimension size; private int colomnNumber; private int chipWidth,chipHeight,verticalSpacing,x,y,noOfChips; FPModel model; FPView gameView; public ColomnPanel(int width, int height, int noOfChips, int colomnNumber, FPModel model,FPView gameView){ this.size = new Dimension(width,height); chipWidth=(int)(width-(width*0.1)); chipHeight=(int)(height/noOfChips-((height/noOfChips)*0.1)); x=(size.width-chipWidth)/2; this.noOfChips=noOfChips; y=(height/noOfChips)-chipHeight; this.colomnNumber=colomnNumber; this.model = model; this.gameView=gameView; this.addMouseListener(this); } public void paintComponent(Graphics g) { super.paintComponent(g); int[][] boardStatus = model.getChipStatus(); for(int i=0; i < noOfChips; i++){ switch(boardStatus[(noOfChips-1)-i][colomnNumber]){ case 0: g.setColor(Color.GRAY); break; case 1: g.setColor(Color.RED); break; case 2: g.setColor(Color.BLACK); break; default: g.setColor(Color.GRAY); break; } g.fillOval(x,((chipHeight+y)*i),chipWidth,chipHeight); } } /** * * @return colomnNumber */ public int getColomnNumber(){ return colomnNumber; } @Override public Dimension getPreferredSize(){ return size; } @Override public Dimension getMinimumSize(){ return getPreferredSize(); } @Override public Dimension getMaximumSize(){ return getPreferredSize(); } public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { gameView.mouseClicked(e.getY(), colomnNumber); } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseMoved(MouseEvent e) { } public void mouseDragged(MouseEvent e) { } }
true
8fa3ab60f9c163285a84ef71189ea51bcae0d68f
Java
poyi41/SMBG
/app/src/main/java/apexbio/smbg/DashBoardActivity.java
UTF-8
6,847
2.125
2
[]
no_license
package apexbio.smbg; /** * Created by A1302 on 2015/7/7. */ import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.View; import android.view.ViewStub; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.LinearLayout; import android.widget.PopupWindow; public class DashBoardActivity extends FragmentActivity{ boolean statisicsBoolean = false; boolean ExportBoolean = false; private PopupWindow popupWindow; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setWindowAnimations(0); popupWindow = new PopupWindow(); } // 設定選單列 public void setHeader(boolean btnStatisticsVisible, boolean btnExportVisible, boolean btnGameVisible, boolean btnSettingsVisible) { ViewStub stub = (ViewStub)findViewById(R.id.vsHeader); View inflated = stub.inflate(); Button btnStatistics = (Button) inflated.findViewById(R.id.btnStatistics); if(!btnStatisticsVisible) btnStatistics.setEnabled(false); Button btnExport = (Button) inflated.findViewById(R.id.btnExport); if(!btnExportVisible) btnExport.setEnabled(false); Button btnSettings = (Button) inflated.findViewById(R.id.btnSettings); if(!btnSettingsVisible) btnSettings.setEnabled(false); } // 選單事件 public void menuOnClicker(View view){ switch(view.getId()){ case R.id.btnStatistics: if(popupWindow.isShowing()){ popupWindow.dismiss(); } if(statisicsBoolean==false){ PopupStaticis(); }else{ statisicsBoolean=false; popupWindow.dismiss(); } break; case R.id.btnExport: if(popupWindow.isShowing()){ popupWindow.dismiss(); } if(ExportBoolean==false){ PopupExport(); }else{ ExportBoolean=false; popupWindow.dismiss(); } break; case R.id.btnSettings: Intent intentSettings = new Intent(getApplicationContext(), SettingsActivity.class); startActivity(intentSettings); finish(); break; } } // 彈出統計選單列視窗 public void PopupStaticis(){ statisicsBoolean=true; ExportBoolean=false; DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); Button btnStatistics = (Button)findViewById(R.id.btnStatistics); // TODO Auto-generated method stub LayoutInflater layoutInflater=(LayoutInflater)getBaseContext() .getSystemService(LAYOUT_INFLATER_SERVICE); View popupView=layoutInflater.inflate(R.layout.popupwindow, null); popupWindow = new PopupWindow( popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); Button btnOverView = (Button)popupView.findViewById(R.id.btnOverView); Button btnChart = (Button)popupView.findViewById(R.id.btnChart); btnOverView.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intentStatistics = new Intent(getApplicationContext(), StatisicsActivity.class); startActivity(intentStatistics); finish(); popupWindow.dismiss(); }}); btnChart.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intentStatistics = new Intent(getApplicationContext(), ChartActivity.class); startActivity(intentStatistics); finish(); /** can undo to last activity **/ popupWindow.dismiss(); }}); popupWindow.showAsDropDown(btnStatistics, 0, (int)(btnStatistics.getY() - btnStatistics.getHeight()*3)); } //彈出資料上傳選單列視窗 public void PopupExport(){ ExportBoolean=true; statisicsBoolean=false; DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); Button btnExport = (Button)findViewById(R.id.btnExport); // TODO Auto-generated method stub LayoutInflater layoutInflater=(LayoutInflater)getBaseContext() .getSystemService(LAYOUT_INFLATER_SERVICE); View ExportpopupView=layoutInflater.inflate(R.layout.exportpopupwindow, null); popupWindow = new PopupWindow( ExportpopupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); Button btnKeyin = (Button)ExportpopupView.findViewById(R.id.btnKeyin); Button btnCable = (Button)ExportpopupView.findViewById(R.id.btnCable); Button btnBLE = (Button)ExportpopupView.findViewById(R.id.btnBLE); btnKeyin.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intentExport = new Intent(getApplicationContext(), ExportActivity.class); startActivity(intentExport); finish(); popupWindow.dismiss(); } }); btnCable.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intentStatistics = new Intent(getApplicationContext(), CableActivity.class); startActivity(intentStatistics); finish(); popupWindow.dismiss(); } }); btnBLE.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intentExport = new Intent(getApplicationContext(), BLEActivity.class); startActivity(intentExport); finish(); popupWindow.dismiss(); } }); popupWindow.showAsDropDown(btnExport, 0, (int)(btnExport.getY() - btnExport.getHeight()*4)); } }
true
ded796b1042ca00e26dd6476c28932ba5f2bde67
Java
Gavin89/TravelMemories
/app/src/main/java/com/hardygtw/travelmemories/fragments/Places/EditPlaceFragment.java
UTF-8
11,068
1.773438
2
[]
no_license
package com.hardygtw.travelmemories.fragments.Places; import android.app.ActionBar; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.location.Address; import android.location.Geocoder; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTabHost; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMapOptions; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.hardygtw.travelmemories.DatePickerFragment; import com.hardygtw.travelmemories.GPSTracker; import com.hardygtw.travelmemories.SQLDatabaseSingleton; import com.hardygtw.travelmemories.activity.MainActivity; import com.hardygtw.travelmemories.R; import com.hardygtw.travelmemories.model.PlaceVisited; import java.io.IOException; import java.util.Calendar; import java.util.List; public class EditPlaceFragment extends Fragment implements OnMapReadyCallback { private ActionBar actionBar; private int place_id; private EditText placeName; private Button dateVisited; private EditText companions; private TextView location; private EditText editPlaceNotes; private String address; private SupportMapFragment fragment; public static LatLng LOCATION = null; private GPSTracker gps; public EditPlaceFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.edit_place_details,container, false); place_id = getArguments().getInt("PLACE_ID"); actionBar = getActivity().getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.removeAllTabs(); PlaceVisited place = SQLDatabaseSingleton.getInstance(getActivity()).getPlaceDetails(place_id); String title = place.getPlaceName(); placeName = (EditText) rootView.findViewById(R.id.place_name); dateVisited = (Button) rootView.findViewById(R.id.dateVisited); companions = (EditText) rootView.findViewById(R.id.companion_name); editPlaceNotes = (EditText) rootView.findViewById(R.id.place_notes); location = (TextView) rootView.findViewById(R.id.location); setDateVisited(rootView); addButtonListener(rootView); placeName.setText(place.getPlaceName()); dateVisited.setText(place.getDateVisited()); companions.setText(place.getTravelCompanions()); editPlaceNotes.setText(place.getTravellerNotes()); location.setText(place.getAddress()); LOCATION = place.getLocation(); if (!title.equals("")) { actionBar.setTitle(title); } return rootView; } @Override public void onPrepareOptionsMenu(Menu menu){ MenuItem settings = menu.findItem(R.id.action_settings); settings.setVisible(false); actionBar.setDisplayHomeAsUpEnabled(false); actionBar.setHomeButtonEnabled(false); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater){ super.onCreateOptionsMenu(menu, menuInflater); menuInflater.inflate(R.menu.menu_add_place, menu); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.add_cancel: ((MainActivity)getActivity()).goBackFragment(); break; case R.id.add_accept: new AlertDialog.Builder(getActivity()) .setTitle("Edit Place") .setMessage("Are you sure you want to edit this place?") .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (placeName.getText().toString().equals("")) { Toast.makeText(getActivity(), "Fields must not be empty", Toast.LENGTH_SHORT).show(); } else { SQLDatabaseSingleton.getInstance(getActivity()).createPlaceVisit(placeName.getText().toString(), dateVisited.getText().toString(), editPlaceNotes.getText().toString(), companions.getText().toString(), EditPlaceFragment.LOCATION, address, 0); Toast.makeText(getActivity(), "Place Updated", Toast.LENGTH_SHORT).show(); ((MainActivity) getActivity()).goBackFragment(); } } }) .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // do nothing } }) .setIcon(android.R.drawable.ic_dialog_alert) .show(); break; } return super.onOptionsItemSelected(item); } public void onViewCreated (View view, Bundle savedInstanceState) { if(LOCATION == null){ Toast.makeText(getActivity(), "Unable to retrieve GPS location", Toast.LENGTH_LONG).show(); LOCATION = new LatLng(51.5008, 0.1247); } new LongOperation(this).execute(""); } // display current date both on the text view and the Date Picker when the application starts. public void setDateVisited(View v) { final Calendar calendar = Calendar.getInstance(); int endDay = calendar.get(Calendar.DAY_OF_MONTH); int endMonth = calendar.get(Calendar.MONTH); int endYear = calendar.get(Calendar.YEAR); // set current date into textview dateVisited.setText(new StringBuilder() // Month is 0 based, so you have to add 1 .append(endDay).append("-") .append(endMonth + 1).append("-") .append(endYear).append(" ")); } public void addButtonListener(View v) { dateVisited.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DialogFragment picker = new DatePickerFragment(dateVisited); picker.show(getFragmentManager(), "datePicker1"); } }); } private class LongOperation extends AsyncTask<String, Void, Boolean> { EditPlaceFragment placeFragment; public LongOperation(EditPlaceFragment placeFragment) { this.placeFragment = placeFragment; } @Override protected Boolean doInBackground(String... params) { try { FragmentManager fm = getChildFragmentManager(); fragment = (SupportMapFragment) fm.findFragmentById(R.id.place_map); if (fragment == null) { fragment = SupportMapFragment.newInstance(new GoogleMapOptions().zOrderOnTop(true)); fm.beginTransaction().replace(R.id.place_map, fragment).commit(); } return true; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } @Override protected void onPostExecute(final Boolean success) { fragment.getMapAsync(placeFragment); } } @Override public void onMapReady(final GoogleMap map) { map.setMyLocationEnabled(true); map.setIndoorEnabled(true); if (EditPlaceFragment.LOCATION == null) { EditPlaceFragment.LOCATION = new LatLng(0,0); } map.addMarker(new MarkerOptions().position(EditPlaceFragment.LOCATION)); Geocoder geoCoder = new Geocoder(getActivity()); List<Address> matches = null; try { matches = geoCoder.getFromLocation(EditPlaceFragment.LOCATION.latitude, EditPlaceFragment.LOCATION.longitude, 1); } catch (IOException e) { e.printStackTrace(); } android.location.Address bestMatch = (matches.isEmpty() ? null : matches.get(0)); if (bestMatch != null) { location.setText(bestMatch.getAddressLine(0) + ", " + bestMatch.getLocality() + ", " + bestMatch.getCountryName()); address = bestMatch.getAddressLine(0) + ", " + bestMatch.getLocality() + ", " + bestMatch.getCountryName(); } CameraPosition cameraPosition = new CameraPosition.Builder() .target(EditPlaceFragment.LOCATION) .zoom(10) .build(); map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); map.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng latLng) { map.clear(); map.addMarker(new MarkerOptions().position(latLng)); EditPlaceFragment.LOCATION = latLng; Geocoder geoCoder = new Geocoder(getActivity()); List<android.location.Address> matches = null; try { matches = geoCoder.getFromLocation(latLng.latitude, latLng.longitude, 1); } catch (IOException e) { e.printStackTrace(); } android.location.Address bestMatch = (matches.isEmpty() ? null : matches.get(0)); location.setText(bestMatch.getAddressLine(0)+", " + bestMatch.getLocality() + ", " + bestMatch.getCountryName()); address = bestMatch.getAddressLine(0)+", " + bestMatch.getLocality() + ", " + bestMatch.getCountryName(); } }); } }
true
b997752b0c0e7d7b8ff0a11c66d9bcf0ace38c98
Java
spring-projects/spring-framework
/spring-web/src/main/java/org/springframework/web/context/ConfigurableWebApplicationContext.java
UTF-8
3,786
2.0625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2002-2014 the original author or authors. * * 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 * * https://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.springframework.web.context; import jakarta.servlet.ServletConfig; import jakarta.servlet.ServletContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.lang.Nullable; /** * Interface to be implemented by configurable web application contexts. * Supported by {@link ContextLoader} and * {@link org.springframework.web.servlet.FrameworkServlet}. * * <p>Note: The setters of this interface need to be called before an * invocation of the {@link #refresh} method inherited from * {@link org.springframework.context.ConfigurableApplicationContext}. * They do not cause an initialization of the context on their own. * * @author Juergen Hoeller * @since 05.12.2003 * @see #refresh * @see ContextLoader#createWebApplicationContext * @see org.springframework.web.servlet.FrameworkServlet#createWebApplicationContext */ public interface ConfigurableWebApplicationContext extends WebApplicationContext, ConfigurableApplicationContext { /** * Prefix for ApplicationContext ids that refer to context path and/or servlet name. */ String APPLICATION_CONTEXT_ID_PREFIX = WebApplicationContext.class.getName() + ":"; /** * Name of the ServletConfig environment bean in the factory. * @see jakarta.servlet.ServletConfig */ String SERVLET_CONFIG_BEAN_NAME = "servletConfig"; /** * Set the ServletContext for this web application context. * <p>Does not cause an initialization of the context: refresh needs to be * called after the setting of all configuration properties. * @see #refresh() */ void setServletContext(@Nullable ServletContext servletContext); /** * Set the ServletConfig for this web application context. * Only called for a WebApplicationContext that belongs to a specific Servlet. * @see #refresh() */ void setServletConfig(@Nullable ServletConfig servletConfig); /** * Return the ServletConfig for this web application context, if any. */ @Nullable ServletConfig getServletConfig(); /** * Set the namespace for this web application context, * to be used for building a default context config location. * The root web application context does not have a namespace. */ void setNamespace(@Nullable String namespace); /** * Return the namespace for this web application context, if any. */ @Nullable String getNamespace(); /** * Set the config locations for this web application context in init-param style, * i.e. with distinct locations separated by commas, semicolons or whitespace. * <p>If not set, the implementation is supposed to use a default for the * given namespace or the root web application context, as appropriate. */ void setConfigLocation(String configLocation); /** * Set the config locations for this web application context. * <p>If not set, the implementation is supposed to use a default for the * given namespace or the root web application context, as appropriate. */ void setConfigLocations(String... configLocations); /** * Return the config locations for this web application context, * or {@code null} if none specified. */ @Nullable String[] getConfigLocations(); }
true
39178eb4414b9f5680134b20c29770aaad16c977
Java
ySant/triads
/J8SevenTriangles.java
UTF-8
12,731
2.9375
3
[]
no_license
/* * J8SevenTriangles.java * Counting/Enumerating Triangles in a Directed Graph, * classified into 7 types of triangles (i.e., 7 counters). * Suppose triangle (u,v,w) : edges e1=uv, e2=vw, e3=wu (notice this!) * - Type 1: ->, ->, -> (1 cycle) * - Type 2: ->, ->, <- (1 trust) * - Type 3: ->, ->, <-> (1 trust + 1 cycle) * - Type 4: ->, <-, <-> (2 trust merge) * - Type 5: <-, ->, <-> (2 trust parting) * - Type 6: <->, <->, -> (4trust + 1 cycle) * - Type 7: <->, <->, <-> (6 trusts + 2 cycles) * Edges types: * . . 0 * .->. 1 * .<-. 2 * .<->. 3 * There are 3*3*3 = 27 combinations of 3 non-zero edges. * Triangle types in edge types combinations: * - Type 1: 111, 212, 122, 222, 121, 211 * - Type 2: 112, 221 * - Type 3: 113, 312, 132, 223, 321, 231 * - Type 4: 123, 311, 232 * - Type 5: 213, 322, 131 * - Type 6: 133, 233, 313, 323, 331, 332 * - Type 7: 333 * Use parallel stream (Java 8). * Dependency: * - WebGraph library. * - java.util.stream.IntStream * Input: A directed graph and its transpose in webgraph format. * Usage: java J8SevenTriangles basename * Note: both the graph and the transpose graph must be present. * Output: Seven counts of triangles, one for each type. * Can be modified to enumerate the triangles. * Algorithm: Use Edge Iteration, on both G and Gt simultaneously. * Use Four Pointers iteration to find common neighbors. * Use flags for edge type/direction. * None = 0 * -> = 1 * <- = 2 * <-> = 3 * Notes: * - use long for mG and mGt * Version 1.00 - derived from SevenTriangles 1.30 * - use Java 8 stream Parallel * - Aug 06, 2018 - Yudi Santoso * Version 1.10 - add trust and cycle counts * Version 1.20 - clean up code * - Nov 08, 2018 - Yudi Santoso * Version 1.30 - use lookup table for triad type to avoid multiple * computation. * - Nov 10, 2018 - Yudi Santoso */ import it.unimi.dsi.webgraph.ImmutableGraph; import java.util.stream.IntStream; public class J8SevenTriangles { String basename; ImmutableGraph G; // a directed graph ImmutableGraph Gt; // transpose of G int n; int nG; int nGt; long mG; int maxdegG; long mGt; int maxdegGt; int[][][] de7Type; public J8SevenTriangles(String basename) throws Exception { de7Type = new int[4][4][4]; // to avoid computing detype again and again for (int i=0; i<4; i++){ for (int j=0; j<4; j++){ for (int k=0; k<4; k++){ de7Type[i][j][k] = detype(i, j, k); } } } this.basename = basename; G = ImmutableGraph.loadMapped(basename); Gt = ImmutableGraph.loadMapped(basename+"-t"); nG = G.numNodes(); nGt = Gt.numNodes(); if (nG != nGt) System.out.println("WARNING!! Number of nodes do not match:" + nG + " != " + nGt); n = nG; maxdegG = 0; mG = 0; maxdegGt = 0; mGt = 0; for(int v=0; v<n; v++) { int v_degG = G.outdegree(v); mG += v_degG; if(v_degG > maxdegG) maxdegG = v_degG; int v_degGt = Gt.outdegree(v); mGt += v_degGt; if(v_degGt > maxdegGt) maxdegGt = v_degGt; } System.out.println("n=" + n + ", mG=" + mG + ", maxdegG=" + maxdegG + ", mGt=" + mGt + ", maxdegGt=" + maxdegGt); } public void computeTriangles() throws Exception { long[] t_count = IntStream.range(0,n).parallel().mapToObj(u -> { if(u%1_000_000 == 0) System.out.println(u); ImmutableGraph H = G.copy(); ImmutableGraph Ht = Gt.copy(); int[] u_neighbors = H.successorArray(u); int[] ut_neighbors = Ht.successorArray(u); int u_deg = H.outdegree(u); int ut_deg = Ht.outdegree(u); long[] tp_count = new long[8]; for(int i=0, j=0; i<u_deg || j<ut_deg; ) { int v=0; int e1 = 0; // edge uv if (u_deg != 0 && ut_deg != 0){ if (i == u_deg){ // i done (cannot be both done) v = ut_neighbors[j]; e1 = 2; j++; } else if (j == ut_deg){ // j done (cannot be both done) v = u_neighbors[i]; e1 = 1; i++; } else if (u_neighbors[i] < ut_neighbors[j]){ v = u_neighbors[i]; e1 = 1; i++; } else if (u_neighbors[i] > ut_neighbors[j]){ v = ut_neighbors[j]; e1 = 2; j++; } else if (u_neighbors[i] == ut_neighbors[j]){ v = u_neighbors[i]; e1 = 3; i++; j++; } } else if (u_deg != 0 ){ // only u_neighbors v = u_neighbors[i]; e1 = 1; i++; } else if (ut_deg != 0 ){ // only ut_neighbors v = ut_neighbors[j]; e1 = 2; j++; } if (u < v){ // to avoid double counting // also, when v=0 it means that e1=0, so do not iterate int[] v_neighbors = H.successorArray(v); int[] vt_neighbors = Ht.successorArray(v); int v_deg = H.outdegree(v); int vt_deg = Ht.outdegree(v); int[] ucount = new int[8]; // temp counters ucount = census4(u, v, e1, u_neighbors, ut_neighbors, v_neighbors, vt_neighbors, u_deg, ut_deg, v_deg, vt_deg); for (int t=1; t<8; t++) { tp_count[t] += ucount[t]; } } continue; } return tp_count; }).reduce(new long[]{0,0,0,0,0,0,0,0}, (a,b)->sumArrays(a,b,8)); long t_total_cnt = 0; for (int t=1; t<8; t++){ System.out.println("Number of triangles type " + t + ": " + t_count[t]); t_total_cnt += t_count[t]; } System.out.println("Total number of triad triangles: " + t_total_cnt); System.out.println("Number of trust triangles: " + (t_count[2] + t_count[3] + 2*t_count[4]+ 2*t_count[5]+ 3*t_count[6]+ 6*t_count[7])); System.out.println("Number of cycle triangles: " + (t_count[1] + t_count[3] + t_count[6]+ 2*t_count[7])); } int[] census4(int u, int v, int e1, int[] u_N, int[] ut_N, int[] v_N, int[] vt_N, int u_deg, int ut_deg, int v_deg, int vt_deg) { int[] ucount = new int[8]; // triangle counts for each types for (int t=0; t<8; t++) ucount[t] = 0; for(int i=0,j=0,k=0,l=0; (i<u_deg || j<ut_deg) && (k<v_deg || l < vt_deg); ) { int A = (i == u_deg ? n : u_N[i]); int B = (j == ut_deg ? n : ut_N[j]); int C = (k == v_deg ? n : v_N[k]); int D = (l == vt_deg ? n : vt_N[l]); if(A < v) { i++; continue; } if(B < v) { j++; continue; } if(C < v) { k++; continue; } if(D < v) { l++; continue; } int w = 0; int e2 = 0; // edge vw int e3 = 0; // edge uw int type = 0; // Check the edges to the smallest neighbor. // Note that each case is mutually disjoint to others. if(A < B && A < C && A < D) { i++; } else if(B < A && B < C && B < D) { j++; } else if(C < A && C < B && C < D) { k++; } else if(D < A && D < B && D < C) { l++; } else if(A == B && A < C && A < D) { i++; j++; } else if(C == D && C < A && C < B) { k++; l++; } else if(A == C && A < B && A < D) { e2 = 1; e3 = 2; w = A; i++; k++; } else if(A == D && A < B && A < C) { e2 = 2; e3 = 2; w = A; i++; l++; } else if(B == C && B < A && B < D) { e2 = 1; e3 = 1; w = B; j++; k++; } else if(B == D && B < A && B < C) { e2 = 2; e3 = 1; w = B; j++; l++; } else if(A == B && A == C && A < D) { e2 = 1; e3 = 3; w = A; i++; j++; k++; } else if(A == B && A == D && A < C) { e2 = 2; e3 = 3; w = A; i++; j++; l++; } else if(A == C && A == D && A < B) { e2 = 3; e3 = 2; w = A; i++; k++; l++; } else if(B == C && B == D && B < A) { e2 = 3; e3 = 1; w = B; j++; k++; l++; } else if(A == B && A == C && A == D ) { e2 = 3; e3 = 3; w = A; i++; j++; k++; l++; } if (v < w) { // to avoid double counting // Now determine the type: // type = detype(e1,e2,e3); type = de7Type[e1][e2][e3]; // use lookup array // For enumeration: // System.out.println("u,v,w, [e1e2e3], type: " + u + "\t" + v + "\t" + w + "\t[" + e1 + e2 + e3 + "] " + type); // Add to the count: ucount[type]++; } continue; } return ucount; } int detype(int e1, int e2, int e3){ int type = 0; int T = ((e1 << 2) | e2) << 2 | e3; int t1 = T >> 3; // the left 3 bits int t2 = T & 7; // the right 3 bits int Sigma = Hamming(T, 6); if (Sigma == 6){ type = 7; return type; } else if (Sigma == 5){ type = 6; return type; } else if (Sigma == 4){ int Lambda = Hamming(e1 & e2 & e3, 2); if (Lambda == 1){ type = 3; return type; } else if (Lambda == 0){ int Lambda3 = Hamming(t1 & t2, 3); if (Lambda3 == 2){ type = 4; return type; } else if (Lambda3 == 1){ type = 5; return type; } } } else if (Sigma == 3){ int Lambda = Hamming(e1 & e2 & e3, 2); if (Lambda == 1){ type = 1; return type; } else if (Lambda == 0){ type = 2; return type; } } return type; } int Hamming(int N, int M){ int ham = 0; for (int i=0; i<M; i++){ if ((N >>> i) % 2 == 1) ++ham; } return ham; } static long[] sumArrays(long[] A, long[] B, int N){ long[] C = new long[N]; for (int i=0;i<N;i++){ C[i] = A[i] + B[i]; } return C; } public static void main(String[] args) throws Exception { long startTime = System.currentTimeMillis(); String basename = args[0]; J8SevenTriangles t = new J8SevenTriangles(basename); t.computeTriangles(); System.out.println("Total time elapsed = " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); } }
true
d6d7839c63c8aaee5a2272bc23e22bb966f7bc29
Java
JavierEGoTe/Ejercicio-Figuras-Geometricas
/src/Circulo.java
UTF-8
233
2.734375
3
[]
no_license
import static java.lang.Math. *; public class Circulo extends FigurasGeometricas{ float radio=0.0f; double area=0; public String calcularArea() { area = Math.PI*Math.pow(radio,2); return "El area del circulo es: "+area; } }
true
3bb30c2565ea7c7f986e0d0e18bd7128c2ee1a9f
Java
nelsonwhf/InviteMsgCenter
/src/com/duowan/gamebox/msgcenter/msg/response/JoinGameResponse.java
UTF-8
317
1.75
2
[]
no_license
/** * */ package com.duowan.gamebox.msgcenter.msg.response; import com.duowan.gamebox.msgcenter.msg.AbstractMessage; /** * @author zhangtao.robin * */ public class JoinGameResponse extends AbstractMessage<Object> { public JoinGameResponse() { super(); setCode(JOIN_GAME_CODE); } }
true
84259ccc0793eec12d737c7eb4228946e041e7de
Java
chiangming/leetcode-solution
/src/main/java/com/leetcode/solution/Solution32_Longest_Valid_Parentheses.java
UTF-8
3,965
3.546875
4
[]
no_license
package com.leetcode.solution; import java.util.Map; import java.util.Stack; /** * @Author mingjiang * @Date 2019/4/11 17:41 */ public class Solution32_Longest_Valid_Parentheses { //如果能使用for循环就使用for循环,而不是没有剪枝的DFS迭代 public int longestValidParentheses(String s) { int maxlen = 0; for (int i = 0; i < s.length(); i++) { for (int j = i + 2; j <= s.length(); j+=2) { if (isValid(s.substring(i, j))) { maxlen = Math.max(maxlen, j - i); } } } return maxlen; } //动态规划 // dp [ i ] 代表以下标 i 结尾!!!!! 的合法序列的最长长度 // 首先我们初始化所有的 dp 都等于零。 // 以左括号结尾的字符串一定是非法序列,所以 dp 是零,不用更改。 // 以右括号结尾的字符串分两种情况。 // // 右括号前边是 ( ,类似于 ……【……】()。 // dp [ i ] = dp [ i - 2] + 2 (前一个合法序列的长度,加上当前新增的长度 2) // // 右括号前边是 ),类似于 ……【……】))。 // 此时我们需要判断 i - dp[i - 1] - 1 (前一个合法序列的前边一个位置) 是不是左括号。 // 即为判断 类似于……(【……】))还是……)【……】)) public int longestValidParentheses2(String s) { int maxans = 0; int dp[] = new int[s.length()]; for (int i = 1; i < s.length(); i++) { if (s.charAt(i) == ')') { //右括号前边是左括号 if (s.charAt(i - 1) == '(') { dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2; //右括号前边是右括号,并且除去前边的合法序列的前边是左括号 } else if (i - dp[i - 1] > 0 && s.charAt(i - dp[i - 1] - 1) == '(') { dp[i] = dp[i - 1] + ((i - dp[i - 1]) >= 2 ? dp[i - dp[i - 1] - 2] : 0) + 2; } maxans = Math.max(maxans, dp[i]); } } return maxans; } //使用栈解决配对问题 public int longestValidParentheses3(String s) { int maxans = 0; Stack<Integer> stack = new Stack<>(); stack.push(-1); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') { stack.push(i); } else { stack.pop(); if (stack.empty()) { stack.push(i); } else { maxans = Math.max(maxans, i - stack.peek()); } } } return maxans; } /* int res = -1; public int longestValidParentheses(String s) { if(s.length()==0||s.length()==1) return 0; validString(s,0,s.length()); return res; } public int validString(String s,int i,int j){ if(isValid(s.substring(i,j))){ res = (j-i)>res?j-i:res; return res; }else{ int a =(validString(s,i,j-1)); int b = (validString(s,i+1,j)); res= res>Math.max(a,b)?res: Math.max(a,b); return res; } }*/ public boolean isValid(String s) { if (s == null || s.length() == 0) return true; if (s.length() % 2 != 0) return false; Stack<Character> chs= new Stack<Character>(); for(int i=0;i<s.length();i++){ char ch = s.charAt(i); if (ch=='('){ chs.push(ch); } else if (!chs.isEmpty() && ch==')'){ if(chs.peek()=='(') chs.pop(); }else{ return false; } } return chs.isEmpty(); } public static void main(String[] args) { System.out.println(new Solution32_Longest_Valid_Parentheses().longestValidParentheses(")()")); } }
true
4266005b2ee00f7020c904b0480f072212485b6c
Java
Cocanuta/Marble
/com/planet_ink/marble_mud/Abilities/Songs/Play_Accompaniment.java
UTF-8
2,484
1.96875
2
[]
no_license
package com.planet_ink.marble_mud.Abilities.Songs; import com.planet_ink.marble_mud.core.interfaces.*; import com.planet_ink.marble_mud.core.*; import com.planet_ink.marble_mud.core.collections.*; import com.planet_ink.marble_mud.Abilities.interfaces.*; import com.planet_ink.marble_mud.Areas.interfaces.*; import com.planet_ink.marble_mud.Behaviors.interfaces.*; import com.planet_ink.marble_mud.CharClasses.interfaces.*; import com.planet_ink.marble_mud.Commands.interfaces.*; import com.planet_ink.marble_mud.Common.interfaces.*; import com.planet_ink.marble_mud.Exits.interfaces.*; import com.planet_ink.marble_mud.Items.interfaces.*; import com.planet_ink.marble_mud.Locales.interfaces.*; import com.planet_ink.marble_mud.MOBS.interfaces.*; import com.planet_ink.marble_mud.Races.interfaces.*; import java.util.*; /* 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. */ public class Play_Accompaniment extends Play { public String ID() { return "Play_Accompaniment"; } public String name(){ return "Accompaniment";} public int abstractQuality(){ return Ability.QUALITY_BENEFICIAL_OTHERS;} public void affectPhyStats(Physical E, PhyStats stats) { super.affectPhyStats(E,stats); if((E instanceof MOB)&&(E!=invoker())&&(((MOB)E).charStats().getCurrentClass().baseClass().equals("Bard"))) { int lvl=adjustedLevel(invoker(),0)/10; if(lvl<1) lvl=1; stats.setLevel(stats.level()+lvl); } } public void affectCharStats(MOB E, CharStats stats) { super.affectCharStats(E,stats); if((E instanceof MOB)&&(E!=invoker())&&(stats.getCurrentClass().baseClass().equals("Bard"))) { int lvl=adjustedLevel(invoker(),0)/10; if(lvl<1) lvl=1; stats.setClassLevel(stats.getCurrentClass(),stats.getCurrentClassLevel()+lvl); } } public int castingQuality(MOB mob, Physical target) { if(mob!=null) { if(mob.getGroupMembers(new HashSet<MOB>()).size()<2) return Ability.QUALITY_INDIFFERENT; } return super.castingQuality(mob,target); } }
true
a4e0d1316b024d47164d71ee40674000d9a5fa50
Java
geovas01/mathpiper
/src/library_apps/piper_me/piper_me/org/mathrider/piper_me/ParsedObject.java
UTF-8
9,606
2.484375
2
[]
no_license
package org.mathpiper.ide.piper_me; class ParsedObject { public ParsedObject(InfixParser aParser) { iParser = aParser; iError = false; iEndOfFile = false; iLookAhead = null; } public void Parse() throws Exception { ReadToken(); if (iEndOfFile) { iResult.setNext(iParser.iEnvironment.iEndOfFile.Copy(true)); return; } ReadExpression(InfixPrinter.KMaxPrecedence); // least precedence if (iLookAhead != iParser.iEnvironment.iEndStatement.String()) { Fail(); } if (iError) { while (iLookAhead.length() > 0 && iLookAhead != iParser.iEnvironment.iEndStatement.String()) { ReadToken(); } } if (iError) { iResult.setNext(null); } LispError.Check(!iError,LispError.KLispErrInvalidExpression); } void ReadToken() throws Exception { // Get token. iLookAhead = iParser.iTokenizer.NextToken(iParser.iInput, iParser.iEnvironment.HashTable()); if (iLookAhead.length() == 0) iEndOfFile=true; } void MatchToken(String aToken) throws Exception { if (aToken != iLookAhead) Fail(); ReadToken(); } void ReadExpression(int depth) throws Exception { ReadAtom(); for(;;) { //Handle special case: a[b]. a is matched with lowest precedence!! if (iLookAhead == iParser.iEnvironment.iProgOpen.String()) { // Match opening bracket MatchToken(iLookAhead); // Read "index" argument ReadExpression(InfixPrinter.KMaxPrecedence); // Match closing bracket if (iLookAhead != iParser.iEnvironment.iProgClose.String()) { LispError.RaiseError("Expecting a ] close bracket for program block, but got "+iLookAhead+" instead"); return; } MatchToken(iLookAhead); // Build into Ntn(...) String theOperator = iParser.iEnvironment.iNth.String(); InsertAtom(theOperator); Combine(2); } else { LispInFixOperator op = (LispInFixOperator)iParser.iInfixOperators.get(iLookAhead); if (op == null) { //printf("op [%s]\n",iLookAhead.String()); if (LispTokenizer.IsSymbolic(iLookAhead.charAt(0))) { int origlen = iLookAhead.length(); int len = origlen; //printf("IsSymbolic, len=%d\n",len); while (len>1) { len--; String lookUp = iParser.iEnvironment.HashTable().LookUp(iLookAhead.substring(0,len)); //printf("trunc %s\n",lookUp.String()); op = (LispInFixOperator)iParser.iInfixOperators.get(lookUp); //if (op) printf("FOUND\n"); if (op != null) { String toLookUp = iLookAhead.substring(len,origlen); String lookUpRight = iParser.iEnvironment.HashTable().LookUp(toLookUp); //printf("right: %s (%d)\n",lookUpRight.String(),origlen-len); if (iParser.iPrefixOperators.get(lookUpRight) != null) { //printf("ACCEPT %s\n",lookUp.String()); iLookAhead = lookUp; LispInput input = iParser.iInput; int newPos = input.Position()-(origlen-len); input.SetPosition(newPos); //printf("Pushhback %s\n",&input.StartPtr()[input.Position()]); break; } else op=null; } } if (op == null) return; } else { return; } // return; } if (depth < op.iPrecedence) return; int upper=op.iPrecedence; if (op.iRightAssociative == 0) upper--; GetOtherSide(2,upper); } } } void ReadAtom() throws Exception { LispInFixOperator op; // Parse prefix operators op = (LispInFixOperator)iParser.iPrefixOperators.get(iLookAhead); if (op != null) { String theOperator = iLookAhead; MatchToken(iLookAhead); { ReadExpression(op.iPrecedence); InsertAtom(theOperator); Combine(1); } } // Else parse brackets else if (iLookAhead == iParser.iEnvironment.iBracketOpen.String()) { MatchToken(iLookAhead); ReadExpression(InfixPrinter.KMaxPrecedence); // least precedence MatchToken(iParser.iEnvironment.iBracketClose.String()); } //Parse lists else if (iLookAhead == iParser.iEnvironment.iListOpen.String()) { int nrargs=0; MatchToken(iLookAhead); while (iLookAhead != iParser.iEnvironment.iListClose.String()) { ReadExpression(InfixPrinter.KMaxPrecedence); // least precedence nrargs++; if (iLookAhead == iParser.iEnvironment.iComma.String()) { MatchToken(iLookAhead); } else if (iLookAhead != iParser.iEnvironment.iListClose.String()) { LispError.RaiseError("Expecting a } close bracket for a list, but got "+iLookAhead+" instead"); return; } } MatchToken(iLookAhead); String theOperator = iParser.iEnvironment.iList.String(); InsertAtom(theOperator); Combine(nrargs); } // Parse prog bodies else if (iLookAhead == iParser.iEnvironment.iProgOpen.String()) { int nrargs=0; MatchToken(iLookAhead); while (iLookAhead != iParser.iEnvironment.iProgClose.String()) { ReadExpression(InfixPrinter.KMaxPrecedence); // least precedence nrargs++; if (iLookAhead == iParser.iEnvironment.iEndStatement.String()) { MatchToken(iLookAhead); } else { LispError.RaiseError("Expecting ; end of statement in program block, but got "+iLookAhead+" instead"); return; } } MatchToken(iLookAhead); String theOperator = iParser.iEnvironment.iProg.String(); InsertAtom(theOperator); Combine(nrargs); } // Else we have an atom. else { String theOperator = iLookAhead; MatchToken(iLookAhead); int nrargs=-1; if (iLookAhead == iParser.iEnvironment.iBracketOpen.String()) { nrargs=0; MatchToken(iLookAhead); while (iLookAhead != iParser.iEnvironment.iBracketClose.String()) { ReadExpression(InfixPrinter.KMaxPrecedence); // least precedence nrargs++; if (iLookAhead == iParser.iEnvironment.iComma.String()) { MatchToken(iLookAhead); } else if (iLookAhead != iParser.iEnvironment.iBracketClose.String()) { LispError.RaiseError("Expecting ) closing bracket for sub-expression, but got "+iLookAhead+" instead"); return; } } MatchToken(iLookAhead); op = (LispInFixOperator)iParser.iBodiedOperators.get(theOperator); if (op != null) { ReadExpression(op.iPrecedence); // InfixPrinter.KMaxPrecedence nrargs++; } } InsertAtom(theOperator); if (nrargs>=0) Combine(nrargs); } // Parse postfix operators while ((op = (LispInFixOperator)iParser.iPostfixOperators.get(iLookAhead)) != null) { InsertAtom(iLookAhead); MatchToken(iLookAhead); Combine(1); } } void GetOtherSide(int aNrArgsToCombine, int depth) throws Exception { String theOperator = iLookAhead; MatchToken(iLookAhead); ReadExpression(depth); InsertAtom(theOperator); Combine(aNrArgsToCombine); } void Combine(int aNrArgsToCombine) throws Exception { LispPtr subList = new LispPtr(); subList.setNext(LispSubList.New(iResult.getNext())); LispIterator iter = new LispIterator(iResult); int i; for (i=0;i<aNrArgsToCombine;i++) { if (iter.GetObject() == null) { Fail(); return; } iter.GoNext(); } if (iter.GetObject() == null) { Fail(); return; } subList.getNext().setNext(iter.GetObject().getNext()); iter.GetObject().setNext(null); LispStandard.InternalReverseList(subList.getNext().SubList().getNext(), subList.getNext().SubList().getNext()); iResult.setNext(subList.getNext()); } void InsertAtom(String aString) throws Exception { LispPtr ptr = new LispPtr(); ptr.setNext(LispAtom.New(iParser.iEnvironment,aString)); ptr.getNext().setNext(iResult.getNext()); iResult.setNext(ptr.getNext()); } void Fail() throws Exception // called when parsing fails, raising an exception { iError = true; if (iLookAhead != null) { LispError.RaiseError("Error parsing expression, near token "+iLookAhead); } LispError.RaiseError("Error parsing expression"); } InfixParser iParser; boolean iError; boolean iEndOfFile; String iLookAhead; public LispPtr iResult = new LispPtr(); };
true
149a23d349fd721914159869584c638b1e75cf27
Java
quarl894/Algorithm_exam
/Algo/src/backjune/DFS_BFS/bj_15655.java
UTF-8
1,365
2.953125
3
[]
no_license
package backjune.DFS_BFS; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; public class bj_15655 { static int n; static int m; static int[] arr; static int[] tmp; static boolean[] visited; public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] t1 = br.readLine().split(" "); n = Integer.parseInt(t1[0]); m = Integer.parseInt(t1[1]); arr = new int[n]; tmp = new int[m]; visited = new boolean[10001]; String[] t2 = br.readLine().split(" "); for(int i=0; i<n; i++){ arr[i] = Integer.parseInt(t2[i]); } Arrays.sort(arr); dfs(0,0); br.close(); } private static void dfs(int pos,int cnt){ if(cnt==m){ print(); return; } for(int i=pos; i<n; i++){ if(!visited[arr[i]]) { visited[arr[i]]=true; dfs(i+1,cnt+1); visited[arr[i]] = false; } } } private static void print(){ StringBuilder st = new StringBuilder(); for(int i=0; i<n; i++){ if(visited[arr[i]]) st.append(arr[i] + " "); } System.out.println(st); } }
true
da9c5de99230a1921167b284b58eac6372a117e0
Java
boosey/resource-scheduler
/reservation/reservation-api/src/main/java/boosey/ReservationAPI.java
UTF-8
4,363
2.234375
2
[]
no_license
package boosey; import java.util.List; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.NotAcceptableException; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import boosey.reservation.Reservation; import io.smallrye.mutiny.Uni; import io.smallrye.mutiny.operators.UniCreateWithEmitter; import lombok.val; import lombok.extern.slf4j.Slf4j; @Slf4j @Path("/reservation") @ApplicationScoped public class ReservationAPI { @Inject ReservationQuery query; @Inject ReservationCommand command; @GET @Produces(MediaType.TEXT_PLAIN) public Uni<List<Reservation>> listAll() { return query.listAll(); } // @GET // @Transactional // @Produces(MediaType.TEXT_PLAIN) // @Path("/createtestdata") // public Boolean createtestdata() { // Reservation r = new Reservation(); // r.resourceId = UUID.randomUUID().toString(); // r.resourceActive = true; // r.startTime = LocalDateTime.of(2020, Month.OCTOBER, 20, 6, 00); // r.endTime = LocalDateTime.of(2020, Month.OCTOBER, 20, 18, 00); // r.persist(); // r = new Reservation(); // r.resourceId = UUID.randomUUID().toString(); // r.resourceActive = true; // r.startTime = LocalDateTime.of(2020, Month.OCTOBER, 21, 10, 00); // r.endTime = LocalDateTime.of(2020, Month.OCTOBER, 21, 18, 00); // r.persist(); // r = new Reservation(); // r.resourceId = UUID.randomUUID().toString(); // r.resourceActive = true; // r.startTime = LocalDateTime.of(2020, Month.OCTOBER, 20, 8, 00); // r.endTime = LocalDateTime.of(2020, Month.OCTOBER, 20, 20, 00); // r.persist(); // return true; // } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Uni<Response> addReservation(Reservation reservation) { return new UniCreateWithEmitter<Response>( emitter -> { try { String reservationId = command.addReservation(reservation); emitter.complete(Response.accepted(reservationId).build()); } catch (NotAcceptableException e) { emitter.complete(Response.status(Status.NOT_FOUND).build()); } }); } @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/{reservationId}") public Uni<Response> replaceReservation(@PathParam("reservationId") String reservationId, Reservation reservation) { log.info("command.replaceReservation"); return new UniCreateWithEmitter<Response>( emitter -> { try { command.replaceReservation(reservationId, reservation); emitter.complete(Response.ok(reservationId).build()); } catch (NotAcceptableException e) { emitter.complete(Response.status(Status.NOT_FOUND).build()); } }); } @DELETE @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Uni<Response> deleteAllReservation() { return new UniCreateWithEmitter<Response>( emitter -> { val cnt = query.count(); command.deleteAllReservation(); emitter.complete(Response.ok(cnt).build()); }); } @DELETE @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/{reservationId}") public Uni<Response> deleteReservation(@PathParam("reservationId") String reservationId) { log.info("command.deleteReservation"); return new UniCreateWithEmitter<Response>( emitter -> { try { command.deleteReservation(reservationId); emitter.complete(Response.ok("1").build()); } catch (NotAcceptableException e) { emitter.complete(Response.status(Status.NOT_FOUND).build()); } }); } }
true
c11848be2e1bbd8279e22f7933917ec355c44959
Java
Fxhnd13/TS1-Tiempo-Maya
/Proyecto Escritorio/src/modelos/objetos/Energia.java
UTF-8
1,905
3.21875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package modelos.objetos; /** * Clase destinada a almacenar la información de una energia * @author jose_ */ public class Energia { private int id; private String nombre; private Imagen imagen; /** * Constructor */ public Energia() { } /** * Constructor * @param id Identificador de la instancia energia * @param nombre Nombre de la instancia energia * @param imagen Imagen de la instancia energia */ public Energia(int id, String nombre, Imagen imagen) { this.id = id; this.nombre = nombre; this.imagen = imagen; } /** * @return Identificador de la instancia energia */ public int getId() { return id; } /** * Procedimiento para modificar el identificador de la instancia energia * @param id Nuevo identificador que deseamos que posea la instancia energía */ public void setId(int id) { this.id = id; } /** * @return Nombre de la instancia energía */ public String getNombre() { return nombre; } /** * Procedimiento para modificar el nombre de la instancia energia * @param nombre Nuevo nombre que deseamos que posea la instancia energia */ public void setNombre(String nombre) { this.nombre = nombre; } /** * @return Imagen de la instancia energia */ public Imagen getImagen() { return imagen; } /** * Procedimiento para modificar la imagen de la instancia energía * @param imagen Nueva imagen que deseamos que posea la instancia energía */ public void setImagen(Imagen imagen) { this.imagen = imagen; } }
true
eaf496d6fd51e6bfdac3c3b20f9ec931d5afb288
Java
jianJizz/JUC
/src/main/java/com/usc/leetcode/RemoveNthFromEnd.java
UTF-8
2,240
3.90625
4
[]
no_license
package com.usc.leetcode; import java.util.*; /** *给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。 * * 示例: * * 给定一个链表: 1->2->3->4->5, 和 n = 2. * * 当删除了倒数第二个节点后,链表变为 1->2->3->5. * 说明: * * 给定的 n 保证是有效的。 * * 进阶: * * 你能尝试使用一趟扫描实现吗? * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class RemoveNthFromEnd { public static void main(String[] args) { ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(3); head.next.next.next = new ListNode(4); head.next.next.next.next = new ListNode(5); RemoveNthFromEnd.removeNthFromEnd2(head, 2); } public static ListNode removeNthFromEnd1(ListNode head, int n) { ListNode curr = head; Map<Integer, ListNode> map = new HashMap<>(); int size = 0; while (curr != null){ map.put(size++, curr); curr = curr.next; } // 0 1->2->3->4->5 // 1 2->3->4->5 // 2 3->4->5 // 3 4->5 // 4 5->null int pre = size - n - 1; int last = size - n + 1; if (pre < 0 && last > size - 1) //[1] 1 return null; if (pre < 0 ) head = map.get(last); //[1,2] 2 if (last > size - 1) map.get(pre).next = null; // [1,2] 1 if (pre >= 0 && last <= size - 1) map.get(pre).next = map.get(last); return head; } //双指针 public static ListNode removeNthFromEnd2(ListNode head, int n){ ListNode dummy = new ListNode(0); dummy.next = head;// 1,2,3,4,5 2 ListNode left = dummy; ListNode right = dummy; while (n + 1 > 0) { right = right.next; n--; } while (right != null){ left = left.next; right = right.next; } left.next = left.next.next; return dummy.next; } }
true
1695c4f662828d38c816a79923242068d16e25e1
Java
broeschi/Versuch1307
/src/converter/ResultatConverter.java
ISO-8859-3
4,061
2.6875
3
[]
no_license
package converter; import java.util.HashMap; import java.util.Map; import com.healthmarketscience.jackcess.Row; import Person.Person; import Person.Resultat; /** * Klasse zur Konvertierung der Resultatdaten zwischen DB und Javamodell * * @author Ruedi Broger */ public class ResultatConverter { /** * Daten aus Access transformieren * * @author Ruedi Broger * @param row auslesen der Tabellenzeilen * @return persnliche Daten aus der DB */ public Resultat dbToModelR(Row row) { Integer resId = (Integer) row.get("res_id"); Integer jahr = (Integer) row.get("resJahr"); Integer resAdrref = (Integer) row.get("resAdrref"); Integer resWfRefOp = (Integer) row.get("resWafRef_OP"); Integer resWfRefFs = (Integer) row.get("resWafRef_FS"); Integer resAlter = (Integer) row.get("resAlter"); Integer resLimRef = (Integer) row.get("resLimref"); Integer resOp = (Integer) row.get("resResultat_OP"); Integer resWhg1 = (Integer) row.get("resResultat_OP_Whg_1"); Integer resWhg2 = (Integer) row.get("resResultat_OP_Whg_2"); Integer resAnzNullerOp = (Integer) row.get("resAnzahlNuller"); Integer resAnzNullerWhg1 = (Integer) row.get("resAnzahlNuller"); Integer resAnzNullerWhg2 = (Integer) row.get("resAnzahlNuller"); Integer resFs = (Integer) row.get("resResultat_FS"); Integer resFigFs = (Integer) row.get("resFigurentreffer_FS"); Resultat r = new Resultat(resId, jahr, resAdrref, resWfRefOp, resWfRefFs, resAlter, resLimRef, resOp, resWhg1, resWhg2, resAnzNullerOp, resAnzNullerWhg1, resAnzNullerWhg2, resFs, resFigFs); return r; } /** * Resultate Daten aus gui in das Datenbankformat konvertieren * * @author Rudolf Broger * @param Resultat * @return */ public static Map<String, Object> convertToMap(Resultat resultat, Integer a) { Map<String, Object> map = new HashMap<>(); map.put("res_id", resultat.getRes_id().get()); map.put("resJahr", util.DateUtil.getYear()); // map.put("resJahr", resultat.getResJahr()); map.put("resAdrref", resultat.getResAdrref().get()); map.put("ResWafRef_OP", resultat.getResWfRefOp().get()); map.put("resWafRef_FS", resultat.getResWfRefFs().get()); map.put("resAlter", a); map.put("resLimref", resultat.getResLimRef().get()); map.put("resResultat_OP", resultat.getResOp().get()); map.put("resResultat_OP_Whg_1", resultat.getResWhg1().get()); map.put("resResultat_OP_Whg_2", resultat.getResWhg2().get()); map.put("resAnzahlNuller", resultat.getResAnzNullerOp().get()); map.put("resAnzahlNuller_Whg_1", resultat.getResAnzNullerOp().get()); map.put("resAnzahlNuller_Whg_2", resultat.getResAnzNullerOp().get()); map.put("resResultat_FS", resultat.getResFs().get()); map.put("resFigurentreffer_FS", resultat.getResFigFs().get()); return map; } public static Map<String, Object> convertToMap(Resultat resultat) { Map<String, Object> map = new HashMap<>(); map.put("res_id", resultat.getRes_id().get()); map.put("resJahr", util.DateUtil.getYear()); // map.put("resJahr", resultat.getResJahr()); map.put("resAdrref", resultat.getResAdrref().get()); map.put("ResWafRef_OP", resultat.getResWfRefOp().get()); map.put("resWafRef_FS", resultat.getResWfRefFs().get()); map.put("resAlter", resultat.getResAlter().get()); map.put("resLimref", resultat.getResLimRef().get()); map.put("resResultat_OP", resultat.getResOp().get()); map.put("resResultat_OP_Whg_1", resultat.getResWhg1().get()); map.put("resResultat_OP_Whg_2", resultat.getResWhg2().get()); map.put("resAnzahlNuller", resultat.getResAnzNullerOp().get()); map.put("resAnzahlNuller_Whg_1", resultat.getResAnzNullerOp().get()); map.put("resAnzahlNuller_Whg_2", resultat.getResAnzNullerOp().get()); map.put("resResultat_FS", resultat.getResFs().get()); map.put("resFigurentreffer_FS", resultat.getResFigFs().get()); return map; } public static Map<String, Object> convertToMap(Integer adrId) { // TODO Auto-generated method stub return null; } }
true
ae5623e3bcfc7f3bd8e92f19dd25ae638ff46e99
Java
Cenyijin/interview-assignments
/java/src/main/java/com/cx/shorturl/app/service/impl/ShortUrlServiceImpl.java
UTF-8
3,434
2.703125
3
[]
no_license
package com.cx.shorturl.app.service.impl; import com.cx.shorturl.app.data.ShortUrl; import com.cx.shorturl.app.id.IdGenerator; import com.cx.shorturl.app.service.ShortUrlService; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.RemovalListener; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; import java.util.concurrent.*; public class ShortUrlServiceImpl implements ShortUrlService, InitializingBean { private IdGenerator idGenerator; public ShortUrlServiceImpl(IdGenerator idGenerator) { this.idGenerator = idGenerator; } @Value("${shorturl.cached.max:5000000}") private int maxUriCached; private ConcurrentMap<String, ShortUrl> shortUrlMap = new ConcurrentHashMap<>(); private BlockingQueue<String> shortUrlQueue = new LinkedBlockingDeque<>(); private Cache<String, ShortUrl> cahced; private ExecutorService singlePool = Executors.newSingleThreadExecutor(); @Override public String generatorShortUrl(String longUrl) { ShortUrl url = null; try { url = cahced.get(longUrl, () -> { if (shortUrlQueue.size() == 0){ synchronized (this){ if (shortUrlQueue.size() == 0){ singlePool.execute(() -> { //预生成1000个 for(int i=0; i<1000; i++){ long id = idGenerator.incrId(); String shortStr = toBase62(id); shortUrlQueue.add(shortStr); } }); } } } String str = shortUrlQueue.take(); ShortUrl shortUrl = new ShortUrl(str, longUrl); shortUrlMap.put(str, shortUrl); return shortUrl; }); } catch (Exception e) { throw new RuntimeException(e); } return url.getShortUrl(); } @Override public String getLongUrl(String shortUrl) { ShortUrl tinyUrl = shortUrlMap.get(shortUrl); if (null == tinyUrl) { return null; } return tinyUrl.getLongUrl(); } @Override public void afterPropertiesSet() throws Exception { cahced = CacheBuilder.newBuilder() .maximumSize(maxUriCached) .removalListener((RemovalListener<String, ShortUrl>) notification -> { ShortUrl shortUrl = notification.getValue(); if (null != shortUrl) { shortUrlMap.remove(shortUrl.getShortUrl()); } }) .expireAfterWrite(Long.MAX_VALUE, TimeUnit.DAYS).build(); } private static final String str = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; /** * 只要num不超过 281474976710656 62的8次方,就可以保证位数在8位 */ public String toBase62(long num) { StringBuilder sb = new StringBuilder(); while(num > 0){ int i = (int) (num % 62); sb.append(str.charAt(i)); num /= 62; } return sb.reverse().toString(); } }
true
3407b4ff819833e00d163efc338d629e9ce5836d
Java
Sebastian-Noren/PoliceSystem
/src/main/java/pust/model/entity/Person.java
UTF-8
2,673
2.484375
2
[]
no_license
package pust.model.entity; import pust.model.administrative_functions.application_functions.Identification; import pust.model.administrative_functions.report_system.report.CrimeReport; import pust.model.administrative_functions.report_system.record.Record; import pust.model.enumerations.Gender; public abstract class Person { private String firstName; private String surname; private PersonalNumber personalNumber; private Address address; private Record crimeRecord; private int height; private Identification identification; private String phoneNumber; private Gender gender; private boolean isWanted; private boolean isMissing; private boolean inCustody; private boolean isSuspect; Person( String firstName, String surname, PersonalNumber personalNumber, Address address, Record crimeRecord, int height, Identification identification, String phoneNumber, Gender gender, boolean isWanted, boolean isMissing, boolean inCustody, boolean isSuspect ) { this.firstName = firstName; this.surname = surname; this.personalNumber = personalNumber; this.address = address; this.crimeRecord = crimeRecord; this.height = height; this.identification = identification; this.phoneNumber = phoneNumber; this.gender = gender; this.isWanted = isWanted; this.isMissing = isMissing; this.inCustody = inCustody; this.isSuspect = isSuspect; } public String getFirstName() { return firstName; } public String getSurname() { return surname; } public PersonalNumber getPersonalNumber() { return personalNumber; } public Address getAddress() { return address; } public Record getCrimeRecord() { return crimeRecord; } public int getHeight() { return height; } public Identification getIdentification() { return identification; } public String getPhoneNumber() { return phoneNumber; } public void setPersonalNumber(PersonalNumber personalNumber) { this.personalNumber = personalNumber; } public Gender getGender() { return gender; } public boolean isWanted() { return isWanted; } public boolean isMissing() { return isMissing; } public boolean isInCustody() { return inCustody; } public boolean isSuspect() { return isSuspect; } }
true
123e4b754f3dbe812f9d8db06f9d0d161985541d
Java
abhi8panmand/TvShowApp
/app/src/main/java/com/gravity/tvshows/API/ApiClient.java
UTF-8
1,835
2.28125
2
[]
no_license
package com.gravity.tvshows.API; import android.app.Activity; import com.readystatesoftware.chuck.ChuckInterceptor; import java.net.CookieManager; import java.net.CookiePolicy; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.internal.JavaNetCookieJar; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; public class ApiClient { private static Retrofit retrofit = null; public static Retrofit getClient(Activity activity) { if (retrofit == null) { CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient.Builder oktHttpClient = new OkHttpClient.Builder() .connectTimeout(120, TimeUnit.MINUTES) .writeTimeout(120, TimeUnit.MINUTES) .readTimeout(120, TimeUnit.MINUTES) .addInterceptor(new ConnectivityInterceptor(activity)) // chuck remove .addInterceptor(new ChuckInterceptor(activity)) .cookieJar(new JavaNetCookieJar(cookieManager)); oktHttpClient.addInterceptor(logging); retrofit = new Retrofit.Builder() .baseUrl(WebService.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(oktHttpClient.build()) .build(); } return retrofit; } }
true
86c1c90979496d639eb61e44e9e2d5e87a9e052d
Java
nginer/CloudWeb
/src/testweb/vo/Admin.java
UTF-8
1,002
2.140625
2
[]
no_license
package testweb.vo; public class Admin { private String admin_ID; private String admin_name; private String time_regist; private String time_login; private String email; private String password; public String getAdmin_ID() { return admin_ID; } public void setAdmin_ID(String admin_ID) { this.admin_ID = admin_ID; } public String getAdmin_name() { return admin_name; } public void setAdmin_name(String admin_name) { this.admin_name = admin_name; } public String getTime_regist() { return time_regist; } public void setTime_regist(String time_regist) { this.time_regist = time_regist; } public String getTime_login() { return time_login; } public void setTime_login(String time_login) { this.time_login = time_login; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
true
bb2845ded50aa1de5dda20965d63d6312c923049
Java
asanka88/Learning
/Read_Data_Sources/ReadDataSources/src/main/java/org/wso2/carbon/am/internal/Util.java
UTF-8
415
1.671875
2
[]
no_license
package org.wso2.carbon.am.internal; import org.wso2.carbon.ndatasource.core.DataSourceService; public class Util { private static DataSourceService dataSourceAdminService; public static DataSourceService getNDataService() { return dataSourceAdminService; } public static synchronized void setNDataService(DataSourceService realmSer) { dataSourceAdminService= realmSer; } }
true
eb70463ee5b339bba94ba5f08dda1ec414a884b4
Java
Nesomar/facisa-plp-162
/Projeto 1 - Estágio 1/Analisador.java
UTF-8
17,126
2.921875
3
[]
no_license
/* Generated By:JavaCC: Do not edit this line. Analisador.java */ public class Analisador implements AnalisadorConstants { /*impressão dos tokens recebidos como entrada */ public void processa() throws Exception { while (true) { Token t = getNextToken(); String nomeToken = tokenImage[t.kind]; System.out.println(nomeToken); if (t.kind == ponto_virg) /* para de ler até encontrar um ponto e vírgula */ break; } } /* método main que recebe a expressão e chama o método acima */ public static void main(String[] args) { System.out.print("Input:"); Analisador analisador = new Analisador(System.in); try { analisador.processa(); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } /*Gramatina Lexical Inicio*/ /*Sintatica INICIO*/ final public void Programa() throws ParseException { Program(); jj_consume_token(0); } final public void Program() throws ParseException { jj_consume_token(PROGRAMA); jj_consume_token(IDENTIFICADOR); jj_consume_token(DPARENTE); Block(); jj_consume_token(LPARENTE); jj_consume_token(0); } final public void Block() throws ParseException { Variable_Declaration_Part(); Statement_Part(); } final public void Variable_Declaration_Part() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 0: jj_consume_token(0); break; case VAR: jj_consume_token(VAR); Variable_Declaration(); jj_consume_token(PONTO_VIRGULA); label_1: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFICADOR: ; break; default: jj_la1[0] = jj_gen; break label_1; } Variable_Declaration(); jj_consume_token(PONTO_VIRGULA); } break; default: jj_la1[1] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } final public void Variable_Declaration() throws ParseException { jj_consume_token(IDENTIFICADOR); label_2: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case VIRGULA: ; break; default: jj_la1[2] = jj_gen; break label_2; } jj_consume_token(VIRGULA); jj_consume_token(IDENTIFICADOR); } jj_consume_token(DOIS_PONTOS); Type(); } final public void Type() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case TYPE: jj_consume_token(TYPE); break; case ARRAY: ArrayType(); break; default: jj_la1[3] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } final public void ArrayType() throws ParseException { jj_consume_token(ARRAY); jj_consume_token(LCOLCHETES); IndexRange(); jj_consume_token(DCOLCHETES); jj_consume_token(OF); jj_consume_token(TYPE); } final public void IndexRange() throws ParseException { jj_consume_token(NUMERO); jj_consume_token(PONTOS); jj_consume_token(NUMERO); } final public void Statement_Part() throws ParseException { Compound_Statement(); } final public void Compound_Statement() throws ParseException { jj_consume_token(BEGIN); Statement(); label_3: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PONTO_VIRGULA: ; break; default: jj_la1[4] = jj_gen; break label_3; } jj_consume_token(PONTO_VIRGULA); Statement(); } jj_consume_token(END); } final public void Statement() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case READ: case IDENTIFICADOR: Simple_Statement(); break; case BEGIN: case IF: case WHILE: Structured_Statement(); break; default: jj_la1[5] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } final public void Simple_Statement() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFICADOR: Assignment_Statement(); break; case READ: Read_Statement(); break; default: jj_la1[6] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } final public void Assignment_Statement() throws ParseException { Variable(); jj_consume_token(ATRIBUICAO); Expression(); } final public void Read_Statement() throws ParseException { jj_consume_token(READ); jj_consume_token(LPARENTE); Variable(); label_4: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case VIRGULA: ; break; default: jj_la1[7] = jj_gen; break label_4; } jj_consume_token(VIRGULA); Variable(); } jj_consume_token(DPARENTE); } final public void Structured_Statement() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case BEGIN: Compound_Statement(); break; case IF: If_Statement(); break; case WHILE: While_Statement(); break; default: jj_la1[8] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } final public void If_Statement() throws ParseException { jj_consume_token(IF); Expression(); jj_consume_token(THEN); Statement(); If_Statement_Fatoracao(); } final public void If_Statement_Fatoracao() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case ELSE: jj_consume_token(ELSE); Statement(); break; default: jj_la1[9] = jj_gen; } } final public void While_Statement() throws ParseException { jj_consume_token(WHILE); Expression(); jj_consume_token(DO); Statement(); } final public void Expression() throws ParseException { Simple_Expression(); Expression_Fatoracao(); } final public void Expression_Fatoracao() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case MAIORQUE: case MENORQUE: case MAIORIGUAL: case MENORIGUAL: case IGUAL: case DIFERENTE: case OR: case AND: Relational_Operator(); Simple_Expression(); break; default: jj_la1[10] = jj_gen; } } final public void Simple_Expression() throws ParseException { Sign(); Term(); label_5: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPERADOR_SOMA: case OPERADOR_SUBTRACAO: ; break; default: jj_la1[11] = jj_gen; break label_5; } Adding_Operator(); Term(); } } final public void Term() throws ParseException { Factor(); label_6: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPERADOR_DIVISAO: case OPERADOR_MULTIPLICACAO: ; break; default: jj_la1[12] = jj_gen; break label_6; } Multiplying_Operator(); Factor(); } } final public void Factor() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFICADOR: Variable(); break; case NUMERO: case ASPAS_SIMPLES: case ASPAS_DUPLA: Constant(); break; case LPARENTE: jj_consume_token(LPARENTE); Expression(); jj_consume_token(DPARENTE); break; case NOT: jj_consume_token(NOT); Factor(); break; default: jj_la1[13] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } final public void Relational_Operator() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IGUAL: jj_consume_token(IGUAL); break; case DIFERENTE: jj_consume_token(DIFERENTE); break; case MENORQUE: jj_consume_token(MENORQUE); break; case MENORIGUAL: jj_consume_token(MENORIGUAL); break; case MAIORIGUAL: jj_consume_token(MAIORIGUAL); break; case MAIORQUE: jj_consume_token(MAIORQUE); break; case OR: jj_consume_token(OR); break; case AND: jj_consume_token(AND); break; default: jj_la1[14] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } final public void Sign() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPERADOR_SOMA: jj_consume_token(OPERADOR_SOMA); break; case OPERADOR_SUBTRACAO: jj_consume_token(OPERADOR_SUBTRACAO); break; default: jj_la1[15] = jj_gen; } } final public void Adding_Operator() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPERADOR_SOMA: jj_consume_token(OPERADOR_SOMA); break; case OPERADOR_SUBTRACAO: jj_consume_token(OPERADOR_SUBTRACAO); break; default: jj_la1[16] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } final public void Multiplying_Operator() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OPERADOR_MULTIPLICACAO: jj_consume_token(OPERADOR_MULTIPLICACAO); break; case OPERADOR_DIVISAO: jj_consume_token(OPERADOR_DIVISAO); break; default: jj_la1[17] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } final public void Variable() throws ParseException { jj_consume_token(IDENTIFICADOR); Indexed_Variable(); } final public void Indexed_Variable() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LCOLCHETES: jj_consume_token(LCOLCHETES); Expression(); jj_consume_token(DCOLCHETES); break; default: jj_la1[18] = jj_gen; } } final public void Constant() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case NUMERO: jj_consume_token(NUMERO); break; case ASPAS_SIMPLES: case ASPAS_DUPLA: Character_Constant(); break; case IDENTIFICADOR: jj_consume_token(IDENTIFICADOR); break; default: jj_la1[19] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } final public void Letter_or_Digit() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LETRAS: jj_consume_token(LETRAS); break; case DIGITOS: jj_consume_token(DIGITOS); break; default: jj_la1[20] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } final public void Character_Constant() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case ASPAS_SIMPLES: jj_consume_token(ASPAS_SIMPLES); Letter_or_Digit(); jj_consume_token(ASPAS_SIMPLES); break; case ASPAS_DUPLA: jj_consume_token(ASPAS_DUPLA); Letter_or_Digit(); label_7: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DIGITOS: case LETRAS: ; break; default: jj_la1[21] = jj_gen; break label_7; } Letter_or_Digit(); } jj_consume_token(ASPAS_DUPLA); break; default: jj_la1[22] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } /** Generated Token Manager. */ public AnalisadorTokenManager token_source; SimpleCharStream jj_input_stream; /** Current token. */ public Token token; /** Next token. */ public Token jj_nt; private int jj_ntk; private int jj_gen; final private int[] jj_la1 = new int[23]; static private int[] jj_la1_0; static private int[] jj_la1_1; static private int[] jj_la1_2; static { jj_la1_init_0(); jj_la1_init_1(); jj_la1_init_2(); } private static void jj_la1_init_0() { jj_la1_0 = new int[] {0x0,0x1,0x0,0x20,0x0,0x400080,0x0,0x0,0x400080,0x8000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,}; } private static void jj_la1_init_1() { jj_la1_1 = new int[] {0x400000,0x4000,0x0,0x40000,0x0,0x408020,0x400020,0x0,0x8000,0x0,0xc0000000,0x3000000,0xc000000,0x600000,0xc0000000,0x3000000,0x3000000,0xc000000,0x0,0x600000,0x180000,0x180000,0x0,}; } private static void jj_la1_init_2() { jj_la1_2 = new int[] {0x0,0x0,0x10000,0x0,0x8000,0x0,0x0,0x10000,0x0,0x0,0x6f,0x0,0x0,0x6180,0x6f,0x0,0x0,0x0,0x400,0x6000,0x0,0x0,0x6000,}; } /** Constructor with InputStream. */ public Analisador(java.io.InputStream stream) { this(stream, null); } /** Constructor with InputStream and supplied encoding */ public Analisador(java.io.InputStream stream, String encoding) { try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } token_source = new AnalisadorTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 23; i++) jj_la1[i] = -1; } /** Reinitialise. */ public void ReInit(java.io.InputStream stream) { ReInit(stream, null); } /** Reinitialise. */ public void ReInit(java.io.InputStream stream, String encoding) { try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 23; i++) jj_la1[i] = -1; } /** Constructor. */ public Analisador(java.io.Reader stream) { jj_input_stream = new SimpleCharStream(stream, 1, 1); token_source = new AnalisadorTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 23; i++) jj_la1[i] = -1; } /** Reinitialise. */ public void ReInit(java.io.Reader stream) { jj_input_stream.ReInit(stream, 1, 1); token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 23; i++) jj_la1[i] = -1; } /** Constructor with generated Token Manager. */ public Analisador(AnalisadorTokenManager tm) { token_source = tm; token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 23; i++) jj_la1[i] = -1; } /** Reinitialise. */ public void ReInit(AnalisadorTokenManager tm) { token_source = tm; token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 23; i++) jj_la1[i] = -1; } private Token jj_consume_token(int kind) throws ParseException { Token oldToken; if ((oldToken = token).next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; if (token.kind == kind) { jj_gen++; return token; } token = oldToken; jj_kind = kind; throw generateParseException(); } /** Get the next Token. */ final public Token getNextToken() { if (token.next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; jj_gen++; return token; } /** Get the specific Token. */ final public Token getToken(int index) { Token t = token; for (int i = 0; i < index; i++) { if (t.next != null) t = t.next; else t = t.next = token_source.getNextToken(); } return t; } private int jj_ntk() { if ((jj_nt=token.next) == null) return (jj_ntk = (token.next=token_source.getNextToken()).kind); else return (jj_ntk = jj_nt.kind); } private java.util.List<int[]> jj_expentries = new java.util.ArrayList<int[]>(); private int[] jj_expentry; private int jj_kind = -1; /** Generate ParseException. */ public ParseException generateParseException() { jj_expentries.clear(); boolean[] la1tokens = new boolean[83]; if (jj_kind >= 0) { la1tokens[jj_kind] = true; jj_kind = -1; } for (int i = 0; i < 23; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { if ((jj_la1_0[i] & (1<<j)) != 0) { la1tokens[j] = true; } if ((jj_la1_1[i] & (1<<j)) != 0) { la1tokens[32+j] = true; } if ((jj_la1_2[i] & (1<<j)) != 0) { la1tokens[64+j] = true; } } } } for (int i = 0; i < 83; i++) { if (la1tokens[i]) { jj_expentry = new int[1]; jj_expentry[0] = i; jj_expentries.add(jj_expentry); } } int[][] exptokseq = new int[jj_expentries.size()][]; for (int i = 0; i < jj_expentries.size(); i++) { exptokseq[i] = jj_expentries.get(i); } return new ParseException(token, exptokseq, tokenImage); } /** Enable tracing. */ final public void enable_tracing() { } /** Disable tracing. */ final public void disable_tracing() { } }
true
cf77c9eb0849cf8285c8529ab226ed52ea432955
Java
reverseengineeringer/com.yelp.android
/src/bolts/j.java
UTF-8
258
1.5
2
[]
no_license
package bolts; public abstract interface j<TTaskResult, TContinuationResult> { public abstract TContinuationResult then(k<TTaskResult> paramk); } /* Location: * Qualified Name: bolts.j * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
95e4345101edf2fc96d105ac996ff1471aef025d
Java
purushottam-kr-singh/Practice_code
/Practice_Test/src/com/company/main/stack/NearestSmallerElementRight.java
UTF-8
1,665
4.03125
4
[]
no_license
package com.company.main.stack; import java.util.Scanner; import java.util.Stack; public class NearestSmallerElementRight { /** This method accept the input as array of integer and find the neares * smaller element to the right of each element and return the value for * each element * @param nums input array of integer * @return array of integer having the nearest element of each element in the given array */ public static int[] nearestSmallerElementRight(int[] nums) { int length = nums.length; int[] res = new int[length]; Stack<Integer> stack = new Stack<>(); for (int i = length - 1; i >= 0; i--) { if (stack.empty()) { res[i] = -1; } else if (nums[i] > stack.peek()) { res[i] = stack.peek(); } else { while (!stack.empty() && stack.peek() >= nums[i]) { stack.pop(); } if (stack.empty()) { res[i] = -1; } else { res[i] = stack.peek(); } } stack.push(nums[i]); } return res; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the number of element"); int size = sc.nextInt(); int[] nums = new int[size]; int index = 0; while (index < size) { nums[index++] = sc.nextInt(); } int[] res = nearestSmallerElementRight(nums); for (int a : res) { System.out.println(a); } } }
true
321c16c31d08c35c70fee4b02acc1645094697a8
Java
kkhalili16/ApiTesing
/src/test/java/utils/Utility.java
UTF-8
1,595
2.65625
3
[]
no_license
package utils; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import com.BaseClassWebDriver; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; public class Utility extends BaseClassWebDriver { public static String getScreenshot(WebDriver driver) { TakesScreenshot ts=(TakesScreenshot)driver; File src=ts.getScreenshotAs(OutputType.FILE); //time String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()); String path="Reports/screenshots/"+timeStamp+".jpg"; // String path="Reports/screenshots/"+System.currentTimeMillis()+".jpg"; File destination=new File(path); try { FileUtils.copyFile(src, destination); } catch (IOException e) { System.out.println("Capture Failed "+e.getMessage()); } return path; } public static String takescreenShot(WebDriver driver) throws IOException { TakesScreenshot ts = (TakesScreenshot) driver; File scrFile = ts.getScreenshotAs(OutputType.FILE); String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(DateFormat.FULL); //.format(new Date()); String img = "image"+timeStamp+".png"; FileUtils.copyFile(scrFile,new File("Reports/screenshots/"+img)); return img; } }
true
fb377bbc7e84b422b1ed841380cb19096c0ed3b0
Java
Guksu/AcademyClass
/chapter11_reference_array/src/Test03/WeekScheduler.java
UTF-8
2,948
3.890625
4
[]
no_license
package Test03; import java.util.Scanner; public class WeekScheduler { Day[] days; Scanner sc; String[] week = {"월","화","수","목","금","토","일"}; public WeekScheduler() { sc = new Scanner(System.in); days = new Day[7]; for (int i=0; i<days.length; i++) { days[i] = new Day(); } } void menu() { System.out.println(); System.out.println("1. 스케줄 생성"); System.out.println("2. 스케줄 삭제"); System.out.println("3. 스케줄 수정"); System.out.println("4. 스케줄 보기"); System.out.println("0. 스케줄러 종료"); } void makeSchedule() { System.out.println("등록할 요일을 입력하시오"); String day = sc.nextLine(); for(int i = 0; i<week.length; i++) { if(day.equals(week[i])) { if(days[i].getSchedule() == null) { System.out.println("스케줄을 입력하세요"); String schedule = sc.nextLine(); days[i].setSchedule(schedule); }else { System.out.println(week[i]+"요일은 이미 스케줄이 있습니다."); } } } } void removeSchedule() { System.out.println("삭제할 요일을 입력하세요"); String remove = sc.nextLine(); for( int i =0; i<week.length; i++) { if(remove.equals(week[i])) { days[i].setSchedule(null); } } } void modifySchedule() { System.out.println("수정할 요일을 입력하세요"); String modify = sc.nextLine(); for( int i =0; i<week.length; i++) { if(modify.equals(week[i])) { if(days[i].getSchedule() != null) { System.out.println("변경할 스케줄을 다시 입력하세요"); String schedule = sc.nextLine(); days[i].setSchedule(schedule); }else { System.out.println("해당 요일에 스케줄이 없으므로 새로운 스케줄을 입력하겠습니까?"); String yes = sc.nextLine(); if(yes.equalsIgnoreCase("yes")) { System.out.println("스케줄을 다시 입력하세요"); String schedule = sc.nextLine(); days[i].setSchedule(schedule); }else { System.out.println("변경된 스케줄이 없습니다."); } } } } } void output() { System.out.println("스케줄 전체 출력"); for (int i = 0; i<days.length; i++) { System.out.println(week[i]+"요일 스케줄"); days[i].output(); } } void exit() { System.out.println("스케줄러를 종료합니다"); sc.close(); System.exit(0); //프로그램 종료 코드 } void run() { while(true) { menu(); System.out.print("작업선택 >>"); int choice= sc.nextInt(); sc.nextLine(); switch(choice) { case 1 : makeSchedule(); break; case 2 : removeSchedule(); break; case 3 : modifySchedule(); break; case 4 : output(); break; case 0 : exit(); break; default : System.out.println("다시 선택하세요"); } } } }
true
b0a3c2b8c156aa3dd0ec383694cfaec08852cdd6
Java
EmanuelGabriel/processos-api
/src/main/java/br/com/meta/projetoapimeta/services/DocumentService.java
UTF-8
1,023
2.15625
2
[]
no_license
package br.com.meta.projetoapimeta.services; import java.time.LocalDate; import java.util.List; import java.util.Optional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import br.com.meta.projetoapimeta.domain.dtos.request.DocumentModelInputRequest; import br.com.meta.projetoapimeta.domain.dtos.response.DocumentModelResponse; public interface DocumentService { DocumentModelResponse criar(DocumentModelInputRequest request); Page<DocumentModelResponse> findAll(Pageable pageable); Optional<DocumentModelResponse> buscarPorId(Long idDocumento); Optional<DocumentModelResponse> buscarPorNumeroProcesso(Integer numeroProcesso); Optional<DocumentModelResponse> buscarPorNomeDocumento(String nomeDocumento); List<DocumentModelResponse> buscarPorDataEstimadaConclusao(LocalDate dataEstimadaConclusaoInicio, LocalDate dataEstimadaConclusaoFim); List<DocumentModelResponse> buscarPorDataCadastro(LocalDate dataCadastroInicial, LocalDate dataCadastroFinal); }
true
5c84a263565dee39bb04e0a3c271945795601fc2
Java
woshiqiang/txt
/app/src/main/java/com/hbck/txt/MainActivity.java
UTF-8
1,991
2.359375
2
[]
no_license
package com.hbck.txt; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import java.io.File; import java.util.List; public class MainActivity extends AppCompatActivity { private ListView listView; private List<TxtBean> listTxt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setTitle("文本阅读器"); init(); } private void init() { listView = (ListView) findViewById(R.id.listView); final ProgressDialog dialog = ProgressDialog.show(this, "", "正在读取...", false, false); dialog.show(); //遍历sd卡,耗时操作,单独放在线程里 new Thread(new Runnable() { @Override public void run() { File file = Environment.getExternalStorageDirectory(); listTxt = TxtTool.listFileTxt(file); dialog.dismiss(); runOnUiThread(new Runnable() { @Override public void run() { MyAdapter adapter = new MyAdapter(MainActivity.this, listTxt); listView.setAdapter(adapter); } }); } }).start(); //列表项点击事件 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(MainActivity.this, ReadTxtActivity.class); intent.putExtra("txtBean", listTxt.get(position)); startActivity(intent); } }); } }
true
995147dbca63f46a5adf193bef0607ea35067a9e
Java
cgnov/pomfocus
/app/src/main/java/com/example/pomfocus/fragments/profile/ProfileFragment.java
UTF-8
10,359
1.726563
2
[]
no_license
package com.example.pomfocus.fragments.profile; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.pomfocus.ParseApp; import com.example.pomfocus.fragments.profile.blocks.ProfileAchievementsFragment; import com.example.pomfocus.fragments.profile.blocks.ProfileButtonFragment; import com.example.pomfocus.fragments.profile.blocks.ProfilePublicInfoFragment; import com.example.pomfocus.fragments.profile.blocks.ProfileRequestFragment; import com.example.pomfocus.fragments.profile.blocks.ProfileSnapshotFragment; import com.example.pomfocus.parse.FriendRequest; import com.example.pomfocus.parse.Focus; import com.example.pomfocus.parse.FocusUser; import com.example.pomfocus.R; import com.example.pomfocus.databinding.FragmentProfileBinding; import com.github.mikephil.charting.data.BarEntry; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseQuery; import com.parse.ParseRelation; import com.parse.ParseUser; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class ProfileFragment extends Fragment { public static final String TAG = "ProfileFragment"; public ParseUser mUser; public List<BarEntry> mPoints; public List<Focus> mFocuses; private int mFullStreak = 0, mWorkweekStreak = 0; private boolean mConfirmedFriend = false; private ProfileSnapshotFragment mProfileSnapshotFragment = null; private ProfileAchievementsFragment mProfileAchievementsFragment = null; private ProfileButtonFragment mProfileButtonFragment = null; private FragmentProfileBinding mBinding; public ProfileFragment(ParseUser user) { this.mUser = user; } public ProfileFragment(ParseUser user, boolean friend) { this.mUser = user; mConfirmedFriend = friend; } @Override public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Implement view binding mBinding = FragmentProfileBinding.inflate(getLayoutInflater(), container, false); return mBinding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Log.i(TAG, "onViewCreated, mFocuses==null: " + (mFocuses==null) + ", mProfileSnapshot==null: " + (mProfileSnapshotFragment==null)); displayRelevantFragments(); } private void displayRelevantFragments() { getChildFragmentManager().beginTransaction() .replace(R.id.flPublicInfo, new ProfilePublicInfoFragment(mUser)) .commit(); if (mUser.getUsername().equals(ParseUser.getCurrentUser().getUsername())) { mProfileButtonFragment = new ProfileButtonFragment(); getChildFragmentManager().beginTransaction() .replace(R.id.flButtons, mProfileButtonFragment) .commit(); displayFriendPrivileges(); } else { if (mConfirmedFriend) { displayFriendPrivileges(); getChildFragmentManager().beginTransaction() .replace(R.id.flRequest, new ProfileRequestFragment(mUser, FriendRequest.PROCESSED, null)) .commit(); } else { checkFriendStatus(); } } } private void displayFriendPrivileges() { mBinding.pbProfile.setVisibility(View.GONE); mProfileSnapshotFragment = new ProfileSnapshotFragment(mUser.getInt(FocusUser.KEY_TOTAL)); getChildFragmentManager().beginTransaction().replace(R.id.flSnapshot, mProfileSnapshotFragment, ProfileSnapshotFragment.TAG).commit(); mProfileAchievementsFragment = new ProfileAchievementsFragment(); getChildFragmentManager().beginTransaction().replace(R.id.flAchievements, mProfileAchievementsFragment).commit(); if (mFocuses == null) { findFullFocusHistory(); } else { displayInfo(); } } private void findFullFocusHistory() { Log.i(TAG, "Querying full focus history from Parse for user " + mUser.getUsername()); ParseQuery<Focus> fullHistoryQuery = ParseQuery.getQuery(Focus.class); fullHistoryQuery.whereEqualTo(Focus.KEY_CREATOR, mUser); fullHistoryQuery.addDescendingOrder(Focus.KEY_CREATED_AT); fullHistoryQuery.findInBackground(new FindCallback<Focus>() { @Override public void done(List<Focus> focuses, ParseException e) { if (e != null) { Log.e(TAG, "Issue getting focus history", e); mFocuses = null; } else { mFocuses = focuses; countCurrentStreaks(); displayInfo(); } } }); } public void countCurrentStreaks() { final Calendar toCheck = Calendar.getInstance(); final Calendar focusTime = Calendar.getInstance(); boolean fullUnbroken = true; boolean workweekUnbroken = true; int focusIndex = 0; while(workweekUnbroken && (focusIndex < mFocuses.size())) { focusTime.setTime(mFocuses.get(focusIndex).getCreatedAt()); if (focusTime.get(Calendar.DAY_OF_YEAR) == toCheck.get(Calendar.DAY_OF_YEAR)) { if(!isWeekend(focusTime)) { mWorkweekStreak++; } if(fullUnbroken) { mFullStreak++; } toCheck.add(Calendar.DAY_OF_YEAR, -1); } else if (focusTime.compareTo(toCheck) < 0) { if (!isWeekend(toCheck)) { workweekUnbroken = false; } fullUnbroken = false; } focusIndex++; } mProfileAchievementsFragment.mWorkweekStreak = mWorkweekStreak; } public void displayInfo() { Log.i(TAG, "displayInfo"); mProfileSnapshotFragment.setStreak(mFullStreak); if (mProfileAchievementsFragment != null) { mProfileAchievementsFragment.countTotals(mFocuses, mUser.getUsername().equals(ParseApp.currentUsername())); } if (mProfileButtonFragment != null) { mProfileButtonFragment.enableHistory(); } } public static boolean isWeekend(Calendar calendar) { boolean isSaturday = calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY; boolean isSunday = calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY; return isSaturday || isSunday; } private void checkFriendStatus() { ParseQuery<FriendRequest> sentRequest = ParseQuery.getQuery(FriendRequest.class); sentRequest.whereEqualTo(FriendRequest.KEY_TO, ParseUser.getCurrentUser()); sentRequest.whereEqualTo(FriendRequest.KEY_FROM, mUser); ParseQuery<FriendRequest> receivedRequest = ParseQuery.getQuery(FriendRequest.class); receivedRequest.whereEqualTo(FriendRequest.KEY_FROM, ParseUser.getCurrentUser()); receivedRequest.whereEqualTo(FriendRequest.KEY_TO, mUser); List<ParseQuery<FriendRequest>> queryList = new ArrayList<>(); queryList.add(sentRequest); queryList.add(receivedRequest); ParseQuery<FriendRequest> fullQuery = ParseQuery.or(queryList); fullQuery.include(FriendRequest.KEY_FROM); fullQuery.findInBackground(new FindCallback<FriendRequest>() { @Override public void done(List<FriendRequest> friendRequests, ParseException e) { if (e != null) { Log.e(TAG, "Error getting friend request status", e); } else { startRequestFragment(friendRequests); } } }); } private void startRequestFragment(List<FriendRequest> friendRequests) { Log.i(TAG, "Checking friend status"); int status = ProfileRequestFragment.NONE; FriendRequest request = null; if (friendRequests.size() > 0) { request = friendRequests.get(0); status = request.getStatus(); if (request.getFromUsername().equals(ParseApp.currentUsername())) { if (status == FriendRequest.PENDING) { status = ProfileRequestFragment.SENT; } else if (status == FriendRequest.ACCEPTED) { processAcceptance(request); status = FriendRequest.PROCESSED; } } } Log.i(TAG, "Friend status of " + status); if ((status == FriendRequest.PROCESSED) || (status == FriendRequest.ACCEPTED)) { displayFriendPrivileges(); } else { displayNotFriends(); } getChildFragmentManager() .beginTransaction() .replace(R.id.flRequest, new ProfileRequestFragment(mUser, status, request)) .commit(); } private void displayNotFriends() { if (mUser.getBoolean(FocusUser.KEY_PRIVATE)) { mBinding.pbProfile.setVisibility(View.GONE); Toast.makeText(getContext(), "This user is private. Become friends to see their focus details and achievements", Toast.LENGTH_LONG).show(); } else { displayFriendPrivileges(); } } private void processAcceptance(FriendRequest friendRequest) { ParseRelation<ParseUser> friends = ParseUser.getCurrentUser().getRelation(FocusUser.KEY_FRIENDS); friends.add(FriendRequest.makePointer(friendRequest.getFromUser())); ParseUser.getCurrentUser().saveInBackground(ParseApp.makeSaveCallback(TAG, "Error saving new accepted friend")); // Update friend request to have processed and accepted friendRequest.setStatus(FriendRequest.PROCESSED); friendRequest.saveInBackground(ParseApp.makeSaveCallback(TAG, "Error saving processed friend request")); } }
true
81927584bf7767071142c471609b7663726c5e1b
Java
esalty/JavaCourse5GoIT
/src/module9/testCore/Top.java
UTF-8
170
1.882813
2
[]
no_license
package module9.testCore; /** * Created by GodMod on 2/11/2017. */ public class Top { public Top(String s) { System.out.print("B"); } public Top() { } }
true
9e4402af8650523862588284228ab4bf2ae0922f
Java
visalim/ServletProject
/src/com/phonebook/domain/Contact.java
UTF-8
273
2.15625
2
[]
no_license
package com.phonebook.domain; public interface Contact { int getId(); void setId(int id); String getName(); void setName(String name); String getEmail(); void setEmail(String email); String getMobile(); void setMobile(String mobile); }
true
4d1a24a8c62b703e5aca69ccb3d6766a00def505
Java
pmushegh/junit5_for_ui_testing
/src/test/java/test_junit5/TestClassRepeatedTest.java
UTF-8
430
2.328125
2
[]
no_license
package test_junit5; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.TestInfo; public class TestClassRepeatedTest { @RepeatedTest(value = 3, name = "{displayName} -> {currentRepetition}/{totalRepetitions}") @DisplayName("Repeated test name") public void someTest(TestInfo testInfo) { System.out.println(testInfo.getDisplayName()); } }
true
0c9a1e12e73795cb2ff896696df15b3919c33bbf
Java
drobishman/TimeToGo
/app/src/main/java/it/curdrome/timetogo/connection/atac/IdPalinaAsyncTask.java
UTF-8
7,619
2.265625
2
[]
no_license
package it.curdrome.timetogo.connection.atac; import android.os.AsyncTask; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import it.curdrome.timetogo.model.Transit; import it.curdrome.timetogo.xmlrpc.XMLRPCClient; import it.curdrome.timetogo.xmlrpc.XMLRPCException; /** * Created by adrian on 20/01/2017. * * class used to calculate using Roma.mobilita API * the id pallina of a Tansit bus stop * * @author Curreli Alessandro * @version 2 */ public class IdPalinaAsyncTask extends AsyncTask<String, String, String> { // sets response public IdPalinaResponse response = null; private Transit transit; private List<String> paline = new ArrayList<>();// array containing palline candidate /** * constructor method * @param transit transit to calculate the id palina */ public IdPalinaAsyncTask(Transit transit){ this.transit = transit; } /** * default method overrided to connect to muovi.roma * autenticate * use smartSearch service * parse responses and * @param strings default parameter * @return a debug string to verify if calculated id is ok */ @Override protected String doInBackground(String... strings) { String stringUrlAuth = "http://muovi.roma.it/ws/xml/autenticazione/1"; String stringUrlPalina = "http://muovi.roma.it/ws/xml/paline/7"; String key = "8T3U52HFT48N5GRnvImL4hF0rRChrKg9";// key to authenticate String query = transit.getDepartureStop(); // splits name in 2 parts uses the second for query if(query.contains("-")) { String splitted[] = query.split("-"); query = splitted[1]; } JSONObject jsonResult;//new JSONObject(); try { // token request XMLRPCClient authClient = new XMLRPCClient(new URL(stringUrlAuth)); String token = (String) authClient.call("autenticazione.Accedi", key, ""); //get palina using the name of the bus stop or part of it XMLRPCClient getPalina = new XMLRPCClient(new URL(stringUrlPalina)); HashMap result = (HashMap) getPalina.call("paline.SmartSearch", token, query); jsonResult = new JSONObject(result); JSONObject risposta = jsonResult.getJSONObject("risposta"); //check if tipo is NOT ambiguous if(risposta.getString("tipo").matches("Palina")){ //here i have found the id_palina transit.setIdPalina(risposta.getString("id_palina")); }else if (risposta.getString("tipo").matches("Ambiguo")){ //if tipo is "ambiguo" JSONArray paline_semplice = risposta.getJSONArray("paline_semplice"); if (!paline_semplice.isNull(0)) { //if paline_semplice isn't void for (int i = 0; i < paline_semplice.length(); i++) { //for each item in paline_semplice paline.add(paline_semplice.getJSONObject(i).getString("id_palina")); //add all the id_palina found in paline for future filtering } }else { JSONArray paline_extra = risposta.getJSONArray("paline_extra"); //if the paline_semplice is void, i'm looking for the paline_extra array if (!paline_extra.isNull(0)){ for (int i = 0; i < paline_extra.length(); i++) { //for each item in paline_extra paline.add(paline_extra.getJSONObject(i).getString("id_palina")); //add all the id_palina found in paline for future filtering } } } //start the filtering on paline for (int i = 0; i < paline.size(); i++) { //for each id_palina in paline XMLRPCClient getLinee = new XMLRPCClient(new URL(stringUrlPalina)); HashMap palinaLinee = (HashMap) getLinee.call("paline.PalinaLinee", token, paline.get(i),"ITA"); JSONObject palinaLineeJson = new JSONObject(palinaLinee); JSONArray linee = palinaLineeJson.getJSONArray("risposta"); //ask which line passing by id_palina for (int j = 0; j < linee.length(); j++) { //for each line boolean found=false; if (linee.getJSONObject(j).getString("linea").equalsIgnoreCase(transit.getLine())) //if line match found=true; //MATCH FOUND! else if (j==linee.length()&&!found){ //otherwise if haven't found anything paline.remove(i); //remove the item in i position from list paline i--; //now the item in i+1 position is passed in position i, so for non jumping check of "new i" element i reduce i to i-1; } } } for (int i = 0; i < paline.size(); i++){ XMLRPCClient getPrevisioni = new XMLRPCClient(new URL(stringUrlPalina)); HashMap palinePrevisioni = (HashMap) getPrevisioni.call("paline.Previsioni",token,paline.get(i),"ITA"); JSONObject palinePrevisioniJson = new JSONObject(palinePrevisioni); JSONObject rispostaPrevisioni = palinePrevisioniJson.getJSONObject("risposta"); JSONArray primi_per_palina = rispostaPrevisioni.getJSONArray("primi_per_palina"); for (int j = 0; j < primi_per_palina.length() ; j++) { JSONObject primo_per_palina = primi_per_palina.getJSONObject(j); JSONArray arrivi = primo_per_palina.getJSONArray("arrivi"); for (int k = 0; k < arrivi.length(); k++) { if (transit.getLine().matches(arrivi.getJSONObject(k).getString("linea"))){ if (arrivi.getJSONObject(k).has("capolinea")) { if (transit.getHeadsign().equalsIgnoreCase(arrivi.getJSONObject(k).getString("capolinea"))) { return arrivi.getJSONObject(k).getString("id_palina"); } else if(arrivi.getJSONObject(k).getString("capolinea").contains(transit.getHeadsign())){ return arrivi.getJSONObject(k).getString("id_palina"); } } } } } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (XMLRPCException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); transit.setIdPalina(s); Log.d("idPalina", transit.getDepartureStop()+" - "+transit.getIdPalina()); } }
true
984fcedbe0a8718a92659518ce825b33589da8ea
Java
JNKKKK/Rutgers-CS526-Project-Template
/template2/src/main/java/inside/AddTask.java
UTF-8
1,990
2.46875
2
[]
no_license
package inside; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class AddTask */ public class AddTask extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String firstname = request.getParameter("firstname"); String lastname = request.getParameter("lastname"); String netid = request.getParameter("netid"); String email = request.getParameter("email"); if(firstname.isEmpty() || lastname.isEmpty() ||netid.isEmpty() ||email.isEmpty() ) response.sendRedirect("/my-webapp/display"); else{ try { Class.forName("com.mysql.jdbc.Driver" ); } catch (Exception e) { System.err.println("ERROR: failed to load HSQLDB JDBC driver"); e.printStackTrace(System.out); return; } try { Connection connection = DriverManager.getConnection("jdbc:mysql://" + "localhost:3306/list" , "boss", "AAAAAbbbbb888;8"); String queryString = "insert into student (firstname , lastname , email , netid) values(?,?,?,?)"; PreparedStatement statement = connection.prepareStatement(queryString); statement.setString(1,firstname); statement.setString(2,lastname); statement.setString(3,netid); statement.setString(4,email); statement.executeUpdate(); statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(System.out); } response.sendRedirect("/my-webapp/display"); } } }
true
52e4be741565d1cf586a24d9fcca9428870d4b99
Java
supersize/MyProjects
/KimJaeHyeong_1/src/board_dao/BDao.java
UTF-8
8,823
2.3125
2
[]
no_license
package board_dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Timestamp; import java.util.ArrayList; import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; import board_dto.BDto; public class BDao { DataSource datasource; public BDao() { try { Context context = new InitialContext(); datasource = (DataSource)context.lookup("java:comp/env/jdbc/MySQL"); } catch (Exception e) { e.printStackTrace(); } } public void write(String id, String bTitle, String bContent) { Connection conn = null; PreparedStatement pstmt = null; try { String query = "insert into test_board (id, bTitle, bContent, bHit, bGroup, bStep, bIndent) values (?, ?, ?, 0, (select max(bId)+1 from test_board a), 0, 0 )"; conn = datasource.getConnection(); pstmt = conn.prepareStatement(query); pstmt.setString(1, id); pstmt.setString(2, bTitle); pstmt.setString(3, bContent); int rn = pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); }finally{ try { if(pstmt != null) pstmt.close(); if(conn != null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } } } public ArrayList<BDto> list(){ ArrayList<BDto> dtos = new ArrayList<>(); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = datasource.getConnection(); String query = "select bId, id, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent from test_board order by bGroup desc, bStep asc"; pstmt = conn.prepareStatement(query); rs = pstmt.executeQuery(); while(rs.next()){ int bId = rs.getInt("bId"); String id = rs.getString("id"); String bTitle = rs.getString("bTitle"); String bContent = rs.getString("bContent"); Timestamp bDate = rs.getTimestamp("bDate"); int bHit = rs.getInt("bHit"); int bGroup = rs.getInt("bGroup"); int bStep = rs.getInt("bStep"); int bIndent = rs.getInt("bIndent"); BDto dto = new BDto(bId, id, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent); dtos.add(dto); } } catch (Exception e) { e.printStackTrace(); }finally{ try { if(rs != null) rs.close(); if(pstmt != null) pstmt.close(); if(conn != null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } } return dtos; } public BDto contentView(String strID) { upHit(strID); BDto dto = null; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = datasource.getConnection(); String query = "select * from test_board where bId= ?"; pstmt = conn.prepareStatement(query); pstmt.setInt(1, Integer.parseInt(strID)); rs = pstmt.executeQuery(); if(rs.next()){ int bId = rs.getInt("bId"); String id = rs.getString("id"); String bTitle = rs.getString("bTitle"); String bContent = rs.getString("bContent"); Timestamp bDate = rs.getTimestamp("bDate"); int bHit = rs.getInt("bHit"); int bGroup = rs.getInt("bGroup"); int bStep = rs.getInt("bStep"); int bIndent = rs.getInt("bIndent"); dto = new BDto(bId, id, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent); } } catch (Exception e) { e.printStackTrace(); }finally{ try { if(rs != null) rs.close(); if(pstmt != null) pstmt.close(); if(conn != null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } } return dto; } public BDto modifyView(String strID) { BDto dto = null; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = datasource.getConnection(); String query = "select * from test_board where bId= ?"; pstmt = conn.prepareStatement(query); pstmt.setInt(1, Integer.parseInt(strID)); rs = pstmt.executeQuery(); if(rs.next()){ int bId = rs.getInt("bId"); String id = rs.getString("id"); String bTitle = rs.getString("bTitle"); String bContent = rs.getString("bContent"); Timestamp bDate = rs.getTimestamp("bDate"); int bHit = rs.getInt("bHit"); int bGroup = rs.getInt("bGroup"); int bStep = rs.getInt("bStep"); int bIndent = rs.getInt("bIndent"); dto = new BDto(bId, id, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent); } } catch (Exception e) { e.printStackTrace(); }finally{ try { if(rs != null) rs.close(); if(pstmt != null) pstmt.close(); if(conn != null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } } return dto; } public void modify(String bId, String id, String bTitle, String bContent){ Connection conn = null; PreparedStatement pstmt = null; try { conn = datasource.getConnection(); String query = "update test_board set id=?, bTitle = ?, bContent = ? where bId=?"; pstmt = conn.prepareStatement(query); pstmt.setString(1, id); pstmt.setString(2, bTitle); pstmt.setString(3, bContent); pstmt.setInt(4, Integer.parseInt(bId)); int rn = pstmt.executeUpdate(); System.out.println(bId+" , "+id+" , "+bTitle+" , "+bContent); } catch (Exception e) { e.printStackTrace(); }finally{ try { if(pstmt != null) pstmt.close(); if(conn != null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } } } public void delete(String bId){ Connection conn = null; PreparedStatement pstmt = null; try { conn = datasource.getConnection(); String query ="delete from test_board where bId=?"; pstmt = conn.prepareStatement(query); pstmt.setInt(1, Integer.parseInt(bId)); int rn = pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); }finally{ try { if(pstmt != null) pstmt.close(); if(conn != null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } } } public BDto reply_view(String str){ BDto dto = null; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = datasource.getConnection(); String query = "select * from test_board where bId=?"; pstmt = conn.prepareStatement(query); pstmt.setInt(1, Integer.parseInt(str)); rs = pstmt.executeQuery(); if(rs.next()){ int bId = rs.getInt("bId"); String id = rs.getString("id"); String bTitle = rs.getString("bTitle"); String bContent = rs.getString("bContent"); Timestamp bDate = rs.getTimestamp("bDate"); int bHit = rs.getInt("bHit"); int bGroup = rs.getInt("bGroup"); int bStep = rs.getInt("bStep"); int bIndent = rs.getInt("bIndent"); dto = new BDto(bId, id, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(pstmt != null) pstmt.close(); if(conn != null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } } return dto; } public void reply(String bId, String id, String bTitle, String bContent, String bGroup, String bStep, String bIndent){ System.out.println("답글 : "+bId+" , "+id+" , "+bTitle+" , "+bContent); Connection conn = null; PreparedStatement pstmt = null; try { conn = datasource.getConnection(); String query = "insert into test_board (id, bTitle, bContent, bGroup, bStep, bIndent) values (?, ?, ?, ?, ?, ?)"; pstmt = conn.prepareStatement(query); pstmt.setString(1, id); pstmt.setString(2, bTitle); pstmt.setString(3, bContent); pstmt.setInt(4, Integer.parseInt(bGroup)); pstmt.setInt(5, Integer.parseInt(bStep) +1); pstmt.setInt(6, Integer.parseInt(bIndent) +1); int rn = pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { try { if(pstmt != null) pstmt.close(); if(conn != null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } } } private void upHit(String bId) { Connection conn = null; PreparedStatement pstmt = null; try { conn = datasource.getConnection(); String query = "update test_board set bHit = bHit +1 where bId= ? "; pstmt = conn.prepareStatement(query); pstmt.setInt(1, Integer.parseInt(bId)); int rn = pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { try { if(pstmt != null) pstmt.close(); if(conn != null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } } } }
true
18119cf2be0bdce14155b8da2755d88b3551e35c
Java
sohanKumawat/java-sample-project
/mb-spring-service/process-springboot-jpa/src/main/java/com/mb/demo/entity/common/ticket/TicketLogging.java
UTF-8
572
1.914063
2
[]
no_license
package com.mb.demo.entity.common.ticket; import java.io.Serializable; import javax.persistence.Column; import com.mb.demo.beans.BaseBean; import com.mb.demo.constants.PickPackConstants.TicketType; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper = false) public class TicketLogging extends BaseBean implements Serializable { private static final long serialVersionUID = 1L; @Column(unique = true) private String ticketId; private String ticketName; private TicketType ticketType; private String ticketDescription; }
true
4ef5c39d9ad96bf9e484b72caf9f8ed1d3b7c656
Java
devom7022/Blix
/app/src/main/java/com/example/blix/ui/discover/DiscoverPresenter.java
UTF-8
3,783
2.328125
2
[ "MIT" ]
permissive
package com.example.blix.ui.discover; import android.util.Log; import com.example.blix.api.ApiClient; import com.example.blix.model.ResponseDiscover; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class DiscoverPresenter implements DiscoverListener.Presenter{ private static String TAG = DiscoverPresenter.class.getSimpleName(); ResponseDiscover itemsMedia; private ApiClient apiClient; private DiscoverListener.View view; public DiscoverPresenter(ResponseDiscover itemsMedia, ApiClient apiClient) { this.itemsMedia = itemsMedia; this.apiClient = apiClient; } @Override public void getDiscoverRequest(String apiKey, String lang, int pag) { Call<ResponseDiscover> call = apiClient.getDiscoverMovies(apiKey, lang, pag); call.enqueue(new Callback<ResponseDiscover>() { @Override public void onResponse(Call<ResponseDiscover> call, Response<ResponseDiscover> response) { Log.e(TAG, "log: -----------------------------"); Log.d(TAG, "onResponse: " + response.body()); if (response.isSuccessful()){ itemsMedia = response.body(); view.showDiscoverList(itemsMedia); } } @Override public void onFailure(Call<ResponseDiscover> call, Throwable t) { Log.e(TAG, "onFailure: ", t); } }); } @Override public void getPopularRequest(String apiKey, String lang, int pag) { Call<ResponseDiscover> call = apiClient.getPopularMovies(apiKey, lang, pag); call.enqueue(new Callback<ResponseDiscover>() { @Override public void onResponse(Call<ResponseDiscover> call, Response<ResponseDiscover> response) { if (response.isSuccessful()){ itemsMedia = response.body(); view.showPopularList(itemsMedia); } } @Override public void onFailure(Call<ResponseDiscover> call, Throwable t) { Log.e(TAG, "onFailure: ", t); } }); } @Override public void getTopRatedRequest(String apiKey, String lang, int pag) { Call<ResponseDiscover> call = apiClient.getTopMovies(apiKey, lang, pag); call.enqueue(new Callback<ResponseDiscover>() { @Override public void onResponse(Call<ResponseDiscover> call, Response<ResponseDiscover> response) { if (response.isSuccessful()){ itemsMedia = response.body(); view.showTopRatedList(itemsMedia); } } @Override public void onFailure(Call<ResponseDiscover> call, Throwable t) { Log.e(TAG, "onFailure: ", t); } }); } @Override public void getUpcomingRequest(String apiKey, String lang, int pag) { Call<ResponseDiscover> call = apiClient.getUpcomingMovies(apiKey, lang, pag); call.enqueue(new Callback<ResponseDiscover>() { @Override public void onResponse(Call<ResponseDiscover> call, Response<ResponseDiscover> response) { if (response.isSuccessful()){ itemsMedia = response.body(); view.showUpcomingList(itemsMedia); } } @Override public void onFailure(Call<ResponseDiscover> call, Throwable t) { Log.e(TAG, "onFailure: ", t); } }); } @Override public void setView(DiscoverListener.View view) { this.view = view; itemsMedia = new ResponseDiscover(); } }
true
cc80b7d2c35be3878314e37014fd40c612346270
Java
gleatham/CST-135_AddressBook
/src/Location.java
UTF-8
985
2.984375
3
[]
no_license
/** * Stand along class. * Used by BaseContact to add a location */ public class Location { private String locationId; private String street; private String city; private String state; Location(String locationId, String street, String city, String state){ this.locationId = locationId; this.street = street; this.city = city; this.state = state; } public String getLocationId() { return locationId; } public void setLocationId(String locationId) { this.locationId = locationId; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } }
true
b6f28635ca736e5a93d0a0660f0073754db2c85f
Java
moutainhigh/center-1
/newscenter/src/main/java/com/cmall/newscenter/model/DeliveryCharResult.java
UTF-8
818
1.867188
2
[]
no_license
package com.cmall.newscenter.model; import java.util.ArrayList; import java.util.List; import com.srnpr.zapcom.baseannotation.ZapcomApi; import com.srnpr.zapweb.webapi.RootResultWeb; /** * 发货输出类 * @author shiyz * date 2016-03-20 * */ public class DeliveryCharResult extends RootResultWeb { @ZapcomApi(value="发货单查看") private List<AgentEntityClass> agentEntity = new ArrayList<AgentEntityClass>(); @ZapcomApi(value = "翻页结果") private PageResults paged = new PageResults(); public List<AgentEntityClass> getAgentEntity() { return agentEntity; } public void setAgentEntity(List<AgentEntityClass> agentEntity) { this.agentEntity = agentEntity; } public PageResults getPaged() { return paged; } public void setPaged(PageResults paged) { this.paged = paged; } }
true
9308d1ccd8985b9febe80e213aa1c91b05f267d2
Java
thanghv1711/Battleship_android
/app/src/main/java/fu/prm391/example/view/RegisterDialog.java
UTF-8
1,605
2.203125
2
[]
no_license
package fu.prm391.example.view; import android.app.ActionBar; import android.app.Activity; import android.app.Dialog; import android.os.Bundle; import android.widget.Button; import fu.prm391.example.event.DRegisterBtnCancelOnClickListener; import fu.prm391.example.event.DRegisterBtnRegisterOnClickListener; public class RegisterDialog extends Dialog implements IActivity { private LoginDialog loginDialog; // login dialog private Button btnRegister; private Button btnCancel; public RegisterDialog(Activity activity, Dialog dialog) { super(activity); this.loginDialog = (LoginDialog) dialog; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dialog_register); getViewById(); configureComponent(); implementEvent(); } @Override public void configureScreen() { } @Override public void getViewById() { btnRegister = findViewById(R.id.dRegisterBtnRegister); btnCancel = findViewById(R.id.dRegisterBtnCancel); } @Override public void configureComponent() { // set layout size getWindow().setLayout(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT); } @Override public void loadData() { } @Override public void implementEvent() { btnRegister.setOnClickListener(new DRegisterBtnRegisterOnClickListener(loginDialog, this)); btnCancel.setOnClickListener(new DRegisterBtnCancelOnClickListener(this)); } }
true
7633b70082fc159a7468d5694c89071ff116c008
Java
VXolevchuk/verysimplebank
/src/main/java/com/example/verysimplebank/repos/TransactionRepository.java
UTF-8
647
1.976563
2
[]
no_license
package com.example.verysimplebank.repos; import com.example.verysimplebank.dto.TransactionToDisplayDTO; import com.example.verysimplebank.model.Account; import com.example.verysimplebank.model.Transaction; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; public interface TransactionRepository extends JpaRepository<Transaction, Long> { @Query("SELECT t FROM Transaction t WHERE t.account.customUser.login = :login") List<Transaction> getTransactionDTO(@Param("login") String login); }
true
5823075b2075bf7aecdfbdb373fa3163be78f02d
Java
kawasima/services-by-lifecycle
/src/main/java/net/unit8/examples/user/domain/Requester.java
UTF-8
688
2.21875
2
[]
no_license
package net.unit8.examples.user.domain; import lombok.Getter; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import java.util.Collection; import java.util.Set; @Getter public class Requester extends Member { private final ProjectOwnerId projectOwnerId; public Requester(String id, String email, String password, ProjectOwnerId projectOwnerId) { super(id, email, password); this.projectOwnerId = projectOwnerId; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return Set.of(new SimpleGrantedAuthority("requester")); } }
true
0043e82f36b66eccaf3d0cadcff2ce79d022f2d1
Java
GigaSpaces-ProfessionalServices/distributed-collections
/collections-core/src/main/java/org/openspaces/collections/queue/distributed/operations/DistrQueueHeadResult.java
UTF-8
2,285
2.703125
3
[]
no_license
package org.openspaces.collections.queue.distributed.operations; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import static org.openspaces.collections.util.SerializationUtils.readNullableObject; import static org.openspaces.collections.util.SerializationUtils.writeNullableObject; public class DistrQueueHeadResult implements Externalizable { private boolean queueEmpty; private Long headIndex; private boolean removedIndexesChanged; public DistrQueueHeadResult() { } /** * Creates empty queue result * * @return result */ public static DistrQueueHeadResult emptyQueueResult() { return headIndexResult(true, null, false); } /** * Creates empty queue result with new head index * * @return result */ public static DistrQueueHeadResult emptyQueueResult(Long index, boolean removedIndexesChanged) { return headIndexResult(true, index, removedIndexesChanged); } /** * Creates non-empty queue result with new head index * * @return result */ public static DistrQueueHeadResult headIndexResult(Long index, boolean removedIndexesChanged) { return headIndexResult(false, index, removedIndexesChanged); } private static DistrQueueHeadResult headIndexResult(boolean queueEmpty, Long index, boolean removedIndexesChanged) { DistrQueueHeadResult result = new DistrQueueHeadResult(); result.queueEmpty = queueEmpty; result.headIndex = index; result.removedIndexesChanged = removedIndexesChanged; return result; } public boolean isQueueEmpty() { return queueEmpty; } public Long getHeadIndex() { return headIndex; } public boolean getRemovedIndexesChanged() { return removedIndexesChanged; } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeBoolean(isQueueEmpty()); writeNullableObject(out, getHeadIndex()); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.queueEmpty = in.readBoolean(); this.headIndex = readNullableObject(in); } }
true
d8d0b4392e3d037cc1a2dd299f464cf1a11a67a6
Java
MahdiHoseiniTabar/TaskManager
/app/src/main/java/com/example/caspian/taskmanager/CallBack.java
UTF-8
93
1.867188
2
[]
no_license
package com.example.caspian.taskmanager; public interface CallBack { void callBack(); }
true
69525b48aecb1a7d3d60030b5513ccdaf54ea56f
Java
Sravani04/WEEELCO
/app/src/main/java/com/example/yellowsoft/weeelco/AccountFragment.java
UTF-8
20,245
1.804688
2
[]
no_license
package com.example.yellowsoft.weeelco; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewFlipper; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.kaopiz.kprogresshud.KProgressHUD; import com.koushikdutta.async.future.FutureCallback; import com.koushikdutta.ion.Ion; /** * Created by yellowsoft on 7/2/18. */ public class AccountFragment extends Fragment { LinearLayout login_screen; TextView login_btn,signin_btn,fp_btn,name,email,phone; ViewFlipper flipper; EditText login_email,login_password,user_fname,user_lname,email_text,password_text,user_phone,old_pass,new_pass,confirm_pass,forgot_email; LinearLayout login_ll,create_acc_ll,password_ll,logout_ll,change_pass_popup,forgot_pass_popup,submit_ll,submit_btn,bookings_btn; ImageView edit_profile,changepw_close_btn,forgot_close; MainActivity mainActivity; String emailPattern = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; String write; String lname,block,street,house,flat,floor; TextView st_login; public static AccountFragment newInstance(int someInt) { AccountFragment myFragment = new AccountFragment(); Bundle args = new Bundle(); args.putInt("someInt", someInt); myFragment.setArguments(args); return myFragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View view = inflater.inflate(R.layout.account_screen,container,false); Session.forceRTLIfSupported(getActivity()); mainActivity = (MainActivity) getActivity(); getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); login_email = (EditText) view.findViewById(R.id.login_email); login_password = (EditText) view.findViewById(R.id.login_password); user_fname = (EditText) view.findViewById(R.id.user_fname); user_lname = (EditText) view.findViewById(R.id.user_lname); email_text = (EditText) view.findViewById(R.id.email_text); password_text = (EditText) view.findViewById(R.id.password_text); user_phone = (EditText) view.findViewById(R.id.user_phone); old_pass = (EditText) view.findViewById(R.id.old_pass); new_pass = (EditText) view.findViewById(R.id.new_pass); confirm_pass = (EditText) view.findViewById(R.id.confirm_pass); forgot_email = (EditText) view.findViewById(R.id.forgot_email); login_screen = (LinearLayout) view.findViewById(R.id.login_screen); login_ll = (LinearLayout) view.findViewById(R.id.login_ll); create_acc_ll = (LinearLayout) view.findViewById(R.id.create_acc_ll); password_ll = (LinearLayout) view.findViewById(R.id.password_ll); logout_ll = (LinearLayout) view.findViewById(R.id.logout_ll); change_pass_popup = (LinearLayout) view.findViewById(R.id.change_pass_popup); forgot_pass_popup = (LinearLayout) view.findViewById(R.id.forgot_pass_popup); bookings_btn = (LinearLayout) view.findViewById(R.id.bookings_btn); submit_ll = (LinearLayout) view.findViewById(R.id.submit_ll); submit_btn = (LinearLayout) view.findViewById(R.id.submit_btn); login_btn = (TextView) view.findViewById(R.id.login_btn); signin_btn = (TextView) view.findViewById(R.id.signin_btn); fp_btn = (TextView) view.findViewById(R.id.fp_btn); name = (TextView) view.findViewById(R.id.name); email = (TextView) view.findViewById(R.id.email); phone = (TextView) view.findViewById(R.id.phone); edit_profile = (ImageView) view.findViewById(R.id.edit_profile); changepw_close_btn = (ImageView) view.findViewById(R.id.close_btn); forgot_close = (ImageView) view.findViewById(R.id.forgot_close); flipper = (ViewFlipper) view.findViewById(R.id.viewFlipper); st_login = (TextView) view.findViewById(R.id.st_login); login_btn.setText(Session.GetWord(getActivity(),"Login")); signin_btn.setText(Session.GetWord(getActivity(),"SignUp")); fp_btn.setText(Session.GetWord(getActivity(),"Forgot Password?")); st_login.setText(Session.GetWord(getActivity(),"Login")); login_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { login_btn.setTextColor(getResources().getColor(R.color.background)); signin_btn.setTextColor(Color.parseColor("#aa000000")); flipper.setDisplayedChild(0); } }); signin_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { signin_btn.setTextColor(getResources().getColor(R.color.background)); login_btn.setTextColor(Color.parseColor("#aa000000")); flipper.setDisplayedChild(1); } }); bookings_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(),BookingsOrdersActivity.class); startActivity(intent); } }); login_ll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { login(); } }); create_acc_ll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { register(); } }); fp_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { forgot_pass_popup.setVisibility(View.VISIBLE); } }); forgot_close.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { forgot_pass_popup.setVisibility(View.GONE); } }); submit_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { forgot_pass(); } }); password_ll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { change_pass_popup.setVisibility(View.VISIBLE); } }); if (Session.GetUserId(getActivity()).equals("-1")){ mainActivity.toolbar.setVisibility(View.GONE); login_screen.setVisibility(View.VISIBLE); }else { mainActivity.toolbar.setVisibility(View.VISIBLE); login_screen.setVisibility(View.GONE); } logout_ll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Session.SetUserId(getActivity(),"-1"); mainActivity.mViewPager.setCurrentItem(0); } }); submit_ll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { change_password(); } }); changepw_close_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { change_pass_popup.setVisibility(View.GONE); } }); edit_profile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(),EditProfile.class); intent.putExtra("fname",name.getText().toString()); intent.putExtra("lname",lname); intent.putExtra("phone",phone.getText().toString()); intent.putExtra("block",block); intent.putExtra("street",street); intent.putExtra("house",house); intent.putExtra("flat",flat); intent.putExtra("floor",floor); startActivity(intent); } }); get_members(); return view; } public void get_members(){ final KProgressHUD hud = KProgressHUD.create(getContext()) .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE) .setLabel("Please wait") .setCancellable(true) .setMaxProgress(100) .show(); Ion.with(getContext()) .load(Session.SERVERURL+"members.php") .setBodyParameter("member_id",Session.GetUserId(getContext())) .asJsonArray() .setCallback(new FutureCallback<JsonArray>() { @Override public void onCompleted(Exception e, JsonArray result) { try { hud.dismiss(); JsonObject jsonObject = result.get(0).getAsJsonObject(); name.setText(jsonObject.get("fname").getAsString()); email.setText(jsonObject.get("email").getAsString()); phone.setText(jsonObject.get("phone").getAsString()); lname = jsonObject.get("lname").getAsString(); block = jsonObject.get("block").getAsString(); street = jsonObject.get("street").getAsString(); house = jsonObject.get("house").getAsString(); flat = jsonObject.get("flat").getAsString(); floor = jsonObject.get("floor").getAsString(); }catch (Exception e1){ e1.printStackTrace(); } } }); } public void change_password(){ String oldpass_string = old_pass.getText().toString(); String newpass_string = new_pass.getText().toString(); String confirmpass_string = confirm_pass.getText().toString(); if (oldpass_string.equals("")){ Toast.makeText(getContext(),"Please Enter Old Password",Toast.LENGTH_SHORT).show(); old_pass.requestFocus(); }else if (newpass_string.equals("")){ Toast.makeText(getContext(),"Please Enter New Password",Toast.LENGTH_SHORT).show(); new_pass.requestFocus(); }else if (confirm_pass.equals("")){ Toast.makeText(getContext(),"Please Enter Confirm Password",Toast.LENGTH_SHORT).show(); confirm_pass.requestFocus(); }else { final KProgressHUD hud = KProgressHUD.create(getContext()) .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE) .setLabel("Please wait") .setCancellable(true) .setMaxProgress(100) .show(); Ion.with(getContext()) .load(Session.SERVERURL + "change-password.php") .setBodyParameter("member_id", Session.GetUserId(getContext())) .setBodyParameter("opassword", oldpass_string) .setBodyParameter("password",newpass_string) .setBodyParameter("cpassword",confirmpass_string) .asJsonObject() .setCallback(new FutureCallback<JsonObject>() { @Override public void onCompleted(Exception e, JsonObject result) { try { hud.dismiss(); if (result.get("status").getAsString().equals("Success")){ Toast.makeText(getContext(),result.get("message").getAsString(),Toast.LENGTH_SHORT).show(); getActivity().onBackPressed(); }else { Toast.makeText(getContext(),result.get("message").getAsString(),Toast.LENGTH_SHORT).show(); } }catch (Exception e1){ e1.printStackTrace(); } } }); } } public void login(){ String email_string = login_email.getText().toString(); String password_string = login_password.getText().toString(); if (email_string.equals("")){ Toast.makeText(getActivity(),"Please Enter Your Email",Toast.LENGTH_SHORT).show(); login_email.requestFocus(); }else if (password_string.equals("")){ Toast.makeText(getActivity(),"Please Enter Your Password",Toast.LENGTH_SHORT).show(); login_password.requestFocus(); }else { final KProgressHUD hud = KProgressHUD.create(getActivity()) .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE) .setLabel("Please wait") .setCancellable(true) .setMaxProgress(100) .show(); Ion.with(this) .load(Session.SERVERURL + "login.php") .setBodyParameter("email", email_string) .setBodyParameter("password", password_string) .asJsonObject() .setCallback(new FutureCallback<JsonObject>() { @Override public void onCompleted(Exception e, JsonObject result) { try { hud.dismiss(); Log.e("loginresult", result.toString()); if (result.get("status").getAsString().equals("Success")) { Session.SetUserId(getActivity(), result.get("member_id").getAsString()); Log.e("member_id", result.get("member_id").toString()); //Toast.makeText(getActivity(),result.get("message").getAsString(),Toast.LENGTH_SHORT).show(); Intent intent = new Intent(getActivity(), MainActivity.class); intent.putExtra("act","1"); startActivity(intent); } else { Toast.makeText(getActivity(), result.get("message").getAsString(), Toast.LENGTH_SHORT).show(); } } catch (Exception e1) { e1.printStackTrace(); } } }); } } public void register(){ String fname_string = user_fname.getText().toString(); String lname_string = user_lname.getText().toString(); String email_string = email.getText().toString(); String password_string = password_text.getText().toString(); String phone_string = user_phone.getText().toString(); if (fname_string.equals("")){ Toast.makeText(getActivity(),"Please Enter Your First Name",Toast.LENGTH_SHORT).show(); user_fname.requestFocus(); }else if (lname_string.equals("")){ Toast.makeText(getActivity(),"Please Enter Your Last Name",Toast.LENGTH_SHORT).show(); user_lname.requestFocus(); }else if (email_string.equals("")){ Toast.makeText(getActivity(),"Please Enter Your Email",Toast.LENGTH_SHORT).show(); email_text.requestFocus(); }else if (password_string.equals("")){ Toast.makeText(getActivity(),"Please Enter Your Password",Toast.LENGTH_SHORT).show(); password_text.requestFocus(); }else if (phone_string.equals("")){ Toast.makeText(getActivity(),"Please Enter Your Phone",Toast.LENGTH_SHORT).show(); user_phone.requestFocus(); }else { final KProgressHUD hud = KProgressHUD.create(getActivity()) .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE) .setLabel("Please wait") .setCancellable(true) .setMaxProgress(100) .show(); Ion.with(this) .load(Session.SERVERURL + "member.php") .setBodyParameter("fname", fname_string) .setBodyParameter("lname", lname_string) .setBodyParameter("email", email_string) .setBodyParameter("password", password_string) .setBodyParameter("phone", phone_string) .asJsonObject() .setCallback(new FutureCallback<JsonObject>() { @Override public void onCompleted(Exception e, JsonObject result) { try { hud.dismiss(); Log.e("loginresult", result.toString()); if (result.get("status").getAsString().equals("Success")) { Toast.makeText(getActivity(), result.get("message").getAsString(), Toast.LENGTH_SHORT).show(); flipper.setDisplayedChild(0); } else { Toast.makeText(getActivity(), result.get("message").getAsString(), Toast.LENGTH_SHORT).show(); } } catch (Exception e1) { e1.printStackTrace(); } } }); } } public void forgot_pass(){ String email_string = forgot_email.getText().toString(); if (email_string.equals("")){ Toast.makeText(getActivity(), "Please Enter email", Toast.LENGTH_SHORT).show(); }else if (!email_string.matches(emailPattern)){ Toast.makeText(getActivity(), "Please Enter Valid Email", Toast.LENGTH_SHORT).show(); }else { final KProgressHUD hud = KProgressHUD.create(getActivity()) .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE) .setLabel("Please wait") .setCancellable(true) .setMaxProgress(100) .show(); Ion.with(this) .load(Session.SERVERURL + "forget-password.php") .setBodyParameter("email", email_string) .asJsonObject() .setCallback(new FutureCallback<JsonObject>() { @Override public void onCompleted(Exception e, JsonObject result) { try { hud.dismiss(); if (result.get("status").getAsString().equals("Success")) { Toast.makeText(getActivity(), result.get("message").getAsString(), Toast.LENGTH_SHORT).show(); getActivity().finish(); } else { Toast.makeText(getActivity(), result.get("message").getAsString(), Toast.LENGTH_SHORT).show(); } } catch (Exception e1) { e1.printStackTrace(); } } }); } } }
true
ad76aec5d68c1182dbcde5a7bf67a14fe2ab97f5
Java
ianuoui/elasticsearch
/server/src/main/java/org/elasticsearch/index/query/Rewriteable.java
UTF-8
6,450
2.171875
2
[ "Apache-2.0", "Elastic-2.0", "SSPL-1.0", "LicenseRef-scancode-other-permissive" ]
permissive
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.index.query; import org.elasticsearch.action.ActionListener; import org.elasticsearch.common.ParsingException; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * A basic interface for rewriteable classes. */ public interface Rewriteable<T> { int MAX_REWRITE_ROUNDS = 16; /** * Rewrites this instance based on the provided context. The returned * objects will be the same instance as this if no changes during the * rewrite were applied. */ T rewrite(QueryRewriteContext ctx) throws IOException; /** * Rewrites the given {@link Rewriteable} into its primitive form. Rewriteables that for instance fetch resources from remote hosts or * can simplify / optimize itself should do their heavy lifting during {@link #rewrite(QueryRewriteContext)}. This method * rewrites the rewriteable until it doesn't change anymore. * @param original the original rewriteable to rewrite * @param context the rewrite context to use * @throws IOException if an {@link IOException} occurs */ static <T extends Rewriteable<T>> T rewrite(T original, QueryRewriteContext context) throws IOException { return rewrite(original, context, false); } /** * Rewrites the given {@link Rewriteable} into its primitive form. Rewriteables that for instance fetch resources from remote hosts or * can simplify / optimize itself should do their heavy lifting during * {@link #rewriteAndFetch(Rewriteable, QueryRewriteContext, ActionListener)} (QueryRewriteContext)}. This method rewrites the * rewriteable until it doesn't change anymore. * @param original the original rewriteable to rewrite * @param context the rewrite context to use * @param assertNoAsyncTasks if <code>true</code> the rewrite will fail if there are any pending async tasks on the context after the * rewrite. See {@link QueryRewriteContext#executeAsyncActions(ActionListener)} for details * @throws IOException if an {@link IOException} occurs */ static <T extends Rewriteable<T>> T rewrite(T original, QueryRewriteContext context, boolean assertNoAsyncTasks) throws IOException { T builder = original; int iteration = 0; for (T rewrittenBuilder = builder.rewrite(context); rewrittenBuilder != builder; rewrittenBuilder = builder.rewrite(context)) { if (assertNoAsyncTasks && context.hasAsyncActions()) { throw new IllegalStateException("async actions are left after rewrite"); } builder = rewrittenBuilder; if (iteration++ >= MAX_REWRITE_ROUNDS) { // this is some protection against user provided queries if they don't obey the contract of rewrite we allow 16 rounds // and then we fail to prevent infinite loops throw new IllegalStateException( "too many rewrite rounds, rewriteable might return new objects even if they are not rewritten" ); } } return builder; } /** * Rewrites the given rewriteable and fetches pending async tasks for each round before rewriting again. */ static <T extends Rewriteable<T>> void rewriteAndFetch(T original, QueryRewriteContext context, ActionListener<T> rewriteResponse) { rewriteAndFetch(original, context, rewriteResponse, 0); } /** * Rewrites the given rewriteable and fetches pending async tasks for each round before rewriting again. */ static <T extends Rewriteable<T>> void rewriteAndFetch( T original, QueryRewriteContext context, ActionListener<T> rewriteResponse, int iteration ) { T builder = original; try { for (T rewrittenBuilder = builder.rewrite(context); rewrittenBuilder != builder; rewrittenBuilder = builder.rewrite(context)) { builder = rewrittenBuilder; if (iteration++ >= MAX_REWRITE_ROUNDS) { // this is some protection against user provided queries if they don't obey the contract of rewrite we allow 16 rounds // and then we fail to prevent infinite loops throw new IllegalStateException( "too many rewrite rounds, rewriteable might return new objects even if they are not rewritten" ); } if (context.hasAsyncActions()) { T finalBuilder = builder; final int currentIterationNumber = iteration; context.executeAsyncActions( ActionListener.wrap( n -> rewriteAndFetch(finalBuilder, context, rewriteResponse, currentIterationNumber), rewriteResponse::onFailure ) ); return; } } rewriteResponse.onResponse(builder); } catch (IOException | IllegalArgumentException | ParsingException ex) { rewriteResponse.onFailure(ex); } } /** * Rewrites each element of the list until it doesn't change and returns a new list iff there is at least one element of the list that * changed during it's rewrite. Otherwise the given list instance is returned unchanged. */ static <T extends Rewriteable<T>> List<T> rewrite(List<T> rewritables, QueryRewriteContext context) throws IOException { List<T> list = rewritables; boolean changed = false; if (rewritables != null && rewritables.isEmpty() == false) { list = new ArrayList<>(rewritables.size()); for (T instance : rewritables) { T rewrite = rewrite(instance, context); if (instance != rewrite) { changed = true; } list.add(rewrite); } } return changed ? list : rewritables; } }
true
24d895753255aec38453fe99a5fadbe3fadcba3d
Java
aanchal-n/CCBD-Project
/microservices/ms3/src/main/java/com/ms3/services/ms3serviceimpl.java
UTF-8
357
2.03125
2
[]
no_license
package com.ms3.services; import com.ms3.entity.ms3; import org.springframework.stereotype.Service; import java.util.List; @Service public class ms3serviceimpl implements ms3service{ @Override public String getms3(Integer a) { if (a%2 == 0) return ("EVEN"); else return ("ODD"); } }
true
b611c7922f95377644c9c38616a72419eb3c2f55
Java
avilesj/taskr-api
/src/main/java/com/javiles/taskr/services/TaskServiceImpl.java
UTF-8
786
2.46875
2
[]
no_license
package com.javiles.taskr.services; import com.javiles.taskr.models.Task; import com.javiles.taskr.repositories.TaskRepository; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; import java.util.Optional; public class TaskServiceImpl implements TaskService { @Autowired private TaskRepository taskRepository; @Override public Task getTaskById(long id) { Optional<Task> task = taskRepository.findById(id); if (task.isPresent()) { return task.get(); } return null; } @Override public List<Task> getAllTasks() { return taskRepository.findAll(); } @Override public void saveTask(Task task) { taskRepository.save(task); } }
true
2295f0b10302ec9c50005338bc573d4c1108b89d
Java
mikiebrenbren/spel-spring-sample
/src/main/java/com/caveofprogramming/spring/test/RandomText.java
UTF-8
491
2.640625
3
[]
no_license
package com.caveofprogramming.spring.test; import org.springframework.stereotype.Component; import java.util.Random; /** * Created by michaelbrennan on 3/22/15. */ @Component public class RandomText { private static String[] text = { "I'll be back", "Get to the choppa!", "Hello robut!!" }; public String getText(){ Random random = new Random(); // return null; return text[random.nextInt(text.length)]; } }
true
ce5e7a91dc362ee0ee4b02b98dd8b51c7c2f50b5
Java
lakerswq7/Interview
/dp/LongestIncreasingSubsequence.java
GB18030
1,739
3.703125
4
[]
no_license
package dp; /* * http://www.lintcode.com/zh-cn/problem/longest-increasing-subsequence/ * 0. ½еijȣ sequence -> dp * 1. f[i] -> Ϊi + 1LISһСΪ * 2. f[i] -> 쵽jλõʱ򣬴f[i]ҵĵһnums[j]λΪiʱ͸f[i]ֵΪnums[j] * ǣʵһСģ԰LISλüһnums[j] * 3. f[i]ΪInteger.MAX_VALUE * 4. һlen¼ǰLIS ɨһԺ󣬷len * * Ż㷨ӶO(nlogn) * һdpĻҪO(n^2),ɨһͬʱҪɨַ֮ǰ */ public class LongestIncreasingSubsequence { public int longestIncreasingSubsequence(int[] nums) { int len = 0; int[] lis = new int[nums.length]; for (int i = 0; i < lis.length; i++) { lis[i] = Integer.MAX_VALUE; } for (int i = 0; i < nums.length; i++) { int pos = findPos(lis, nums[i], 0, len); lis[pos] = nums[i]; if (pos == len) { len++; } } return len; } // ֲҵһtargetλ public int findPos(int[] lis, int target, int start, int end) { while (start + 1 < end) { int mid = start + (end - start) / 2; if (lis[mid] <= target) { start = mid; } else { end = mid; } } if (lis[start] > target) { return start; } else { return end; } } }
true
db4a4fd17a61ea248293fd4c9cdf19b2e6fb9a77
Java
Darkceus/Programacion-Ambientada-a-Cliente-Servidor
/5 - Archivo_v2/ArchivoCliente_v2/src/archivocliente/Cliente.java
UTF-8
18,711
2.921875
3
[]
no_license
package archivocliente; import java.awt.Desktop; import java.net.*; import java.io.*; import java.util.Scanner; /** * Clase Cliente. En esta clase se manejan todos los Clientes vistos en el * parcial. * @author Alexander Gámez Urías * @version 1.0 */ public class Cliente { private String direccion; private int puerto; private String mensaje; private Socket socket; private final String[] arreglo; private BufferedReader lector; private PrintWriter escritor; private FileOutputStream destino; private DataInputStream datosRecibidos; private BufferedOutputStream salidaDatos; private BufferedInputStream entradaDatos; private String salida; private boolean respuesta; private long tam; private int tam2; private String valorFinal; private String archivo; private String nombreArchivo; private String directorio; private String nombreArchivos; private String rutaArchivoCliente; private final int KB = 1024; private final int MB = 1048576; private final int GB = 1073741824; private final long TB = 1099511627776L; /** * Aquí se inicia se agarran los datos del Array de String del main. * @param arreglo El array de String del main. */ public Cliente(String[] arreglo) { this.entradaDatos = null; this.salidaDatos = null; this.destino = null; this.arreglo = arreglo; } /** * Al abrir el Cliente Simple se debe meter una dirección, un puerto y un * mensaje. * Ejemplo: -jar "C:\Programación Ambientada a Cliente-Servidor\1 - * Cliente/Servidor Simple\ClienteSimple\dist\ClienteSimple.jar" 127.0.0.1 * 2001 "Este es un mensaje" */ public void iniciarClienteSimple() { validarSimple(arreglo.length); validarDireccion(arreglo[0]); validarPuerto(arreglo[1]); mensaje = arreglo[2]; crearSocket(); mandarMensaje(); cerrarSocket(); } /** * Al abrir el Cliente Bidireccional se debe meter una dirección y * un puerto. * Ejemplo: -jar "C:\Programación Ambientada a Cliente-Servidor\2 - * Cliente/Servidor Bidireccional\ClienteBidireccional\dist\ * ClienteBidireccional.jar" 127.0.0.1 2001 */ public void iniciarClienteBidireccional() { validarBidireccional(arreglo.length); validarDireccion(arreglo[0]); validarPuerto(arreglo[1]); Inicializar(); } /** * Al abrir el Cliente Archivo se debe meter una dirección, un puerto y la * ruta de un Archivo. * Ejemplo: -jar "C:\Programación Ambientada a Cliente-Servidor\3 - * Cliente/Servidor Archivos\ArchivoCliente\dist\ArchivoCliente.jar" * 127.0.0.1 2001 "C:\Prueba.exe" */ public void iniciarClienteArchivo() { validarArchivoCliente(arreglo.length); validarDireccion(arreglo[0]); validarPuerto(arreglo[1]); archivo = arreglo[2]; crearSocket(); mandarRuta(); recibirClienteArchivo(); cerrarSocket(); } /** * Al abrir el Cliente Directorio se debe meter una dirección, un puerto y * la ruta de un Directorio. * Ejemplo: -jar "C:\Programación Ambientada a Cliente-Servidor\4 - * Cliente/Servidor Directorios\DirectorioCliente\dist\DirectorioCliente.jar" * 127.0.0.1 2001 "C:\Windows" */ public void iniciarClienteDirectorio() { validarCDirectorio(arreglo.length); validarDireccion(arreglo[0]); validarPuerto(arreglo[1]); directorio = arreglo[2]; crearSocket(); mandarDirectorio(); recibirDatos(); cerrarSocket(); } /** * Al abrir el Cliente Archivo_v2 se debe meter una dirección, un puerto y * la ruta de un Archivo. * Ejemplo: -jar "C:\Programación Ambientada a Cliente-Servidor\5 - * Cliente/Servidor Archivos_v2\ArchivoCliente\dist\ArchivoCliente.jar" * 127.0.0.1 2001 "C:\Prueba.exe" */ public void iniciarClienteArchivov2() { validarArchivoCliente(arreglo.length); validarDireccion(arreglo[0]); validarPuerto(arreglo[1]); archivo = arreglo[2]; crearSocket(); mandarRuta(); recibirClienteArchivov2(); cerrarSocket(); } //Métodos usados en todos los Clientes private int convertirInt(String valor) { try { return Integer.valueOf(valor); } catch (Exception e) { System.err.println("Debes de poner una dirección válida"); System.exit(0); } return -1; } private void validarDireccion(String valor) { if(valor.equals("localhost")){ direccion = "127.0.0.1"; return; } char[] algo = valor.toCharArray(); int cont = 0; for (int i = 0; i < algo.length; i++) { if (algo[i] == '.') { cont++; } } String[] dir = valor.split("\\."); boolean bol = (convertirInt(dir[0]) <= 255 && convertirInt(dir[1]) <= 255 && convertirInt(dir[2]) <= 255 && convertirInt(dir[3]) <= 254); if (cont == 3 && bol) { direccion = valor; } else { System.err.println("Debes de poner una dirección válida"); System.exit(0); } } private void validarPuerto(String valor) { try { puerto = Integer.parseInt(valor); } catch (Exception e) { System.err.println("Debes de poner un puerto válido"); System.exit(0); } } private void crearSocket() { try { socket = new Socket(direccion, puerto); } catch (Exception e) { System.err.println("Error al crear el socket, " + e.toString()); System.exit(1); } } private void cerrarSocket() { try { socket.close(); } catch (Exception e) { System.err.println("Error al cerrar el socket, " + e.toString()); System.exit(3); } } //Métodos usados en el Cliente Simple private void validarSimple(int tam) { if (tam == 0 || tam < 3 || tam >= 4) { System.err.println("Debes de poner valores válidos"); System.exit(0); } } private void mandarMensaje() { try { PrintWriter escritor2 = new PrintWriter(socket.getOutputStream(), true); escritor2.println(mensaje); } catch (Exception e) { System.err.println("Error al mandar el mensaje, " + e.toString()); System.exit(2); } } //Métodos usados en el Cliente Bidireccional private void validarBidireccional(int tam) { if (tam == 0 || tam < 2 || tam >= 3) { System.err.println("Debes de poner valores válidos"); System.exit(0); } } private void Inicializar() { crearSocket(); crearLector(); crearEscritor(); String entrada = ""; Scanner scanner = new Scanner(System.in); while (true) { try { entrada = scanner.nextLine(); } catch (Exception e) { System.out.println("Cerrando cliente."); System.exit(0); } if (!entrada.isEmpty() || !entrada.equals("")) { if (entrada.equals("fin")) { System.out.println("Cerrando cliente"); escritor.println(entrada); cerrarSocket(); System.exit(0); } escritor.println(entrada); leerLinea(); System.out.println(salida); } } } private void crearLector() { try { lector = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (Exception e) { System.out.println("Error al crear el lector: " + e); System.exit(0); } } private void crearEscritor() { try { escritor = new PrintWriter(socket.getOutputStream(), true); } catch (Exception e) { System.out.println("Error al crear el escritor: " + e); System.exit(0); } } private void leerLinea() { try { salida = lector.readLine(); } catch (Exception e) { System.out.println("Error al leer línea: " + e); System.exit(0); } } //Métodos usados en el Cliente de Directorios private void validarCDirectorio(int tam) { if (tam == 0 || tam < 3 || tam >= 4) { System.err.println("Debes de poner valores válidos"); System.exit(0); } } private void mandarDirectorio() { try { PrintWriter escritor2 = new PrintWriter(socket.getOutputStream(), true); escritor2.println(directorio); } catch (Exception e) { System.err.println("Error al mandar la información, " + e.toString()); System.exit(2); } } private void recibirDatos() { crearRecepcion(); respuesta = leerBol(); if (respuesta) { nombreArchivos = leerString(); System.out.println("Datos en el directorio " + directorio + ": \n" + nombreArchivos); cerrarSocket(); System.exit(0); } else { System.out.println("No existe el Directorio en el Servidor"); cerrarSocket(); System.exit(0); } } //Métodos usados en el Cliente de Archivos (se toman en cuenta ambos Clientes, con barra de progreso y sin ella). private void validarArchivoCliente(int tam) { if (tam == 0 || tam < 3 || tam >= 4) { System.err.println("Debes de poner valores válidos"); System.exit(0); } } private void crearRuta() { try { rutaArchivoCliente = new File(".").getCanonicalPath() + "\\Downloads\\"; System.out.println("El Archivo se guardará en: "+rutaArchivoCliente); } catch (Exception e) { System.out.println("Error al crear ruta: " + e); } } //Usado en el primer Cliente de Archivos, sin la barra de progreso private void recibirClienteArchivo() { crearRuta(); crearRecepcion(); respuesta = leerBol(); if (respuesta) { tam = leerLong(); tam2 = leerInt(); nombreArchivo = leerString(); crearSalida(); salidaDatos = new BufferedOutputStream(destino); crearEntrada(); byte[] archivo2 = new byte[tam2]; int num; long num2 = 0; while ((num2 += (num = leerEntrada(archivo2))) <= tam) { salida(archivo2, num); if (num2 == tam) { break; } } comp(); String algo; Scanner scanner2 = new Scanner(System.in); boolean si = false; do { System.out.println("\n¿Deseas abrir el archivo? Si/No"); algo = scanner2.nextLine(); if (algo.equalsIgnoreCase("Si")) { si = true; } } while (!algo.equalsIgnoreCase("Si") && !algo.equalsIgnoreCase("No")); if (si) { abrirArchivo(); } cerrarES(); cerrarSocket(); System.exit(0); } else { System.out.println("No existe el archivo en el Servidor"); cerrarSocket(); System.exit(0); } } //Usado en el segundo Cliente de Archivos, con la barra de progreso private void recibirClienteArchivov2() { crearRuta(); crearRecepcion(); respuesta = leerBol(); if (respuesta) { tam = leerLong(); tam2 = leerInt(); nombreArchivo = leerString(); crearSalida(); salidaDatos = new BufferedOutputStream(destino); crearEntrada(); byte[] archivo2 = new byte[tam2]; int num; long num2 = 0; float num3; valorFinal = convertirBytes(tam); while ((num2 += (num = leerEntrada(archivo2))) <= tam) { salida(archivo2, num); num3 = ((float)num2 / tam); num3 *= 100; barraProgreso(num2, tam, Math.round(num3)); if (num2 == tam) { break; } } comp(); String algo; Scanner scanner2 = new Scanner(System.in); boolean si = false; do { System.out.println("\n¿Deseas abrir el archivo? Si/No"); algo = scanner2.nextLine(); if (algo.equalsIgnoreCase("Si")) { si = true; } } while (!algo.equalsIgnoreCase("Si") && !algo.equalsIgnoreCase("No")); if (si) { abrirArchivo(); } cerrarES(); cerrarSocket(); System.exit(0); } else { System.out.println("No existe el archivo en el Servidor"); cerrarSocket(); System.exit(0); } } private void comp() { try { salidaDatos.flush(); } catch (Exception e) { System.err.println("Error al sacar datos: " + e); System.exit(0); } } public String convertirBytes(long tam) { String num; double kb = tam / 1024; double mb = kb / 1024; double gb = mb / 1024; if(tam < 1024) { num = tam + " Bytes"; } else if(tam >= KB && tam < MB) { num = String.format("%.2f", kb) + " KB"; } else if(tam >= MB && tam < GB) { num = String.format("%.2f", mb) + " MB"; } else if(tam >= GB && tam < TB) { num = String.format("%.2f", gb) + " GB"; } else { return null; } return num; } private void barraProgreso(long suma, long total, int por) { int porcentaje = (int) ((suma * 100) / total) / 10; char caracterFalta = ' '; String caracterLleva = "█"; String barra = new String(new char[10]).replace('\0', caracterFalta) + "|"; StringBuilder barra2 = new StringBuilder(); barra2.append("|"); for (int i = 0; i < porcentaje; i++) { barra2.append(caracterLleva); } String remanente = barra.substring(porcentaje, barra.length()); System.out.print("\r "); System.out.print("\rRecibiendo... ("+ por + "%) " + barra2 + remanente + " " + convertirBytes(suma) + " de " + valorFinal); if (suma == total) { System.out.print("\n"); } } private void cerrarES() { try { entradaDatos.close(); salidaDatos.close(); } catch (IOException e) { System.err.println("Error al cerrar la E/S: " + e); System.exit(0); } } private int leerEntrada(byte[] arreglo) { try { return entradaDatos.read(arreglo); } catch (IOException e) { System.err.println("Error al leer datos de la entrada: " + e); System.exit(0); } return -1; } private void crearEntrada() { try { entradaDatos = new BufferedInputStream(socket.getInputStream()); } catch (IOException e) { System.err.println("Error al crear la entrada de datos: " + e); System.exit(0); } } private void crearSalida() { try { destino = new FileOutputStream(rutaArchivoCliente + nombreArchivo); } catch (IOException e) { System.err.println("Error al sacar datos: " + e); System.exit(0); } } private void salida(byte[] dato, int num) { try { salidaDatos.write(dato, 0, num); } catch (IOException e) { System.err.println("Error al pasar datos: " + e); System.exit(0); } } private long leerLong() { try { return datosRecibidos.readLong(); } catch (IOException e) { System.out.println("Error leer datos: " + e); System.exit(0); } return -1; } private int leerInt() { try { return datosRecibidos.readInt(); } catch (IOException e) { System.out.println("Error leer datos: " + e); System.exit(0); } return -1; } private void abrirArchivo() { try { File archivo2 = new File(rutaArchivoCliente + nombreArchivo); Desktop.getDesktop().open(archivo2); } catch (IOException e) { System.out.println("Error al abrir archivo: " + e); System.exit(0); } } private void mandarRuta() { try { PrintWriter escritor2 = new PrintWriter(socket.getOutputStream(), true); escritor2.println(archivo); } catch (IOException e) { System.err.println("Error al mandar la información, " + e.toString()); System.exit(2); } } //Métodos usados en dos o más Clientes //Usado en el Cliente de Directorios y los dos de Archivos private void crearRecepcion() { try { datosRecibidos = new DataInputStream(socket.getInputStream()); } catch (IOException e) { System.err.println("Error al poner datos: " + e); System.exit(0); } } //Usado en el Cliente de Directorios y los dos de Archivos private String leerString() { try { return datosRecibidos.readUTF(); } catch (IOException e) { System.out.println("Error leer datos: " + e); System.exit(0); } return null; } //Usado en el Cliente de Directorios y los dos de Archivos private boolean leerBol() { try { return datosRecibidos.readBoolean(); } catch (IOException e) { System.out.println("Error leer datos: " + e); System.exit(0); } return false; } }
true
43948dbc44c6bfda5254e660ef7767b4455c3b0f
Java
princeprag/Buy-Rent-Sell-IITG
/app/src/main/java/com/example/rentbuysell/Buy.java
UTF-8
1,675
1.914063
2
[]
no_license
package com.example.rentbuysell; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.viewpager.widget.ViewPager; import android.os.Bundle; import com.example.rentbuysell.Fragment.*; import com.example.rentbuysell.adapter.ViewPagerAdapter; import com.gigamole.navigationtabstrip.NavigationTabStrip; public class Buy extends AppCompatActivity { private ViewPager mViewPager; private ViewPagerAdapter mSectionsPagerAdapter; public users myuser ; private Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_buy); myuser = new users(this); toolbar = findViewById(R.id.toolbar); //setSupportActionBar(toolbar); mSectionsPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.pager); mSectionsPagerAdapter.addFragments(new AppliancesFragment(),"A"); mSectionsPagerAdapter.addFragments(new BooksFragment(),"b"); mSectionsPagerAdapter.addFragments(new SportsFragment(),"S"); mSectionsPagerAdapter.addFragments(new FurnitureFragment(),"Furni"); mSectionsPagerAdapter.addFragments(new FashionFragment(),"Fashion"); mSectionsPagerAdapter.addFragments(new VehiclesFragment(),"Vehicles"); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setCurrentItem(0); final NavigationTabStrip navigationTabStrip = (NavigationTabStrip) findViewById(R.id.nts); navigationTabStrip.setViewPager(mViewPager); } }
true
cd0d1eef91356ca22ab4ae06ad6c2e01137c3cf0
Java
vireninterviewkit/code-backup
/coding-skills/geeksforgeeks-module/src/main/java/com/geeks/problem/datastructures/BSTProblems.java
UTF-8
20,956
3.828125
4
[]
no_license
package com.geeks.problem.datastructures; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import java.util.Stack; import com.common.model.TreeNode; import com.common.model.ListNode; public class BSTProblems { /************************ BST Basics ***********************/ public TreeNode insert(TreeNode root, int data) { if (root == null) { root = new TreeNode(data); } else if (data <= root.data) { root.left = insert(root.left, data); } else { root.right = insert(root.right, data); } return root; } public TreeNode insertIterative(TreeNode root, int n) { TreeNode newNode = new TreeNode(n); if (root == null) return newNode; TreeNode temp = root; while (temp != null) { if (n < temp.data) { if (temp.left == null) { temp.left = newNode; break; } else temp = temp.left; } else { if (temp.right == null) { temp.right = newNode; break; } else temp = temp.right; } } return root; } public TreeNode delete(TreeNode root, int data) { if (root != null) { if (data < root.data) { root.left = delete(root.left, data); } else if (data > root.data) { root.right = delete(root.right, data); } else if (root.left != null && root.right != null) { // Case 3: Two child int minElement = findMin(root.right); root.data = minElement; root.right = delete(root.right, minElement); } else { // Case 1 & 2: No Child and One Child if (root.left == null) root = root.right; else if (root.right == null) root = root.left; } } return root; } public TreeNode binarySearch(TreeNode root, int data) { if (root == null) return null; if (root.data == data) { return root; } else if (data <= root.data) { return binarySearch(root.left, data); } else { return binarySearch(root.right, data); } } public TreeNode binarySearchIterative(TreeNode root, int data) { if (root == null) return null; TreeNode temp = root; while (temp != null) { if (data == temp.data) { return temp; } else if (data < temp.data) { temp = temp.left; } else { temp = temp.right; } } return null; } // Find the node with minimum value in a Binary Search Tree public int findMin(TreeNode root) { if (root == null) return -1; while (root.left != null) root = root.left; return root.data; } public int findMax(TreeNode root) { if (root == null) return -1; while (root.right != null) root = root.right; return root.data; } /* BST Traversals */ public void preOrder(TreeNode root) { if (root != null) { System.out.print(root.data + " "); preOrder(root.left); preOrder(root.right); } } public void inOrder(TreeNode root) { if (root != null) { inOrder(root.left); System.out.print(root.data + " "); inOrder(root.right); } } public void postOrder(TreeNode root) { if (root != null) { postOrder(root.left); postOrder(root.right); System.out.print(root.data + " "); } } public int sizeOfBinaryTree(TreeNode root) { if (root == null) return 0; return 1 + sizeOfBinaryTree(root.left) + sizeOfBinaryTree(root.right); } /************************ Construction Problems ***********************/ // Serialize & Deserialize - Uses Preorder // 1.Serialize:Uses Tree to List public ArrayList<Integer> serialize1(ArrayList<Integer> result, TreeNode root) { if (root != null) { result.add(root.data); serialize1(result, root.left); serialize1(result, root.right); } return result; } // 1.Deserialize: List to Tree public TreeNode deserialize1(Integer[] preOrder, int low, int high) { if (low > high) return null; TreeNode root = new TreeNode(preOrder[low]); int mid = findRight(preOrder, root.data, low, high); root.left = deserialize1(preOrder, low + 1, mid - 1); root.right = deserialize1(preOrder, mid, high); return root; } int findRight(Integer[] preOrder, int root, int low, int high) { int i; for (i = low; i <= high; i++) { if (root < preOrder[i]) break; } return i; } // 2. Serialize: Tree to String public String serialize2(TreeNode root) { if (root == null) return ""; StringBuilder sb = new StringBuilder(); serialize2(root, sb); System.out.println(sb.toString()); return sb.toString(); } public void serialize2(TreeNode root, StringBuilder sb) { if (root == null) return; sb.append(root.data + ","); serialize2(root.left, sb); serialize2(root.right, sb); } // Decodes your encoded data to tree. public TreeNode deserialize2(String data) { if (data == null || data == "") return null; String[] str = data.split(","); return deserialize2(str, 0, str.length - 1); } public TreeNode deserialize2(String[] str, int l, int h) { if (l > h) return null; TreeNode root = new TreeNode(Integer.valueOf(str[l])); int m = findMid(str, l, h, root.data); root.left = deserialize2(str, l + 1, m - 1); root.right = deserialize2(str, m, h); return root; } public int findMid(String[] str, int l, int h, int data) { int val, i; for (i = l; i <= h; i++) { val = Integer.valueOf(str[i]); if (data < val) break; } return i; } // Similar to approach2 public TreeNode deserialize21(String data) { if (data.isEmpty()) return null; Queue<String> q = new LinkedList<>(Arrays.asList(data.split(","))); return deserialize21(q, Integer.MIN_VALUE, Integer.MAX_VALUE); } public TreeNode deserialize21(Queue<String> q, int lower, int upper) { if (q.isEmpty()) return null; String s = q.peek(); int val = Integer.parseInt(s); if (val < lower || val > upper) return null; q.poll(); TreeNode root = new TreeNode(val); root.left = deserialize21(q, lower, val); root.right = deserialize21(q, val, upper); return root; } /************************ Conversion Problems ***********************/ /* Binary Tree to Binary Search Tree Conversion Convert Sorted Array to Binary Search Tree */ public TreeNode sortedArrayToBST(int[] nums) { if (nums.length == 0) return null; return arrayToBST(nums, 0, nums.length - 1); } private TreeNode arrayToBST(int[] nums, int low, int high) { if (low > high) return null; int mid = (low + high) / 2; TreeNode root = new TreeNode(nums[mid]); root.left = arrayToBST(nums, low, mid - 1); root.right = arrayToBST(nums, mid + 1, high); return root; } // Approach1: Similar to sortedArrayToBST; // Time: O(nlogn) & Space:(Recursion Stack): O(n) public TreeNode sortedListToBST(ListNode head) { if (head == null) return null; if (head.next == null) return new TreeNode(head.data); ListNode prev = null; ListNode slow = head; ListNode fast = head; // Find the middle Node while (fast != null && fast.next != null) { prev = slow; slow = slow.next; fast = fast.next.next; } prev.next = null; TreeNode root = new TreeNode(slow.data); root.left = sortedListToBST(head); root.right = sortedListToBST(slow.next); return root; } // Another Approach: Both gives the same complexity; // Time: O(n) & Space(Recursion Stack): O(logn) ListNode node; public TreeNode sortedListToBST2(ListNode head) { if (head == null) return null; int size = length(head); node = head; return buildTree(0, size - 1); } public TreeNode buildTree(int l, int h) { if (l > h) return null; int m = l + (h - l) / 2; TreeNode left = buildTree(l, m - 1); TreeNode root = new TreeNode(node.data); root.left = left; node = node.next; root.right = buildTree(m + 1, h); return root; } public int length(ListNode head) { int count = 0; while (head != null) { count++; head = head.next; } return count; } /************************ Checking Problems ***************************/ public boolean isBST(TreeNode root) { // return isBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE); return isBST1(root, null, null); } /* * It handles all the corner cases: * Eg: [-2147483648,null,2147483647], [1,1],[-2147483648], [2147483647], [-2147483648,-2147483648], * [2147483647, null,2147483647] */ private boolean isBST1(TreeNode root, TreeNode minNode, TreeNode maxNode) { if (root == null) return true; if (minNode != null && minNode.data >= root.data) return false; else if (maxNode != null && maxNode.data <= root.data) return false; return isBST1(root.left, minNode, root) && isBST1(root.right, root, maxNode); } /* This method does not work for corner cases * Eg: [-2147483648,null,2147483647], [1,1],[-2147483648], [2147483647],[-2147483648,-2147483648], * [2147483647, null,2147483647] */ public boolean isBST(TreeNode root, int min, int max) { if (root == null) return true; /*if (root.data <= min && root.data > max) return false;*/ if (root.data <= min || root.data >= max) return false; return isBST(root.left, min, root.data) && isBST(root.right, root.data, max); // return isBST(root.left, min, root.data - 1) && isBST(root.right, root.data + 1, max); } /**************************** Searching/Path Problems **************************/ public int inOrderPredecessor(TreeNode root, int key) { if (root == null) return -1; if (key == root.data) { TreeNode leftSubTree = root.left; if (leftSubTree != null) { // Find the next node in the left subtree(Pred should be present in the left sub tree) while (leftSubTree.right != null)// Keep moving to right side, to find the prev(successor) node in BST leftSubTree = leftSubTree.right; return leftSubTree.data; } else { return -1; } } else if (key < root.data) { return inOrderPredecessor(root.left, key); } else { int pred = inOrderPredecessor(root.right, key); if (pred == -1) // If there is no element in leftSubtree, then root element should be previous element pred = root.data; return pred; } } public int inOrderSuccessor(TreeNode root, int key) { if (root == null) return -1; if (key == root.data) { // Find the next node in the right subtree TreeNode rightSubTree = root.right; if (rightSubTree != null) { while (rightSubTree.left != null)// Keep moving to left side, to find the next(successor) node in BST rightSubTree = rightSubTree.left; return rightSubTree.data; } return -1; } else if (key < root.data) { int successor = inOrderSuccessor(root.left, key); if (successor == -1) // If there is no element in rightSubtree, then root element should be next element successor = root.data; return successor; } else { return inOrderSuccessor(root.right, key); } } /** * Closest Binary Search Tree Value: Given a non-empty binary search tree and a target value, find the value in the * BST that is closest to the target. Note: Given target value is a floating point. You are guaranteed to have only * one unique value in the BST that is closest to the target. Use: Binary Search Alg */ int closest; double minDiff = Double.MAX_VALUE; // Approach1: Recursive Approach public int closestValue1(TreeNode root, double target) { helper(root, target); return closest; } public void helper(TreeNode root, double target) { if (root == null) return; if (Math.abs(root.data - target) < minDiff) { minDiff = Math.abs(root.data - target); closest = root.data; } if (target < root.data) { helper(root.left, target); } else { helper(root.right, target); } } // Approach2: Iterative Approach public int closestValue2(TreeNode root, double target) { double closest = Integer.MAX_VALUE; int value = 0; TreeNode current = root; while (current != null) { if (closest > Math.abs(current.data - target)) { closest = Math.abs(current.data - target); value = current.data; } if (current.data < target) { current = current.right; } else if (current.data > target) { current = current.left; } else { break; } } return value; } /* Closest Binary Search Tree Value II: * Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target. * * Note: * Given target value is a floating point. You may assume k is always valid, that is: k ≤ total nodes. * You are guaranteed to have only one unique set of k values in the BST that are closest to the target. * * Follow up: Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)? */ public List<Integer> closestKValues(TreeNode root, double target, int k) { List<Integer> result = new ArrayList<>(); if (root == null) { return result; } Stack<Integer> precedessor = new Stack<>(); Stack<Integer> successor = new Stack<>(); getPredecessor(root, target, precedessor); getSuccessor(root, target, successor); for (int i = 0; i < k; i++) { if (precedessor.isEmpty()) { result.add(successor.pop()); } else if (successor.isEmpty()) { result.add(precedessor.pop()); } else if (Math.abs((double) precedessor.peek() - target) < Math.abs((double) successor.peek() - target)) { result.add(precedessor.pop()); } else { result.add(successor.pop()); } } return result; } private void getPredecessor(TreeNode root, double target, Stack<Integer> precedessor) { if (root == null) { return; } getPredecessor(root.left, target, precedessor); if (root.data > target) { return; } precedessor.push(root.data); getPredecessor(root.right, target, precedessor); } private void getSuccessor(TreeNode root, double target, Stack<Integer> successor) { if (root == null) { return; } getSuccessor(root.right, target, successor); if (root.data <= target) { return; } successor.push(root.data); getSuccessor(root.left, target, successor); } public TreeNode lowestCommonAncestor(TreeNode root, int data1, int data2) { if (root != null) { if (data1 < root.data && data2 < root.data) { return lowestCommonAncestor(root.left, data1, data2); } else if (data1 > root.data && data2 > root.data) { return lowestCommonAncestor(root.right, data1, data2); } else { return root; } } return root; } /* Following are some important points in favor of BSTs: * We can get all keys in sorted order by just doing Inorder Traversal of BST. This is not a natural operation in * Hash Tables and requires extra efforts. * Doing "finding closest lower and greater elements", "range queries", "order statistics" are easy to do with BSTs. * Like sorting, these operations are not a natural operation with Hash Tables. * With Self-Balancing BSTs, all operations are guaranteed to work in O(Logn) time. But with Hashing, Θ(1) is average * time and some particular operations may be costly, especially when table resizing happens. */ // 1.finding closest lower and greater elements - Floor and Ceil from a BST: static TreeNode root; // Function to find ceil of a given input in BST. If input is more than the max key in BST, return -1 int Ceil(TreeNode node, int input) { if (node == null) return -1; if (node.data == input) return node.data; // If root's key is smaller, ceil must be in right subtree if (node.data < input) return Ceil(node.right, input); // Else, either left subtree or root has the ceil value int ceil = Ceil(node.left, input); return (ceil >= input) ? ceil : node.data; } // Function to find floor of a given input in BST. If input is less than the min key in BST, return -1 public TreeNode floor(TreeNode root) { return null; } /* 2.Range Queries: Print BST keys in the given range * Given two values k1 and k2 (where k1 < k2) and a root pointer to a Binary Search Tree. Print all the keys of tree in * range k1 to k2. i.e. print all x such that k1<=x<=k2 and x is a key of given BST. Print all the keys in increasing order. */ /* The functions prints all the keys which in the given range [k1..k2]. The function assumes than k1 < k2 */ void printRange(TreeNode node, int k1, int k2) { if (node == null) return; /* Since the desired o/p is sorted, recurse for left subtree first If root->data is greater than k1, then only we can get o/p keys in left subtree */ if (k1 < node.data) { printRange(node.left, k1, k2); } /* if root's data lies in range, then prints root's data */ if (k1 <= node.data && k2 >= node.data) { System.out.print(node.data + " "); } /* If root->data is smaller than k2, then only we can get o/p keys in right subtree */ if (k2 > node.data) { printRange(node.right, k1, k2); } } // TODO: Simplify Kth Element Problemss... // 3.Order Statistics: Find k-th smallest/Largest element in BST // 3.i.Find k-th smallest element in BST // Approach1: Using Inorder traversal & additional O(n) space public int kthSmallestElement1(TreeNode root, int k) { if (root == null || k == 0) return 0; ArrayList<Integer> list = new ArrayList<>(); kthSmallestElement1(root, list); return list.get(k - 1); } private void kthSmallestElement1(TreeNode root, ArrayList<Integer> list) { if (root == null) return; kthSmallestElement1(root.left, list); list.add(root.data); kthSmallestElement1(root.right, list); } // Approach2: Using Inorder traversal, without additional space public int kthSmallestElement2(TreeNode root, int k) { int[] count = new int[1]; TreeNode result = kthSmallestElement2(root, k, count); return result != null ? result.data : 0; } private TreeNode kthSmallestElement2(TreeNode root, int k, int[] count) { if (root == null || count[0] > k) return null; TreeNode kthLargestNode = kthSmallestElement2(root.left, k, count); if (kthLargestNode == null) { count[0]++; if (count[0] == k) return root; } if (kthLargestNode == null) kthLargestNode = kthSmallestElement2(root.right, k, count); return kthLargestNode; } // Approach3: Using Priority Queue, Inorder traversal -> This solution gives kth eleemnt in BT also public int kthSmallestElement3(TreeNode root, int k) { if (root == null) return 0; PriorityQueue<Integer> queue = new PriorityQueue<>(Collections.reverseOrder()); kthSmallestElement3(root, queue, k); return queue.peek(); } public void kthSmallestElement3(TreeNode root, PriorityQueue<Integer> queue, int k) { if (root == null) return; if (queue.size() < k || root.data < queue.peek()) { if (queue.size() >= k) queue.remove(); queue.add(root.data); } kthSmallestElement3(root.left, queue, k); kthSmallestElement3(root.right, queue, k); } // Approach4: Morris Traversal public int kthSmallestElement4(TreeNode root, int k) { return 0; } // Approach5: Augmented Tree Data Structure public int kthSmallestElement5(TreeNode root, int k) { if (root == null) return 0; int subTreeSize = sizeOfBinaryTree(root); if (subTreeSize == k - 1) return root.data; else if (subTreeSize >= k) return kthSmallestElement5(root.left, k); else return kthSmallestElement5(root, k - subTreeSize - 1); } // 3.ii. K’th Largest element in BST // Approach1: Using Reverse Inorder traversal & additional O(n) space- (RiRoL) public int kthLargestElement1(TreeNode root, int k) { if (root == null || k == 0) return 0; ArrayList<Integer> list = new ArrayList<>(); kthLargestElement1(root, list); return list.get(k - 1); } private void kthLargestElement1(TreeNode root, ArrayList<Integer> list) { if (root == null) return; kthLargestElement1(root.right, list); list.add(root.data); kthLargestElement1(root.left, list); } // Approach2: Using reverse inorder traversal, without additional space- (RiRoL) public int kthLargestElement2(TreeNode root, int k) { int[] count = new int[1]; TreeNode result = kthLargestElement2(root, k, count); return result != null ? result.data : 0; } private TreeNode kthLargestElement2(TreeNode root, int k, int[] count) { if (root == null || count[0] > k) return null; TreeNode kthLargestNode = kthLargestElement2(root.right, k, count); if (kthLargestNode == null) { count[0]++; if (count[0] == k) return root; } if (kthLargestNode == null) kthLargestNode = kthLargestElement2(root.left, k, count); return kthLargestNode; } // Approach3: Using Priority Queue, Inorder traversal public int kthLargestElement3(TreeNode root, int k) { if (root == null) return 0; PriorityQueue<Integer> queue = new PriorityQueue<>(); kthLargestElement3(root, queue, k); return queue.peek(); } public void kthLargestElement3(TreeNode root, PriorityQueue<Integer> queue, int k) { if (root == null) return; if (queue.size() < k || root.data > queue.peek()) { if (queue.size() >= k) queue.remove(); queue.add(root.data); } kthLargestElement3(root.left, queue, k); kthLargestElement3(root.right, queue, k); } /************************ Other BST Problems ***********************/ }
true
2de6142bc7506027933f68f3e41b0a5f6a18b4f5
Java
zJiangnan/Java
/RD_IDEA_Java/JavaIO/src/main/java/cn/echo/bufferedstream/BufferedInputStreamTest.java
UTF-8
2,961
3.296875
3
[]
no_license
package cn.echo.bufferedstream; import java.io.*; /** * @ClassName : BufferedInputStreamTest * @Author : Jiangnan * @Date: 2020/11/3 10:50 * @Description : 缓冲字节输入流 **/ public class BufferedInputStreamTest { public static void main(String[] args) throws IOException { InputStream is = new FileInputStream("FileData/a.txt"); BufferedInputStream bis = new BufferedInputStream(is); // 是否支持mark 或 reset System.out.println(bis.markSupported()); // 读取操作时---pos标记 // 输出1 ------读取一次pos标记1 System.out.println((char) + bis.read()); // 后退多少个字节-----往前回退(后面读取后流是不可以逆的,mark会退回到1的后面) // 参数:限制回退的范围--缓冲大小的意思,也就是说mark(3)就只能让流向前流三个超出则会失效 // --BufferedInputStream超出也不会失效,因为BufferedInputStream有自己的缓冲区 只要不超过自己的缓冲区就不会失效 // bis.mark(4); // 输出2 -----在mark执行后读取4次 System.out.println((char) + bis.read()); // 输出3-4-5 System.out.println((char) + bis.read()); bis.mark(4); System.out.println((char) + bis.read()); // --- 此时pos等于5 ----读取了5次 System.out.println((char) + bis.read()); // 重置---重置到mark的指定位置,当mark的参数为4时,就是mark能回退流的位置的范围,超出则会失效 bis.reset(); // 输出2---- 因为是读取1后回退到1之后的位置,如果mark在第三次读取时,就会回退到第三次之后。 System.out.println("重置后----" + (char) + bis.read()); // 调用复制文件方法 copy("FileData/Lover.flac", "D:\\SystemZ\\desktop\\Lover.flac"); bis.close(); is.close(); } /** * 复制文件(大文件适用) * @param src 源文件 * @param disc 目标地址 * @throws IOException IO异常 */ public static void copy(String src, String disc) throws IOException { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(disc)); // 字节数组越大消耗时间越少----内存占用越大 byte[] b = new byte[2048]; int len = 0; // 开始复制的时间戳 long sta = System.currentTimeMillis(); while ((len = bis.read(b)) != -1) { bos.write(b, 0 ,len); } // 结束复制时的时间戳 long ove = System.currentTimeMillis(); System.out.println("时间消耗:" + (ove - sta)); // 关闭流--如果存储处理流和简单流时,可以只关闭处理流,JVM会自动关闭简单流 bis.close(); bos.close(); } }
true
b5f10ebceef380557ad36b2f00bcfeb677af6dff
Java
zhanglei-1987/project
/project-utility/src/test/java/cn/quickly/project/utility/reflect/AnnotationsTest.java
UTF-8
1,698
2.265625
2
[]
no_license
package cn.quickly.project.utility.reflect; import java.lang.reflect.Method; import org.junit.Test; import cn.quickly.project.utility.map.Maps; import cn.quickly.project.utility.mock.MockComponent; import cn.quickly.project.utility.mock.MockDemo; import cn.quickly.project.utility.mock.MockInstance; import cn.quickly.project.utility.mock.MockMethod; import cn.quickly.project.utility.mock.MockService; public class AnnotationsTest { @Test public void testNotGetExtend() { System.out.println(Annotations.getExtend(MockDemo.class, Override.class)); } @Test public void testGetExtend() { System.out.println(MockDemo.class.getAnnotation(MockComponent.class)); MockService mockService = MockDemo.class.getAnnotation(MockService.class); System.out.println(mockService.annotationType().getAnnotation(MockComponent.class)); System.out.println(mockService.getClass().getAnnotation(MockComponent.class)); System.out.println(MockDemo.class.getAnnotation(MockService.class)); System.out.println(Annotations.getExtend(MockDemo.class, MockComponent.class)); System.out.println(Annotations.getExtend(MockDemo.class, MockComponent.class)); } @Test public void testGetMap() { MockService mockService = MockDemo.class.getAnnotation(MockService.class); System.out.println(Annotations.getMap(mockService)); System.out.println(Maps.getMap(mockService)); } @Test public void testGetDeclared() throws Exception { Method method = MockInstance.class.getDeclaredMethod("say", String.class); System.out.println(method); System.out.println(Annotations.getDeclared(method, MockMethod.class)); } }
true
81553ccf50d063a9680a4e6f503ba1cd5dafceb0
Java
alex-carvalho/clean-code
/src/main/java/com/ac/example/cleanCode/service/CandidateServiceImpl.java
UTF-8
3,755
2.5625
3
[ "MIT" ]
permissive
package com.ac.example.cleanCode.service; import com.ac.example.cleanCode.model.Candidate; import com.ac.example.cleanCode.model.Course; import com.ac.example.cleanCode.repository.CandidateRepository; import com.ac.example.cleanCode.service.exceptions.CandidateDoesntMeetRequirementsException; import com.ac.example.cleanCode.service.exceptions.NoSessionsApprovedException; import com.ac.example.cleanCode.utis.WebBrowser; import java.util.Arrays; import java.util.List; /** * @author Alex Carvalho */ public class CandidateServiceImpl implements CandidateService { private CandidateRepository repository; public CandidateServiceImpl(CandidateRepository repository) { this.repository = repository; } @Override public int register(Candidate candidate) { validateRegistration(candidate); return repository.save(candidate); } private void validateRegistration(Candidate candidate) { validateData(candidate); boolean isQualified = candidateExceptional(candidate) || !obviousRedFlags(candidate); if (!isQualified) { throw new CandidateDoesntMeetRequirementsException("This Candidate doesn't meet our standards."); } approveCourses(candidate); } private void validateData(Candidate candidate) { if (candidate.getFirstName() == null || candidate.getFirstName().isEmpty()) { throw new IllegalArgumentException("First Name is required."); } if (candidate.getLastName() == null || candidate.getLastName().isEmpty()) { throw new IllegalArgumentException("Last Name is required."); } if (candidate.getEmail() == null || candidate.getEmail().isEmpty()) { throw new IllegalArgumentException("Email is required."); } if (candidate.getCourseList().isEmpty()) { throw new IllegalArgumentException("Can't register speaker with no sessions to present."); } } private boolean candidateExceptional(Candidate candidate) { if (candidate.getYearsExperience() > 10) return true; if (candidate.hasBlog()) return true; if (candidate.getCourseList().size() > 3) return true; List<String> preferredEmployers = Arrays.asList("Pluralsight", "Microsoft", "Google", "Fog Creek Software", "37Signals", "Telerik"); return preferredEmployers.contains(candidate.getEmployer()); } private boolean obviousRedFlags(Candidate candidate) { String emailDomain = candidate.getEmail().split("@")[1]; List<String> ancientEmailDomains = Arrays.asList("aol.com", "hotmail.com", "prodigy.com", "compuserve.com"); return (ancientEmailDomains.contains(emailDomain) || ((candidate.getBrowser().getName() == WebBrowser.BrowserName.INTERNET_EXPLORER && candidate.getBrowser().getMajorVersion() < 9))); } private void approveCourses(Candidate candidate) { for (Course course : candidate.getCourseList()) { course.setApproved(!coursesIsAboutOldTechnology(course)); } boolean noSessionsApproved = candidate.getCourseList().stream().noneMatch(Course::isApproved); if (noSessionsApproved) { throw new NoSessionsApprovedException("No sessions approved"); } } private boolean coursesIsAboutOldTechnology(Course course) { List<String> oldTechnologies = Arrays.asList("Cobol", "Punch Cards", "Commodore", "VBScript"); for (String oldTechnology : oldTechnologies) { if (course.getTitle().contains(oldTechnology) || course.getDescription().contains(oldTechnology)) { return true; } } return false; } }
true
f40211ee0b1bfa66b243df69779218f415b1ddd7
Java
Deborina/DataStreamingService
/data-streaming-service/src/main/java/com/hellofreash/constant/QueryConstant.java
UTF-8
524
1.960938
2
[]
no_license
package com.hellofreash.constant; public class QueryConstant { public static final String QUERY_SAVE = "insert into EVENTS(timestamp_millis, event_col1, event_col2) " + "values(?, ?, ?) "; public static final String QUERY_EVENT_STATS = "select count(*) as count, sum(EVENT_COL1) as firstColumnSum," + " avg(EVENT_COL1) as firstColumnAvg, sum(EVENT_COL2) as secondColumnSum," + " avg(EVENT_COL2) as secondColumnAvg from EVENTS" + " where TIMESTAMP_MILLIS >= timestampadd(second, -60, now());"; }
true
38929a2d06bb7641dd9af9bca6b35d520e9770bd
Java
GenYuanLian/monera
/Service/shop-soa/shop-soa-api/src/main/java/com/genyuanlian/consumer/shop/api/IWeixinpayApi.java
UTF-8
1,034
1.890625
2
[]
no_license
package com.genyuanlian.consumer.shop.api; import java.util.Map; import com.genyuanlian.consumer.shop.vo.ShopMessageVo; import com.genyuanlian.consumer.shop.vo.WeixinpayParamsVo; public interface IWeixinpayApi { /** * 微信支付,同意下单接口 * @param req * @return */ public ShopMessageVo<Map<String,Object>> unifiedOrder(WeixinpayParamsVo req); /** * 微信支付回调接口处理 * @param map * @return */ public ShopMessageVo<String> weixinpayAysnNotify(Map<String, String> map); /** * 获取微信openId * @param code * @param isMinProgram 是否小程序 * @return */ public ShopMessageVo<Map<String, Object>>getWeixinOpenId(String code,Boolean isMinProgram) throws Exception ; /** * 微信回调结果XML构造 * @param return_code * @param return_msg * @return */ public String setXML(String return_code, String return_msg); /** * 获取微信分享配置参数 * @return */ public ShopMessageVo<Map<String, String>> getWeixinShareConfig(String url); }
true
d7cf37f1078d1fd490efff03761a2ce22ee75961
Java
sirinath/Terracotta
/dso/branches/3.5/code/base/dso-l1/src/com/tc/object/handler/ReInvalidateHandler.java
UTF-8
3,610
2.265625
2
[]
no_license
/* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. */ package com.tc.object.handler; import com.tc.object.ObjectID; import com.tc.object.cache.CachedItemStore; import com.tc.util.ObjectIDSet; import com.tc.util.TCTimerService; import java.util.Iterator; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.locks.ReentrantLock; public class ReInvalidateHandler { private final static long EXPIRE_SET_TIMER_PERIOD = 60 * 1000; private final static long RE_INVALIDATE_TIMER_PERIOD = 1 * 1000; private final CachedItemStore store; private ConcurrentObjectIDSet prev = null; private ConcurrentObjectIDSet current = new ConcurrentObjectIDSet(); private final Timer timer = TCTimerService.getInstance() .getTimer("Re-invalidation Timer"); public ReInvalidateHandler(CachedItemStore store) { this.store = store; timer.schedule(new ExpireSetTimerTask(), EXPIRE_SET_TIMER_PERIOD, EXPIRE_SET_TIMER_PERIOD); timer.schedule(new ReInvalidateTimerTask(), RE_INVALIDATE_TIMER_PERIOD, RE_INVALIDATE_TIMER_PERIOD); } public void add(ObjectID oid) { current.add(oid); } private class ExpireSetTimerTask extends TimerTask { @Override public void run() { synchronized (ReInvalidateHandler.this) { prev = current; current = new ConcurrentObjectIDSet(); } } } private class ReInvalidateTimerTask extends TimerTask { @Override public void run() { final ConcurrentObjectIDSet tempPrev; final ConcurrentObjectIDSet tempCurrent; synchronized (ReInvalidateHandler.this) { tempPrev = prev; tempCurrent = current; } if (tempPrev != null) { tempPrev.processInvalidations(); } if (tempCurrent != null) { tempCurrent.processInvalidations(); } } } private class ConcurrentObjectIDSet { private static final int CONCURRENCY = 4; private final ReentrantLock[] locks; private final ObjectIDSet[] oidSets; public ConcurrentObjectIDSet() { this(CONCURRENCY); } public ConcurrentObjectIDSet(int concurrency) { locks = new ReentrantLock[concurrency]; oidSets = new ObjectIDSet[concurrency]; for (int i = 0; i < concurrency; i++) { oidSets[i] = new ObjectIDSet(); locks[i] = new ReentrantLock(); } } private ReentrantLock getLock(ObjectID oid) { return locks[(int) (Math.abs(oid.toLong()) % CONCURRENCY)]; } private ObjectIDSet getSet(ObjectID oid) { return oidSets[(int) (Math.abs(oid.toLong()) % CONCURRENCY)]; } public void processInvalidations() { for (int i = 0; i < oidSets.length; i++) { ReentrantLock lock = locks[i]; ObjectIDSet oidSet = oidSets[i]; lock.lock(); try { if (oidSet.size() == 0) { continue; } Iterator<ObjectID> iterator = oidSet.iterator(); while (iterator.hasNext()) { ObjectID oid = iterator.next(); if (store.flush(oid)) { iterator.remove(); } } } finally { lock.unlock(); } } } public void add(ObjectID oid) { ReentrantLock lock = getLock(oid); ObjectIDSet set = getSet(oid); lock.lock(); try { set.add(oid); } finally { lock.unlock(); } } } }
true
2bcdd83707f7f5e6c969a7eb132f2254b21b65bc
Java
montoyaguzman/itapizaco
/1_Fundamentos/Programacion Orientada A Objetos/Practicas de clase/Teclado.java
ISO-8859-1
447
3.4375
3
[]
no_license
import java.io.*; public class Teclado { public int leeEntero() { boolean bandera=false; int dato=0; while(!bandera) { try { BufferedReader br= new BufferedReader (new InputStreamReader(System.in)); dato=Integer.parseInt(br.readLine()); bandera=true; } catch(Exception dato) { System.out.print("El nmero que usted introdujo no es un entero"); bandera=false; } } return dato; } }
true
f78d86d161dd2b04be7211f5ce8d09a905e1a9ef
Java
j-white/hacked-castor
/cpa/src/main/java/org/exolab/castor/jdo/engine/JDOFieldDescriptor.java
UTF-8
1,761
1.789063
2
[]
no_license
/* * Copyright 2006 Ralf Joachim * * 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.exolab.castor.jdo.engine; import org.exolab.castor.mapping.FieldDescriptor; import org.exolab.castor.mapping.TypeConvertor; /** * @author <a href="mailto:ralf DOT joachim AT syscon DOT eu">Ralf Joachim</a> * @version $Revision$ $Date: 2005-12-06 14:55:28 -0700 (Tue, 06 Dec 2005) $ */ public interface JDOFieldDescriptor extends FieldDescriptor { /** * Returns the convertor from the field type to an external type. * * @return Convertor from field type */ TypeConvertor getConvertor(); /** * Returns the convertor parameter. * * @return Convertor parameter */ String getConvertorParam(); /** * Returns the SQL name of this field. * * @return The SQL name of this field */ String[] getSQLName(); /** * Returns the SQL type of this field. * * @return The SQL type of this field */ int[] getSQLType(); String getManyTable(); String[] getManyKey(); /** * Returns true if dirty checking is required for this field. * * @return True if dirty checking required */ boolean isDirtyCheck(); boolean isReadonly(); }
true
61467f3a4d5e199fcb52ae3bfe959af1b6d2bab1
Java
dcoraboeuf/txconsole
/txconsole-core/src/main/java/net/txconsole/core/model/TranslationMapResponse.java
UTF-8
357
1.632813
2
[]
no_license
package net.txconsole.core.model; import lombok.Data; import java.util.List; import java.util.Locale; /** * Truncated version of a {@link TranslationMap}, to be used at client side. */ @Data public class TranslationMapResponse { private final int total; private final List<Locale> locales; private final List<TranslationEntry> entries; }
true
e24e5204daae3d9f41d479cb1cd00be7f427cb0c
Java
andressj6/spring-social-spotify
/src/main/java/org/springframework/social/spotify/api/Spotify.java
UTF-8
1,295
1.585938
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2014 the original author or authors. * * 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.springframework.social.spotify.api; import org.springframework.social.ApiBinding; /** * Interface specifying a basic set of operations for interacting with Spotify. * Implemented by {@link SpotifyTemplate}. * * @author André Lima */ public interface Spotify extends ApiBinding { AlbumOperations albumOperations(); ArtistOperations artistOperations(); BrowseOperations browseOperations(); FollowOperations followOperations(); LibraryOperations libraryOperations(); PlaylistOperations playlistOperations(); SearchOperations searchOperations(); ProfileOperations profileOperations(); TrackOperations trackOperations(); }
true
90cd8dc66b0022019a167f9dd9e629622e4555fc
Java
tvunak/springbackend
/src/main/java/com/example/restexampletv/model/ArticleDetail.java
UTF-8
1,248
2.34375
2
[]
no_license
package com.example.restexampletv.model; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; @Entity public class ArticleDetail{ @Id private long id; private String description; private String manufacturer; @OneToOne @MapsId @JsonIgnore private Article article; public ArticleDetail() { } public ArticleDetail(long id, String description, String manufacturer){ this.id = id; this.description = description; this.manufacturer = manufacturer; } public ArticleDetail(Article article) { this.article = article; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getManufacturer() { return manufacturer; } public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } public Article getArticle() { return article; } public void setArticle(Article article) { this.article = article; } }
true
0eec23d0a9172681b6ecd2d37e74b2e30cf590b3
Java
Kushagra369/Codeforces_Sol
/MaximumInTable.java
UTF-8
521
3.140625
3
[]
no_license
import java.util.*; public class MaximumInTable { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.close(); int[][] a = new int[n][n]; int max = 0; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { if(i==0 ||j==0) { a[i][j] = 1; } else { a[i][j] = a[i-1][j] + a[i][j-1]; } if(a[i][j]>max) { max =a[i][j]; } } } System.out.println(max); } }
true
1ae24a6069678ca8d120a8d8cf44911f18127fdb
Java
yangsongshui/xds
/ebottle/src/main/java/com/wsq/ebottle/fragment/LoveFragment.java
UTF-8
4,150
2.0625
2
[]
no_license
package com.wsq.ebottle.fragment; import java.util.ArrayList; import com.wsq.ebittle.common.Constants; import com.wsq.ebottle.R; import com.wsq.ebottle.adapter.LoveAdapter; import com.wsq.ebottle.bean.Event; import com.wsq.ebottle.broadcast.CountDownReceiver; import com.wsq.ebottle.db.dao.EventTableDao; import com.wsq.ebottle.widget.MarqueeText; import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; 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.ListView; import android.widget.TextView; public class LoveFragment extends Fragment{ private ListView listLove; private LoveAdapter loveAdapter; private ArrayList<Event> events; private TextView tvRemindTime; //剩余时间 private static int UPDATE_UI_TEXT=1001; private static int UPDATE_UI_GONE=1002; String remindTime; private MarqueeText marqueeText; SharedPreferences.Editor editor; EventTableDao dao; private BroadcastReceiver receiver=new BroadcastReceiver() { @Override public void onReceive(Context arg0, Intent arg1) { // TODO Auto-generated method stub String action=arg1.getAction(); if(Constants.BROADCAST_ONTICKING.equals(action)) { remindTime=arg1.getStringExtra("time"); handler.sendEmptyMessage(UPDATE_UI_TEXT); Log.i("wsq","time"); }else if(Constants.BROADCAST_ONTICK_FINISH.equals(action)) { handler.sendEmptyMessage(UPDATE_UI_GONE); if(editor!=null) { editor.putBoolean("isStart",false); editor.commit(); } } } }; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // TODO Auto-generated method stub return inflater.inflate(R.layout.fragment_love,container,false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { // TODO Auto-generated method stub super.onActivityCreated(savedInstanceState); getActivity().registerReceiver(receiver, makeGattUpdateIntentFilter()); initView(); } @SuppressLint("InflateParams") private void initView() { editor=getActivity().getSharedPreferences(Constants.COUNT_DOWN_TIME,Context.MODE_PRIVATE).edit(); listLove=(ListView)getView().findViewById(R.id.list_love); View view=LayoutInflater.from(getActivity()).inflate(R.layout.love_list_head_item, null); listLove.addHeaderView(view); marqueeText=(MarqueeText) getActivity().findViewById(R.id.txt_marquee); marqueeText.setVisibility(View.GONE); //发一次广播更新时间 Intent intent=new Intent(getActivity(),CountDownReceiver.class); intent.setAction("com.wsq.ebottle"); getActivity().sendBroadcast(intent); //数据库 dao=new EventTableDao(getActivity()); initEvents(); } private static IntentFilter makeGattUpdateIntentFilter() { IntentFilter filter=new IntentFilter(); filter.addAction(Constants.BROADCAST_ONTICKING); filter.addAction(Constants.BROADCAST_ONTICK_FINISH ); return filter; } //初始化事件 private void initEvents() { events=dao.getAllEvent(); loveAdapter=new LoveAdapter(getActivity(), events); listLove.setAdapter(loveAdapter); } Handler handler=new Handler() { public void handleMessage(android.os.Message msg) { if(msg.what==UPDATE_UI_TEXT) { marqueeText.setVisibility(View.VISIBLE); marqueeText.setText("距离喂奶的时间还剩"+remindTime); }else if(msg.what==UPDATE_UI_GONE) { marqueeText.setVisibility(View.GONE); } }; }; @Override public void onDestroy() { super.onDestroy(); getActivity().unregisterReceiver(receiver); } @Override public void onHiddenChanged(boolean hidden) { if(!hidden) { events.clear(); initEvents(); } super.onHiddenChanged(hidden); } }
true
686dfcf2277d738b9025fff9f3c26879163a8a65
Java
an-jun/springboot-wechat-demo
/src/main/java/cc/anjun/wechat/domain/res/ImageMessage.java
UTF-8
300
1.789063
2
[]
no_license
package cc.anjun.wechat.domain.res; import cc.anjun.wechat.domain.BaseMessage; public class ImageMessage extends BaseMessage { private Image Image;//Image节点 public Image getImage() { return Image; } public void setImage(Image image) { Image = image; } }
true
7853195d1abd08730b25290b7fc9240d4ca8c7f3
Java
Kseniya-Katselnikava/JB29_HT1
/Z37p9.java
UTF-8
1,501
3.328125
3
[]
no_license
//Составить линейную программу, печатающую значение true, если указанное //высказывание является истинным, и false — в противном случае: //• График функции у = ах2 + bх+ с проходит через заданную точку с координатами (m, //п). package by.epam.jb29.task01; import java.util.Scanner; public class Z37p9 { public static void main(String[] args) { double a, b, c, x, y, m, n; boolean flag = false; Scanner sc = new Scanner(System.in); System.out.println("Введите значение a: "); a = sc.nextDouble(); System.out.println("Введите значение b: "); b = sc.nextDouble(); System.out.println("Введите значение с: "); c = sc.nextDouble(); System.out.println("Введите значение x: "); x = sc.nextDouble(); System.out.println("Введите значение координаты m: "); m = sc.nextDouble(); System.out.println("Введите значение координаты n: "); n = sc.nextDouble(); y = a * Math.pow(x, 2) + b * x + c; if (y == m && x == n) { flag = true; System.out.println(flag); } else { System.out.println(flag); } } }
true
4709214cda6a3ce6dcf74f1f0870e150addec45e
Java
Roxic-stackoverflowerror/RoxicProject
/crm/src/main/java/com/roxic/crm/workbench/dao/ContactsActivityRelationDao.java
UTF-8
394
1.601563
2
[]
no_license
package com.roxic.crm.workbench.dao; import com.roxic.crm.workbench.domain.ContactsActivityRelation; public interface ContactsActivityRelationDao { int save(ContactsActivityRelation contactsActivityRelation); int getCountsByConids(String[] ids); int deletByConids(String[] ids); int unbound(String id); int bound(ContactsActivityRelation contactsActivityRelation); }
true
3b61d27718ad0d47b3120995e34542a822903bb5
Java
xu20160924/leetcode
/leetcodejava/src/main/java/com/designpattern/singleton/Singleton2.java
UTF-8
1,470
3.671875
4
[]
no_license
package com.designpattern.singleton; /** * @author: John * @date: 2020-11-01 17:39 * @description: 懒汉式单例 **/ public class Singleton2 { // 指向自己实例的私有静态引用 private static Singleton2 singleton2; // 私有的构造方法 private Singleton2() {} // // 以自己实例为返回值的静态的公有方法,静态工厂方法 // public static Singleton2 getSingleton2() { // // 被动创建,在真正需要使用时才去创建 // if (singleton2 == null) { // singleton2 = new Singleton2(); // } // return singleton2; // } // // 使用synchronized 修饰,达到线程安全的懒汉式单例 以自己实例为返回值的静态的公有方法,静态工厂方法 // public static synchronized Singleton2 getSingleton2() { // // 被动创建,在真正需要使用时才去创建 // if (singleton2 == null) { // singleton2 = new Singleton2(); // } // return singleton2; // } //达到线程安全的懒汉式单例 以自己实例为返回值的静态的公有方法,静态工厂方法 public static Singleton2 getSingleton2() { // 使用synchronized块 被动创建,在真正需要使用时才去创建 synchronized (Singleton2.class) { if (singleton2 == null) { singleton2 = new Singleton2(); } } return singleton2; } }
true
ab6fa8840b599169adfad0f6620a758b776b03c8
Java
huebschwerlen/JavaApp
/apptbook-android/app/src/main/java/edu/pdx/cs410J/hueb/SearchViewActivity.java
UTF-8
4,988
2.375
2
[ "Apache-2.0" ]
permissive
package edu.pdx.cs410J.hueb; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.Locale; import edu.pdx.cs410J.ParserException; public class SearchViewActivity extends AppCompatActivity { private ArrayAdapter<Appointment> appts; private ArrayAdapter<String> apptStrings; private TextView ownerDisplay; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search_view); // Intent intent = getIntent(); // Bundle extras = intent.getExtras(); // String owner = extras.getString("OWNER"); // String beginTime = extras.getString("BTIME"); // String endTime = extras.getString("ETIME"); String owner = getIntent().getStringExtra("OWNER"); String beginTime = getIntent().getStringExtra("BTIME"); String endTime = getIntent().getStringExtra("ETIME"); ownerDisplay = findViewById(R.id.apptBookOwnerSearchAllAppts); ownerDisplay.setText(owner.toUpperCase(Locale.ROOT) + "'S APPOINTMENTS: "); AppointmentBook appointmentBook; appointmentBook = parseFile(owner); Date beginTime1 = null; try { beginTime1 = new SimpleDateFormat("MM/dd/yyyy hh:mm aa").parse(beginTime); } catch (ParseException e) { toast("While Parsing BeginTime Pretty file: " + e.getMessage()); } Date endTime1 = null; try { endTime1 = new SimpleDateFormat("MM/dd/yyyy hh:mm aa").parse(endTime); } catch (ParseException e) { toast("While Parsing EndTime Pretty file: " + e.getMessage()); } AppointmentBook bookByTime = new AppointmentBook(owner); for (Appointment appt : appointmentBook.getAppointments()){ Boolean between = appt.getBeginTime().after(beginTime1) && appt.getBeginTime().before(endTime1); Boolean equals = appt.getBeginTime().equals(beginTime1) || appt.getBeginTime().equals(endTime1); // System.out.println("\n between: " + between + " equals: " + equals + "\n"); if(between || equals ) { bookByTime.addAppointment(appt); } } Collection<Appointment> apptArr = bookByTime.getAppointments(); if (apptArr.isEmpty()) { toast("No Appointments Found Matching Search Criteria"); } File contextDirectory = getApplicationContext().getDataDir(); File file = new File(contextDirectory, owner+"Search.txt"); try { PrintWriter pw = new PrintWriter(new FileWriter(file)); PrettyPrinter prettyPrinter = new PrettyPrinter(pw); prettyPrinter.dump(bookByTime); } catch (IOException e) { toast("While Search Printing to file: " + e.getMessage()); } this.apptStrings = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line = br.readLine(); while(line!=null) { this.apptStrings.add(line); line=br.readLine(); } } catch (IOException e) { toast("While Reading Search file: " + e.getMessage()); } ListView listOfAppts = findViewById(R.id.searchAllAppts); listOfAppts.setAdapter(this.apptStrings); } private void toast(String message) { Toast.makeText(SearchViewActivity.this, message, Toast.LENGTH_LONG).show(); } private AppointmentBook parseFile(String owner) { File contextDir = getApplicationContext().getDataDir(); File file = new File(contextDir, owner+".txt"); AppointmentBook apptBook = new AppointmentBook(owner); if (file.exists()) { // toast("EXISTS!"); try { BufferedReader br = new BufferedReader(new FileReader(file)); TextParser tp = new TextParser(br); apptBook = tp.parse(); return apptBook; } catch (FileNotFoundException | ParserException e) { toast("Couldnt Parse File " + e.getMessage()); return apptBook; } } else { toast("Could Not Find Appointment Book For "+owner); return apptBook; } } }
true
c50c0239b9a84e3c5d63176d99ffb8ebf2d1830a
Java
cadereynoldson/raffleprogram
/GUI_V2/subpanels/TestingFrame.java
UTF-8
3,963
2.46875
2
[]
no_license
package subpanels; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; import fadingComponents.FadingBorderedPanel; import fadingComponents.FadingButton; import fadingComponents.FadingCheckBox; import fadingComponents.FadingLabel; import fadingComponents.FadingLabeledSlider; import fadingComponents.FadingScrollTable; import fadingComponents.FadingSlider; import fadingComponents.FadingTable; import fadingComponents.FadingTimer; import logic.ProgramPresets; import logic.TextStyles; import main_structure.SpreadSheet; import mainpanels.MainWindow; public class TestingFrame extends JFrame { private JCheckBox fade; private FadingLabel label; private FilteringPanel panel; private FadingCheckBox box; private FadingButton button; private FadingLabeledSlider slider; private FadingScrollTable table; private FadingTimer masterTimer; public TestingFrame() { setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setMinimumSize(new java.awt.Dimension(1080, 720)); setLayout(new BorderLayout()); FadingBorderedPanel p = new FadingBorderedPanel("TESTING"); masterTimer = new FadingTimer(5, null, "TEST"); // p.setLayout(new GridLayout(0, 1)); // slider = new FadingLabeledSlider(0, 100, 20, TextStyles.DEFAULT); // slider.setTickSpacing(5, 10); table = new FadingScrollTable(new FadingTable(SpreadSheet.readCSV("testFiles/mock_entries.csv"))); fade = new JCheckBox("Display"); fade.setSelected(true); fade.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(fade.isSelected()) masterTimer.fadeIn(); else masterTimer.fadeOut(); showError(); } }); // masterTimer.addComponent(slider); // p.add(slider); masterTimer.addComponent(table); add(fade, BorderLayout.NORTH); add(table, BorderLayout.CENTER); } private void showError() { ProgramPresets.displayYesNoConfirm("THIS IS A CONFIRM THING! YSES\nNO IDK", "TEST", this); } public static void main(String[] args) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } UIManager.put("nimbusBase", ProgramPresets.COLOR_TEXT); UIManager.put("nimbusFocus", ProgramPresets.COLOR_FOCUS); UIManager.put("Slider.tickColor", ProgramPresets.COLOR_TEXT); } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TestingFrame().setVisible(true); } }); } }
true
5d9c6ed3f4fb653e023a3aa1bf01904a5e309573
Java
svashish305/ftpusingudp
/simple_ftp_client.java
UTF-8
7,324
2.609375
3
[ "MIT" ]
permissive
/* * 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. */ import java.io.*; import java.net.*; /** * * @author shubhashish */ public class simple_ftp_client { String hostname="127.0.0.1"; int port,n,mss,count=0,buffer=0,seq,ack=0; DatagramSocket clientsocket; File name; byte [][] fs; InetAddress ip; boolean done=false; long rtt=0; simple_ftp_client(String host,int a,String f,int b,int c) { hostname=host; port=a; n=b; mss=c; try { clientsocket=new DatagramSocket(); name=new File(f); ip=InetAddress.getByName(hostname); } catch(SocketException s) { System.err.println(s); } catch(UnknownHostException h) { System.err.println(h); } } public static void main(String []args) { // String arg[]=new String[5]; // arg[0]="192.168.1.117"; // arg[1]="7735"; // arg[2]="02.overview.pdf"; // arg[3]="64"; // arg[4]="100"; long avgdelay=0; simple_ftp_client sfc=new simple_ftp_client(args[0],Integer.parseInt(args[1]),args[2],Integer.parseInt(args[3]),Integer.parseInt(args[4])); System.out.println("Preparing file for transfer"); sfc.filesplit(); System.out.println("Sending File...Please wait"); sfc.rtt=sfc.execute(); System.out.println("Avg. delay="+(sfc.rtt-avgdelay)); System.out.println("File transfer complete!!"); } long execute() { long strt,end; //task1 strt=System.currentTimeMillis(); //task1 while((count*mss)<(int)name.length()) { while(buffer<n&&fs.length>count) { DatagramPacket send=rdt_send(count); try { clientsocket.send(send); //System.out.println("Packet sent with seq no!!"+count); buffer++; count++; } catch(IOException e) { System.err.println(e); } } byte [] receivedata=new byte[1024]; DatagramPacket receive=new DatagramPacket(receivedata,receivedata.length); done=false; try { clientsocket.setSoTimeout(100); one:while(!done) { clientsocket.receive(receive); // System.out.println("Packet received!!"); String unpack=new String(receive.getData()); if(unpack.substring(48,64).equals("1010101010101010")) { // System.out.println("Packet is acknowledgement"); String seqtemp=unpack.substring(0,32); int seqn=bintodeci(seqtemp); ack=seqn; // System.out.println("ack::"+ack); if(ack==count) { // System.out.println("All packets are acknowledged now"); done=true; count=ack; buffer=0; break one; } } } } catch(SocketTimeoutException sto) { System.out.println("Timeout, Sequence number="+(ack)); buffer=count-ack; count=ack; } catch(IOException ioe) { System.err.println(ioe); } } end=System.currentTimeMillis(); //task1 endfile(); return end-strt; //task1 } void filesplit() { int i=(int)name.length()/mss; int j; System.out.println("File Size::"+name.length()+"bytes"); fs=new byte[i+1][mss]; try { byte [] bytearray = new byte [(int)name.length()]; FileInputStream fin = new FileInputStream(name); BufferedInputStream bin = new BufferedInputStream(fin); bin.read(bytearray,0,bytearray.length); for(j=0;j<bytearray.length;j++) { fs[j/mss][j%mss]=bytearray[j]; //System.out.println(j); } i=j/mss; while(j%mss!=0) { j++; fs[i][j%mss]=0; //System.out.println(j); } } catch(FileNotFoundException e) { System.err.println(); } catch(IOException er) { System.err.println(er); } } String getseq(int n) { String temp=Integer.toBinaryString(n); for(int i=temp.length();i<32;i++) temp="0"+temp; return temp; } DatagramPacket rdt_send(int c) { DatagramPacket p; String sequ=getseq(c); String chcksum=checksum(fs[c]); String type="0101010101010101"; String header=sequ+chcksum+type; byte[] senddata; senddata=header.getBytes(); byte[] pack= new byte[mss+senddata.length]; for(int i=0;i<pack.length;i++) { if(i<senddata.length) pack[i]=senddata[i]; else pack[i]=fs[c][i-senddata.length]; } p= new DatagramPacket(pack,pack.length,ip,port); return p; } String checksum(byte [] b) { byte sum1=0,sum2=0; for(int i=0;i<b.length;i=i+2) { sum1+=b[i]; if((i+1)<b.length) sum2+=b[i+1]; } String res=Byte.toString(sum1),res1=Byte.toString(sum2); for(int i=res.length();i<8;i++) res="0"+res; for(int i=res1.length();i<8;i++) res1="0"+res1; return res+res1; } int bintodeci(String str) { double j=0; for(int i=0;i<str.length();i++) { if(str.charAt(i)== '1') { j=j+ Math.pow(2,str.length()-1-i); } } return (int) j; } void endfile() { try { String temp=Integer.toBinaryString(count); for(int i=temp.length();i<32;i++) temp="0"+temp; byte emp[]=new byte[mss]; String check=checksum(emp); String eof=temp+check+"0000000000000000"+(new String(emp)); byte b[]=eof.getBytes(); DatagramPacket p=new DatagramPacket(b,b.length,ip,7735); clientsocket.send(p); //System.out.println("EOF sent"); } catch(IOException ioe){ System.err.print(ioe); } } }
true
06db465b7d0a5b9e62c7429288bdeb772debd885
Java
LittleDecorator/JointPurchase
/src/main/java/com/acme/controller/MediaController.java
UTF-8
4,941
2.34375
2
[]
no_license
package com.acme.controller; import com.acme.enums.ImageSize; import com.acme.handlers.Base64BytesSerializer; import com.acme.model.Content; import com.acme.repository.ContentRepository; import com.acme.service.ImageService; import com.acme.service.ResizeService; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Date; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.request.async.DeferredResult; /** * Контроллер предназначен для получения подходящего изображения * Внутри себя должен использовать сервис возвращающий изображение. */ @RestController @RequestMapping(value = "/media") public class MediaController { @Autowired ContentRepository contentRepository; @Autowired ResizeService resizeService; @Autowired ImageService imageService; //fake last modify date private long lastModifyDate = getResourceLastModified(); private static final ExecutorService ex = Executors.newFixedThreadPool(100); // generate fake last modify date private long getResourceLastModified () { ZonedDateTime zdt = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("GMT")); return zdt.toInstant().toEpochMilli(); } @RequestMapping(method = RequestMethod.GET, value = "/image/{contentId}") public void getImageForGallery(@PathVariable(value = "contentId") String contentId, @RequestParam(name = "asWebp", required = false) Boolean asWebp, ServletWebRequest request, HttpServletResponse response) throws Exception { long lastModifiedFromBrowser = ((HttpServletRequest)request.getNativeRequest()).getDateHeader("If-Modified-Since"); long lastModifiedFromServer = lastModifyDate; if (lastModifiedFromBrowser != -1 && lastModifiedFromServer <= lastModifiedFromBrowser) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } writeResponse(ImageSize.ORIGINAL, contentId, Boolean.TRUE.equals(asWebp), response); } @RequestMapping(method = RequestMethod.GET, value = "/image/{size}/{contentId}") public DeferredResult<byte[]> getImage(@PathVariable(value = "size") String size, @PathVariable(value = "contentId") String contentId, @RequestParam(name = "asWebp", required = false) Boolean asWebp, ServletWebRequest request, HttpServletResponse response) throws Exception { long lastModifiedFromBrowser = ((HttpServletRequest)request.getNativeRequest()).getDateHeader("If-Modified-Since"); long lastModifiedFromServer = lastModifyDate; if (lastModifiedFromBrowser != -1 && lastModifiedFromServer <= lastModifiedFromBrowser) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return null; } DeferredResult<byte[]> result = new DeferredResult<>();//TODO add timeout CompletableFuture.supplyAsync(() -> { ImageSize imageSize = ImageSize.valueOf(size.toUpperCase()); byte[] c = new byte[]{}; try { c = writeResponse(imageSize, contentId, Boolean.TRUE.equals(asWebp), response); } catch (Exception e) { e.printStackTrace(); } return c; }, ex).thenAccept(result::setResult); return result; } private byte[] writeResponse(ImageSize size, String contentId, boolean asWebp, HttpServletResponse response) throws Exception { BufferedImage image; Content entity = contentRepository.findOne(contentId); String content = contentRepository.getContentData(contentId); String type = asWebp ? "webp" : entity.getType(); byte[] data = Base64BytesSerializer.deserialize(content); switch (size) { case GALLERY: image = resizeService.forGallery(data); break; case VIEW: image = resizeService.forView(data); break; case PREVIEW: image = resizeService.forPreview(data); break; case THUMB: image = resizeService.forThumb(data); break; case ORIGINAL: image = resizeService.forOrign(data); break; default: image = imageService.getImage(data); } byte[] result = imageService.toBytes(image, type); response.setContentType(type); response.addDateHeader("Expires", lastModifyDate + 24*60*60*1000); response.addDateHeader("Last-Modified", getResourceLastModified()); return result; } }
true
ace5cb539b3293c1f2ab0b9b420eb8789dfc4318
Java
kiritoAsunaXy/house
/house/house-common/src/main/java/com/xuyu/house_common/Testasurl.java
UTF-8
235
1.585938
2
[]
no_license
package com.xuyu.house_common; import com.xuyu.house_common.result.ResultMsg; public class Testasurl { public static void main(String args[]){ System.out.println(ResultMsg.successMsg("你好啊").asUrlParams()); } }
true
539051fbf565f05c76e8d084c87584ef690b77cf
Java
rcrodrigues/movie_app
/app/src/main/java/com/example/android/movie/activities/discovery/view/DiscoveryAdapterOnClickHandler.java
UTF-8
242
1.65625
2
[]
no_license
package com.example.android.movie.activities.discovery.view; import com.example.android.movie.activities.discovery.entities.DiscoveryModel; public interface DiscoveryAdapterOnClickHandler { void onClick(DiscoveryModel discoveryModel); }
true
3fcdb0f868af3ee192d886aed7f8bf83ca7a7478
Java
vb143/simple_basic_programs
/Java_Project/javaArray/programs/ArrayUserInput.java
UTF-8
659
3.5625
4
[]
no_license
package javaArray.programs; import java.util.Scanner; public class ArrayUserInput { public static void main(String[] args) { Scanner scanner =new Scanner(System.in); int [] array = new int[10]; System.out.print("Enter 10 numbers "); for (int i = 0; i < 10; i++) { array[i] = scanner.nextInt(); } System.out.println("#######################################"); System.out.println("the size of array is " + array.length); System.out.println("***************************************"); for (int i = 0; i < array.length; i++) { System.out.println("Position " +i+ " Element in array = " + array[i]); } scanner.close(); } }
true
986662213ef1510798c1e1eb5ec12e67e98fe875
Java
MashiroSky/springboot-EbookStore
/src/main/java/com/bookstore/controller/CartController.java
UTF-8
917
2.15625
2
[]
no_license
package com.bookstore.controller; import com.bookstore.entity.Cart; import com.bookstore.service.CartService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class CartController { @Autowired CartService cartService; @RequestMapping("/addToCart") public boolean AddToCart(int bookID, int userID) { return cartService.AddToCart(bookID, userID); } @PostMapping("/deleteCartById") public boolean DeleteCartById(@RequestParam("id") int id) { return cartService.DeleteById(id); } @GetMapping("/cartlist") public List<Cart> cartlist(int userId) { return cartService.cartlist(userId); } @PostMapping("/clearCart") public boolean ClearCart(@RequestParam("userID") int userID) { return cartService.ClearCart(userID); } }
true
827b6505e2fcca954246f216d4b155e9d34584db
Java
margarita910/laba7
/laba/commands/Show.java
UTF-8
1,296
3.015625
3
[]
no_license
package laba.commands; import laba.com.company.DataBaseHandler; import laba.commands.general.*; import laba.com.company.Ticket; import java.sql.SQLException; import java.util.List; /** * Класс, осуществлящий вывод всех элементов коллекции */ public class Show implements Command { public static final String ANSI_YELLOW = "\u001B[33m"; public static final String ANSI_RESET = "\u001B[0m"; public static final String ANSI_RED = "\u001B[31m"; private StringBuilder answer; @Override public String getName() { return "SHOW"; } @Override public void execute(List<Ticket> list) { answer = new StringBuilder(); try{ list = DataBaseHandler.getTicketCollection(); } catch(SQLException e){ e.printStackTrace(); } if (list.size() > 0 ){ for (Ticket ticket : list){ answer.append(ticket.toString()).append("\n"); } } else { answer.append(ANSI_RED+"Коллекция не имеет элементов."+ANSI_RESET); } } @Override public void printAnswer() { System.out.println(answer); } }
true
d32b2115c8904a9308fc7bbf5e3709e256aaedb6
Java
waadfahadq/RafeegWAAD
/app/src/main/java/com/example/myapplication/admin_portal/ui/ProfileFragment/add.java
UTF-8
12,518
1.640625
2
[]
no_license
package com.example.myapplication.admin_portal.ui.ProfileFragment; import android.Manifest; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import com.example.myapplication.R; import com.example.myapplication.ui.home.storeinfo; import com.google.android.gms.tasks.Continuation; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.database.ChildEventListener; 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 com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import com.karumi.dexter.Dexter; import com.karumi.dexter.PermissionToken; import com.karumi.dexter.listener.PermissionDeniedResponse; import com.karumi.dexter.listener.PermissionGrantedResponse; import com.karumi.dexter.listener.PermissionRequest; import com.karumi.dexter.listener.single.PermissionListener; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class add extends AppCompatActivity { TextView write; Button enter; DatabaseReference ref; ImageView image; Uri uri; EditText nameform,baken,type; Spinner num,num2,emailSp; ArrayAdapter<String> adapter,adapter2; RadioGroup place_type; DatabaseReference requests; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add); Toolbar toolbar = findViewById(R.id.toolbar900); place_type = findViewById(R.id.place_type); setSupportActionBar(toolbar); image=findViewById(R.id.image); nameform=findViewById(R.id.nameform); num=findViewById(R.id.num2); num2=findViewById(R.id.num); emailSp=findViewById(R.id.Emailnum); String [] array=getResources().getStringArray(R.array.numbers); //new final List<String> arrayOfEmails = new ArrayList<String>(); adapter2= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arrayOfEmails); adapter2.add("لم يتم إختيار متجر"); requests = FirebaseDatabase.getInstance().getReference().child("requests"); requests.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { String email = dataSnapshot.child("email").getValue(String.class); adapter2.add(email); } @Override public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { } @Override public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) { } @Override public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,array); num.setAdapter(adapter); num2.setAdapter(adapter); emailSp.setAdapter(adapter2); // email=findViewById(R.id.email); baken=findViewById(R.id.baken); // type=findViewById(R.id.type); image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Dexter.withActivity(add.this).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE) .withListener(new PermissionListener() { @Override public void onPermissionGranted(PermissionGrantedResponse response) { openImage(); } @Override public void onPermissionDenied(PermissionDeniedResponse response) { Toast.makeText(add.this, "Permmission not granted", Toast.LENGTH_SHORT).show(); } @Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) { } }) .check(); } }); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setTitle("إضافة محل"); // toolbar.setBackgroundColor(Color.GRAY); //toolbar.setTitleTextColor(Color.WHITE); // write=(TextView)findViewById(R.id.textView); enter=findViewById(R.id.reema); ref= FirebaseDatabase.getInstance().getReference().child("storeinfo"); enter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String name=nameform.getText().toString().trim(); //String number=num.getText().toString().trim(); // final String ownerEmail=email.getText().toString().trim(); final String baken_number=baken.getText().toString().trim(); // final String place_type=type.getText().toString().trim(); if(TextUtils.isEmpty(name)){ Toast.makeText(add.this, "ادخل اسم المحل", Toast.LENGTH_SHORT).show(); return; } /* if(TextUtils.isEmpty(number)){ Toast.makeText(add.this, "Please Enter number", Toast.LENGTH_SHORT).show(); return; }*/ if(num.getSelectedItemPosition()==0){ Toast.makeText(add.this, "اختر رقم المحل", Toast.LENGTH_SHORT).show(); return; } if(num2.getSelectedItemPosition()==0){ Toast.makeText(add.this, "اختر رقم الدور", Toast.LENGTH_SHORT).show(); return; } if(emailSp.getSelectedItemPosition()==0){ Toast.makeText(add.this, "اختر إيميل المالك", Toast.LENGTH_SHORT).show(); return; } if(TextUtils.isEmpty(baken_number)){ Toast.makeText(add.this, "ادخل رقم البيكن", Toast.LENGTH_SHORT).show(); return; } /* if(TextUtils.isEmpty(place_type)){ Toast.makeText(add.this, "Please Enter place type", Toast.LENGTH_SHORT).show(); return; }*/ if(uri ==null){ Toast.makeText(add.this, "ادخل صورة المحل", Toast.LENGTH_SHORT).show(); return; } FirebaseDatabase.getInstance() .getReference(). child("storeinfo").orderByChild("num") .equalTo(Integer.parseInt((String) num.getSelectedItem())).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.exists()){ Toast.makeText(add.this, "قد تم اختيار هذا الرقم لمحل آخر", Toast.LENGTH_SHORT).show(); return; }else { try { Log.d("MUTEE","getSelectedItem() :"+(String) num.getSelectedItem()); uploadPhoto(name,Integer.parseInt((String) num.getSelectedItem()),String.valueOf(emailSp.getSelectedItemPosition()),baken_number,uri); }catch (Exception e){ uploadPhoto(name,00000,String.valueOf(emailSp.getSelectedItemPosition()),baken_number,uri); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }); } void openImage(){ Intent i = new Intent( Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, 1); } private void uploadPhoto(final String name, final int number, final String email, final String baken, Uri uri) { Calendar calendar = Calendar.getInstance(); FirebaseStorage storage = FirebaseStorage.getInstance(); StorageReference media = storage.getReference("photos"); final StorageReference child = media.child("img" + calendar.getTimeInMillis()); UploadTask uploadTask = child.putFile(uri); Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() { @Override public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception { if (!task.isSuccessful()) { throw task.getException(); } // Continue with the task to get the download URL return child.getDownloadUrl(); } }).addOnCompleteListener(new OnCompleteListener<Uri>() { @Override public void onComplete(@NonNull Task<Uri> task) { if (task.isSuccessful()) { Uri downloadUri = task.getResult(); String key = ref.push().getKey(); storeinfo storeinfo1=new storeinfo(name,number,email,baken, ((RadioButton)findViewById(place_type.getCheckedRadioButtonId())).getText().toString(), downloadUri.toString(),key,"","",num2.getSelectedItem().toString(),""); ref.child(key).setValue(storeinfo1).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()){ Toast.makeText(add.this, "تم إضافة المحل بنجاح ", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(add.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } } }); } else { Toast.makeText(add.this, "Upload " + task.getException().getMessage(), Toast.LENGTH_SHORT).show(); // Handle failures // ... } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1 && resultCode == RESULT_OK && data.getData() != null ) { uri = data.getData(); image.setImageURI(uri); } } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == android.R.id.home) // Press Back Icon { finish(); } return super.onOptionsItemSelected(item); } }
true
8ccbdced2640ce648b26d2ea7a4b6f654852b36a
Java
PiccaBro/java_api_training
/src/main/java/fr/lernejo/navy_battle/RivalMap.java
UTF-8
3,863
2.828125
3
[]
no_license
package fr.lernejo.navy_battle; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.LinkedList; import java.util.List; enum consequence { hit, miss, } public class RivalMap { private final List<String> board = new LinkedList<>();; private final List<String> rival_url = new LinkedList<>(); private final List<Integer> cells = new LinkedList<>(); private final List<Integer> count = new LinkedList<>(); private final List<Boolean> win =new LinkedList<>(); public RivalMap(){ win.add(false); count.add(0); for (char l ='A'; l <= 'J'; l++){ for (int j =1; j <11;j++){ String poz = l + String.valueOf(j); board.add(poz); } } } public String get_random(){ int pos = (int)(Math.random()*100); while(board.get(pos) == "00" || board.get(pos) == "XX"){ pos = (int)(Math.random()*100); } return board.get(pos); } public void setRival_url(String rival_url){ this.rival_url.add(rival_url); } public JSONObject send_get_request(String cell) throws IOException, InterruptedException, ParseException { HttpClient httpClient = HttpClient.newHttpClient(); HttpRequest reGet = HttpRequest.newBuilder() .uri(URI.create(rival_url.get(0) + "/api/game/fire?cell=" + cell)) .header("Accept","application/json") .build(); HttpResponse<String> response = httpClient.send(reGet, HttpResponse.BodyHandlers.ofString()); Object r = new JSONParser().parse(response.body()); JSONObject j_r = (JSONObject) r; mecanic(j_r,cell); return j_r; } private void mecanic(JSONObject j_r,String cell){ if (count.get(0)>3){ count.set(0, 0); cells.remove(0); } if (!j_r.get("consequence").equals(consequence.miss.toString())){ if (j_r.get("consequence").equals(consequence.hit.toString())) { cells.add(board.indexOf(cell)); //board.set(board.indexOf(cell),"XX"); } else { count.set(0, 0); cells.remove(0); } } else{ board.set(board.indexOf(cell),"00"); } } private String distruct_ship(int position,int result){ restart: while (true){ result = position; switch (count.get(0)){ case 0: result+=1; if (result%10 == 0) count.set(0, count.get(0) + 1); else break restart; break; case 1: result-=1; if (result<0 || result % 10 == 9) count.set(0, count.get(0) + 1); else break restart; break; case 2: result+=10; if (result>99) count.set(0, count.get(0) + 1); else break restart; break; case 3: result-=10; if (result<0) count.set(0, count.get(0) + 1); else break restart; break; default: System.out.println("Error switch count"); break restart; } } count.set(0,count.get(0)+1); return board.get(result); } public void strike() throws IOException, ParseException, InterruptedException { JSONObject resp = null; if (cells.size() == 0) resp = send_get_request(get_random()); else resp = send_get_request(distruct_ship(cells.get(0),-1)); System.out.println(resp.toJSONString()); if (resp.get("shipLeft").equals(false)){ System.out.println("Game is over, you win!"); win.set(0,true); } } }
true
1a85dd1bc0fcdcd6d8a6d138330aa40c34cdf64c
Java
DavidSoto5317/HojaTrabajo3
/HojaTrabajo3/test/hojatrabajo3/MergeSortTest.java
UTF-8
1,079
2.828125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package hojatrabajo3; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * @author David Soto y Jose Cifunetes */ public class MergeSortTest { private int [] arrayTest = {1,5,6,3,9,7,2}; @Test public void PruebaSort(){ MergeSort.mergesort(arrayTest); int result = arrayTest[0]; assertEquals(1, result); } @Test public void PruebaSort2(){ MergeSort.mergesort(arrayTest); int result = arrayTest[5]; assertEquals(7, result); } /** * El proximo es erroneo a proposito */ @Test public void PruebaSort3(){ MergeSort.mergesort(arrayTest); int result = arrayTest[2]; assertEquals(9, result); } }
true