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
2bfefe1acf2731fb193340541f30c4fe54c9fb41
Java
le-savage/ascalon-ps
/src/com/AscalonPS/util/ShutdownHook.java
UTF-8
1,305
2.375
2
[]
no_license
package com.AscalonPS.util; import com.AscalonPS.GameServer; import com.AscalonPS.world.World; import com.AscalonPS.world.content.WellOfGoodwill; import com.AscalonPS.world.content.WellOfWealth; import com.AscalonPS.world.content.clan.ClanChatManager; import com.AscalonPS.world.content.grandexchange.GrandExchangeOffers; import com.AscalonPS.world.entity.impl.player.Player; import com.AscalonPS.world.entity.impl.player.PlayerHandler; import java.util.logging.Logger; public class ShutdownHook extends Thread { /** * The ShutdownHook logger to print out information. */ private static final Logger logger = Logger.getLogger(ShutdownHook.class.getName()); @Override public void run() { logger.info("The shutdown hook is processing all required actions..."); World.savePlayers(); GameServer.setUpdating(true); for (Player player : World.getPlayers()) { if (player != null) { // World.deregister(player); PlayerHandler.handleLogout(player); } } WellOfGoodwill.save(); WellOfWealth.save(); GrandExchangeOffers.save(); ClanChatManager.save(); logger.info("The shudown hook actions have been completed, shutting the server down..."); } }
true
af60a459cb1bb5c567f1928c515684f057ea3376
Java
eahom1/MessageBus
/app/src/main/java/com/eahom/messagebus/message/RefreshUiMessage.java
UTF-8
539
1.96875
2
[]
no_license
package com.eahom.messagebus.message; import android.graphics.Bitmap; import com.eahom.messagebuslib.message.IMessage; /** * Created by eahom on 17/1/10. */ public class RefreshUiMessage extends IMessage { private String text; private Bitmap bitmap; public String getText() { return text; } public void setText(String text) { this.text = text; } public Bitmap getBitmap() { return bitmap; } public void setBitmap(Bitmap bitmap) { this.bitmap = bitmap; } }
true
3cc88a4cdbad4b539dd14088bafc2e7b7d01b9c0
Java
cshang2017/myread
/flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/restart/FixedDelayRestartStrategy.java
UTF-8
3,436
2.796875
3
[]
no_license
package org.apache.flink.runtime.executiongraph.restart; import org.apache.flink.api.common.time.Time; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.RestartStrategyOptions; import org.apache.flink.runtime.concurrent.FutureUtils; import org.apache.flink.runtime.concurrent.ScheduledExecutor; import org.apache.flink.runtime.executiongraph.ExecutionGraph; import org.apache.flink.util.Preconditions; import java.util.concurrent.CompletableFuture; /** * Restart strategy which tries to restart the given {@link ExecutionGraph} a fixed number of times * with a fixed time delay in between. */ public class FixedDelayRestartStrategy implements RestartStrategy { private final int maxNumberRestartAttempts; private final long delayBetweenRestartAttempts; private int currentRestartAttempt; public FixedDelayRestartStrategy( int maxNumberRestartAttempts, long delayBetweenRestartAttempts) { Preconditions.checkArgument(maxNumberRestartAttempts >= 0, "Maximum number of restart attempts must be positive."); Preconditions.checkArgument(delayBetweenRestartAttempts >= 0, "Delay between restart attempts must be positive"); this.maxNumberRestartAttempts = maxNumberRestartAttempts; this.delayBetweenRestartAttempts = delayBetweenRestartAttempts; currentRestartAttempt = 0; } public int getCurrentRestartAttempt() { return currentRestartAttempt; } @Override public boolean canRestart() { return currentRestartAttempt < maxNumberRestartAttempts; } @Override public CompletableFuture<Void> restart(final RestartCallback restarter, ScheduledExecutor executor) { currentRestartAttempt++; return FutureUtils.scheduleWithDelay(restarter::triggerFullRecovery, Time.milliseconds(delayBetweenRestartAttempts), executor); } /** * Creates a FixedDelayRestartStrategy from the given Configuration. * * @param configuration Configuration containing the parameter values for the restart strategy * @return Initialized instance of FixedDelayRestartStrategy * @throws Exception */ public static FixedDelayRestartStrategyFactory createFactory(Configuration configuration) throws Exception { int maxAttempts = configuration.getInteger(RestartStrategyOptions.RESTART_STRATEGY_FIXED_DELAY_ATTEMPTS); long delay = configuration.get(RestartStrategyOptions.RESTART_STRATEGY_FIXED_DELAY_DELAY).toMillis(); return new FixedDelayRestartStrategyFactory(maxAttempts, delay); } @Override public String toString() { return "FixedDelayRestartStrategy(" + "maxNumberRestartAttempts=" + maxNumberRestartAttempts + ", delayBetweenRestartAttempts=" + delayBetweenRestartAttempts + ')'; } public static class FixedDelayRestartStrategyFactory extends RestartStrategyFactory { private final int maxNumberRestartAttempts; private final long delayBetweenRestartAttempts; public FixedDelayRestartStrategyFactory(int maxNumberRestartAttempts, long delayBetweenRestartAttempts) { this.maxNumberRestartAttempts = maxNumberRestartAttempts; this.delayBetweenRestartAttempts = delayBetweenRestartAttempts; } @Override public RestartStrategy createRestartStrategy() { return new FixedDelayRestartStrategy(maxNumberRestartAttempts, delayBetweenRestartAttempts); } int getMaxNumberRestartAttempts() { return maxNumberRestartAttempts; } long getDelayBetweenRestartAttempts() { return delayBetweenRestartAttempts; } } }
true
7b6ff9b82d902a8ba2615e3d7c5a78091e602137
Java
vacaly/Alink
/core/src/main/java/com/alibaba/alink/operator/stream/regression/BertTextRegressorPredictStreamOp.java
UTF-8
885
1.914063
2
[ "Apache-2.0" ]
permissive
package com.alibaba.alink.operator.stream.regression; import org.apache.flink.ml.api.misc.param.Params; import com.alibaba.alink.common.annotation.NameCn; import com.alibaba.alink.common.annotation.NameEn; import com.alibaba.alink.operator.batch.BatchOperator; /** * Prediction with a text regressor using Bert models. */ @NameCn("Bert文本回归预测") @NameEn("Bert Text Regressor Prediction") public class BertTextRegressorPredictStreamOp extends TFTableModelRegressorPredictStreamOp <BertTextRegressorPredictStreamOp> { public BertTextRegressorPredictStreamOp() { super(); } public BertTextRegressorPredictStreamOp(Params params) { super(params); } public BertTextRegressorPredictStreamOp(BatchOperator <?> model) { this(model, new Params()); } public BertTextRegressorPredictStreamOp(BatchOperator <?> model, Params params) { super(model, params); } }
true
a69e23979fb50172b10e847fadf6e021e2bd5ca2
Java
teofilp/InSight
/app/src/main/java/com/racoders/racodersproject/classes/Review.java
UTF-8
2,606
2.390625
2
[]
no_license
package com.racoders.racodersproject.classes; import android.animation.Animator; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.View; import android.widget.Toast; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.Date; import static com.facebook.FacebookSdk.getApplicationContext; public class Review { private String author; private String description; private double rating; private Date date; public Review(){ } public Review( String author, String description, double rating, Date date) { this.author = author; this.description = description; this.rating = rating; this.date = date; } public String getAuthor() { return author; } public String getDescription() { return description; } public double getRating() { return rating; } public Date getDate(){ return date; } public void save(String locationId, final View startView, final View finalView){ FirebaseDatabase.getInstance().getReference().child("Reviews").child(locationId) .child(this.getAuthor()).setValue(this, new DatabaseReference.CompletionListener() { @Override public void onComplete(@Nullable DatabaseError databaseError, @NonNull DatabaseReference databaseReference) { if(databaseError == null){ Toast.makeText(getApplicationContext(), "Successful", Toast.LENGTH_SHORT).show(); startView.animate().alpha(0).setDuration(200).setListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { startView.setVisibility(View.GONE); finalView.setVisibility(View.VISIBLE); finalView.animate().alpha(1).setDuration(200); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); } } }); } }
true
fd7c8ee49dca92ee738699f52a89baf477e319b7
Java
tentasys/study_algorithm
/SWEA/SW_4012/src/Solution.java
UTF-8
1,588
2.984375
3
[]
no_license
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Solution { static int N; static int S[][]; static int min = Integer.MAX_VALUE; public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine()); StringTokenizer st; for(int ii=0; ii<T; ii++) { N = Integer.parseInt(br.readLine()); S = new int[N][N]; //input for(int i=0; i<N; i++) { st = new StringTokenizer(br.readLine()); for(int j=0; j<N; j++) S[i][j] = Integer.parseInt(st.nextToken()); } for(int i=0; i<N; i++) { for(int j=i; j<N; j++) S[i][j] += S[j][i]; } int arr_a[] = new int[N/2]; int arr_b[] = new int[N/2]; f(arr_a, arr_b, 1, N/2, N/2, 0); System.out.println("#" + (ii+1) + " " + min); min = Integer.MAX_VALUE; }//end of each TC } //a:0 b:1, a : acount, b: bcount static void f(int arr_a[], int arr_b[], int d, int a, int b, int flag) { if(flag == 0) { arr_a[N/2-a] = d; a--; } else { arr_b[N/2-b] = d; b--; } if(d == N) { int sum_a = 0; int sum_b = 0; for(int i=0; i<N/2-1; i++) { for(int j=i+1; j<N/2; j++) { sum_a += S[arr_a[i]-1][arr_a[j]-1]; sum_b += S[arr_b[i]-1][arr_b[j]-1]; } } if(min > Math.abs(sum_b-sum_a)) min = Math.abs(sum_b-sum_a); return; } if(a>0) f(arr_a, arr_b, d+1, a, b, 0); if(b>0) f(arr_a, arr_b, d+1, a, b, 1); } }
true
31b474809a5b583c33b01c8fbdc6adb082ff891f
Java
dongfanggugu/owner_Android
/app/src/main/java/com/honyum/owner/activity/wbdd/MtHistoryOrderActivity.java
UTF-8
3,373
2
2
[]
no_license
package com.honyum.owner.activity.wbdd; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.honyum.owner.R; import com.honyum.owner.base.BaseActivity; import com.honyum.owner.data.MtHistoryOrderInfo; import com.honyum.owner.net.MtHistoryOrderResponse; import com.honyum.owner.net.base.NetConstant; import com.honyum.owner.net.base.NetTask; import java.util.List; public class MtHistoryOrderActivity extends BaseActivity { private RecyclerView recyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mt_history_order); initTitleBar(R.id.title, "服务历史", R.mipmap.back, backClickListener, 0, null); initView(); reqHistoryOrder(); } private void reqHistoryOrder() { String server = getConfig().getServer() + NetConstant.GET_MT_HISTORY_ORDER; String request = "{\"head\":{\"osType\":\"2\",\"accessToken\":\"" + getConfig().getToken() + "\",\"userId\":\"" + getConfig().getUserId() + "\"},\"body\":{}}"; NetTask netTask = new NetTask(server, request) { @Override protected void onResponse(NetTask task, String result) { MtHistoryOrderResponse response = MtHistoryOrderResponse.getResult(result); MyAdapter adapter = new MyAdapter(response.getBody()); recyclerView.setAdapter(adapter); } }; addTask(netTask); } private void initView() { recyclerView = (RecyclerView) findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); } private class MyAdapter extends BaseQuickAdapter<MtHistoryOrderInfo> { public MyAdapter(List<MtHistoryOrderInfo> data) { super(R.layout.layout_mt_history_item, data); } @Override protected void convert(BaseViewHolder vh, final MtHistoryOrderInfo info) { vh.setText(R.id.wblx, info.getMaintypeInfo().getName()) .setText(R.id.wbnr, info.getMaintypeInfo().getContent()) .setText(R.id.xdsj, info.getCreateTime()); if ("1".endsWith(info.getMaintypeInfo().getId())) vh.setImageResource(R.id.iv_bg, R.mipmap.icon_level_3); else if ("2".equals(info.getMaintypeInfo().getId())) vh.setImageResource(R.id.iv_bg, R.mipmap.icon_level_2); else if ("3".equals(info.getMaintypeInfo().getId())) vh.setImageResource(R.id.iv_bg, R.mipmap.icon_level_1); vh.getView(R.id.ckfwd).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MtHistoryOrderActivity.this, MtTaskActivity.class); intent.putExtra("mt_order_id", info.getId()); startActivity(intent); } }); } } }
true
b3042a245be10b1737f60645d23a1d42ebeba660
Java
ljtrycatch/item
/prototype/src/com/IT/ghost/CloneableTest.java
UTF-8
658
3.359375
3
[]
no_license
package com.IT.ghost; public class CloneableTest { public static void main(String[] args){ Realizetype obj1 = new Realizetype(); Realizetype obj2 = new Realizetype(); //=判断存储空间 他们是两个不同的对象 存储空间不一样 System.out.println("obj1==obj2"+(obj1==obj2)); } } //具体原型 class Realizetype implements java.lang.Cloneable{ Realizetype(){ System.out.println("具体原型创建成功!"); } public Object clone() throws CloneNotSupportedException{ System.out.println("具体原型复制成功!"); return (Realizetype) super.clone(); } }
true
2f220225972c45053abc52cfabf14a6a0fa08d67
Java
brahyam/tour-reviews
/app/src/main/java/com/dvipersquad/tourreviews/di/ActivityBindingModule.java
UTF-8
734
1.945313
2
[]
no_license
package com.dvipersquad.tourreviews.di; import com.dvipersquad.tourreviews.reviews.ReviewsActivity; import com.dvipersquad.tourreviews.reviews.ReviewsPresenterModule; import com.dvipersquad.tourreviews.tourdetails.TourDetailsActivity; import com.dvipersquad.tourreviews.tourdetails.TourDetailsPresenterModule; import dagger.Module; import dagger.android.ContributesAndroidInjector; @Module public abstract class ActivityBindingModule { @ActivityScoped @ContributesAndroidInjector(modules = TourDetailsPresenterModule.class) abstract TourDetailsActivity tourDetailsActivity(); @ActivityScoped @ContributesAndroidInjector(modules = ReviewsPresenterModule.class) abstract ReviewsActivity reviewsActivity(); }
true
963dd8966fd2a9dafe9127ec4d9be1ffb8cbfae6
Java
jbankz/GithubUsers
/app/src/main/java/bankzworld/com/main/MainActivity.java
UTF-8
3,885
2.125
2
[]
no_license
package bankzworld.com.main; import android.arch.lifecycle.ViewModelProviders; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; import bankzworld.com.R; import bankzworld.com.adapter.UserAdapter; import bankzworld.com.api.RetrofitClient; import bankzworld.com.listener.UserListener; import bankzworld.com.model.UserList; import bankzworld.com.viewmodel.GithubViewmodel; public class MainActivity extends AppCompatActivity implements UserListener { private GithubViewmodel githubViewmodel; String mLanguage, mLocation; String searchParams = "language:c location:lagos"; String language = "language:"; String location = "location:"; private RecyclerView recyclerView; LinearLayoutManager linearLayout; ProgressBar pb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); recyclerView = (RecyclerView) findViewById(R.id.rv); linearLayout = new LinearLayoutManager(this); recyclerView.setLayoutManager(linearLayout); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setHasFixedSize(true); pb = (ProgressBar) findViewById(R.id.pb_loading); Intent intent = getIntent(); if (intent.hasExtra("language") || intent.hasExtra("location")) { mLanguage = intent.getStringExtra("language"); mLocation = intent.getStringExtra("location"); } this.setTitle(mLanguage + " developers from " + mLocation); searchParams = language + mLanguage + " " + location + mLocation; githubViewmodel = ViewModelProviders.of(this).get(GithubViewmodel.class); githubViewmodel.setListener(this); isNetworkAvailable(searchParams); } private void isNetworkAvailable(String searchParams) { if (RetrofitClient.isConnected(getApplicationContext())) { githubViewmodel.getUsers(searchParams); } else { Toast.makeText(this, "Unable to connect. Try refreshing.", Toast.LENGTH_LONG).show(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_refresh) { isNetworkAvailable(searchParams); return true; } return super.onOptionsItemSelected(item); } @Override public void onSuccessfull(UserList userList) { recyclerView.setAdapter(new UserAdapter(userList.getItems())); } @Override public void onFailure(String message) { Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show(); } @Override public void onProgressShow() { pb.setVisibility(View.VISIBLE); } @Override public void onProgressHide() { pb.setVisibility(View.INVISIBLE); } }
true
5ead76d6ea9248f5e9994a193f9d357fbafb153f
Java
BarteKKmita/Project-Gym-Star
/Gym-Star/src/main/java/com/learning/gym/star/gym/GymDataHandler.java
UTF-8
1,049
3
3
[]
no_license
package com.learning.gym.star.gym; import com.learning.gym.star.gym.database.jdbc.GymRepository; import java.util.ArrayList; import java.util.List; /** * This class was created to simulate getting gym data from SQL dadabase. */ public class GymDataHandler implements GymRepository { private final List<String> gymData; public GymDataHandler(){ gymData = new ArrayList<>(); generateGymData(); } private void generateGymData(){ for(int i = 0; i < 90; i++) { gymData.add(String.valueOf(i)); } } @Override public List<String> getGymData(){ return gymData; } @Override public String[] getGymDataById(int id){ return new String[0]; } @Override public String add(Gym gym){ gymData.add(gym.toString()); return ""; } @Override public void update(Gym gym, int index){ gymData.set(index, gym.toString()); } @Override public void delete(int index){ gymData.remove(index); } }
true
7c7d589af1925928ceaef3ea26133edf03a6a9a7
Java
cornelius-muhatia/algorithms-playground
/miscellaneous/src/main/java/com/cmuhatia/playground/sort/MergeSort.java
UTF-8
2,140
3.8125
4
[]
no_license
package com.cmuhatia.playground.sort; import lombok.AccessLevel; import lombok.NoArgsConstructor; /** * Merge sort worst case time complexity: O(n log n) */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class MergeSort { /** * Sorts an array using merge sort * * @param arr array to be sorted */ public static void sort(int[] arr) { MergeSort.sort(arr, 0, arr.length - 1); } /** * Partitions the array inorder to sort individual partitions separately * * @param arr array to be partitioned * @param low array start index * @param high array end index */ public static void sort(int[] arr, int low, int high) { if (low < high) { int midPoint = (high + low) / 2; sort(arr, low, midPoint); sort(arr, midPoint + 1, high); merge(arr, low, midPoint, high); } } /** * Merges the partitions back to the original array * * @param array original array */ private static void merge(int[] array, int startIndex, int midPoint, int endIndex) { int[] lArray = new int[midPoint - startIndex + 1]; int[] rArray = new int[endIndex - midPoint]; //Copy elements into an array System.arraycopy(array, startIndex, lArray, 0, lArray.length); System.arraycopy(array, midPoint + 1, rArray, 0, rArray.length); int leftIdx = 0; int rightIdx = 0; for (int i = startIndex; i < endIndex + 1; i++) { if (leftIdx < lArray.length && rightIdx < rArray.length) { if (lArray[leftIdx] < rArray[rightIdx]) { array[i] = lArray[leftIdx]; leftIdx++; continue; } array[i] = rArray[rightIdx]; rightIdx++; } else if (leftIdx < lArray.length) { array[i] = lArray[leftIdx]; leftIdx++; } else if (rightIdx < rArray.length) { array[i] = rArray[rightIdx]; rightIdx++; } } } }
true
652e752f5ea9a50ef92997f4e6f5a252835a8ccd
Java
Suprita0390/SampleJavaApplication
/SampleProjectSup/src/SampleProject/PrePostIncrement.java
UTF-8
417
3.390625
3
[]
no_license
package SampleProject; public class PrePostIncrement { public static void main(String args[]) { //i++ -> post increment(increment happens after assignment //++i -> pre increment (increment happens first and then assignment) //Post Increment int i=5; int j; j=i++; // post increment System.out.println(j);//here value of j will be 5 //Pre Increment j=++i; System.out.println(j); } }
true
4a37baeb7f962052c4bfe5f7d5caf5b6d55a6556
Java
eric-r-ramos/opala
/src/main/java/com/opala/repository/search/PassageiroSearchRepository.java
UTF-8
330
1.617188
2
[]
no_license
package com.opala.repository.search; import com.opala.domain.Passageiro; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** * Spring Data Elasticsearch repository for the Passageiro entity. */ public interface PassageiroSearchRepository extends ElasticsearchRepository<Passageiro, Long> { }
true
fff3e11f7af0da1c8472b330516db86cfaf9f4ba
Java
JRakin/Problem-Solving-Playground
/NamesScoresPE/src/Solution.java
UTF-8
941
3.25
3
[]
no_license
import java.util.Arrays; import java.util.Scanner; /** * @author Rakin * * Jul 22, 2018 */ public class Solution { private static final Scanner scan = new Scanner(System.in); public static void main(String[] args) { int t = scan.nextInt(); String[] arr = new String[t]; for(int i = 0; i < t; i++) { arr[i] = scan.next(); } scan.nextLine(); Arrays.sort(arr); int n = scan.nextInt(); for(int i = 0; i < n; i++) { String word = scan.next(); int index = 0; for(int k = 0; k < arr.length; k++) { if(arr[k].equals(word)) { index = k+1; } } System.out.println(findValue(word,index)); } } static int findValue(String word, int index) { int res = 0; String name = word.toLowerCase(); for(int i = 0; i < name.length(); i++) { res += name.charAt(i) - 96; } return res*index; } }
true
9ed9462e0e345f0f43a3e3246f83209a56d240e9
Java
Quintec/ExplodingKittens
/src/Bot.java
UTF-8
3,280
3.796875
4
[]
no_license
/** * The base class for you to base your AI on. */ public abstract class Bot { /** * Method called at the start of the game. * @param myIndex your player's index in the list of players */ public abstract void init(int myIndex, GameView view); /** * Method called at the start of the game to deal the starting hand. * @param hand your starting hand (defuse card at index 0) */ public abstract void setHand(Card[] hand); /** * Method called when another player plays a card. * @param playerIndex the index of the player * @param played the card they have played * @param targetIndex the target of the card if the card targets someone, else -1 * @return a reaction card if you want to play one (i.e. nope card), otherwise null */ public abstract Card cardPlayed(int playerIndex, Card played, int targetIndex); /** * Method called when you draw an exploding kitten. * If you have one, a defuse card is automatically removed from your hand. * @return an index where you wish to replace the kitten in the deck. * If you do not have a defuse card, you are out of the game, and you may return anything. * It will be ignored. */ public abstract int selfExplodingKittenDrawn(); /** * Method called when you draw a card. * @param card the card you drew. */ public abstract void selfCardDrawn(Card card); /** * Method called when it is your turn. * This method will repeatedly be called until you draw a card (2 if you have been attacked) * or if you end your turn in other ways (ex. skip, attack, dead to exploding kitten) * @return the action you will take. * @see Action */ public abstract Action takeTurn(); /** * Method called when someone plays a favor card targeting you. * @param playerIndex the index of the player playing the favor card. * @return the card you will give them. */ public abstract Card giveFavor(int playerIndex); /** * Method called when you play a see the future card. * @param future The top 3 cards in the deck. The top of the deck is at index 0. */ public abstract void seeTheFuture(Card[] future); /** * Method called when you play a favor card. * @param playerIndex The player you targeted with your favor card. * @param card The card that player chose to give you. */ public abstract void receiveFavor(int playerIndex, Card card); /** * Method called when someone else draws a card. * @param playerIndex The index of the player that drew a card. */ public abstract void cardDrawn(int playerIndex); /** * Method called when someone else draws an exploding kitten. * @param playerIndex The index of the player that drew an exploding kitten. */ public abstract void explodingKittenDrawn(int playerIndex); /** * Method called when someone else puts an exploding kitten back into the deck. * @param playerIndex The index of the player that put the kitten back. */ public abstract void explodingKittenReplaced(int playerIndex); /** * Method called when someone loses to an exploding kitten. * @param playerIndex The index of the player that exploded. */ public abstract void playerExploded(int playerIndex); }
true
9c9e3103d16dabecd3fb554575ea989dc0eb3986
Java
hapsoa/java_thethelab_workspace
/예전 모음/KeyEventManager(합)_01/src/TestKey.java
UTF-8
2,536
2.484375
2
[]
no_license
import processing.core.PApplet; import java.security.KeyManagementException; import java.util.List; public class TestKey extends PApplet { public static void main(String[] args) { TestKey.main("TestKey"); } private Rect rect = new Rect(this); private boolean isKeyPressed; public static KeyEventManager keyEventManager; public void settings(){ size(500, 500); } public void setup(){ keyEventManager = new KeyEventManager(this); keyEventManager.setListener(37, new KeyEventManager.Listener() { @Override public void onPress(boolean isFirst, float duration) { rect.position.x--; System.out.println(duration); } @Override public void onRelease(float duration) { } }); keyEventManager.setListener(38, new KeyEventManager.Listener() { @Override public void onPress(boolean isFirst, float duration) { rect.position.y--; System.out.println(duration); } @Override public void onRelease(float duration) { } }); keyEventManager.setListener(39, new KeyEventManager.Listener() { @Override public void onPress(boolean isFirst, float duration) { rect.position.x++; System.out.println(isFirst+ " , " + duration); } @Override public void onRelease(float duration) { } }); keyEventManager.setListener(40, new KeyEventManager.Listener() { @Override public void onPress(boolean isFirst, float duration) { rect.position.y++; System.out.println(duration); } @Override public void onRelease(float duration) { } }); } public void draw(){ background(0); rect.update(); rect.render(); // if(keyPressed) // { // keyEventManager.setKeyPress(keyCode); // isKeyPressed = true; // } // else if (isKeyPressed) { // keyEventManager.setKeyRelease(keyCode); // isKeyPressed = false; // } keyEventManager.update(); } public void keyPressed(){ keyEventManager.setKeyPress(keyCode); } public void keyReleased(){ keyEventManager.setKeyRelease(keyCode); } }
true
922c760737ff5ab1c2b50bfb1e2c5ec7f178f249
Java
spring-projects/spring-integration
/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/AbstractTcpConnectionSupport.java
UTF-8
1,593
2.171875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2017-2019 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.integration.ip.tcp.connection; /** * Base class for TCP Connection Support implementations. * * @author Gary Russell * @since 5.0 * */ public abstract class AbstractTcpConnectionSupport { private boolean pushbackCapable; private int pushbackBufferSize = 1; public boolean isPushbackCapable() { return this.pushbackCapable; } /** * Set to true to cause wrapping of the connection's input stream in a * {@link java.io.PushbackInputStream}, enabling deserializers to "unread" data. * @param pushbackCapable true to enable. */ public void setPushbackCapable(boolean pushbackCapable) { this.pushbackCapable = pushbackCapable; } public int getPushbackBufferSize() { return this.pushbackBufferSize; } /** * The size of the push back buffer; defaults to 1. * @param pushbackBufferSize the size. */ public void setPushbackBufferSize(int pushbackBufferSize) { this.pushbackBufferSize = pushbackBufferSize; } }
true
7b2c730a1f2f1f2bcc2a68a95d50ede66f280508
Java
fullstackjavaprof/oct-java-training
/oct24/TestThread2.java
UTF-8
525
3.1875
3
[]
no_license
package com.threads; class TestThread2 implements Runnable{ public void run(){ for(int i=1;i<5;i++){ try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(i); } } public static void main(String args[]){ TestThread2 tr1=new TestThread2(); TestThread2 tr2=new TestThread2(); Thread t1=new Thread(tr1); Thread t2=new Thread(tr2); t1.start(); t2.start(); } }
true
d6bbcf89aa2487ae125fb323f600251ccf2890f5
Java
Facualv14/xHub-OPENSOURCED
/src/main/java/services/xenlan/hub/queue/plugins/Custom.java
UTF-8
1,057
2.5625
3
[]
no_license
package services.xenlan.hub.queue.plugins; import org.bukkit.entity.Player; import services.xenlan.hub.queue.Queue; import services.xenlan.hub.utils.CC; import services.xenlan.hub.xHub; public class Custom extends Queue { @Override public boolean inQueue(Player p) { return xHub.getInstance().getQueueManager().getQueue(p) != null; } @Override public String getQueueIn(Player p) { return xHub.getInstance().getQueueManager().getQueue(p).getServer(); } @Override public int getPosition(Player p) { int pos = xHub.getInstance().getQueueManager().getQueue(p).getPlayers().indexOf(p) + 1; return pos; } @Override public int getQueueSize(String server) { return xHub.getInstance().getQueueManager().getQueue(server).getSize(); } @Override public void sendPlayer(Player p, String server) { if (xHub.getInstance().getQueueManager().getQueue(server) == null) { p.sendMessage(CC.chat("&cFailed to add you to the " + server + "'s queue.")); return; } xHub.getInstance().getQueueManager().getQueue(server).addToQueue(p); } }
true
c2cf171eebb91b0e0b72cfde586c1ce9a4c37c41
Java
hellcy/leetcode
/Algorithms/496. Next Greater Element I.java
UTF-8
1,484
3.34375
3
[]
no_license
class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { /* Brute force */ // int[] ans = new int[nums1.length]; // for (int i = 0; i < nums1.length; ++i) { // boolean flag = false; // for (int j = 0; j < nums2.length; ++j) { // if (nums2[j] == nums1[i]) flag = true; // if (flag) { // if (nums2[j] > nums1[i]) { // ans[i] = nums2[j]; // break; // } // } // if (j == nums2.length - 1) ans[i] = -1; // } // } // return ans; /* Mono Stack HashMap */ HashMap<Integer, Integer> map = new HashMap<>(); Stack<Integer> stack = new Stack<>(); for (int i : nums2) { while (!stack.empty() && stack.peek() < i) { map.put(stack.pop(), i); } stack.add(i); } while (!stack.empty()) { map.put(stack.pop(), -1); } //System.out.println(map); int[] ans = new int[nums1.length]; for (int i = 0; i < nums1.length; ++i) { ans[i] = map.get(nums1[i]); } return ans; } }
true
763266304a8f4570ab10af262db7884c09bcac55
Java
heineman/ebc-example
/EBC_SoftwareEngineeringProject/src/example/calc/controller/ComputeController.java
UTF-8
1,251
2.875
3
[]
no_license
package example.calc.controller; import javax.swing.JOptionPane; import example.calc.model.Constant; import example.calc.model.Model; import example.calc.view.CalculatorApp; public class ComputeController { CalculatorApp app; Model model; public ComputeController(CalculatorApp app, Model m) { this.app = app; this.model = m; } public void compute() { String arg1 = app.getTextArg1().getText(); String arg2 = app.getTextArg2().getText(); double v1, v2; try { v1 = Double.parseDouble(arg1); } catch (Exception e) { Constant c = model.getConstant(arg1); if (c == null) { JOptionPane.showMessageDialog(app, "Arg1 \"" + arg1 + "\" is not a constant or value.", "WARNING.", JOptionPane.WARNING_MESSAGE); return; } else { v1 = c.value; } } try { v2 = Double.parseDouble(arg2); } catch (Exception e) { Constant c = model.getConstant(arg2); if (c == null) { JOptionPane.showMessageDialog(app, "Arg2 \"" + arg2 + "\" is not a constant or value.", "WARNING.", JOptionPane.WARNING_MESSAGE); return; } else { v2 = c.value; } } double sum = v1 + v2; app.getTextSum().setText("" + sum); app.repaint(); } }
true
98e78973a4456216ec5ec099cb7eac4766cf80ec
Java
christophorBlagoev/JavaOOP
/L04_InterfacesAndAbstraction/Exercise/P02_MultipleImplementation/Birthable.java
UTF-8
149
2.40625
2
[]
no_license
package Exercise.P02_MultipleImplementation; /* @created by Ch.B. on 23-Mar-21 - 18:59 */ public interface Birthable { String getBirthDate(); }
true
e076afe0208551f66cf694db807337e37d151d50
Java
KirillIvushkin/testGitHW
/src/Lesson06/Cat.java
UTF-8
1,345
3.59375
4
[]
no_license
package Lesson06; import models.Animal; public class Cat extends Animal { private String catName = "Кошка"; private static int catMaxRunDistance = 200; private static int catMaxSwimDistance = 0; private static int catsCount = 0; public Cat(String nickname) { super(nickname); setSkillsToDefault(catName, catMaxRunDistance, catMaxSwimDistance); catsCount += 1; } public Cat(String nickname, int maxRunDistance, int maxSwimDistance) { super(nickname, maxRunDistance, maxSwimDistance); this.name = catName; catsCount += 1; } public Cat(String nickname, String sex, int age){ super(nickname, sex, age); setSkillsToDefault(catName, catMaxRunDistance, catMaxSwimDistance); catsCount += 1; } public Cat(String nickname, String sex){ super(nickname, sex); setSkillsToDefault(catName, catMaxRunDistance, catMaxSwimDistance); catsCount += 1; } @Override public void swim(int distance) { //Плавание System.out.println(name + " " + nickname + " говорит, что не умеет плавать"); } // @Override public static int getAnimalCount() {return Cat.catsCount;} //Не совсем понятно, почему не работает Override? }
true
7b95d424840ba59d31b5249260e380a0e1cf81fa
Java
buzheng1949/Message
/app/src/main/java/com/example/yupeibiao/message/com/example/yupeibiao/message/activity/SettingActivity.java
UTF-8
2,251
2.1875
2
[]
no_license
package com.example.yupeibiao.message.com.example.yupeibiao.message.activity; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.yupeibiao.message.R; import com.example.yupeibiao.message.com.example.yupeibiao.message.constant.MyConstants; /** * Created by yupeibiao on 16/4/13. * 设置密码界面 */ public class SettingActivity extends Activity implements View.OnClickListener{ public static boolean NEED_INPUT_PASSWORD=false; private EditText et_password; private EditText et_comfirm_passwprd; private Button button_okay; private SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.passwordactivity); initViews(); initEvents(); } @Override public void onClick(View v) { String password=et_password.getText().toString().trim(); String comfirm_password=et_comfirm_passwprd.getText().toString().trim(); if(TextUtils.isEmpty(password)||TextUtils.isEmpty(comfirm_password)){ Toast.makeText(SettingActivity.this,"请输入您的密码",Toast.LENGTH_SHORT).show(); }else if(!password.equals(comfirm_password)){ Toast.makeText(SettingActivity.this,"您两次的密码不一致",Toast.LENGTH_SHORT).show(); }else{ //将密码保存在sharedprefernce sp=getSharedPreferences("info.txt",MODE_PRIVATE); SharedPreferences.Editor editor=sp.edit(); editor.putString("password",password); editor.commit(); MyConstants.PASSWORD_RIGHT=1; MyConstants.NEED_TO_LOGGING=true; finish(); } } public void initEvents(){ button_okay.setOnClickListener(this); } public void initViews(){ et_password=(EditText)findViewById(R.id.et_password); et_comfirm_passwprd=(EditText)findViewById(R.id.et_confirm_password); button_okay=(Button)findViewById(R.id.button_okay); } }
true
a90603afb19b35d66a4ec06215c7769ce6242604
Java
gabrysbiz/lesscss-extended-compiler
/src/main/java/biz/gabrys/lesscss/extended/compiler/source/ClasspathSource.java
UTF-8
3,961
2.546875
3
[ "BSD-3-Clause" ]
permissive
/* * Extended LessCSS Compiler * http://lesscss-extended-compiler.projects.gabrys.biz/ * * Copyright (c) 2015 Adam Gabryś * * This file is licensed under the BSD 3-Clause (the "License"). * You may not use this file except in compliance with the License. * You may obtain: * - a copy of the License at project page * - a template of the License at https://opensource.org/licenses/BSD-3-Clause */ package biz.gabrys.lesscss.extended.compiler.source; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import java.util.Date; import org.apache.commons.io.IOUtils; /** * Represents a <a href="http://lesscss.org/">Less</a> source file located in classpath. * @since 2.1.0 */ public class ClasspathSource implements LessSource { /** * Stores protocol prefix with colon and slashes. * @since 2.1.0 */ protected static final String PROTOCOL_PREFIX = "classpath://"; private final URI uri; private final String path; private final String encoding; private Date lastModificationDate; /** * Constructs a new instance and sets {@link URI} of the source file with default platform encoding. * @param uri the {@link URI} which pointer to source file. * @since 2.1.0 */ public ClasspathSource(final URI uri) { this(uri, Charset.defaultCharset().toString()); } /** * Constructs a new instance and sets {@link URI} of the source file and its encoding. * @param uri the {@link URI} which pointer to source file. * @param encoding the source file encoding. * @since 2.1.0 */ public ClasspathSource(final URI uri, final String encoding) { this.uri = uri; path = uri.toString().substring(PROTOCOL_PREFIX.length()); this.encoding = encoding; } public String getPath() { return uri.toString(); } public String getEncoding() { return encoding; } public String getContent() { final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); final InputStream stream = classLoader.getResourceAsStream(path); if (stream == null) { throw new SourceException(String.format("Cannot find resource \"%s\" in classpath", path)); } final String content; try { content = IOUtils.toString(stream, encoding); } catch (final IOException e) { throw new SourceException(String.format("Cannot read content of the \"%s\" resource", path), e); } finally { IOUtils.closeQuietly(stream); } lastModificationDate = getModificationDate(); return content; } /** * {@inheritDoc} Before the first {@link #getContent()} call returns current source modification time. After the * first {@link #getContent()} call always returns the source modification time read while reading the source * contents. * @return the encoding. * @since 2.1.0 */ public Date getLastModificationDate() { if (lastModificationDate != null) { return (Date) lastModificationDate.clone(); } return getModificationDate(); } private Date getModificationDate() { final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); final URL resource = classLoader.getResource(path); if (resource == null) { throw new SourceException(String.format("Cannot find resource \"%s\" in classpath", path)); } final URLConnection connection; try { connection = resource.openConnection(); } catch (final IOException e) { throw new SourceException(String.format("Cannot read last modification date for \"%s\" resource", path), e); } return new Date(connection.getLastModified()); } }
true
61f19f5d6f941742a2c28f71ddd2e200d9df4a1c
Java
reactivesystems-eu/jax-2018-microservices-workshop
/booking-api/src/main/java/eu/reactivesystems/workshop/booking/api/BookingRequest.java
UTF-8
1,140
2.375
2
[]
no_license
package eu.reactivesystems.workshop.booking.api; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Value; import java.time.LocalDate; import java.util.UUID; /** */ @Value public final class BookingRequest { /** * The user that requests the booking. */ private final UUID guest; /** * The starting date of the booking */ private final LocalDate startingDate; /** * The duration of the booking */ private final int duration; /** * The number of guests */ private final int numberOfGuests; @JsonCreator // parameter annotations needed until https://github.com/lagom/lagom/issues/172 is fixed. public BookingRequest(@JsonProperty("guest") UUID guest, @JsonProperty("startingDate") LocalDate startingDate, @JsonProperty("duration") int duration, @JsonProperty("numberOfGuests") int numberOfGuests) { this.guest = guest; this.startingDate = startingDate; this.duration = duration; this.numberOfGuests = numberOfGuests; } }
true
35ff6456ccb476a74186ca8d9a883025eb173a11
Java
abhi-manyu/Hibernate
/ORM_is-a_Table_per_ConcreetClass/src/classses/Hardware_Company.java
UTF-8
613
2.625
3
[]
no_license
package classses; public class Hardware_Company extends Company { private double hike; private int no_of_holydays; public Hardware_Company() { } public Hardware_Company(int reg_no, String name, double hike, int no_of_holydays) { super(reg_no, name); this.hike = hike; this.no_of_holydays = no_of_holydays; } public double getHike() { return hike; } public void setHike(double hike) { this.hike = hike; } public int getNo_of_holydays() { return no_of_holydays; } public void setNo_of_holydays(int no_of_holydays) { this.no_of_holydays = no_of_holydays; } }
true
dbcc58acc13590502d1df3dae00ce94d9e956327
Java
rvelhote/university
/pyra/src/BlocoSprite.java
UTF-8
288
2.40625
2
[ "Unlicense" ]
permissive
import javax.microedition.lcdui.Image; import javax.microedition.lcdui.game.Sprite; public class BlocoSprite extends Sprite { public boolean colidiu; public BlocoSprite(Image img, int w, int h) { super(img, w, h); colidiu = false; } }
true
c281dba8ec12491ea4049b51ce16b2cfe41c9901
Java
maratimaev/job4j
/chapter_003/src/test/java/ru/job4j/comparator/ListCompareTest.java
UTF-8
2,304
3.140625
3
[]
no_license
package ru.job4j.comparator; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.MatcherAssert.assertThat; /** * @author Marat Imaev (mailto:imaevmarat@outlook.com) * @version $Id$ * @since 0.1 */ public class ListCompareTest { /** * Тест проверяет сравнение 2х одинаковых строк */ @Test public void whenStringsAreEqualThenZero() { ListCompare compare = new ListCompare(); int rst = compare.compare( "Ivanov", "Ivanov" ); assertThat(rst, is(0)); } /** * Тест проверяет сравнение разных по длине строк */ @Test public void whenLeftLessThanRightResultShouldBeNegative() { ListCompare compare = new ListCompare(); int rst = compare.compare( "Ivanov", "Ivanova" ); assertThat(rst, lessThan(0)); } /** * Тест проверяет сравнение разных по длине и содержанию строк */ @Test public void whenLeftGreaterThanRightResultShouldBePositive() { ListCompare compare = new ListCompare(); int rst = compare.compare( "Petrov", "Ivanova" ); assertThat(rst, greaterThan(0)); } /** * Тест проверяет сравнение одинаковых по длине с одной отличающейся буквой */ @Test public void secondCharOfLeftGreaterThanRightShouldBePositive() { ListCompare compare = new ListCompare(); int rst = compare.compare( "Petrov", "Patrov" ); assertThat(rst, greaterThan(0)); } /** * Тест проверяет сравнение когда 1ая строка длинее второй */ @Test public void secondCharOfLeftLessThanRightShouldBeNegative() { ListCompare compare = new ListCompare(); int rst = compare.compare( "Patrova", "Petrov" ); assertThat(rst, lessThan(0)); } }
true
1c21b8bdfe18ef1c2a54029ba888e6e830ab3b5f
Java
DaniyalKhan/Orcs-n-Barrels
/gca-game/src/com/gca/models/projectiles/Spell.java
UTF-8
951
2.703125
3
[]
no_license
package com.gca.models.projectiles; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.gca.screens.GameScreen; public class Spell extends LineProjectile { public static final float LENGTH = 74f/GameScreen.PIX_PER_UNIT; public static final float FIRE_HEIGHT = 108f/GameScreen.PIX_PER_UNIT; public static final float FIRE_WIDTH = 243f/GameScreen.PIX_PER_UNIT; public static final float VELOCITY = 700f/GameScreen.PIX_PER_UNIT; public float angle; public final int type; private final Rectangle hitBox; public Spell(float x, float y, float length, Vector2 velocity, float angle, int damage, int type) { super(x, y, length, velocity, angle, damage); this.angle = angle; this.type = type; this.hitBox = new Rectangle(); hitBox.width = FIRE_WIDTH; hitBox.height = FIRE_HEIGHT; } public Rectangle getHitBox() { hitBox.x = position.x; hitBox.y = position.y; return hitBox; } }
true
01ad489916e6103375b6036281551dfa50ecd156
Java
hydrangea86/spring_core_study
/src/main/java/com/spring/core/oop/hotel/FrenchRestaurant.java
UTF-8
596
2.609375
3
[]
no_license
package com.spring.core.oop.hotel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; @Component("fr") //이름 설정 가능("xx") public class FrenchRestaurant implements Restaurant{ private final Chef chef; @Autowired public FrenchRestaurant(@Qualifier("kimChef") Chef chef) { this.chef = chef; } @Override public void orderDinner() { System.out.println("프랑스 요리를 주문합니다."); chef.cook(); } }
true
0177cdd686e69c74a5bb1d29764962f9bf1efbe0
Java
YidaChen/UVa-Java
/UVa10101_BanglaNumbers.java
UTF-8
954
4.09375
4
[]
no_license
/* 有點看不懂題目 */ import java.util.Scanner; class UVa10101_BanglaNumbers { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int count = 1; while(sc.hasNext()) { System.out.printf("%4d.", count++); long n = sc.nextLong(); if(n == 0) { System.out.println(" 0"); continue; } bangla(n); System.out.println(); } } //’kuti’ (10000000), ’lakh’ (100000), ’hajar’ (1000), ’shata’ (100) static void bangla(long n) { if(n >= 10000000) { bangla(n / 10000000); System.out.print(" kuti"); n = n % 10000000; } if(n >= 100000) { bangla(n / 100000); System.out.print(" lakh"); n = n % 100000; } if(n >= 1000) { bangla(n / 1000); System.out.print(" hajar"); n = n % 1000; } if(n >= 100) { bangla(n / 100); System.out.print(" shata"); n = n % 100; } if(n > 0) System.out.print(" " + n); } }
true
5ff7c4d88777a2d688921cb3cf0fc685a99afb06
Java
pborczyk/BracketlyFrontend
/app/src/main/java/edu/bracketly/frontend/dto/MatchDto.java
UTF-8
365
1.992188
2
[]
no_license
package edu.bracketly.frontend.dto; import java.io.Serializable; import java.util.List; import edu.bracketly.frontend.consts.MATCH_STATUS; import lombok.Data; @Data public class MatchDto implements Serializable { private Long id; private String tag; private List<SeatDto> seats; private MATCH_STATUS matchStatus; private PlayerDto winner; }
true
3e75979923dfaac7aaed95a778bf9c488fe0a8f7
Java
manishgdev/MyJavaProjects
/ExtentReportsProject/TestNG-Parallel-Methods/com/manish/beans/Student.java
UTF-8
406
2.625
3
[]
no_license
package com.manish.beans; public class Student { private String name; private int marks; public void setName(String name) { this.name = name; } public void setMarks(int marks) { this.marks = marks; } public String getName() { return name; } public int getMarks() { return marks; } public String falseName() { return "Arjun"; } public int fixMarks() { return 54; } }
true
633da870022ec1342e636e26afb393eb380ce1ea
Java
Donpommelo/Gallery-Rouge
/core/src/abilities/CallforBackup.java
UTF-8
739
2.125
2
[]
no_license
package abilities; import java.util.ArrayList; import party.Enforcer; import party.Schmuck; import states.BattleState; public class CallforBackup extends Skill{ public final static String name = "Call for Backup"; public final static String descr = "TEMP"; public final static int id = 1; public final static int cost = 6; public final static double init = 0.0; public final static int target = 0; public final static int numTargets = 0; public CallforBackup() { super(name, descr, id, cost, init, target,numTargets); } public void use(Schmuck user, ArrayList<Schmuck> target, BattleState bs){ bs.bq.initSchmuck(new Enforcer(), bs.bq.toq.size(), bs.bq.team1.contains(user.getButton())); bs.bq.adjustButtons(); } }
true
7cf4340fecba85861ab76f3f974b42452af8ccc0
Java
RohitB97/Baseform-Epanet-Java-Library
/org/addition/epanet/hydraulic/models/PipeHeadModel.java
UTF-8
1,938
2.25
2
[]
no_license
/* * Copyright (C) 2012 Addition, Lda. (addition at addition dot pt) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package org.addition.epanet.hydraulic.models; import org.addition.epanet.util.ENException; import org.addition.epanet.hydraulic.structures.SimulationLink; import org.addition.epanet.network.PropertiesMap; /** * Pipe head loss model calculator. */ public interface PipeHeadModel { /** * Link coefficients. */ public static class LinkCoeffs{ public LinkCoeffs(double invHeadLoss, double flowCorrection) { this.invHeadLoss = invHeadLoss; this.flowCorrection = flowCorrection; } private double invHeadLoss; private double flowCorrection; public double getInvHeadLoss() { return invHeadLoss; } public double getFlowCorrection() { return flowCorrection; } } //public double compute(PropertiesMap pMap,SimulationLink link) throws ENException; /** * Compute link coefficients through the implemented pipe headloss model. * @param pMap Network properties map. * @param sL Simulation link. * @return Computed link coefficients. * @throws ENException */ public LinkCoeffs compute(PropertiesMap pMap,SimulationLink sL) throws ENException; }
true
00dda8f13cb130423a74379a7c195add693b0882
Java
deepthikamaraj/javaCode
/opserv-sp-core/src/main/java/com/cognizant/opserv/sp/core/dao/TAlgmntBussRuleDAO.java
UTF-8
8,490
2.515625
3
[]
no_license
package com.cognizant.opserv.sp.core.dao; import java.util.List; import com.cognizant.opserv.sp.core.entity.TAlgmntBussRule; import com.cognizant.opserv.sp.core.entity.TAlgmntSalesTeam; import com.cognizant.opserv.sp.core.entity.TBussRuleConfig; import com.cognizant.peg.core.common.SearchFilter; /** * Interface represents API's of TAlgmntBussRule DAO. * * @author JCoE team * @version 1.0 * */ public interface TAlgmntBussRuleDAO { /** * Stores a new TAlgmntBussRule entity object in to the persistent store * * @param tAlgmntBussRule * TAlgmntBussRule Entity object to be persisted * @return tAlgmntBussRule Persisted TAlgmntBussRule object */ TAlgmntBussRule createTAlgmntBussRule(TAlgmntBussRule tAlgmntBussRule); /** * Deletes a TAlgmntBussRule entity object from the persistent store * * @param tAlgmntBussRule * TAlgmntBussRule Entity object to be deleted */ void deleteTAlgmntBussRule(Integer ruleId); /** * Updates a TAlgmntBussRule entity object in to the persistent store * * @param tAlgmntBussRule * TAlgmntBussRule Entity object to be updated * @return tAlgmntBussRule Persisted TAlgmntBussRule object */ TAlgmntBussRule updateTAlgmntBussRule(TAlgmntBussRule tAlgmntBussRule); /** * Retrieve an TAlgmntBussRule object based on given ruleId. * * @param ruleId * the primary key value of the TAlgmntBussRule Entity. * @return an Object if it exists against given primary key. Returns null of * not found */ TAlgmntBussRule findTAlgmntBussRuleById(Integer ruleId); /** * Retrieve TAlgmntBussRule based on given search criteria using Dynamic JPAQL. * * @param searchFilter * The query criteria and search filter conditions are set * @return List<TAlgmntBussRule> list of TAlgmntBussRules if it exists against given * criteria. Returns null if not found */ List<TAlgmntBussRule> findTAlgmntBussRules(SearchFilter<TAlgmntBussRule> searchFilter); /** * Count TAlgmntBussRule based on given search criteria using Dynamic JPAQL. * * @param searchFilter * The query criteria and search filter conditions are set * @return a Object indicating the count */ Object countTAlgmntBussRules(SearchFilter<TAlgmntBussRule> searchFilter); /** * Retrieve TAlgmntBussRule based on given search criteria using JPA named Query. * The search criteria is of TBussRuleConfig type. * * @param searchFilter * The query criteria and search filter conditions are set * @return List<TAlgmntBussRule> list of TAlgmntBussRules if it exists against given * criteria. Returns null if not found */ List<TAlgmntBussRule> getTAlgmntBussRulesByTBussRuleConfig(SearchFilter<TBussRuleConfig> searchFilter); /** * Count TAlgmntBussRule based on given search criteria using JPA named Query. * The search criteria is of TBussRuleConfig type. * * @param searchFilter * The query criteria and search filter conditions are set * @return a Object indicating the count */ Object countTAlgmntBussRulesByTBussRuleConfig(SearchFilter<TBussRuleConfig> searchFilter); /** * Retrieve TAlgmntBussRule based on given search criteria using JPA named Query. * The search criteria is of TAlgmntSalesTeam type. * * @param searchFilter * The query criteria and search filter conditions are set * @return List<TAlgmntBussRule> list of TAlgmntBussRules if it exists against given * criteria. Returns null if not found */ List<TAlgmntBussRule> getTAlgmntBussRulesByTAlgmntSalesTeam(SearchFilter<TAlgmntSalesTeam> searchFilter); /** * Count TAlgmntBussRule based on given search criteria using JPA named Query. * The search criteria is of TAlgmntSalesTeam type. * * @param searchFilter * The query criteria and search filter conditions are set * @return a Object indicating the count */ Object countTAlgmntBussRulesByTAlgmntSalesTeam(SearchFilter<TAlgmntSalesTeam> searchFilter); /** * Gets the t algmnt buss rules by t algmnt sales team rule config id. * * @param searchFilter the search filter * @return the t algmnt buss rules by t algmnt sales team rule config id */ List<TAlgmntBussRule> getTAlgmntBussRulesByTAlgmntSalesTeamRuleConfigId(SearchFilter<TAlgmntBussRule> searchFilter); /** * Search customer share rule. * * @param algmntId the algmnt id * @param bussUnitId the buss unit id * @param salesTeamId the sales team id * @param tenantId the tenant id * @return the list */ List <TAlgmntBussRule> searchCustomerShareRule(String algmntId,String bussUnitId,String salesTeamId,String tenantId); /** * Find valueby align info and rule name. * * @param algmntId the algmnt id * @param bussUnitId the buss unit id * @param salesTeamId the sales team id * @param BussRuleName the buss rule name * @return the list */ List<Object[]> findValuebyAlignInfoAndRuleName(Long algmntId,Long bussUnitId,Long salesTeamId,String BussRuleName); /** * Gets the all t algmnt buss rule. * * @param tenantId the tenant id * @return the all t algmnt buss rule */ List<TAlgmntBussRule> getAllTAlgmntBussRule(Short tenantId); /** * Gets the all t algmnt buss rule by id. * * @param tenantId the tenant id * @param alignId the align id * @param bussUnitId the buss unit id * @param salesTeamId the sales team id * @return the all t algmnt buss rule by id */ List<TAlgmntBussRule> getAllTAlgmntBussRuleById(Short tenantId, Long alignId,Long bussUnitId,Long salesTeamId); /** * Gets the rule by albust rule id. * * @param alignId the align id * @param bussUnitId the buss unit id * @param salesTeamId the sales team id * @param bussRuleId the buss rule id * @param tenantId the tenant id * @return the rule by albust rule id */ List<TAlgmntBussRule> getRuleByALBUSTRuleID(Long alignId,Long bussUnitId,Long salesTeamId,Integer bussRuleId,Short tenantId); /** * Find valueby align info and rule config id. * * @param algmntId the algmnt id * @param bussUnitId the buss unit id * @param salesTeamId the sales team id * @param ruleId the rule id * @param tenantId the tenant id * @return the list */ List<Object[]> findValuebyAlignInfoAndRuleConfigId(Long algmntId, Long bussUnitId, Long salesTeamId, Integer ruleId, Short tenantId); // newly added for secondary address validation /** * Find flag valueby align info and rule config id. * * @param algmntId the algmnt id * @param bussUnitId the buss unit id * @param salesTeamId the sales team id * @param ruleId the rule id * @param tenantId the tenant id * @return the string */ String findFlagValuebyAlignInfoAndRuleConfigId(Long algmntId, Long bussUnitId, Long salesTeamId, Integer ruleId, Short tenantId); /** * Find valueby align info and rule config id fr bricks. * * @param algmntId the algmnt id * @param bussUnitId the buss unit id * @param salesTeamId the sales team id * @param ruleId the rule id * @param tenantId the tenant id * @return the list */ List<String> FindValuebyAlignInfoAndRuleConfigIdFrBricks(Long algmntId, Long bussUnitId, Long salesTeamId, Integer ruleId, Short tenantId); /** * Feth secondary address flag. * * @param algmntId the algmnt id * @param bussUnitId the buss unit id * @param salesTeamId the sales team id * @param bussRuleConfId the buss rule conf id * @param tenantId the tenant id * @return the list */ List<String> fethSecondaryAddressFlag(Long algmntId, Long bussUnitId, Long salesTeamId,Integer bussRuleConfId,Short tenantId); /** * Gets the all t algmnt buss rule by albust. * * @param tenantId the tenant id * @param alignId the align id * @param bussUnitId the buss unit id * @param salesTeamId the sales team id * @return the all t algmnt buss rule by albust */ List<TAlgmntBussRule> getAllTAlgmntBussRuleByALBUST(Short tenantId, Long alignId,Long bussUnitId,Long salesTeamId); /** * Gets the customer movement flag. * * @param alignmentId the alignment id * @param businessUnitId the business unit id * @param salesTeamId the sales team id * @param tenantId the tenant id * @return the customer movement flag */ List<TAlgmntBussRule> getBusinessRuleValue(Long alignmentId, Long businessUnitId, Long salesTeamId, String ruleName, Short tenantId); }
true
9ef008e5a2eba0d0773772f53d64866f38439dbb
Java
yuanyuanheng/framework
/dataPull/src/main/java/com/mn/config/Init.java
UTF-8
1,203
2.171875
2
[]
no_license
package com.mn.config; import java.util.logging.Level; import java.util.logging.Logger; import com.mn.bean.Mysql; import com.mn.persistent.MysqlOpt; import com.mn.proc.PersistentOpt; import com.mn.util.ReadText; public class Init { private static Mysql m_mysql; public static Mysql initMysql() { if (null == m_mysql) { m_mysql = new Mysql(); m_mysql.setM_sDriverClassName("com.mysql.jdbc.Driver"); m_mysql.setM_sUrl("jdbc:mysql://127.0.0.1:3306/mn?useUnicode=yes&amp;characterEncoding=UTF8"); m_mysql.setM_sUserName("sdsj"); m_mysql.setM_sPassword("sdsj"); } return m_mysql; } private static Logger m_logger; public static Logger initLogger(Class<?> clsTemp,String filePath,Level logLevel){ if(null == m_logger){ System.setProperty("java.util.logging.config.file", filePath); } m_logger = Logger.getLogger(clsTemp.getName()); m_logger.setLevel(logLevel); return m_logger; } public static void initMysqlTable(){ String sSql = ReadText.Read(Const.CURR_PATH+Const.SQL_TABLE); if(sSql.trim().length()>0){ PersistentOpt mysqlOpt = new MysqlOpt(); mysqlOpt.start(); mysqlOpt.update(sSql); mysqlOpt.end(); mysqlOpt = null; } } }
true
1d7397a57aab6f2425ba328b3a4527b1c4e0545d
Java
vuleenguyen/DataStructure_Algorithm_Java
/learning-datastructures/src/ds/circurlarlinkedlist/TestCircularLinkedList.java
UTF-8
652
2.71875
3
[]
no_license
package ds.circurlarlinkedlist; import ds.singlylinkedlist.SinglyLinkedList; /** * Created by Do My Duyen on 9/24/2017. */ public class TestCircularLinkedList { public static void main(String[] args) { CircularLinkedList myList = new CircularLinkedList(); myList.insertFirst(100); myList.insertFirst(50); myList.insertFirst(99); myList.insertFirst(88); myList.insertLast(101); myList.insertFirst(25); myList.insertLast(300); myList.displayList(); myList.deleteFirst(); myList.displayList(); myList.deleteLast(); myList.displayList(); } }
true
3dd02f0dff6ee2aa04e64f01dd3c2bdae57b6361
Java
ManjunathPrabhakar/ReportBuilderJava
/src/main/java/com/rajatthareja/reportbuilder/report/Hook.java
UTF-8
733
1.976563
2
[ "MIT" ]
permissive
package com.rajatthareja.reportbuilder.report; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.time.Duration; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) public class Hook { private Result result = new Result(); private List<Embedding> embeddings; public Duration getDuration() { return Duration.ofNanos(result.getDuration()); } public Result getResult() { return result; } public void setResult(Result result) { this.result = result; } public List<Embedding> getEmbeddings() { return embeddings; } public void setEmbeddings(List<Embedding> embeddings) { this.embeddings = embeddings; } }
true
8cb784db149e23866360563c21e1b7c04d2504ac
Java
Adityacprtm/NetBeansProjects
/SEMESTER 2/src/Tugas1/Peternakan.java
UTF-8
734
2.890625
3
[]
no_license
package Tugas1; public class Peternakan { public String jenis; public int jumlah; public int harga; public int untung; public int melahirkan(int a) { return this.jumlah = jumlah + a; } public void penjualan(int x) { this.untung = harga * x; this.jumlah = jumlah - x; } public void tampilkanData() { System.out.println("Jenis : " + jenis); System.out.println("Jumlah : " + jumlah); System.out.println("Harga : " + harga); } public void tampilkanUntung() { System.out.println("Jenis : " + jenis); System.out.println("Jumlah sisa : " + jumlah); System.out.println("Keuntungan : " + untung); } }
true
6c878972ee2951f65ff0f77d456fa184b17c599c
Java
cr951213/CR_pinduoduo
/app/src/main/java/com/example/administrator/cr_pinduoduo/activity/model/Ssyy_Imodel.java
UTF-8
331
1.828125
2
[]
no_license
package com.example.administrator.cr_pinduoduo.activity.model; import com.example.administrator.cr_pinduoduo.activity.bean.SsyyBean; import rx.Observer; /** * Created by Administrator on 2017/12/13. */ public interface Ssyy_Imodel { //将观察者传(bean)进去 public void shuju(Observer<SsyyBean> observer); }
true
9300cab9ad1f39b84fa41853ea67628bdda29676
Java
Sq-List/LeetCode
/src/main/java/com/sqlist/leetcode/editor/cn/Q668KthSmallestNumberInMultiplicationTable.java
UTF-8
2,059
3.53125
4
[]
no_license
package com.sqlist.leetcode.editor.cn; /** 几乎每一个人都用 乘法表。但是你能在乘法表中快速找到第k小的数字吗? 给定高度m 、宽度n 的一张 m * n的乘法表,以及正整数k,你需要返回表中第k 小的数字。 例 1: 输入: m = 3, n = 3, k = 5 输出: 3 解释: 乘法表: 1 2 3 2 4 6 3 6 9 第5小的数字是 3 (1, 2, 2, 3, 3). 例 2: 输入: m = 2, n = 3, k = 6 输出: 6 解释: 乘法表: 1 2 3 2 4 6 第6小的数字是 6 (1, 2, 2, 3, 4, 6). 注意: m 和 n 的范围在 [1, 30000] 之间。 k 的范围在 [1, m * n] 之间。 Related Topics 数学 二分查找 👍 313 👎 0 */ /** * [668]乘法表中第k小的数 * @author SqList * @createTime 2022-05-20 11:47:58 **/ public class Q668KthSmallestNumberInMultiplicationTable { public static void main(String[] args) { Solution solution = new Q668KthSmallestNumberInMultiplicationTable().new Solution(); } //leetcode submit region begin(Prohibit modification and deletion) /** * 二分 * 逆向思维 不找第k数是谁 * 而是找 在 [1, m * n] 之间的数哪个是第k个数 * 因为是有序的 所以可以使用二分 */ class Solution { public int findKthNumber(int m, int n, int k) { int left = 1, right = m * n; while (right >= left) { int mid = left + ((right - left) >> 1); int count = count(m, n, mid); if (count > k) { right = mid - 1; } else if (count < k) { left = mid + 1; } else { right = mid - 1; } } return left; } public int count(int m, int n, int x) { int ans = 0; for (int i = 1; i <= m; i++) { ans += Math.min(x / i, n); } return ans; } } //leetcode submit region end(Prohibit modification and deletion) }
true
28705d7ffb9c7be4658f6bbf5210b2287436341f
Java
andriychuk94/java_pft
/sandbox/src/main/java/ru/stqa/pft/sandbox/Rectangle.java
UTF-8
218
2.484375
2
[ "Apache-2.0" ]
permissive
package ru.stqa.pft.sandbox; /** * Created by Boris on 07.06.2017. */ public class Rectangle { public double a; public double b; public Rectangle(double a, double b) { this.a = a; this.b = b; } }
true
02ad12667a525ac9d73ca451acbc2fe9ee280950
Java
VasilSokolov/TestProject
/src/contains/Person.java
UTF-8
719
3.046875
3
[]
no_license
package contains; //@SuppressWarnings(value = { "" }) public class Person { public String p = "Person field"; private String name; public Person() { System.out.println("construct"); } public String getName() { return name; } public void setName(String name) { this.name = name; } { String init = "init"; System.out.println(init); methods(); } static{ String staticBlock = "static block"; System.out.println(staticBlock); methodStatic(); } public void methods() { System.out.println("method"); } public static void methodStatic() { System.out.println("static method"); } @Override public String toString() { return "Person [p=" + p + ", name=" + name + "]"; } }
true
be9cfcdc7ad35a0b536479e1db6a83ff8224c8c7
Java
HeliasEurodyn/Camel-Spring-Test
/src/main/java/com/flexi/controller/MySqlConnectionController.java
UTF-8
1,565
2.25
2
[]
no_license
package com.flexi.controller; import com.flexi.model.MySqlConnection; import com.flexi.repository.MySqlConnectionRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; @org.springframework.web.bind.annotation.RestController public class MySqlConnectionController { @Autowired private MySqlConnectionRepository mysqlConnectionRepository; @GetMapping("/mySqlConnection/get") public List<MySqlConnection> get(){ return mysqlConnectionRepository.findAll(new Sort(Sort.Direction.ASC, "id")); } @GetMapping("/mySqlConnection/getFirst") public MySqlConnection getFirst(){ List<MySqlConnection> sqlServerConnections = mysqlConnectionRepository.findAll(); Optional<MySqlConnection> sqlServerConnectionOption = sqlServerConnections.stream().findFirst(); if(sqlServerConnectionOption.isPresent()) return sqlServerConnectionOption.get(); return null; } @DeleteMapping("/mySqlConnection/delete/{id}") public ResponseEntity<Void> delete(@PathVariable Long id){ mysqlConnectionRepository.deleteById(id); return ResponseEntity.noContent().build(); } @PostMapping("/mySqlConnection/update") public MySqlConnection update(@RequestBody MySqlConnection sqlServerConnection){ return mysqlConnectionRepository.save(sqlServerConnection); } }
true
fddf56b89f8433bcdda2e776ff9c5ce48ed21a8c
Java
mns1234/Mrinalini_shah
/Innovapath/src/com/main/ThrowExample.java
UTF-8
838
3.296875
3
[]
no_license
package com.main; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class ThrowExample { /*public static void checkage(int age){ if(age<18) throw new ArithmeticException(); else{ System.out.println("the age is fine"); } }*/ public static void checage(int age)throws FileNotFoundException,NullPointerException, ArithmeticException { if (age<16){ FileReader io= new FileReader(""); } else{ System.out.println("fine"); } } public static void main(String[] args){ try{ //ThrowExample.checkage(17); ThrowExample.checage(15); } catch(ArithmeticException e) {System.out.println("The error came");} catch (FileNotFoundException e) { System.out.println("OMG"); } catch (NullPointerException e) { e.printStackTrace(); } } }
true
339ea99d3e50c6488bfef7d1094da1ef122afb2d
Java
NeroAo/DemoBox
/NettyDemo/src/main/java/neroao/demobox/subreqserver/SubReqServerHandler.java
UTF-8
913
2.59375
3
[]
no_license
package neroao.demobox.subreqserver; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class SubReqServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx,Object msg)throws Exception{ SubscribeReq req = (SubscribeReq) msg; if("neroao".equalsIgnoreCase(req.getUserName())){ System.out.println("Service accept client subscribe req : ["+req.toString()+"]"); ctx.writeAndFlush(resp(req.getSubReqID())); } } private SubscribeResp resp(int subReqID){ SubscribeResp resp = new SubscribeResp(); resp.setSubReqID(subReqID); resp.setRespCode(0); resp.setDesc("Netty demo will sent to your address"); return resp; } @Override public void exceptionCaught(ChannelHandlerContext ctx , Throwable cause){ cause.printStackTrace();ctx.close(); } }
true
76c9a0315d05d510acc60383cdbd7d289fbc5d20
Java
yezijiang/matthew-alpha
/matthew-algorithm-practice/src/main/java/com/matthew/google/challenge/thirteen/Solution.java
UTF-8
3,182
3.3125
3
[]
no_license
package com.matthew.google.challenge.thirteen; import com.google.common.base.Strings; import com.sun.org.apache.xalan.internal.xsltc.compiler.util.StringStack; import org.junit.Assert; import org.junit.Test; import java.util.HashMap; import java.util.Map; /** * Created with IntelliJ IDEA * User: maxing * TIME: 2019-03-27 9:42 * Roman to Integer * 将一个罗马数字转化为证书 */ public class Solution { public int romanToInt(String s) { Map<String,Integer> romanSymbol = new HashMap<String,Integer>(); romanSymbol.put("I",1); romanSymbol.put("V",5); romanSymbol.put("X",10); romanSymbol.put("L",50); romanSymbol.put("C",100); romanSymbol.put("D",500); romanSymbol.put("M",1000); String temRomStr = ""; char[] sArrays = s.toCharArray(); int sum = 0; for(int i=0;i<sArrays.length;i++){ if(!"".equals(temRomStr)){ if(romanSymbol.get(temRomStr) < romanSymbol.get(""+sArrays[i])){ sum = sum + romanSymbol.get(""+sArrays[i]) - romanSymbol.get(temRomStr); temRomStr = ""; }else{ sum = sum + romanSymbol.get(temRomStr); temRomStr = ""+sArrays[i]; } }else{ temRomStr = ""+sArrays[i]; } } if(!"".equals(temRomStr)){ sum = sum + romanSymbol.get(temRomStr); } return sum; } /** * 解题思路是 * 1,如果前一个字符小于后一个字符,则前一个字符为- * 2,否则为正,再考虑溢出情况就好了。 * @param s * @return */ public int romanToInt2(String s) { Map<String,Integer> romanSymbol = new HashMap<String,Integer>(); romanSymbol.put("I",1); romanSymbol.put("V",5); romanSymbol.put("X",10); romanSymbol.put("L",50); romanSymbol.put("C",100); romanSymbol.put("D",500); romanSymbol.put("M",1000); String temRomStr = ""; char[] sArrays = s.toCharArray(); int sum = 0; int size =sArrays.length-1; for(int i=0;i<=size;i++){ if(i==size){ sum +=romanSymbol.get(sArrays[i]+""); return sum; } if(romanSymbol.get(sArrays[i]+"")>=romanSymbol.get(sArrays[i+1]+"")){ sum +=romanSymbol.get(sArrays[i]+""); }else{ sum -=romanSymbol.get(sArrays[i]+""); } } return sum; } /** * 解题思路是 * 1,如果前一个字符小于后一个字符,则前一个字符为- * 2,否则为正,再考虑溢出情况就好了。 * 网上思路,不转str,不用hashmap * @param s * @return */ public int romanToInt3(String s) { int sum = 0; int preNum = getValue(s.charAt(0)); for(int i=1;i<s.length();i++){ int num = getValue(s.charAt(i)); if(num>preNum){ sum-=preNum; }else{ sum+=preNum; } preNum = num; } sum += preNum; return sum; } 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; } } @Test public void testValue(){ Assert.assertEquals(1,romanToInt3("I")); Assert.assertEquals(4,romanToInt("IV")); Assert.assertEquals(9,romanToInt("IX")); Assert.assertEquals(58,romanToInt("LVIII")); Assert.assertEquals(1994,romanToInt("MCMXCIV")); } }
true
dc8e3690a53b9879cef5a561e045d1ef84630b07
Java
Creator-Youth/Leetcode
/src/com/wxs/leetcode/TreeNode.java
UTF-8
774
3.15625
3
[]
no_license
package com.wxs.leetcode; import java.util.ArrayList; import java.util.List; import java.util.Stack; public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } List<Integer> list = new ArrayList<>(); public List<Integer> preorderTraversal(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode> (); if(null !=root ){ stack.push(root); list.add(root.val); root = root.left; } while(!stack.isEmpty()){ root = stack.pop(); while(null != root.right){ stack.push(root.left); list.add(root.val); root =root.left; } } return list; } }
true
41f1c1fbb017d05386d0d63fea419a5f6331655a
Java
flocela/IngAve-Android
/InglesAventurero/app/src/androidTest/java/com/olfybsppa/inglesaventurero/tests/linesCPtests/ProviderBackgroundsTest.java
UTF-8
4,071
2.234375
2
[]
no_license
package com.olfybsppa.inglesaventurero.tests.linesCPtests; import android.content.ContentValues; import android.database.Cursor; import android.provider.BaseColumns; import android.test.ProviderTestCase2; import android.test.mock.MockContentResolver; import com.olfybsppa.inglesaventurero.collectors.Background; import com.olfybsppa.inglesaventurero.start.LinesCP; import com.olfybsppa.inglesaventurero.utils.Ez; public class ProviderBackgroundsTest extends ProviderTestCase2<LinesCP> { private MockContentResolver mMockResolver; private Background background1; private Background background2; public ProviderBackgroundsTest() { super(LinesCP.class, LinesCP.AUTHORITY); } @Override protected void setUp() throws Exception { super.setUp(); mMockResolver = getMockContentResolver(); background1 = new Background("background 1","background1.jpg"); background1.addFilename("one"); background2 = new Background("background 2", "background2.jpg"); background2.addFilename("two"); } @Override protected void tearDown() throws Exception { super.tearDown(); } public void testInsertOneBackground () { ContentValues cV = background1.getContentValues(); mMockResolver.insert(LinesCP.backgroundTableUri, cV); Cursor cursor = mMockResolver.query(LinesCP.backgroundTableUri, null, null, null, null); cursor.moveToFirst(); assertEquals(1, cursor.getCount()); Background backgroundReturned = new Background(cursor.getString(cursor.getColumnIndex(LinesCP.background_name)), cursor.getString(cursor.getColumnIndex(LinesCP.filename))); assertTrue(backgroundReturned.equals(background1)); } public void testInsertTwoBackgroundDeleteOne () { ContentValues cV1 = background1.getContentValues(); ContentValues cV2 = background2.getContentValues(); mMockResolver.insert(LinesCP.backgroundTableUri, cV1); mMockResolver.insert(LinesCP.backgroundTableUri, cV2); Cursor cursor1 = mMockResolver.query(LinesCP.backgroundTableUri, null, null, null, null); cursor1.moveToFirst(); assertEquals(2, cursor1.getCount()); cursor1.close(); Cursor cursor2 = mMockResolver.query(LinesCP.backgroundTableUri, new String[]{BaseColumns._ID}, Ez.where(LinesCP.background_name, "background 1"), null, null); cursor2.moveToFirst(); int background1Id = cursor2.getInt(cursor2.getColumnIndex(BaseColumns._ID)); cursor2.close(); mMockResolver.delete(LinesCP.backgroundTableUri, Ez.where(BaseColumns._ID, "" + background1Id), null); Cursor cursor3 = mMockResolver.query(LinesCP.backgroundTableUri, null, null, null, null); assertEquals(1, cursor3.getCount()); cursor3.moveToFirst(); Background backgroundNotDeleted = new Background(cursor3.getString(cursor3.getColumnIndex(LinesCP.background_name)), cursor3.getString(cursor3.getColumnIndex(LinesCP.filename))); assertTrue(backgroundNotDeleted.equals(background2)); cursor3.close(); } public void testDoesNotAllowTwoBackgroundsWithSameName () { ContentValues cV1 = background1.getContentValues(); ContentValues cV2 = new ContentValues(); cV2.put(LinesCP.background_name, "background 1"); cV2.put(LinesCP.filename, "different"); mMockResolver.insert(LinesCP.backgroundTableUri, cV1); boolean failed = false; try { mMockResolver.insert(LinesCP.backgroundTableUri, cV2); } catch (Exception e) { failed = true; } assertTrue(failed); } public void testDoesNotAllowsTwoBackgroundsWithSameFilename () { ContentValues cV1 = background1.getContentValues(); ContentValues cV2 = new ContentValues(); cV2.put(LinesCP.background_name, background2.getBackgroundName()); cV2.put(LinesCP.filename, background1.getBackgroundFilename()); mMockResolver.insert(LinesCP.backgroundTableUri, cV1); boolean failed = false; try { mMockResolver.insert(LinesCP.backgroundTableUri, cV2); } catch (Exception e) { failed = true; } assertTrue(failed); } }
true
4002593f38e5110ac29d5b44476ca26d31eb03b2
Java
renderlife/travel-spring-hibernate
/src/main/java/com/travel/utility/parsing/Parsing.java
UTF-8
2,231
2.59375
3
[]
no_license
package com.travel.utility.parsing; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.openqa.selenium.WebDriver; import org.openqa.selenium.phantomjs.PhantomJSDriver; import java.io.File; /** * Парсинг авиабилетов и номеров в отеле при составлении тура * * @author Artem Faenko */ public class Parsing { private static ClassLoader classloader = Thread.currentThread().getContextClassLoader(); private static String FILE_RESOURCE = classloader.getResource("phantomjs/bin/phantomjs.exe").getFile(); private Document util(String url) { File file = new File(FILE_RESOURCE); System.setProperty("phantomjs.binary.path", file.getAbsolutePath()); WebDriver driver = new PhantomJSDriver(); driver.get(url); // Ожидание 5 секунд long end = System.currentTimeMillis() + 5000; while (System.currentTimeMillis() < end) { } String htmlContent = driver.getPageSource(); Document doc = Jsoup.parse(htmlContent); driver.close(); return doc; } public String parsingAvia(String url){ System.out.println(url); String urlAvia = String.valueOf(url); Document doc = util(urlAvia); Element element = doc.getElementById("results_add_container"); // lin3.getElementsByClass("creative").remove(); String parse = String.valueOf(element); return parse; } public String parsingHotel(String url){ System.out.println(url); String urlHotel = String.valueOf(url); Document doc = util(urlHotel); Element element = doc.getElementsByClass("hotels-grid-list").first(); String parse = String.valueOf(element); return parse; } public String parsingHotelNumber(String url){ System.out.println(url); String urlHotelNumber = String.valueOf(url); Document doc = util(urlHotelNumber); Element element = doc.getElementsByClass("hotels-one-info-collection").first(); String parse = String.valueOf(element); System.out.println(parse); return parse; } }
true
d9639d6fbc95f7f2ea19bb114defa9c46587fc3b
Java
jmg216/tsi2-g1-2012
/GeoRed-BackOffice-Web/src/com/geored/backoffice/managedBean/eventos/GestionEventoBean.java
UTF-8
5,909
2.109375
2
[]
no_license
package com.geored.backoffice.managedBean.eventos; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import com.geored.backoffice.managedBean.BaseBean; import com.geored.backoffice.utiles.UtilesWeb; import com.geored.negocio.EventoDTO; import com.geored.negocio.TematicaDTO; @ManagedBean(name="gestionEventoBean") @RequestScoped public class GestionEventoBean extends BaseBean implements Serializable { /** * */ private static final long serialVersionUID = -5348254664595085666L; private static final int VALIDAR_CREAR = 1; private static final int VALIDAR_MODIFICAR = 2; private static final String EVENTO_DTO_KEY = "EVENTO_DTO_KEY"; private static final String TO_LISTADO_EVENTOS = "to_listado_eventos"; private EventoDTO eventoDTO = new EventoDTO(); private List<TematicaDTO> listaTematicas = new ArrayList<TematicaDTO>(); private List<String> tematicasSeleccionadas = new ArrayList<String>(); public GestionEventoBean() { eventoDTO = (EventoDTO) getFlashAttribute(EVENTO_DTO_KEY); if(eventoDTO == null) { String idEvento = getRequestParameter("idEvento"); if(UtilesWeb.isNullOrEmpty(idEvento)) { eventoDTO = new EventoDTO(); } else { try { eventoDTO = getEventoPort().obtener(Long.valueOf(idEvento)); } catch (Exception e) { addBeanError(e.getMessage()); } } setFlashAttribute(EVENTO_DTO_KEY, eventoDTO); } cargarDatosIniciales(); } private void cargarDatosIniciales() { try { TematicaDTO[] arrayTematicas = getGlobalPort().obtenerListadoTematicas(); if(arrayTematicas != null) { listaTematicas = Arrays.asList(arrayTematicas); } // Cargo los ids de las tematicas seleccionadas en el sitio tematicasSeleccionadas = new ArrayList<String>(); if(eventoDTO.getListaTematicasDTO() != null) { for(TematicaDTO tematicaDTO : eventoDTO.getListaTematicasDTO()) { tematicasSeleccionadas.add(tematicaDTO.getId().toString()); } } } catch (Exception e) { handleWSException(e); } } public String guardarEvento() { try { if(getEventoDTO() == null) { addBeanError("Evento no puede ser nulo"); } else { // Transformo las tematicas seleccionadas List<TematicaDTO> listaTematicasDTO = new ArrayList<TematicaDTO>(); if(tematicasSeleccionadas != null) { for(String idTematica : tematicasSeleccionadas) { TematicaDTO tematicaDTO = new TematicaDTO(); tematicaDTO.setId(Long.valueOf(idTematica)); listaTematicasDTO.add(tematicaDTO); } } getEventoDTO().setListaTematicasDTO(listaTematicasDTO.toArray(new TematicaDTO[]{})); // Pregunto si es creacion o edicion if(UtilesWeb.isNullOrZero(getEventoDTO().getId())) { if(validar(VALIDAR_CREAR)) { Long idEventoNuevo = getEventoPort().insertar(getEventoDTO()); setEventoDTO(getEventoPort().obtener(idEventoNuevo)); addBeanMessage("Evento guardado correctamente"); } } else { if(validar(VALIDAR_MODIFICAR)) { getEventoPort().actualizar(getEventoDTO()); setEventoDTO(getEventoPort().obtener(getEventoDTO().getId())); addBeanMessage("Evento guardado correctamente"); } } } } catch (Exception e) { handleWSException(e); } return SUCCESS; } private boolean validar(int opValidar) { boolean isValid = true; if(opValidar == VALIDAR_CREAR || opValidar == VALIDAR_MODIFICAR) { if(UtilesWeb.isNullOrEmpty(getEventoDTO().getNombre())) { addBeanError("gestionEventoForm:nombreEvento", "Obligatorio"); isValid = false; } if(UtilesWeb.isNullOrEmpty(getEventoDTO().getDescripcion())) { addBeanError("gestionEventoForm:descripcionEvento", "Obligatorio"); isValid = false; } if(getEventoDTO().getFechaInicio() == null) { addBeanError("gestionEventoForm:fechaInicioEvento", "Obligatorio"); isValid = false; } if(getEventoDTO().getFechaFin() == null) { addBeanError("gestionEventoForm:fechaFinEvento", "Obligatorio"); isValid = false; } if(UtilesWeb.isNullOrEmpty(getEventoDTO().getUbicacionGeografica())) { addBeanError("gestionEventoForm:ubicacionGeografica", "Obligatorio"); isValid = false; } if(getEventoDTO().getFechaInicio() != null && getEventoDTO().getFechaFin() != null) { if(getEventoDTO().getFechaFin().before(getEventoDTO().getFechaInicio())) { addBeanError("gestionEventoForm:fechaFinEvento", "La fecha fin debe se mayor a la inicial"); isValid = false; } } if(tematicasSeleccionadas == null || tematicasSeleccionadas.isEmpty()) { addBeanError("gestionEventoForm:tematicasEvento", "Debe seleccionar al menos una."); isValid = false; } } return isValid; } public String toListadoEventos() { return TO_LISTADO_EVENTOS; } public EventoDTO getEventoDTO() { return eventoDTO; } public void setEventoDTO(EventoDTO eventoDTO) { this.eventoDTO = eventoDTO; } public List<TematicaDTO> getListaTematicas() { return listaTematicas; } public void setListaTematicas(List<TematicaDTO> listaTematicas) { this.listaTematicas = listaTematicas; } public List<String> getTematicasSeleccionadas() { return tematicasSeleccionadas; } public void setTematicasSeleccionadas(List<String> tematicasSeleccionadas) { this.tematicasSeleccionadas = tematicasSeleccionadas; } }
true
83769633b046425f9d4d4d7f135e0ad0d841701d
Java
madcatlove/NationalAssembly
/app/src/main/java/kr/or/osan21/nationalassembly/Media/MediaAPI.java
UTF-8
1,006
2.25
2
[]
no_license
package kr.or.osan21.nationalassembly.Media; import java.util.List; import kr.or.osan21.nationalassembly.Utils.API; import retrofit.Callback; import retrofit.http.GET; import retrofit.http.Path; /** * Created by madcat on 12/30/15. */ public class MediaAPI extends API { private static final String LOG_TAG = "MediaAPI"; private MediaService mMediaService; public static interface MediaService { String MOBILE_VIEW_URI = "/media/mobileview/"; @GET("/media/record_list") void getMediaList(Callback<List<Media>> cb); @GET("/media/view/{media_id}") void getMedia(@Path("media_id") Integer media_id, Callback<Media> cb); } public MediaAPI() { mMediaService = mRestAdapter.create(MediaService.class); } public void getMediaList(Callback<List<Media>> cb) { mMediaService.getMediaList(cb); } public void getMedia(Integer media_id, Callback<Media> cb) { mMediaService.getMedia(media_id, cb); } }
true
c69f56990598c13141aba0dca1669515535ec424
Java
phoenixvk/COC
/app/src/main/java/com/hashstar/cocbases/activity/SendAuuthentication.java
UTF-8
4,953
1.984375
2
[]
no_license
package com.hashstar.cocbases.activity; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.provider.Settings; import com.hashstar.cocbases.data.ServiceUrls; import com.hashstar.cocbases.network.ServerResponseHandler; import com.hashstar.cocbases.network.WebService; import com.hashstar.cocbases.utilities.Constants; import com.hashstar.cocbases.utilities.StoreData; import org.json.JSONObject; import java.util.HashMap; /** * Created by phoenix on 23/4/17. */ public class SendAuuthentication extends AsyncTask<JSONObject,JSONObject,JSONObject>{ Activity activity; ProgressDialog progressDialog ; SendAuuthentication(Activity activity) { this.activity = activity; progressDialog = new ProgressDialog(activity); progressDialog.setMessage("Loading bases...."); progressDialog.setTitle("Please wait...."); progressDialog.setCancelable(false); progressDialog.show(); } @Override protected JSONObject doInBackground(JSONObject... params) { String GOOGLEPLUS_USER_NAME= StoreData.LoadString(Constants.GOOGLEPLUS_USER_NAME,"",activity); String GOOGLEPLUS_USER_EMAIL=StoreData.LoadString(Constants.GOOGLEPLUS_USER_EMAIL,"",activity); String GOOGLEPLUS_PROFILEIMAGE_URL=StoreData.LoadString(Constants.GOOGLEPLUS_PROFILEIMAGE_URL, "",activity); String GOOGLEPLUS_USER_ID=StoreData.LoadString(Constants.GOOGLEPLUS_USER_ID,"",activity); String FACEBOOK_PROFILEIMAGE_URL=StoreData.LoadString(Constants.FACEBOOK_PROFILEIMAGE_URL,"",activity); String FACEBOOK_USER_ID=StoreData.LoadString(Constants.FACEBOOK_USER_ID,"",activity); String FACEBOOK_USER_BIRTHDATE=StoreData.LoadString(Constants.FACEBOOK_USER_BIRTHDATE,"",activity); String FACEBOOK_USER_EMAIL=StoreData.LoadString(Constants.FACEBOOK_USER_EMAIL,"",activity); String FACEBOOK_USER_NAME=StoreData.LoadString(Constants.FACEBOOK_USER_NAME,"",activity); String UNIQUEID = Settings.Secure.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID); String GCMID = StoreData.LoadString(Constants.PROPERTY_REG_ID,"",activity); HashMap<String,String> hashMap = new HashMap(); hashMap.put(Constants.GOOGLEPLUS_USER_NAME,GOOGLEPLUS_USER_NAME); hashMap.put(Constants.GOOGLEPLUS_USER_EMAIL,GOOGLEPLUS_USER_EMAIL); hashMap.put(Constants.GOOGLEPLUS_PROFILEIMAGE_URL,GOOGLEPLUS_PROFILEIMAGE_URL); hashMap.put(Constants.GOOGLEPLUS_USER_ID,GOOGLEPLUS_USER_ID); hashMap.put(Constants.FACEBOOK_PROFILEIMAGE_URL,FACEBOOK_PROFILEIMAGE_URL); hashMap.put(Constants.FACEBOOK_USER_ID,FACEBOOK_USER_ID); hashMap.put(Constants.FACEBOOK_USER_BIRTHDATE,FACEBOOK_USER_BIRTHDATE); hashMap.put(Constants.FACEBOOK_USER_EMAIL,FACEBOOK_USER_EMAIL); hashMap.put(Constants.FACEBOOK_USER_NAME,FACEBOOK_USER_NAME); hashMap.put(Constants.UNIQUEID,UNIQUEID); hashMap.put(Constants.GCMID,GCMID); JSONObject object = WebService.sendServer(hashMap, ServiceUrls.CREATE_ENTRY,WebService.POST_REQUEST); return object; } @Override protected void onPostExecute(JSONObject jsonObject) { super.onPostExecute(jsonObject); progressDialog.dismiss(); if (ServerResponseHandler.handleResponse(activity, jsonObject, null)) { String GOOGLEPLUS_USER_NAME = StoreData.LoadString(Constants.GOOGLEPLUS_USER_NAME, "", activity); String GOOGLEPLUS_USER_EMAIL = StoreData.LoadString(Constants.GOOGLEPLUS_USER_EMAIL, "", activity); String GOOGLEPLUS_PROFILEIMAGE_URL = StoreData.LoadString(Constants.GOOGLEPLUS_PROFILEIMAGE_URL, "", activity); String FACEBOOK_PROFILEIMAGE_URL = StoreData.LoadString(Constants.FACEBOOK_PROFILEIMAGE_URL, "", activity); String FACEBOOK_USER_EMAIL = StoreData.LoadString(Constants.FACEBOOK_USER_EMAIL, "", activity); String FACEBOOK_USER_NAME = StoreData.LoadString(Constants.FACEBOOK_USER_NAME, "", activity); if (GOOGLEPLUS_USER_NAME.length() > 0) { StoreData.SaveString(Constants.NAME, GOOGLEPLUS_USER_NAME, activity); StoreData.SaveString(Constants.EMAIL, GOOGLEPLUS_USER_EMAIL, activity); StoreData.SaveString(Constants.IMGURL, GOOGLEPLUS_PROFILEIMAGE_URL, activity); } else if (FACEBOOK_USER_NAME.length() > 0) { StoreData.SaveString(Constants.NAME, FACEBOOK_USER_NAME, activity); StoreData.SaveString(Constants.EMAIL, FACEBOOK_USER_EMAIL, activity); StoreData.SaveString(Constants.IMGURL, FACEBOOK_PROFILEIMAGE_URL, activity); } Intent intent = new Intent(activity,MainActivity.class); activity.startActivity(intent); activity.finish(); } } }
true
b52d4e73f807eecb633007c9e94e9e9122819455
Java
oracle614/data-monitor-server
/src/main/java/com/yiche/utils/DateFormatSafe.java
UTF-8
3,373
2.890625
3
[]
no_license
package com.yiche.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateFormatSafe { private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyyMMdd"); } }; private static ThreadLocal<DateFormat> threadLocalSign = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd"); } }; private static ThreadLocal<DateFormat> threadLocalMonth = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyy-MM"); } }; public static ThreadLocal<Boolean> FLAGPASS = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return true; } }; public static String dateFormat(String dataFormat,Date date){ String dateStr; if (dataFormat.contains("-")) { dateStr = DateFormatSafe.formatSign(date==null?new Date():date); } else { dateStr = DateFormatSafe.format(date==null?new Date():date); } return dateStr; } public static String dateFormatMonth(Date date){ return formatMonth(date==null?new Date():date); } public static String format(Date date) { return threadLocal.get().format(date); } public static String formatSign(Date date) { return threadLocalSign.get().format(date); } public static String formatMonth(Date date) { return threadLocalMonth.get().format(date); } public static Date getDay(int dayNum) { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.DATE,-dayNum); return cal.getTime(); } public static Date getMonth(int dayNum) { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.MONTH,-dayNum); return cal.getTime(); } public static boolean isFirstDay(){ Calendar cal = Calendar.getInstance(); int today = cal.get(cal.DAY_OF_MONTH); return 1==today; } public static void updateFlag(boolean flag){ if(FLAGPASS.get()){ FLAGPASS.set(flag); } } /** * 得到本周周3 * * @return yyyy-MM-dd */ public static Date getWedOfThisWeek() { Calendar c = Calendar.getInstance(); int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1; if (day_of_week == 0) day_of_week = 7; c.add(Calendar.DATE, -day_of_week + 3); return c.getTime(); } public static Date getDay(Date date,int dayNum) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE,-dayNum); return cal.getTime(); } public static String getSimpleDate(Date date){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); return sdf.format(date); } }
true
83c39d57486af17ce703de0d1df3b2e8f9b9902a
Java
myongchao/scholarship
/src/main/java/com/myc/scholarship/service/ScoreService.java
UTF-8
509
1.8125
2
[]
no_license
package com.myc.scholarship.service; import com.baomidou.mybatisplus.mapper.Wrapper; import com.baomidou.mybatisplus.plugins.Page; import com.myc.scholarship.entity.Score; import com.baomidou.mybatisplus.service.IService; /** * <p> * 服务类 * </p> * * @author Juci123 * @since 2019-01-10 */ public interface ScoreService extends IService<Score> { Page<Score> selectWithSubject(Page<Score> plusPage, Wrapper<Score> formToEntityWrapperWithSearch); Score selectWithStudentById(Long id); }
true
963aabb149ab08223c230ac56b07f75a9a5eef63
Java
orisayda/OriHub
/projects/Lab-project/src/Views/ChangingPermissionUI.java
UTF-8
2,286
2.640625
3
[]
no_license
package Views; import java.awt.Font; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.JTextField; import graphics.GUIimage; public class ChangingPermissionUI extends JPanel { public JLabel lblChangingPermission; public JLabel lblUserId; public JTextField textField; public JComboBox comboBox; public JLabel lblNewPermission; public JButton btnBack; public JButton btnChange; /** * Create the panel. */ public ChangingPermissionUI() { this.setBounds(0, 0, 677, 562); this.setLayout(null); JSeparator separator = new JSeparator(); separator.setBounds(0, 126, 677, 12); add(separator); lblChangingPermission = new JLabel("Changing Permission"); lblChangingPermission.setFont(new Font("Tahoma", Font.PLAIN, 26)); lblChangingPermission.setBounds(213, 149, 250, 30); add(lblChangingPermission); lblUserId = new JLabel("User ID :"); lblUserId.setFont(new Font("Tahoma", Font.PLAIN, 14)); lblUserId.setBounds(52, 233, 71, 30); add(lblUserId); textField = new JTextField(); textField.setFont(new Font("Tahoma", Font.PLAIN, 14)); textField.setBounds(133, 234, 86, 30); add(textField); textField.setColumns(10); comboBox = new JComboBox(); comboBox.setFont(new Font("Tahoma", Font.PLAIN, 14)); comboBox.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5"})); comboBox.setBounds(362, 234, 44, 30); add(comboBox); lblNewPermission = new JLabel("New Permission :"); lblNewPermission.setFont(new Font("Tahoma", Font.PLAIN, 14)); lblNewPermission.setBounds(240, 233, 135, 30); add(lblNewPermission); btnBack = new JButton("Back"); btnBack.setFont(new Font("Tahoma", Font.PLAIN, 14)); btnBack.setBounds(31, 489, 89, 30); add(btnBack); btnChange = new JButton("Change"); btnChange.setFont(new Font("Tahoma", Font.PLAIN, 14)); btnChange.setBounds(440, 234, 89, 30); add(btnChange); JLabel lblBackground = new JLabel("New label"); lblBackground.setBounds(0, 0, 671, 533); lblBackground.setIcon(new GUIimage("Background",lblBackground.getWidth(),lblBackground.getHeight()).image); add(lblBackground); } }
true
5d032b525f2f9bb57943f1cd12f48e20591e5777
Java
BhaveshKabra/Bewery-Producer
/src/main/java/org/bhavesh/micro/mapper/CustomerMapper.java
UTF-8
318
1.96875
2
[]
no_license
package org.bhavesh.micro.mapper; import org.bhavesh.micro.web.bean.Customer; import org.bhavesh.micro.web.bean.dto.CustomerDTO; import org.mapstruct.Mapper; @Mapper public interface CustomerMapper { CustomerDTO customertoCustomerDTO(Customer customer); Customer customerDTOtoCustomer(CustomerDTO customerDTO); }
true
45917ce0cc5c2b82476e7d49d890454dde92fa30
Java
bellmit/online_education
/education_common/src/main/java/com/oe/domain/dto/TabOperateRecordDTO.java
UTF-8
536
1.671875
2
[]
no_license
package com.oe.domain.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import java.io.Serializable; import java.util.Date; @Data @AllArgsConstructor @NoArgsConstructor @Accessors(chain = true) public class TabOperateRecordDTO implements Serializable { private Long id; private Date loginTime; private String city; private String ip; private String loginEquipment; private String operateSystem; private String userId; }
true
59a821b199742fe4c58ad05ebf81a2ee8558a22c
Java
Yuriel849/Databases
/SQL/src/study/MessageFormat_to_SQL.java
UHC
1,812
3.21875
3
[]
no_license
package study; import java.io.*; import java.text.MessageFormat; /* * 1. SQL Developer ֹ ̺ (ORDER_M, ORDER_D) * 2. α׷ "data.csv" * 3. Java α׷ (eclipse) INSERT & SQL Developer * 4. ORDER_M & ORDER_D join */ class MessageFormat_to_SQL { @SuppressWarnings("resource") public static void main(String[] args) throws IOException { String tableName = "ORDER_M"; String msg = "INSERT INTO " + tableName + " VALUES (''{0}'', ''{1}'', ''{2}'', ''{3}'', ''{4}'');"; FileReader fr = new FileReader("C:\\Users\\Yuriel\\eclipse-workspace\\SQL\\ORDER_M.csv"); BufferedReader br = new BufferedReader(fr); Object[][] arguments = new Object[5][60]; String line = ""; for(int i = 1; (line = br.readLine()) != null; i++) { arguments[i-1] = line.split(","); } FileWriter fw = new FileWriter("C:\\Users\\Yuriel\\eclipse-workspace\\SQL\\INSERT_ORDER.sql"); BufferedWriter bw = new BufferedWriter(fw); for(int i = 0; i < arguments.length; i++) { String result = MessageFormat.format(msg, arguments[i]); System.out.println(result); bw.write(result + "\n"); } tableName = "ORDER_D"; msg = "INSERT INTO " + tableName + " VALUES (''{0}'', ''{1}'', ''{2}'', ''{3}'', ''{4}''" + ", ''{5}'', ''{6}'', ''{7}'');"; fr = new FileReader("C:\\Users\\Yuriel\\eclipse-workspace\\SQL\\ORDER_D.csv"); br = new BufferedReader(fr); Object[][] arguments2 = new Object[6][100]; line = ""; for(int i = 1; (line = br.readLine()) != null; i++) { arguments2[i-1] = line.split(","); } for(int i = 0; i < arguments2.length; i++) { String result = MessageFormat.format(msg, arguments2[i]); System.out.println(result); bw.write(result + "\n"); } bw.close(); } }
true
17ef8c6f4a6c1f003b816477a20ffbd8ed179711
Java
vriche/adrm
/test/service/com/vriche/adrm/service/.svn/text-base/PriceDetailManagerTest.java.svn-base
UTF-8
3,651
2.3125
2
[]
no_license
package com.vriche.adrm.service; import java.util.List; import java.util.ArrayList; import com.vriche.adrm.dao.PriceDetailDao; import com.vriche.adrm.model.PriceDetail; import com.vriche.adrm.service.BaseManagerTestCase; import com.vriche.adrm.service.impl.PriceDetailManagerImpl; import org.jmock.Mock; import org.springframework.orm.ObjectRetrievalFailureException; public class PriceDetailManagerTest extends BaseManagerTestCase { private final String priceDetailId = "1"; private PriceDetailManagerImpl priceDetailManager = new PriceDetailManagerImpl(); private Mock priceDetailDao = null; protected void setUp() throws Exception { super.setUp(); priceDetailDao = new Mock(PriceDetailDao.class); priceDetailManager.setPriceDetailDao((PriceDetailDao) priceDetailDao.proxy()); } protected void tearDown() throws Exception { super.tearDown(); priceDetailManager = null; } public void testGetPriceDetails() throws Exception { List results = new ArrayList(); PriceDetail priceDetail = new PriceDetail(); results.add(priceDetail); // set expected behavior on dao priceDetailDao.expects(once()).method("getPriceDetails") .will(returnValue(results)); List priceDetails = priceDetailManager.getPriceDetails(null); assertTrue(priceDetails.size() == 1); priceDetailDao.verify(); } public void testGetPriceDetail() throws Exception { // set expected behavior on dao priceDetailDao.expects(once()).method("getPriceDetail") .will(returnValue(new PriceDetail())); PriceDetail priceDetail = priceDetailManager.getPriceDetail(priceDetailId); assertTrue(priceDetail != null); priceDetailDao.verify(); } public void testSavePriceDetail() throws Exception { PriceDetail priceDetail = new PriceDetail(); // set expected behavior on dao priceDetailDao.expects(once()).method("savePriceDetail") .with(same(priceDetail)).isVoid(); priceDetailManager.savePriceDetail(priceDetail); priceDetailDao.verify(); } public void testAddAndRemovePriceDetail() throws Exception { PriceDetail priceDetail = new PriceDetail(); // set required fields // set expected behavior on dao priceDetailDao.expects(once()).method("savePriceDetail") .with(same(priceDetail)).isVoid(); priceDetailManager.savePriceDetail(priceDetail); priceDetailDao.verify(); // reset expectations priceDetailDao.reset(); priceDetailDao.expects(once()).method("removePriceDetail").with(eq(new Long(priceDetailId))); priceDetailManager.removePriceDetail(priceDetailId); priceDetailDao.verify(); // reset expectations priceDetailDao.reset(); // remove Exception ex = new ObjectRetrievalFailureException(PriceDetail.class, priceDetail.getId()); priceDetailDao.expects(once()).method("removePriceDetail").isVoid(); priceDetailDao.expects(once()).method("getPriceDetail").will(throwException(ex)); priceDetailManager.removePriceDetail(priceDetailId); try { priceDetailManager.getPriceDetail(priceDetailId); fail("PriceDetail with identifier '" + priceDetailId + "' found in database"); } catch (ObjectRetrievalFailureException e) { assertNotNull(e.getMessage()); } priceDetailDao.verify(); } }
true
c3a4bdcafb9e135e97913e8298e72910d354f7a6
Java
love525150/springcloud
/user-service/src/main/java/org/allen/user/controller/UserController.java
UTF-8
2,415
1.96875
2
[]
no_license
package org.allen.user.controller; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; import org.allen.user.bus.event.UserUpdateEvent; import org.allen.user.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; /** * @author Zhou Zhengwen */ @RestController @RequestMapping("user") public class UserController { @Autowired private UserService userService; @Autowired private ApplicationContext applicationContext; @Value("${spring.application.name}") private String applicationName; @RequestMapping("name") public String name(Integer id, HttpServletRequest request) { return userService.getName(id); } @HystrixCommand(fallbackMethod = "fail1", commandProperties = { @HystrixProperty(name = "circuitBreaker.enabled", value = "true"), @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000"), @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "3"), @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"), @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "50000"), @HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "10"), @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "500"), }) @GetMapping("test1") public String test1(int id) throws InterruptedException { if (id % 2 == 0) { return "ok"; } else { Thread.sleep(1000); return "ok"; } } private String fail1(int id, Throwable e) { return "fail1"; } @RequestMapping("update") public String update(String name) { String id = applicationContext.getApplicationName(); UserUpdateEvent userUpdateEvent = new UserUpdateEvent(name, id, "**"); applicationContext.publishEvent(userUpdateEvent); return "ok"; } }
true
d407f7a5862c9461dd9ddfc7f67a51f50fc01755
Java
calooper/FinalProject
/JPAGearSilo/src/test/java/com/skilldistillery/gearsilo/entities/ReviewOfShopperTest.java
UTF-8
1,551
2.453125
2
[]
no_license
package com.skilldistillery.gearsilo.entities; import static org.junit.jupiter.api.Assertions.assertEquals; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class ReviewOfShopperTest { private static EntityManagerFactory emf; private static EntityManager em; private ReviewOfShopper reviewShopper; @BeforeAll static void setUpBeforeClass() throws Exception { emf = Persistence.createEntityManagerFactory("GearSiloPU"); } @AfterAll static void tearDownAfterClass() throws Exception { emf.close(); } @BeforeEach void setUp() throws Exception { em = emf.createEntityManager(); reviewShopper = em.find(ReviewOfShopper.class, 1); } @AfterEach void tearDown() throws Exception { em.close(); reviewShopper = null; } @Test @DisplayName("ReviewOfGear entity mapping to Id") void test() { assertEquals(1, reviewShopper.getId()); } @Test @DisplayName("ReviewOfGear entity mapping to Rating") void test1() { assertEquals(5, reviewShopper.getRating()); } @Test @DisplayName("ReviewOfGear entity mapping to Review") void test2() { assertEquals("Larry showed up on time and took great care of the bike!", reviewShopper.getReview()); assertEquals(1, reviewShopper.getReservation().getId()); } }
true
a99781fb19b3da44cc2e4c5b820a7d70538ffc31
Java
mdafsar15/ADF_Genx
/Model/src/EOsNew/DepartmentsEOImpl.java
UTF-8
6,026
1.960938
2
[]
no_license
package EOsNew; import oracle.jbo.AttributeList; import oracle.jbo.JboException; import oracle.jbo.Key; import oracle.jbo.RowIterator; import oracle.jbo.server.EntityDefImpl; import oracle.jbo.server.EntityImpl; import oracle.jbo.server.TransactionEvent; // --------------------------------------------------------------------- // --- File generated by Oracle ADF Business Components Design Time. // --- Sun Oct 04 23:51:31 IST 2020 // --- Custom code may be added to this class. // --- Warning: Do not modify method signatures of generated methods. // --------------------------------------------------------------------- public class DepartmentsEOImpl extends EntityImpl { /** * AttributesEnum: generated enum for identifying attributes and accessors. DO NOT MODIFY. */ protected enum AttributesEnum { DepartmentId, DepartmentName, ManagerId, LocationId, EmployeesEO, EmployeesEO1; private static AttributesEnum[] vals = null; private static final int firstIndex = 0; protected int index() { return AttributesEnum.firstIndex() + ordinal(); } protected static final int firstIndex() { return firstIndex; } protected static int count() { return AttributesEnum.firstIndex() + AttributesEnum.staticValues().length; } protected static final AttributesEnum[] staticValues() { if (vals == null) { vals = AttributesEnum.values(); } return vals; } } public static final int DEPARTMENTID = AttributesEnum.DepartmentId.index(); public static final int DEPARTMENTNAME = AttributesEnum.DepartmentName.index(); public static final int MANAGERID = AttributesEnum.ManagerId.index(); public static final int LOCATIONID = AttributesEnum.LocationId.index(); public static final int EMPLOYEESEO = AttributesEnum.EmployeesEO.index(); public static final int EMPLOYEESEO1 = AttributesEnum.EmployeesEO1.index(); /** * This is the default constructor (do not remove). */ public DepartmentsEOImpl() { } /** * Gets the attribute value for DepartmentId, using the alias name DepartmentId. * @return the value of DepartmentId */ public Integer getDepartmentId() { return (Integer) getAttributeInternal(DEPARTMENTID); } /** * Sets <code>value</code> as the attribute value for DepartmentId. * @param value value to set the DepartmentId */ public void setDepartmentId(Integer value) { setAttributeInternal(DEPARTMENTID, value); } /** * Gets the attribute value for DepartmentName, using the alias name DepartmentName. * @return the value of DepartmentName */ public String getDepartmentName() { return (String) getAttributeInternal(DEPARTMENTNAME); } /** * Sets <code>value</code> as the attribute value for DepartmentName. * @param value value to set the DepartmentName */ public void setDepartmentName(String value) { setAttributeInternal(DEPARTMENTNAME, value); } /** * Gets the attribute value for ManagerId, using the alias name ManagerId. * @return the value of ManagerId */ public Integer getManagerId() { return (Integer) getAttributeInternal(MANAGERID); } /** * Sets <code>value</code> as the attribute value for ManagerId. * @param value value to set the ManagerId */ public void setManagerId(Integer value) { setAttributeInternal(MANAGERID, value); } /** * Gets the attribute value for LocationId, using the alias name LocationId. * @return the value of LocationId */ public Integer getLocationId() { return (Integer) getAttributeInternal(LOCATIONID); } /** * Sets <code>value</code> as the attribute value for LocationId. * @param value value to set the LocationId */ public void setLocationId(Integer value) { setAttributeInternal(LOCATIONID, value); } /** * @return the associated entity oracle.jbo.RowIterator. */ public RowIterator getEmployeesEO() { return (RowIterator) getAttributeInternal(EMPLOYEESEO); } /** * @return the associated entity oracle.jbo.server.EntityImpl. */ public EntityImpl getEmployeesEO1() { return (EntityImpl) getAttributeInternal(EMPLOYEESEO1); } /** * Sets <code>value</code> as the associated entity oracle.jbo.server.EntityImpl. */ public void setEmployeesEO1(EntityImpl value) { setAttributeInternal(EMPLOYEESEO1, value); } /** * @param departmentId key constituent * @return a Key object based on given key constituents. */ public static Key createPrimaryKey(Integer departmentId) { return new Key(new Object[] { departmentId }); } /** * @return the definition object for this instance class. */ public static synchronized EntityDefImpl getDefinitionObject() { return EntityDefImpl.findDefObject("EOsNew.DepartmentsEO"); } /** * Add attribute defaulting logic in this method. * @param attributeList list of attribute names/values to initialize the row */ // protected void create(AttributeList attributeList) { // setDepartmentName("Default_Dept_name"); // } @Override protected void prepareForDML(int i, TransactionEvent transactionEvent) { // TODO Implement this method super.prepareForDML(i, transactionEvent); if(i==DML_INSERT) setDepartmentName("INSERTED!!"); else if(i==DML_UPDATE) setDepartmentName("UPDATED!!"); } @Override public void remove() { // if(getDepartmentId().compareTo(new Number(421)) != 0) // throw new JboException("Delete not allowed"); // else // super.remove(); } }
true
07609359e1557d9ffd014ca5957206dc70ffd917
Java
bustomiabdulgoni21/KKP
/src/pembayaran/tampil/Daftar.java
UTF-8
23,137
2.109375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pembayaran.tampil; import java.awt.Toolkit; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import pembayaran.koneksi.koneksi; /** * * @author bustomiag */ public class Daftar extends javax.swing.JFrame { private Connection conn = new koneksi().connect(); private DefaultTableModel tabmode; protected void kosong() { user.setText(""); pass.setText(""); } protected void datatable() { Object[] Baris = {"Username","Password"}; tabmode = new DefaultTableModel(null, Baris); tabeldaftar.setModel(tabmode); String sql = "select * from daftar"; try { java.sql.Statement stat = conn.createStatement(); ResultSet hasil = stat.executeQuery(sql); while(hasil.next()){ String no = hasil.getString("user"); String tgl = hasil.getString("pass"); String[] data = {no,tgl}; tabmode.addRow(data); } }catch (Exception e) { } } public Daftar() { initComponents(); setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - getWidth()) /2, (Toolkit.getDefaultToolkit().getScreenSize().height - getHeight()) /2); setTitle("Daftar"); datatable(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); bsimpan = new javax.swing.JButton(); bhapus = new javax.swing.JButton(); bubah = new javax.swing.JButton(); bexit = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); tabeldaftar = new javax.swing.JTable(); jPanel5 = new javax.swing.JPanel(); jPanel7 = new javax.swing.JPanel(); user = new javax.swing.JTextField(); pass = new javax.swing.JPasswordField(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setMaximumSize(new java.awt.Dimension(511, 453)); setMinimumSize(new java.awt.Dimension(511, 453)); jPanel1.setBackground(new java.awt.Color(0, 232, 176)); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel2.setBackground(new java.awt.Color(0, 232, 176)); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jLabel2.setFont(new java.awt.Font("Dialog", 1, 36)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setBackground(new java.awt.Color(0, 232, 176)); jLabel1.setFont(new java.awt.Font("FreeMono", 1, 48)); // NOI18N jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("DAFTAR"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(60, 60, 60) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel3.setBackground(new java.awt.Color(0, 232, 176)); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("")); bsimpan.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pembayaran/gambar/must_have_icon_set/Save/Save_16x16.png"))); // NOI18N bsimpan.setText("Simpan"); bsimpan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bsimpanActionPerformed(evt); } }); bhapus.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pembayaran/gambar/must_have_icon_set/Delete/Delete_16x16.png"))); // NOI18N bhapus.setText("Hapus"); bhapus.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bhapusActionPerformed(evt); } }); bubah.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pembayaran/gambar/must_have_icon_set/Edit/Edit_16x16.png"))); // NOI18N bubah.setText("Ubah"); bubah.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bubahActionPerformed(evt); } }); bexit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pembayaran/gambar/must_have_icon_set/Log Out/Log Out_16x16.png"))); // NOI18N bexit.setText("Exit"); bexit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bexitActionPerformed(evt); } }); jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pembayaran/gambar/must_have_icon_set/User/User_16x16.png"))); // NOI18N jButton1.setText("Login"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(bsimpan) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bubah, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bhapus) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bexit, javax.swing.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(bexit) .addComponent(bhapus) .addComponent(bubah) .addComponent(bsimpan) .addComponent(jButton1)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel4.setBackground(new java.awt.Color(0, 232, 176)); jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("")); tabeldaftar.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "User", "Password" } )); tabeldaftar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tabeldaftarMouseClicked(evt); } }); jScrollPane1.setViewportView(tabeldaftar); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1) .addContainerGap()) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE) .addContainerGap()) ); jPanel5.setBackground(new java.awt.Color(0, 232, 176)); jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jPanel7.setBackground(new java.awt.Color(0, 232, 176)); jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jLabel6.setForeground(new java.awt.Color(255, 255, 255)); jLabel6.setText("Username"); jLabel7.setForeground(new java.awt.Color(255, 255, 255)); jLabel7.setText("Password"); javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7); jPanel7.setLayout(jPanel7Layout); jPanel7Layout.setHorizontalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(pass, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE) .addComponent(user, javax.swing.GroupLayout.Alignment.TRAILING)) .addContainerGap()) ); jPanel7Layout.setVerticalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(user, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(pass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void bsimpanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bsimpanActionPerformed // TODO add your handling code here: String sql = "insert into daftar values (?,?)"; try { PreparedStatement stat = conn.prepareStatement(sql); stat.setString(1, user.getText()); stat.setString(2, pass.getText()); stat.executeUpdate(); JOptionPane.showMessageDialog(null, "Data Berhasil Disimpan"); kosong(); user.requestFocus(); datatable(); }catch (SQLException e) { JOptionPane.showMessageDialog(null, "Data Gagal disimpan"+e); } }//GEN-LAST:event_bsimpanActionPerformed private void bhapusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bhapusActionPerformed // TODO add your handling code here: int ok = JOptionPane.showConfirmDialog(null, "hapus","Konfirmasi Dialog", JOptionPane.YES_NO_CANCEL_OPTION); if (ok==0) { String sql = "delete from daftar where user='"+user.getText()+"'"; try { PreparedStatement stat = conn.prepareStatement (sql); stat.executeUpdate(); JOptionPane.showMessageDialog(null, "Data berhasil dihapus"); kosong(); user.requestFocus(); datatable(); } catch(SQLException e) { JOptionPane.showMessageDialog(null, "Data gagal dihapus"); } } }//GEN-LAST:event_bhapusActionPerformed private void bubahActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bubahActionPerformed // TODO add your handling code here: String sql = "update daftar set pass=?, status=? where user='"+user.getText()+"'"; try { PreparedStatement stat = conn.prepareStatement(sql); stat.setString(1, pass.getText()); stat.executeUpdate(); JOptionPane.showMessageDialog(null, "Data Berhasil Diubah"); kosong(); user.requestFocus(); datatable(); }catch (SQLException e) { JOptionPane.showMessageDialog(null, "Data Gagal diubah"+e); } }//GEN-LAST:event_bubahActionPerformed private void bexitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bexitActionPerformed // TODO add your handling code here: dispose(); }//GEN-LAST:event_bexitActionPerformed private void tabeldaftarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabeldaftarMouseClicked // TODO add your handling code here: try { int bar = tabeldaftar.getSelectedRow(); String a = tabmode.getValueAt(bar, 0).toString(); String b = tabmode.getValueAt(bar, 1).toString(); user.setText(a); pass.setText(b); }catch (Exception ex){} }//GEN-LAST:event_tabeldaftarMouseClicked private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: new Login().setVisible(true); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Daftar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Daftar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Daftar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Daftar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Daftar().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton bexit; private javax.swing.JButton bhapus; private javax.swing.JButton bsimpan; private javax.swing.JButton bubah; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel7; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JPasswordField pass; private javax.swing.JTable tabeldaftar; private javax.swing.JTextField user; // End of variables declaration//GEN-END:variables }
true
b005b4114b63ca44b29538285dd360066d1bc7a4
Java
brecht-d-m/cros-core
/app/controllers/SecurityController.java
UTF-8
1,935
2.390625
2
[ "MIT" ]
permissive
package controllers; import com.fasterxml.jackson.databind.node.ObjectNode; import exceptions.IncompatibleSystemException; import models.User; import play.data.Form; import play.data.validation.Constraints; import play.libs.Json; import play.mvc.Controller; import play.mvc.Http; import play.mvc.Result; import utilities.annotations.Authenticator; /** * Created by matthias on 20/02/2015. */ public class SecurityController extends Controller { public static final String AUTH_TOKEN_HEADER = "X-AUTH-TOKEN"; public static final String AUTH_TOKEN = "authToken"; public static User getUser() { User user = (User) Http.Context.current().args.get("user"); if(user == null) { user = Authenticator.checkAuthentication(Http.Context.current()); } return user; } // returns an authToken public static Result login() { // Check form data Form<Login> loginForm = Form.form(Login.class).bindFromRequest(); if (loginForm.hasErrors()) return badRequest(loginForm.errorsAsJson()); // Authenticate the user Login login = loginForm.get(); User user = null; try { user = User.authenticate(login.emailAddress, login.password); } catch (IncompatibleSystemException e) { // Password hash not available on this system return internalServerError(e.getMessage()); } if (user == null) return unauthorized(); // Return auth token to the client String authToken = user.getAuthToken(); ObjectNode authTokenJson = Json.newObject(); authTokenJson.put(AUTH_TOKEN, authToken); return ok(authTokenJson); } public static class Login { @Constraints.Required @Constraints.Email public String emailAddress; @Constraints.Required public String password; } }
true
50c68989ac9af400dd317e21c7c04256c1d4c75c
Java
adamtbak/algorithms-data-structures
/Recursion/Exponentiation.java
UTF-8
711
4.4375
4
[]
no_license
/* * This class calculates the exponentiation of a number, in other words, * it calculates the value of the expression, x raised to the power or n, * written also as x^n. * * The recursive formula for the x^n is given by: * x^n = x * x^(n-1) * */ public class Exponentiation { public static void main(String[] args) { /* We create a table of values of 2^0 to 2^10 */ for(int i = 0; i <= 10; i++) { System.out.println("2^" + i + " : " + exp(2, i)); } } private static long exp(int x, int n) { if(n == 0) return 1; else return x * exp(x, n - 1); } }
true
79675331846214b296081cbf14226b45523c1284
Java
aa407766499/springv2
/src/main/java/com/study/springv2/web/servlet/mvc/method/annotation/MyRequestMappingHandlerMapping.java
UTF-8
2,213
2.640625
3
[]
no_license
package com.study.springv2.web.servlet.mvc.method.annotation; import com.study.springv2.annotation.MyController; import com.study.springv2.annotation.MyRequestMapping; import com.study.springv2.context.MyApplicationContext; import com.study.springv2.web.method.MyHandlerMethod; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; /** * url与Controller中方法的对应关系 * * @author Huzi114 * @ClassName: MyRequestMappingHandlerMapping * @Description: * @date 2019/11/22 17:26 */ public class MyRequestMappingHandlerMapping { //url->HandlerMethod Map<String, MyHandlerMethod> handlerMethodMap = new HashMap<>(); public MyRequestMappingHandlerMapping(MyApplicationContext context) { try { init(context); } catch (Exception e) { e.printStackTrace(); } } private void init(MyApplicationContext context) throws Exception { for (String beanName : context.getBeanDefinitionNames()) { Object bean = context.getBean(beanName); Class<?> beanClass = bean.getClass(); if (!beanClass.isAnnotationPresent(MyController.class)) { continue; } String classUrl = ""; if (beanClass.isAnnotationPresent(MyRequestMapping.class)) { MyRequestMapping rm = beanClass.getAnnotation(MyRequestMapping.class); classUrl = rm.value(); } for (Method method : beanClass.getMethods()) { if (method.isAnnotationPresent(MyRequestMapping.class)) { MyRequestMapping rm = method.getAnnotation(MyRequestMapping.class); String methodUrl = rm.value(); String url = (classUrl + "/" + methodUrl).replaceAll("/+", "/"); handlerMethodMap.put(url, new MyHandlerMethod(bean,method)); } } } } public MyHandlerMethod getHandler(HttpServletRequest req) { String url = req.getRequestURI().replace(req.getContextPath(), "").replaceAll("/+", "/"); return this.handlerMethodMap.get(url); } }
true
edd029ee5c92a4b0f997fcc4b4659035fc56167b
Java
Alexlloydwhite/learning-java
/com/ClassExample/Main.java
UTF-8
714
4.1875
4
[]
no_license
package com.ClassExample; public class Main { // Public means it has access to other files // Static means it does not change // Void means it has no return public static void main (String[] args) { // to make an object from a class, type the name of the class, name it, and set it equal to a new class. // the parens make it a constructor which means it makes the object Class1 c = new Class1(); Class1 d = new Class1(); Class2 e = new Class2(); // You can make many objects with one class! System.out.println(c.x); System.out.println(d.x); System.out.println(e.y); c.printHigh(); d.printHigh(); } }
true
1ea84e1efb8d2b3accf92d37cd6c9715cdbac550
Java
Hospitaljavaprojects/HospitalSystemPc
/PatientSQL3.java
GB18030
907
2.5625
3
[]
no_license
package cn.edu.usst.moon; import java.sql.*; public class PatientSQL3 { public static void main(String[] args) { // TODO Auto-generated method stub Connection con=null; Statement stmt=null; String strTemp= ""; try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); }catch(ClassNotFoundException e){ } try{ con=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=Hospital","sa","sa"); stmt=con.createStatement(); }catch(SQLException ee){ } strTemp="CREATE TABLE patient(id varchar(20) PRIMARY KEY,name varchar(20),gender varchar(5),address varchar(50)," +"phone varchar(50),office varchar(10),doctor varchar(10),ispay varchar(50)"; try{ stmt.executeUpdate(strTemp); System.out.println("ݿɹ"); }catch(SQLException e){ e.printStackTrace(); } } }
true
8210a48b0bfc9530adfd4e63e51f4ce69918eabe
Java
CyberLynxTelecom/tutorial_upload_github
/eclipse-3.8.1/eclipse/environments/osgi.cmpn/src/org/osgi/service/blueprint/context/ServiceUnavailableException.java
UTF-8
1,533
2.1875
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) OSGi Alliance (2008, 2009). All Rights Reserved. * * 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.osgi.service.blueprint.context; /** * Thrown when an invocation is made on an OSGi service reference component, and * a backing service is not available. */ public class ServiceUnavailableException extends RuntimeException { private final Class serviceType; private final String filter; public ServiceUnavailableException( String message, Class serviceType, String filterExpression) { super(message); this.serviceType = serviceType; this.filter = filterExpression; } /** * The type of the service that would have needed to be available in * order for the invocation to proceed. */ public Class getServiceType() { return this.serviceType; } /** * The filter expression that a service would have needed to satisfy in order * for the invocation to proceed. */ public String getFilter() { return this.filter; } }
true
4b160a3e41251e97fa3729dc52a7354309daee17
Java
DevManah6Eugenio/moduloAtualizaProjetoNetbeans
/src/moduloAtualizaProjeto/telaTopComponent.java
UTF-8
39,576
1.664063
2
[]
no_license
package moduloAtualizaProjeto; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import javax.swing.JOptionPane; import org.netbeans.api.settings.ConvertAsProperties; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.windows.TopComponent; import org.openide.util.NbBundle.Messages; @ConvertAsProperties( dtd = "-//teste_modulo//tela//EN", autostore = true ) @TopComponent.Description( preferredID = "telaTopComponent", //iconBase="SET/PATH/TO/ICON/HERE", persistenceType = TopComponent.PERSISTENCE_ALWAYS ) @TopComponent.Registration(mode = "output", openAtStartup = true) @ActionID(category = "Window", id = "teste_modulo.telaTopComponent") @ActionReference(path = "Menu/Window" /*, position = 333 */) @TopComponent.OpenActionRegistration( displayName = "#CTL_telaAction", preferredID = "telaTopComponent" ) @Messages({ "CTL_telaAction=tela", "CTL_telaTopComponent=Atualizar Projetos GW", "HINT_telaTopComponent=Atualizar Projetos GW" }) public final class telaTopComponent extends TopComponent { public telaTopComponent() { initComponents(); setName(Bundle.CTL_telaTopComponent()); setToolTipText(Bundle.HINT_telaTopComponent()); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); jTabbedPane2 = new javax.swing.JTabbedPane(); jPanel2 = new javax.swing.JPanel(); painelAlterVersao = new javax.swing.JPanel(); jComboBoxVersao = new javax.swing.JComboBox<>(); jButtonAlterVersao = new javax.swing.JButton(); jComboBoxAlterVersao = new javax.swing.JComboBox<>(); jLabel5 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextPaneLogVersao = new javax.swing.JTextPane(); jPanel1 = new javax.swing.JPanel(); jPanelTag1 = new javax.swing.JPanel(); jTextFieldTag = new javax.swing.JTextField(); jButtonAlterTag = new javax.swing.JButton(); jLabel9 = new javax.swing.JLabel(); jComboBoxAlterTag = new javax.swing.JComboBox<>(); jScrollPane2 = new javax.swing.JScrollPane(); jTextPaneLogTag = new javax.swing.JTextPane(); jPanel3 = new javax.swing.JPanel(); jPanelCaminhoRepoLocal = new javax.swing.JPanel(); jTextFieldCaminhoRepoLocaGweb = new javax.swing.JTextField(); jTextFieldCaminhoRepoLocaGwLib = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jTextFieldCaminhoRepoLocaWebtrans = new javax.swing.JTextField(); jPanelCaminhoRepoRemoto = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); jTextFieldCaminhoRepoRemotoWebtrans = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jTextFieldCaminhoRepoRemotoGweb = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); CaminhoRepoRemotoGwlib = new javax.swing.JTextField(); jPanel4 = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jTextFieldEmailSSH = new javax.swing.JTextField(); jLabel10 = new javax.swing.JLabel(); jButtonGerarChave = new javax.swing.JButton(); jTextFieldSenhaSSH = new javax.swing.JPasswordField(); jScrollPane3 = new javax.swing.JScrollPane(); jTextAreaLogSSH = new javax.swing.JTextArea(); painelAlterVersao.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.painelAlterVersao.border.title"))); // NOI18N jComboBoxVersao.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "master", "atual", "custom" })); org.openide.awt.Mnemonics.setLocalizedText(jButtonAlterVersao, org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jButtonAlterVersao.text")); // NOI18N jButtonAlterVersao.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAlterVersaoActionPerformed(evt); } }); jComboBoxAlterVersao.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Webtrans", "Gweb" })); org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jLabel5.text")); // NOI18N javax.swing.GroupLayout painelAlterVersaoLayout = new javax.swing.GroupLayout(painelAlterVersao); painelAlterVersao.setLayout(painelAlterVersaoLayout); painelAlterVersaoLayout.setHorizontalGroup( painelAlterVersaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(painelAlterVersaoLayout.createSequentialGroup() .addComponent(jComboBoxAlterVersao, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel5) .addGap(18, 18, 18) .addComponent(jComboBoxVersao, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButtonAlterVersao, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(343, Short.MAX_VALUE)) ); painelAlterVersaoLayout.setVerticalGroup( painelAlterVersaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(painelAlterVersaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jComboBoxVersao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonAlterVersao) .addComponent(jComboBoxAlterVersao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) ); jScrollPane1.setViewportView(jTextPaneLogVersao); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1) .addComponent(painelAlterVersao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(painelAlterVersao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 181, Short.MAX_VALUE) .addContainerGap()) ); jTabbedPane2.addTab(org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jPanel2.TabConstraints.tabTitle"), jPanel2); // NOI18N jPanelTag1.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jPanelTag1.border.title"))); // NOI18N jPanelTag1.setMaximumSize(new java.awt.Dimension(492, 53)); jTextFieldTag.setText(org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jTextFieldTag.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jButtonAlterTag, org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jButtonAlterTag.text")); // NOI18N jButtonAlterTag.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAlterTagActionPerformed(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(jLabel9, org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jLabel9.text")); // NOI18N jComboBoxAlterTag.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Webtrans", "Gweb" })); javax.swing.GroupLayout jPanelTag1Layout = new javax.swing.GroupLayout(jPanelTag1); jPanelTag1.setLayout(jPanelTag1Layout); jPanelTag1Layout.setHorizontalGroup( jPanelTag1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelTag1Layout.createSequentialGroup() .addComponent(jComboBoxAlterTag, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel9) .addGap(18, 18, 18) .addComponent(jTextFieldTag, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButtonAlterTag, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(344, Short.MAX_VALUE)) ); jPanelTag1Layout.setVerticalGroup( jPanelTag1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelTag1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldTag, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonAlterTag) .addComponent(jLabel9) .addComponent(jComboBoxAlterTag, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jScrollPane2.setViewportView(jTextPaneLogTag); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelTag1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanelTag1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 181, Short.MAX_VALUE) .addContainerGap()) ); jTabbedPane2.addTab(org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jPanel1.TabConstraints.tabTitle"), jPanel1); // NOI18N jPanelCaminhoRepoLocal.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jPanelCaminhoRepoLocal.border.title"))); // NOI18N jTextFieldCaminhoRepoLocaGweb.setText(org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jTextFieldCaminhoRepoLocaGweb.text")); // NOI18N jTextFieldCaminhoRepoLocaGwLib.setText(org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jTextFieldCaminhoRepoLocaGwLib.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jLabel1.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jLabel2.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jLabel3.text")); // NOI18N jTextFieldCaminhoRepoLocaWebtrans.setText(org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jTextFieldCaminhoRepoLocaWebtrans.text")); // NOI18N jTextFieldCaminhoRepoLocaWebtrans.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldCaminhoRepoLocaWebtransActionPerformed(evt); } }); javax.swing.GroupLayout jPanelCaminhoRepoLocalLayout = new javax.swing.GroupLayout(jPanelCaminhoRepoLocal); jPanelCaminhoRepoLocal.setLayout(jPanelCaminhoRepoLocalLayout); jPanelCaminhoRepoLocalLayout.setHorizontalGroup( jPanelCaminhoRepoLocalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelCaminhoRepoLocalLayout.createSequentialGroup() .addGroup(jPanelCaminhoRepoLocalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelCaminhoRepoLocalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextFieldCaminhoRepoLocaGweb) .addComponent(jTextFieldCaminhoRepoLocaGwLib) .addComponent(jTextFieldCaminhoRepoLocaWebtrans, javax.swing.GroupLayout.PREFERRED_SIZE, 397, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)) ); jPanelCaminhoRepoLocalLayout.setVerticalGroup( jPanelCaminhoRepoLocalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelCaminhoRepoLocalLayout.createSequentialGroup() .addGroup(jPanelCaminhoRepoLocalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextFieldCaminhoRepoLocaWebtrans, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelCaminhoRepoLocalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextFieldCaminhoRepoLocaGweb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelCaminhoRepoLocalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTextFieldCaminhoRepoLocaGwLib, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanelCaminhoRepoRemoto.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jPanelCaminhoRepoRemoto.border.title"))); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jLabel6, org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jLabel6.text")); // NOI18N jTextFieldCaminhoRepoRemotoWebtrans.setText(org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jTextFieldCaminhoRepoRemotoWebtrans.text")); // NOI18N jTextFieldCaminhoRepoRemotoWebtrans.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldCaminhoRepoRemotoWebtransActionPerformed(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(jLabel7, org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jLabel7.text")); // NOI18N jTextFieldCaminhoRepoRemotoGweb.setText(org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jTextFieldCaminhoRepoRemotoGweb.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jLabel8, org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jLabel8.text")); // NOI18N CaminhoRepoRemotoGwlib.setText(org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.CaminhoRepoRemotoGwlib.text")); // NOI18N javax.swing.GroupLayout jPanelCaminhoRepoRemotoLayout = new javax.swing.GroupLayout(jPanelCaminhoRepoRemoto); jPanelCaminhoRepoRemoto.setLayout(jPanelCaminhoRepoRemotoLayout); jPanelCaminhoRepoRemotoLayout.setHorizontalGroup( jPanelCaminhoRepoRemotoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelCaminhoRepoRemotoLayout.createSequentialGroup() .addGroup(jPanelCaminhoRepoRemotoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6) .addComponent(jLabel7) .addComponent(jLabel8)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelCaminhoRepoRemotoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextFieldCaminhoRepoRemotoGweb) .addComponent(CaminhoRepoRemotoGwlib) .addComponent(jTextFieldCaminhoRepoRemotoWebtrans, javax.swing.GroupLayout.PREFERRED_SIZE, 397, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)) ); jPanelCaminhoRepoRemotoLayout.setVerticalGroup( jPanelCaminhoRepoRemotoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelCaminhoRepoRemotoLayout.createSequentialGroup() .addGroup(jPanelCaminhoRepoRemotoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(jTextFieldCaminhoRepoRemotoWebtrans, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelCaminhoRepoRemotoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(jTextFieldCaminhoRepoRemotoGweb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelCaminhoRepoRemotoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(CaminhoRepoRemotoGwlib, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelCaminhoRepoLocal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanelCaminhoRepoRemoto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanelCaminhoRepoLocal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanelCaminhoRepoRemoto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jTabbedPane2.addTab(org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jPanel3.TabConstraints.tabTitle"), jPanel3); // NOI18N jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jPanel5.border.title"))); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jLabel4.text")); // NOI18N jTextFieldEmailSSH.setText(org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jTextFieldEmailSSH.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jLabel10, org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jLabel10.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jButtonGerarChave, org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jButtonGerarChave.text")); // NOI18N jButtonGerarChave.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonGerarChaveActionPerformed(evt); } }); jTextFieldSenhaSSH.setText(org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jTextFieldSenhaSSH.text")); // NOI18N javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextFieldEmailSSH, javax.swing.GroupLayout.PREFERRED_SIZE, 292, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldSenhaSSH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(13, 13, 13) .addComponent(jButtonGerarChave) .addGap(0, 79, Short.MAX_VALUE)) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jTextFieldEmailSSH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel10) .addComponent(jButtonGerarChave) .addComponent(jTextFieldSenhaSSH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jTextAreaLogSSH.setColumns(20); jTextAreaLogSSH.setRows(5); jScrollPane3.setViewportView(jTextAreaLogSSH); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane3)) .addContainerGap()) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 245, Short.MAX_VALUE) .addContainerGap()) ); jTabbedPane2.addTab(org.openide.util.NbBundle.getMessage(telaTopComponent.class, "telaTopComponent.jPanel4.TabConstraints.tabTitle"), jPanel4); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jTabbedPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 797, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPane2) ); }// </editor-fold>//GEN-END:initComponents private void jButtonGerarChaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGerarChaveActionPerformed gerarChaveSSH(); }//GEN-LAST:event_jButtonGerarChaveActionPerformed private void jTextFieldCaminhoRepoRemotoWebtransActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldCaminhoRepoRemotoWebtransActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextFieldCaminhoRepoRemotoWebtransActionPerformed private void jTextFieldCaminhoRepoLocaWebtransActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldCaminhoRepoLocaWebtransActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextFieldCaminhoRepoLocaWebtransActionPerformed private void jButtonAlterTagActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAlterTagActionPerformed AlterarTag(); }//GEN-LAST:event_jButtonAlterTagActionPerformed private void jButtonAlterVersaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAlterVersaoActionPerformed AlterarVersao(); }//GEN-LAST:event_jButtonAlterVersaoActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField CaminhoRepoRemotoGwlib; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JButton jButtonAlterTag; private javax.swing.JButton jButtonAlterVersao; private javax.swing.JButton jButtonGerarChave; private javax.swing.JComboBox<String> jComboBoxAlterTag; private javax.swing.JComboBox<String> jComboBoxAlterVersao; private javax.swing.JComboBox<String> jComboBoxVersao; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanelCaminhoRepoLocal; private javax.swing.JPanel jPanelCaminhoRepoRemoto; private javax.swing.JPanel jPanelTag1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JTabbedPane jTabbedPane2; private javax.swing.JTextArea jTextAreaLogSSH; private javax.swing.JTextField jTextFieldCaminhoRepoLocaGwLib; private javax.swing.JTextField jTextFieldCaminhoRepoLocaGweb; private javax.swing.JTextField jTextFieldCaminhoRepoLocaWebtrans; private javax.swing.JTextField jTextFieldCaminhoRepoRemotoGweb; private javax.swing.JTextField jTextFieldCaminhoRepoRemotoWebtrans; private javax.swing.JTextField jTextFieldEmailSSH; private javax.swing.JPasswordField jTextFieldSenhaSSH; private javax.swing.JTextField jTextFieldTag; private javax.swing.JTextPane jTextPaneLogTag; private javax.swing.JTextPane jTextPaneLogVersao; private javax.swing.JPanel painelAlterVersao; // End of variables declaration//GEN-END:variables @Override public void componentOpened() { // TODO add custom code on component opening } @Override public void componentClosed() { // TODO add custom code on component closing } void writeProperties(java.util.Properties p) { p.setProperty("version", "1.0"); p.setProperty("localWebtransLocal", jTextFieldCaminhoRepoLocaWebtrans.getText()); p.setProperty("localGwebLocal", jTextFieldCaminhoRepoLocaGweb.getText()); p.setProperty("localGwLibLocal", jTextFieldCaminhoRepoLocaGwLib.getText()); p.setProperty("localWebtransRemoto", jTextFieldCaminhoRepoRemotoWebtrans.getText()); p.setProperty("localGwebRemoto", jTextFieldCaminhoRepoRemotoGweb.getText()); p.setProperty("localGwLibRemoto", CaminhoRepoRemotoGwlib.getText()); } void readProperties(java.util.Properties p) { String version = p.getProperty("version"); jTextFieldCaminhoRepoLocaWebtrans.setText(p.getProperty("localWebtransLocal")); jTextFieldCaminhoRepoLocaGweb.setText(p.getProperty("localGwebLocal")); jTextFieldCaminhoRepoLocaGwLib.setText(p.getProperty("localGwLibLocal")); jTextFieldCaminhoRepoRemotoWebtrans.setText(p.getProperty("localWebtransRemoto")); jTextFieldCaminhoRepoRemotoGweb.setText(p.getProperty("localGwebRemoto")); CaminhoRepoRemotoGwlib.setText(p.getProperty("localGwLibRemoto")); } private void AlterarVersao() { try { String caminhoLocal = "", caminhoRemoto = "", branch = "", comando = "", caminhoLocalLib = "", caminhoRemotoLib = ""; //branch switch (jComboBoxVersao.getSelectedIndex()) { case 0: branch = "master"; break; case 1: branch = "atual"; break; case 2: branch = "custom"; break; } switch (jComboBoxAlterVersao.getSelectedIndex()) { case 0://webtrans caminhoLocal = jTextFieldCaminhoRepoLocaWebtrans.getText(); caminhoRemoto = jTextFieldCaminhoRepoRemotoWebtrans.getText(); break; case 1://gweb caminhoLocal = jTextFieldCaminhoRepoLocaGweb.getText(); caminhoRemoto = jTextFieldCaminhoRepoRemotoGweb.getText(); break; } caminhoLocalLib = jTextFieldCaminhoRepoLocaGwLib.getText(); caminhoRemotoLib = CaminhoRepoRemotoGwlib.getText(); comando = comandoAtualizarVersao(caminhoLocal, caminhoRemoto, branch); comando = comando + " && " + comandoAtualizarVersao(caminhoLocalLib, caminhoRemotoLib, branch); executeCommand(comando, "versao"); } catch (Exception e) { mensagem(e.getMessage()); } } private void AlterarTag() { try { String caminhoLocal = "", caminhoRemoto = "", tag = "", comando = "", caminhoLocalLib = "", caminhoRemotoLib = ""; tag = jTextFieldTag.getText(); switch (jComboBoxAlterTag.getSelectedIndex()) { case 0://webtrans caminhoLocal = jTextFieldCaminhoRepoLocaWebtrans.getText(); caminhoRemoto = jTextFieldCaminhoRepoRemotoWebtrans.getText(); break; case 1://gweb caminhoLocal = jTextFieldCaminhoRepoLocaGweb.getText(); caminhoRemoto = jTextFieldCaminhoRepoRemotoGweb.getText(); break; } caminhoLocalLib = jTextFieldCaminhoRepoLocaGwLib.getText(); caminhoRemotoLib = CaminhoRepoRemotoGwlib.getText(); comando = comandoAlterarTag(caminhoLocal, caminhoRemoto, tag); comando = comando + " && " + comandoAlterarTag(caminhoLocalLib, caminhoRemotoLib, tag); executeCommand(comando, "tag"); } catch (Exception e) { mensagem(e.getMessage()); } } private void gerarChaveSSH() { try { String comando = "", email = "", senha = ""; email = jTextFieldEmailSSH.getText(); senha = jTextFieldSenhaSSH.getText(); comando = comandoGerarChaveSSH(senha, email); executeCommand(removerChaveSSH(), ""); executeCommand(comando, "chave"); } catch (Exception ex) { mensagem(ex.getMessage()); } } private String comandoAtualizarVersao(String caminhoDir, String caminhoRemoto, String branch) { return "cd " .concat(caminhoDir) .concat(" && pwd && git fetch ") .concat(caminhoRemoto) .concat(" && git checkout ") .concat(branch) .concat(" && git reset --hard ") .concat(caminhoRemoto) .concat("/") .concat(branch); } private String comandoAlterarTag(String caminhoDir, String caminhoRemoto, String tag ) { return "cd " .concat(caminhoDir) .concat(" && pwd && git fetch --tags ") .concat(caminhoRemoto) .concat(" && git checkout tags/") .concat(tag) .concat(" -b ") .concat(tag); } private String comandoGerarChaveSSH(String senha, String email) { return "ssh-keygen -t rsa -b 4096 -C \"".concat(email).concat("\" -N ") .concat(senha) .concat(" -f $HOME/.ssh/id_rsa ") .concat(" && cd $HOME/.ssh/ ") .concat(" && pwd ") .concat(" && echo '\n\n -------------------- Chave Publica --------------------\n\n' ") .concat(" && cat id_rsa.pub"); } private String removerChaveSSH() { return "rm $HOME/.ssh/id_rsa && rm $HOME/.ssh/id_rsa.pub "; } public void executeCommand(final String command, String exibirLog) { try { final ArrayList<String> commands = new ArrayList<String>(); commands.add("/bin/bash"); commands.add("-c"); commands.add(command); BufferedReader br = null; final ProcessBuilder p = new ProcessBuilder(commands); final Process process = p.start(); final InputStream is = process.getInputStream(); final InputStreamReader isr = new InputStreamReader(is); br = new BufferedReader(isr); String line, log = ""; while ((line = br.readLine()) != null) { log = log + line + "\n"; } switch (exibirLog) { case "versao": jTextPaneLogVersao.setText(log); break; case "tag": jTextPaneLogTag.setText(log); break; case "chave": jTextAreaLogSSH.setText(log); break; } secureClose(isr); } catch (Exception e) { mensagem(e.getMessage()); } } private void secureClose(final Closeable resource) { try { if (resource != null) { resource.close(); } } catch (IOException e) { mensagem(e.getMessage()); } } private void mensagem(String mensagem) { JOptionPane.showMessageDialog(null, mensagem); } }
true
d217beceb6855b0ae6f5973b1d5458bac64795af
Java
pwt-team/thms
/src/com/thms/service/GoodsServiceImpl.java
UTF-8
1,294
2.109375
2
[]
no_license
package com.thms.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.thms.bean.Goods; import com.thms.dao.GoodsDao; @Service public class GoodsServiceImpl implements GoodsService { @Autowired public GoodsDao goodsDao; @Override public Goods findGoods(Integer id) { if(id == null) return null; return goodsDao.findGoods(id); } @Override public Goods create(Goods goods) { if(goods == null) return null; return goodsDao.create(goods); } @Override public Goods update(Goods goods) { if(goods == null) return null; return goodsDao.update(goods); } @Override public int findSize() { return goodsDao.findSize(); } @Override public List<Goods> findAll() { return goodsDao.findAll(); } @Override public List<Goods> findGoods(Integer pageNo, Integer psize) { return goodsDao.findGoods(pageNo,psize); } @Override public List<Goods> findGoods(Integer typeId, String name, Integer pageNo, Integer psize) { return goodsDao.findGoods(typeId,name,pageNo,psize); } @Override public List<Goods> findGoodsByType(Integer type, Integer pageNo, Integer psize) { if(type == null) return null; return goodsDao.findGoodsByType(type,pageNo,psize); } }
true
0af907882b0924231734f694b3da54ce0b463129
Java
bellmit/MSFM
/client/Java/intermarketTranslator/com/cboe/intermarketPresentation/common/formatters/AlertFormatter.java
UTF-8
7,269
2.203125
2
[]
no_license
// // ------------------------------------------------------------------------ // FILE: AlertFormatter.java // // PACKAGE: com.cboe.intermarketPresentation.common.formatters // // ------------------------------------------------------------------------ // Copyright (c) 1999-2003 The Chicago Board Options Exchange. All Rights Reserved. // // ------------------------------------------------------------------------ // package com.cboe.intermarketPresentation.common.formatters; import com.cboe.idl.cmiIntermarketMessages.AlertStruct; import com.cboe.interfaces.intermarketPresentation.intermarketMessages.Alert; import com.cboe.interfaces.intermarketPresentation.intermarketMessages.ExchangeMarket; import com.cboe.interfaces.presentation.common.formatters.AlertFormatStrategy; import com.cboe.interfaces.presentation.common.formatters.DateFormatStrategy; import com.cboe.interfaces.presentation.common.formatters.ExchangeMarketFormatStrategy; import com.cboe.interfaces.presentation.common.formatters.ExtensionsFormatStrategy; import com.cboe.interfaces.presentation.common.formatters.ProductFormatStrategy; import com.cboe.interfaces.presentation.product.SessionProduct; import com.cboe.presentation.api.APIHome; import com.cboe.presentation.common.formatters.*; import com.cboe.presentation.common.logging.GUILoggerHome; import com.cboe.intermarketPresentation.intermarketMessages.AlertFactory; /** * @author torresl@cboe.com */ class AlertFormatter extends AbstractCommonStylesFormatter implements AlertFormatStrategy { public AlertFormatter() { super(); initialize(); } private void initialize() { setDefaultStyle(FULL_STYLE_NAME); } public String format(AlertStruct alertStruct) { return format(alertStruct, getDefaultStyle()); } public String format(AlertStruct alertStruct, String style) { return format(AlertFactory.createAlert(alertStruct), style); } public String format(Alert alert) { return format(alert, getDefaultStyle()); } public String format(Alert alert, String style) { // TODO: implement formatter validateStyle(style); StringBuffer buffer = new StringBuffer(500); boolean brief = isBrief(style); String delimiter = getDelimiterForStyle(style); if( brief ) { buffer.append(AlertTypes.toString(alert.getAlertHeader().getAlertType())); buffer.append(delimiter); buffer.append( CommonFormatFactory.getDateFormatStrategy().format( alert.getAlertHeader().getAlertCreationTime(), DateFormatStrategy.DATE_FORMAT_24_HOURS_STYLE)); buffer.append(delimiter); buffer.append(AlertResolutions.toString(alert.getResolution(), AlertResolutions.TRADERS_FORMAT)); buffer.append(delimiter); try { SessionProduct sessionProduct = APIHome.findProductQueryAPI().getProductByKeyForSession(alert.getSessionName(), alert.getProductKeys().getProductKey()); buffer.append(CommonFormatFactory.getProductFormatStrategy().format(sessionProduct, ProductFormatStrategy.PRODUCT_NAME_WO_TYPE)); } catch (Exception e) { GUILoggerHome.find().exception(e); } buffer.append("Trade Id: ").append(alert.getTradeId().getHighId()); buffer.append(":").append(alert.getTradeId().getLowId()); buffer.append(delimiter); buffer.append("Order Id: ").append(alert.getOrderId().getCboeId().getHighId()); buffer.append(":").append(alert.getOrderId().getCboeId().getLowId()); } else { buffer.append("Alert Type: ").append(AlertTypes.toString(alert.getAlertHeader().getAlertType())); buffer.append(" ").append( CommonFormatFactory.getDateFormatStrategy().format( alert.getAlertHeader().getAlertCreationTime(), DateFormatStrategy.DATE_FORMAT_24_HOURS_STYLE)); buffer.append(" Resolution: "); buffer.append(AlertResolutions.toString(alert.getResolution(), AlertResolutions.TRADERS_FORMAT)); buffer.append("Alert ID: ").append(alert.getAlertHeader().getAlertId().getHighId()); buffer.append(":").append(alert.getAlertHeader().getAlertId().getLowId()); buffer.append(delimiter); buffer.append("Comments: ").append(alert.getComments().length()==0 ? "[NONE]": alert.getComments()); buffer.append(delimiter); buffer.append("NBBO Agent ID: ").append(alert.getNbboAgentId()); buffer.append(" Updated By: ").append(alert.getUpdatedById()); buffer.append(delimiter); try { SessionProduct sessionProduct = APIHome.findProductQueryAPI().getProductByKeyForSession(alert.getSessionName(), alert.getProductKeys().getProductKey()); buffer.append("Product Info: "); buffer.append(CommonFormatFactory.getProductFormatStrategy().format(sessionProduct, ProductFormatStrategy.FULL_PRODUCT_NAME_WITH_SESSION_AND_TYPE)); buffer.append(delimiter); } catch (Exception e) { GUILoggerHome.find().exception(e); } buffer.append("Trade Id: ").append(alert.getTradeId().getHighId()); buffer.append(":").append(alert.getTradeId().getLowId()); buffer.append(delimiter); buffer.append("Order Id: ").append(alert.getOrderId().getCboeId().getHighId()); buffer.append(":").append(alert.getOrderId().getCboeId().getLowId()).append(" "); buffer.append(" "); buffer.append("Branch/Sequence: ").append(alert.getOrderId().getFormattedBranchSequence()); buffer.append(delimiter); buffer.append("GiveUp Firm: ").append(alert.getOrderId().getExecutingOrGiveUpFirm().getExchange()); buffer.append(".").append(alert.getOrderId().getExecutingOrGiveUpFirm().getFirm()); buffer.append(" "); buffer.append("Correspondent Firm: ").append(alert.getOrderId().getCorrespondentFirm()); buffer.append(delimiter); buffer.append("CBOE Marketable Order: ").append( Boolean.toString(alert.getCboeMarketableOrder()).toUpperCase() ); buffer.append(com.cboe.presentation.common.formatters.FormatFactory.getExtensionsFormatStrategy().format("", ExtensionsFormatStrategy.FULL_STYLE_NAME)); ExchangeMarket[] exchangeMarkets = alert.getExchangeMarket(); for (int i = 0; i < exchangeMarkets.length; i++) { ExchangeMarket exchangeMarket = exchangeMarkets[i]; buffer.append( FormatFactory.getExchangeMarketFormatStrategy().format( exchangeMarket, ExchangeMarketFormatStrategy.FULL_STYLE)); buffer.append(delimiter); } } return buffer.toString(); } }
true
eac2024ea511095c5db8c15404c276aa1285ac56
Java
WilsonParker/Algorithm_Study
/Algorithm/171007/이창주_백준_14726번_신용카드판별.java
UTF-8
767
3
3
[]
no_license
package B_14726; import java.util.Scanner; public class Main { public static void main(String args[]) throws Exception { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); sc.nextLine(); for(int test_case = 0; test_case < T; test_case++) { String input=sc.nextLine(); int n= input.length(); int[] arr = new int[n+1]; int sum =0 ; for(int i=0; i<n; i++) { arr[n-i]=Integer.parseInt(String.valueOf(input.charAt(i))); } for(int i=1; i<=n; i++) { if(i%2 ==0) { if(arr[i]*2 >= 10) { arr[i] = (arr[i]*2 / 10) + (arr[i]*2 % 10); }else { arr[i]=arr[i]*2; } } } for(int i=1; i<=n; i++) { sum+=arr[i]; } System.out.println((sum%10 == 0)? "T":"F"); } } }
true
a5e7d5a64a5951cddd058352ffbd729107cb82f3
Java
bernmic/justmusic-javalin
/backend/src/main/java/de/b4/justmusic/service/ServiceRegistry.java
UTF-8
754
2.1875
2
[]
no_license
package de.b4.justmusic.service; import de.b4.justmusic.service.impl.LibraryServiceImpl; public class ServiceRegistry { private static LibraryService libraryService; private static PlaylistService playlistService; private static UserService userService; public static LibraryService getLibraryService() { if (libraryService == null) libraryService = LibraryServiceImpl.create(); return libraryService; } public static PlaylistService getPlaylistService() { if (playlistService == null) playlistService = new PlaylistService(); return playlistService; } public static UserService getUserService() { if (userService == null) { userService = new UserService(); } return userService; } }
true
d41229ee8f575d2fcf045e51db0926b267025292
Java
luotianwen/pgy
/dd_adv_op/src/main/java/com/kkgame/feeop/excel/DataSheetBean.java
UTF-8
1,166
2.15625
2
[]
no_license
package com.kkgame.feeop.excel; import com.kkgame.feeop.util.ThreeRelate; import com.kkgame.feeop.util.TwoRelate; import java.util.List; /** * Function: * * @version $Revision$ $Date$ * Date: 2016/3/17 * Time: 13:11 * @author: Administrator * @since 3.0 */ public class DataSheetBean { /** 查询条件 */ private List<ThreeRelate<Boolean, String, String>> queryList; /** 列名、列数据类型 */ private List<TwoRelate<String, Integer>> columes; /** 行数据 */ private List<DataRowBean> rowsData; public List<ThreeRelate<Boolean, String, String>> getQueryList() { return queryList; } public void setQueryList(List<ThreeRelate<Boolean, String, String>> queryList) { this.queryList = queryList; } public List<TwoRelate<String, Integer>> getColumes() { return columes; } public void setColumes(List<TwoRelate<String, Integer>> columes) { this.columes = columes; } public List<DataRowBean> getRowsData() { return rowsData; } public void setRowsData(List<DataRowBean> rowsData) { this.rowsData = rowsData; } }
true
ad152af7394166f0c8b5082e9011a8a79ca79645
Java
itayelbaz11/beta
/app/src/main/java/com/example/beta/User.java
UTF-8
816
2.625
3
[]
no_license
package com.example.beta; public class User { private String name, email, uid; private Boolean active; public User (){} public User (String name, String email, String uid, Boolean active) { this.name=name; this.email=email; this.uid=uid; this.active=active; } public String getName() { return name; } public void setName(String name) { this.name=name; } public String getEmail() { return email; } public void setEmail(String email) { this.email=email; } public String getUid() { return uid; } public void setUid(String uid) { this.uid=uid; } public Boolean getActive() { return active; } public void setActive(Boolean active) { this.active=active; } }
true
c96bd6947567b86ed3ce6771655321586b9d9685
Java
przemyslawkonik/shop
/src/model/enums/Status.java
UTF-8
265
2.421875
2
[]
no_license
package model.enums; public enum Status { ZREALIZOWANE("ZREALIZOWANE"), BRAK("BRAK"); private String name; private Status(String name) { this.name = name; } @Override public String toString() { return name; } }
true
5f3096c8f2e9fe5e2c88f458bbf188102098fd2e
Java
clarenznet/Homlie
/app/src/main/java/com/luns/neuro/mlkn/library/User.java
UTF-8
1,218
2.265625
2
[]
no_license
package com.luns.neuro.mlkn.library; /** * Created by neuro on 2/24/2018. */ public class User { private String phonenumber, firebaseid, user_priviledge, user_fullname, user_address, user_latitude, user_longitude; public User(String phonenumber, String firebaseid, String user_priviledge, String user_fullname, String user_address, String user_latitude, String user_longitude) { this.phonenumber = phonenumber; this.firebaseid = firebaseid; this.user_priviledge=user_priviledge; this.user_fullname = user_fullname; this.user_address=user_address; this.user_latitude=user_latitude; this.user_longitude=user_longitude; } public String getPhonenumber() { return phonenumber; } public String getFirebaseid() { return firebaseid; } public String getUser_fullname() { return user_fullname; } public String getUser_priviledge() { return user_priviledge; } public String getUser_address() { return user_address; } public String getUser_latitude() { return user_latitude; } public String getUser_longitude() { return user_longitude; } }
true
bf5b7723e437740cac56ab8e1c0d25e0f5f121ec
Java
x2long/webjoin-insight-plugins
/lib/org.springframework.webflow-2.0.5.RELEASE-sources/org/springframework/webflow/conversation/impl/ConversationLockFactory.java
UTF-8
2,734
2.46875
2
[]
no_license
/* * Copyright 2004-2008 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.webflow.conversation.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.JdkVersion; /** * Simple utility class for creating conversation lock instances based on the current execution environment. * * @author Keith Donald * @author Rob Harrop */ class ConversationLockFactory { private static final Log logger = LogFactory.getLog(ConversationLockFactory.class); private static boolean backportConcurrentPresent; static { try { Class.forName("edu.emory.mathcs.backport.java.util.concurrent.locks.ReentrantLock"); backportConcurrentPresent = true; } catch (ClassNotFoundException ex) { backportConcurrentPresent = false; } } private int timeoutSeconds = 30; /** * Returns the period of time that can elapse before a lock attempt times out for locks created by this factory. */ public int getTimeoutSeconds() { return timeoutSeconds; } /** * Sets the period of time that can elapse before a lock attempt times out for locks created by this factory. * @param timeoutSeconds the timeout period in seconds */ public void setTimeoutSeconds(int timeoutSeconds) { this.timeoutSeconds = timeoutSeconds; } /** * When running on Java 1.5+, returns a jdk5 concurrent lock. When running on older JDKs with the * 'backport-util-concurrent' package available, returns a backport concurrent lock. In all other cases a "no-op" * lock is returned. */ public ConversationLock createLock() { if (JdkVersion.getMajorJavaVersion() >= JdkVersion.JAVA_15) { return new JdkConcurrentConversationLock(timeoutSeconds); } else if (backportConcurrentPresent) { return new JdkBackportConcurrentConversationLock(timeoutSeconds); } else { logger.warn("Unable to enable conversation locking. Switch to Java 5 or above, " + "or put the 'backport-util-concurrent' package on the classpath " + "to enable locking in your Java 1.4 environment."); return NoOpConversationLock.INSTANCE; } } }
true
57fa5656af089d4e589efdf545c8d90147adb1fc
Java
jcastro-inf/delfos
/src/main/java/delfos/rs/contentbased/vsm/booleanvsm/symeonidis2007/Symeonidis2007Model.java
UTF-8
3,641
2.0625
2
[]
no_license
/* * Copyright (C) 2016 jcastro * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package delfos.rs.contentbased.vsm.booleanvsm.symeonidis2007; import delfos.rs.contentbased.vsm.booleanvsm.BooleanFeaturesTransformation; import delfos.rs.contentbased.vsm.booleanvsm.SparseVector; import delfos.rs.contentbased.vsm.booleanvsm.profile.BooleanUserProfile; import java.io.Serializable; import java.util.TreeMap; /** * Almacena el modelo del sistema {@link Symeonidis2007FeatureWeighted}, que se compone de los perfiles de producto, los * perfiles de usuario y de las ponderaciones IUF. * * @author jcastro-inf ( https://github.com/jcastro-inf ) * * @version 14-Octubre-2013 */ public class Symeonidis2007Model implements Serializable { private static final long serialVersionUID = -3387516993124229948L; private SparseVector<Long> allIUF; private final BooleanFeaturesTransformation booleanFeaturesTransformation; private final TreeMap<Long, Symeonidis2007UserProfile> userProfiles; private final TreeMap<Long, SparseVector<Long>> itemProfiles; public Symeonidis2007Model(BooleanFeaturesTransformation booleanFeaturesTransformation) { this.userProfiles = new TreeMap<>(); this.itemProfiles = new TreeMap<>(); this.booleanFeaturesTransformation = booleanFeaturesTransformation; } public BooleanFeaturesTransformation getBooleanFeaturesTransformation() { return booleanFeaturesTransformation; } public void setAllIuf(SparseVector<Long> allIuf) { this.allIUF = allIuf.clone(); } public SparseVector<Long> getAllIUF() { return allIUF.clone(); } void putItemProfile(long idItem, SparseVector<Long> itemProfile) { if (itemProfiles.containsKey(idItem)) { throw new IllegalArgumentException("The item " + idItem + " profile had already been assigned the model."); } else { itemProfiles.put(idItem, itemProfile); } } SparseVector<Long> getItemProfile(long idItem) { if (itemProfiles.containsKey(idItem)) { return itemProfiles.get(idItem).clone(); } else { throw new IllegalArgumentException("The item " + idItem + " profile not exists"); } } void putUserProfile(long idUser, Symeonidis2007UserProfile itemProfile) { if (userProfiles.containsKey(idUser)) { throw new IllegalArgumentException("The user " + idUser + " profile had already been assigned the model."); } else { userProfiles.put(idUser, itemProfile); } } BooleanUserProfile getUserProfile(int idUser) { if (userProfiles.containsKey(idUser)) { return userProfiles.get(idUser); } else { throw new IllegalArgumentException("The user " + idUser + " profile not exists"); } } int numOfItemProfiles() { return itemProfiles.size(); } Iterable<Symeonidis2007UserProfile> userProfiles() { return userProfiles.values(); } }
true
abbd2e1c934fd66f56aa13e5a1c4bdcabdae2de1
Java
Ayush-Saxena/Java-Berlin-Clock-UBS
/src/test/java/com/ubs/opsit/interviews/impl/BerlinClockTest.java
UTF-8
1,244
2.6875
3
[]
no_license
package com.ubs.opsit.interviews.impl; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; import org.junit.Test; import com.ubs.opsit.interviews.domain.Colour; public class BerlinClockTest { BerlinClock clock; @Before public void setUp() { clock = new BerlinClock.Builder() .row().lamp(1, Colour.Y) .and() .row().lamp(4, Colour.R) .and() .row().lamp(4, Colour.R) .and() .row().lamp(2, Colour.Y).lamp(1, Colour.R).lamp(2, Colour.Y).lamp(1, Colour.R).lamp(2, Colour.Y).lamp(1, Colour.R).lamp(2, Colour.Y) .and() .row().lamp(4, Colour.Y).build(); } @Test public void convertTime_Invalid() { clock.convertTime("abc"); } @Test public void convertTime_correctTime(){ String expected = "Y OOOO OOOO OOOOOOOOOOO OOOO"; String s = clock.convertTime("00:00:00"); String t = s.replace(String.valueOf('\r') + String.valueOf('\n'), " "); assertThat(t).isEqualTo(expected); } @Test public void convertTime_correctTimeAnother(){ String expected = "O RRRO OOOO YYRYYRYOOOO YYOO"; String s = clock.convertTime("15:37:37"); String t = s.replace(String.valueOf('\r') + String.valueOf('\n'), " "); assertThat(t).isEqualTo(expected); } }
true
f59390e1de67c270745e465c6d569bf10f120ef0
Java
oneid-sa/oneid.bankstatements
/api/java/digital-oneid/src/main/java/digital/oneid/model/AuditSearch.java
UTF-8
1,465
2.125
2
[]
no_license
/** * ****************************************************** * Copyright (c) 2020, PowerRecruit. * All rights reserved. ********************************************************/ package digital.oneid.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * Created by hubinotech on 07/04/20. */ @JsonIgnoreProperties(ignoreUnknown = true) public class AuditSearch { private int page_no; private int limit; private String sortby; // Ascending / Descending private int companyId; private String start_date; private String end_date; public int getPage_no() { return page_no; } public void setPage_no(int page_no) { this.page_no = page_no; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public String getSortby() { return sortby; } public void setSortby(String sortby) { this.sortby = sortby; } public int getCompanyId() { return companyId; } public void setCompanyId(int companyId) { this.companyId = companyId; } public String getStart_date() { return start_date; } public void setStart_date(String start_date) { this.start_date = start_date; } public String getEnd_date() { return end_date; } public void setEnd_date(String end_date) { this.end_date = end_date; } }
true
579a8bca05ae5d6e07b3380fab70be85a5d7f05e
Java
vnmk/product-service
/src/main/java/com/myretail/redskyservice/client/ProductServiceClient.java
UTF-8
1,605
2.453125
2
[]
no_license
package com.myretail.redskyservice.client; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; /** * Client that calls the product web service of redsky.target.com to get product * information. * * @author VenkataRaidu * */ public class ProductServiceClient { private static final String REDSKY_PRODUCT_SERVICE_URL = "http://redsky.target.com/v2/pdp/"; private static ProductServiceClient client = null; private ProductServiceClient() { } public static ProductServiceClient getInstance() { if (client == null) client = new ProductServiceClient(); return client; } public JSONObject getProduct(long id) throws ParseException { JSONObject product = null; Client client = Client.create(); String getProductRequest = REDSKY_PRODUCT_SERVICE_URL + "tcin/" + id; WebResource webResource = client.resource(getProductRequest); ClientResponse response = webResource.accept("application/json").get(ClientResponse.class); if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } String output = response.getEntity(String.class); JSONParser parser = new JSONParser(); try { JSONObject json = (JSONObject) parser.parse(output); product = (JSONObject) json.get("product"); } catch (ParseException e) { throw e; } finally { response.close(); } return product; } }
true
f9bbc0cd1a5667e52680ba41e6316af5308b7953
Java
mirko2021/EX-003_010_YCMSTextComponent
/src/proccess/java/ycms/server/process/web/bean/ProccessBean.java
UTF-8
388
1.960938
2
[]
no_license
package ycms.server.process.web.bean; import java.io.Serializable; /** * Зрно којим се означавају процеси на серверу * који могу утицати на стање апликације. * @author VM * @version 1.0 */ public class ProccessBean implements Serializable{ private static final long serialVersionUID = 6454096321016212886L; }
true
67fcb7df53c071160b79c7fcaf633c4b3e234592
Java
boatengfrankenstein/ofCampus
/src/com/app/ofcampus/SignUpActivity.java
UTF-8
5,808
2.03125
2
[]
no_license
package com.app.ofcampus; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import com.app.ofcampus.networking.SendEmailAsyncTask; import com.app.ofcampus.networking.SendEmailAsyncTask.SendEmailDeligate; import com.app.ui.AbstractActivity; import com.app.utils.AlertMessage.DialogDialogDeligate; import com.app.utils.FiledValidators; import com.parse.ParseException; import com.parse.ParseUser; import com.parse.SignUpCallback; public class SignUpActivity extends AbstractActivity { private EditText edtUsername; private EditText edtEmail; private EditText edtPassword; private EditText edtConfirmPassword; private Button btnActivate; private ProgressDialog loadingDialog; private EditText edtFullName; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_up); intUI(); } @Override protected void intUI() { super.intUI(); edtUsername = (EditText) findViewById(R.id.edt_username); edtEmail = (EditText) findViewById(R.id.edt_email); edtPassword = (EditText) findViewById(R.id.edt_password); edtConfirmPassword = (EditText) findViewById(R.id.edt_confirm_password); edtFullName = (EditText) findViewById(R.id.edt_fullname); btnActivate = (Button) findViewById(R.id.btn_activate); loadingDialog = getLoadingDialog(context,getString(R.string.hold_on_), getString(R.string.signing_up_), false); setListeners(); } private void setListeners() { btnActivate.setOnClickListener(new ActivateBtnClickListener()); } private class ActivateBtnClickListener implements OnClickListener { @Override public void onClick(View arg0) { boolean isValidInput = validateInput(); if(isValidInput) { getSharedPreference(activity).putString(EMAIL_ID, edtEmail.getText().toString()); continueSignUp(); } } } private void continueSignUp() { String username = edtUsername.getText().toString(); String email = edtEmail.getText().toString(); saveEmailId(email); String password = edtPassword.getText().toString(); String fullName = edtFullName.getText().toString(); ParseUser user = new ParseUser(); user.setEmail(email); user.setUsername(username); user.setPassword(password); user.put(IS_EMAIL_VERIFIED, false); user.put(USER_FULL_NAME, fullName); user.signUpInBackground(new SignUpUserCallBack()); loadingDialog.show(); } private class SignUpUserCallBack extends SignUpCallback { @Override public void done(ParseException arg0) { loadingDialog.dismiss(); if(arg0!=null) { showAlert(getString(R.string.signup_failed_), arg0.getLocalizedMessage(), getString(R.string.ok), null, context, null); }else{ SendEmailAsyncTask emailAsyncTask = new SendEmailAsyncTask(getSavedEmailId(), context, new EmailVerificationDeligate()); emailAsyncTask.execute(); } } } private class EmailVerificationDeligate implements SendEmailDeligate { @Override public void onEmailSend() { showAlert(getString(R.string.activation_pending_), getString(R.string.activation_message), getString(R.string.ok), null, context, new DialogDialogDeligate() { @Override public void positiveButtonClick(DialogInterface dialog, int id) { dialog.dismiss(); switchToActivity(activity, EmailVerificationActivity.class, null); } @Override public void negativeButtonClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); } } public void saveEmailId(String emailId) { getSharedPreference(activity).putString(EMAIL_ID, emailId); } public String getSavedEmailId() { return getSharedPreference(activity).getString(EMAIL_ID, ""); } @Override public void onBackPressed() { super.onBackPressed(); switchToActivity(activity, WelcomeActivity.class, null); } private boolean validateInput() { String username = edtUsername.getText().toString(); boolean isValidUserName = TextUtils.isEmpty(username); if(isValidUserName) { showAlert(getString(R.string.valid_username_), getString(R.string.enter_valid_username_),getString(R.string.ok), null, context, null); return false; } String fullName = edtFullName.getText().toString(); boolean isVaildFullName = TextUtils.isEmpty(fullName); if(isVaildFullName) { showAlert(getString(R.string.invalid_fullname_),getString(R.string.enter_valid_fullname),getString(R.string.ok), null, context, null); return false; } String email = edtEmail.getText().toString(); boolean isEmptyEmail = TextUtils.isEmpty(email) ; boolean isValidEmail = FiledValidators.validateEmail(email); if(isEmptyEmail || !isValidEmail) { showAlert(getString(R.string.invalid_email_), getString(R.string.enter_valid_email_), getString(R.string.ok), null, context, null); return false; } String password = edtPassword.getText().toString(); String confrimPassword = edtConfirmPassword.getText().toString(); boolean isPasswordEmpty = TextUtils.isEmpty(password) || TextUtils.isEmpty(confrimPassword); if(isPasswordEmpty) { showAlert(getString(R.string.invalid_password_), getString(R.string.enter_valid_password_), getString(R.string.ok), null, context, null); return false; } boolean isBoothPassMatch = password.equals(confrimPassword); if(!isBoothPassMatch) { showAlert(getString(R.string.password_miss_match_), getString(R.string.both_the_pass_should_match_), getString(R.string.ok), null, context, null); return false; } return true; } }
true
dd41d26076d47719ebc18aeeeeb1757dba678b11
Java
lnbs/mybase
/app/src/main/java/com/example/administrator/mybasetest1/mvp/view/activity_view/GankDataView.java
UTF-8
321
1.796875
2
[]
no_license
package com.example.administrator.mybasetest1.mvp.view.activity_view; import com.example.administrator.mybasetest1.base.mvpbase.BaseView; /** * Created by Administrator on 2018/11/16. */ public interface GankDataView<T> extends BaseView{ void getGankDataSuccess(T bean); void getGankDataError(String msg); }
true
4a5bfa106f71c155aeb3c6bc7795cc70a5fdc8a5
Java
AdeYac/mda-garage
/src/main/java/tech/becoming/mda/one/Main.java
UTF-8
593
2.390625
2
[ "MIT" ]
permissive
package tech.becoming.mda.one; import tech.becoming.mda.one.model.actor.Owner; import tech.becoming.mda.one.model.garage.DigitalKey; import tech.becoming.mda.one.model.garage.DigitalLock; import tech.becoming.mda.one.model.garage.Gate; import tech.becoming.mda.one.model.garage.Motor; public class Main { public static void main(String[] args) { Gate g = new Gate(); Motor m = new Motor(g); DigitalLock dl = new DigitalLock(m); DigitalKey dk = new DigitalKey("1111"); dk.setLock(dl); Owner o = new Owner(dk); o.open(); } }
true
4f72090a8587ee748c721b5f50bf09ac17970ff8
Java
ardolazarini/geplanes
/src/br/com/linkcom/sgm/beans/UsuarioUnidadeGerencial.java
ISO-8859-1
2,561
1.960938
2
[]
no_license
/* Copyright 2007,2008,2009,2010 da Linkcom Informtica Ltda Este arquivo parte do programa GEPLANES. O GEPLANES software livre; voc pode redistribu-lo e/ou modific-lo sob os termos da Licena Pblica Geral GNU, conforme publicada pela Free Software Foundation; tanto a verso 2 da Licena como (a seu critrio) qualquer verso mais nova. Este programa distribudo na expectativa de ser til, mas SEM QUALQUER GARANTIA; sem mesmo a garantia implcita de COMERCIALIZAO ou de ADEQUAO A QUALQUER PROPSITO EM PARTICULAR. Consulte a Licena Pblica Geral GNU para obter mais detalhes. Voc deve ter recebido uma cpia da Licena Pblica Geral GNU junto com este programa; se no, escreva para a Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ package br.com.linkcom.sgm.beans; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import br.com.linkcom.neo.bean.annotation.DisplayName; import br.com.linkcom.neo.validation.annotation.Required; import br.com.linkcom.sgm.beans.enumeration.FuncaoUGEnum; @Entity @SequenceGenerator(name = "sq_usuariounidadegerencial", sequenceName = "sq_usuariounidadegerencial") public class UsuarioUnidadeGerencial { private Integer id; private Usuario usuario; private UnidadeGerencial unidadeGerencial; private FuncaoUGEnum funcao; //=========================Get e Set==================================// @Id @GeneratedValue(strategy=GenerationType.AUTO, generator="sq_usuariounidadegerencial") public Integer getId() { return id; } @ManyToOne(fetch=FetchType.LAZY) @Required public UnidadeGerencial getUnidadeGerencial() { return unidadeGerencial; } @ManyToOne @Required public Usuario getUsuario() { return usuario; } @DisplayName("Funo") @Required public FuncaoUGEnum getFuncao() { return funcao; } public void setId(Integer id) { this.id = id; } public void setUnidadeGerencial(UnidadeGerencial unidadeGerencial) { this.unidadeGerencial = unidadeGerencial; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public void setFuncao(FuncaoUGEnum funcao) { this.funcao = funcao; } }
true
2a962d41c1d239cff38be4e7614e02f561076561
Java
rootmos/audio-journal
/android/app/src/main/java/Sound.java
UTF-8
8,450
2.109375
2
[]
no_license
package io.rootmos.audiojournal; import static io.rootmos.audiojournal.Common.TAG; import android.net.Uri; import android.util.Log; import android.content.Intent; import android.content.Context; import androidx.core.content.FileProvider; import java.io.IOException; import java.io.InputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.SimpleFileVisitor; import java.nio.file.FileVisitResult; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.time.LocalDate; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.json.JSONTokener; import org.json.JSONObject; import org.json.JSONException; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; class Sound implements Comparable<Sound> { private byte[] sha1 = null; private String title = null; private String artist = null; private String composer = null; private float duration = 0; private String filename = null; private String mimeType = null; private Uri uri = null; private Path local = null; private Path metadata = null; private OffsetDateTime datetime = null; private LocalDate date = null; public Sound(String title, String artist, String composer, byte[] sha1, float duration) { this.title = title; this.artist = artist; this.composer = composer; this.sha1 = sha1; this.duration = duration; } public void setDateTime(OffsetDateTime dt) { datetime = dt; date = dt.toLocalDate(); } public void setLocal(Path path) { this.local = path; } public void setURI(Uri uri) { this.uri = uri; } public void setMetadata(Path metadata) { this.metadata = metadata; } public void setMimeType(String mimeType) { this.mimeType = mimeType; } public String getTitle() { return title; } public String getArtist() { return artist; } public String getComposer() { return composer; } public float getDuration() { return duration; } public OffsetDateTime getDateTime() { return datetime; } public LocalDate getDate() { return date; } public byte[] getSHA1() { return sha1; } public Uri getURI() { return uri; } public Path getLocal() { return local; } public String getFilename() { return filename; } public Path getMetadata() { return metadata; } public int hashCode() { return ByteBuffer.wrap(sha1).getInt(); } public int compareTo(Sound o) { if(date.isEqual(o.date)) { if(datetime != null && o.datetime != null) { if(datetime.isEqual(o.datetime)) { return 0; } else { return datetime.isBefore(o.datetime) ? -1 : 1; } } else { return 0; } } else { return date.isBefore(o.date) ? -1 : 1; } } public void merge(Sound o) { if(!Arrays.equals(sha1, o.sha1)) { throw new RuntimeException("merging sounds with different hashes"); } if(o.filename != null) filename = o.filename; if(o.local != null) local = o.local; if(o.uri != null) uri = o.uri; if(o.metadata != null) metadata = o.metadata; } static public List<Sound> scanDir(Path d) { final ArrayList<Sound> ss = new ArrayList<>(); try { Files.walkFileTree(d, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path p, BasicFileAttributes attrs) throws IOException { Log.d(TAG, "considering: " + p); if(p.toFile().getName().endsWith(".json")) { ss.add(fromLocalFile(p)); } return FileVisitResult.CONTINUE; } }); } catch(IOException e) { Log.e(TAG, "exception while scanning: " + d, e); return null; } return ss; } static public Sound fromLocalFile(Path m) throws FileNotFoundException { Log.d(TAG, "reading local metadata: " + m); Sound s = fromInputStream(new FileInputStream(m.toFile())); s.metadata = m; Path p = m.getParent().resolve(s.filename); if(Files.exists(p)) { s.local = p; } else { Log.w(TAG, "corresponding audio file not found: " + p); } return s; } static public Sound fromInputStream(InputStream is) { String raw = null; try { raw = Utils.stringFromInputStream(is); } catch(IOException e) { throw new RuntimeException("unable to read object content", e); } return fromJSON(raw); } static public Sound fromJSON(String raw) { JSONObject j = null; try { j = (JSONObject) new JSONTokener(raw).nextValue(); } catch(JSONException e) { throw new RuntimeException("unable to parse object content", e); } catch(ClassCastException e) { throw new RuntimeException("expected JSON object not present", e); } Sound s = null; try { String t = j.getString("title"); String a = j.getString("artist"); String c = j.getString("composer"); float d = (float)j.getDouble("length"); byte[] sha1 = Hex.decodeHex(j.getString("sha1")); s = new Sound(t, a, c, sha1, d); if(!j.isNull("url")) { String u = j.getString("url"); s.uri = Uri.parse(u); } s.filename = j.getString("filename"); s.mimeType = j.optString("mimetype"); if(s.mimeType == null || s.mimeType == "") { s.mimeType = Format.guessBasedOnFilename(s.filename) .getMimeType(); } } catch(DecoderException e) { throw new RuntimeException("unable to hex decode", e); } catch(JSONException e) { throw new RuntimeException("illstructured JSON content", e); } try { String d = j.getString("date"); try { s.datetime = OffsetDateTime.parse(d); s.date = s.datetime.toLocalDate(); } catch(DateTimeParseException e) { s.date = LocalDate.parse(d); } } catch(JSONException e) { throw new RuntimeException("illstructured date field", e); } return s; } public String toJSON() { JSONObject j = new JSONObject(); try { j.put("title", title); j.put("sha1", Hex.encodeHexString(sha1)); j.put("url", uri != null ? uri.toString() : JSONObject.NULL); if(local != null) { j.put("filename", local.getFileName()); } else if(filename != null) { j.put("filename", filename); } j.put("artist", artist); j.put("composer", composer); if(datetime != null) { j.put("date", datetime.format( DateTimeFormatter.ISO_OFFSET_DATE_TIME)); } else { j.put("date", date.format(DateTimeFormatter.ISO_DATE)); } j.put("year", date.getYear()); j.put("length", duration); j.put("mimetype", mimeType); } catch(JSONException e) { throw new RuntimeException("unable to populate JSON object", e); } return j.toString(); } public Intent getShareIntent(Context ctx) { Intent i = new Intent(Intent.ACTION_VIEW); Uri u = null; if(local != null) { u = FileProvider.getUriForFile(ctx, ctx.getApplicationContext().getPackageName() + ".provider", local.toFile()); i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } else if(uri != null) { u = uri.normalizeScheme(); } i.setDataAndType(u, mimeType); return i; } }
true
8f0238f7a1cdd49d8f1d9936b6135dd9074c6962
Java
FMzhizhi/juc
/src/com/zjj/juc/thread/TestCallable.java
UTF-8
1,183
3.671875
4
[]
no_license
package com.zjj.juc.thread; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; /** * @author zhijiaju * @version 1.0 * @date 2020/6/27 12:58 */ public class TestCallable { public static void main(String[] args) throws ExecutionException, InterruptedException { ThreadDemo th=new ThreadDemo(); FutureTask<Integer> fu=new FutureTask<>(th);//类似于CountDownLatch闭锁 new Thread(fu).start(); System.out.println(fu.get()); System.out.println("-------------------"); } } /* * 一、创建执行线程的方式三:实现 Callable 接口。 相较于实现 Runnable 接口的方式,方法可以有返回值,并且可以抛出异常。 * * 二、执行 Callable 方式,需要 FutureTask 实现类的支持,用于接收运算结果。 FutureTask 是 Future 接口的实现类 */ class ThreadDemo implements Callable<Integer>{ @Override public Integer call() throws Exception { int sum=0; for (int i=0;i<1000;i++){ sum+=i; } return sum; } }
true
27ad8194566748bfed2fbea03f06b08198a262e4
Java
Kepler-Framework/Kepler-Trace
/kepler-trace/src/main/java/com/kepler/trace/SpanContext.java
UTF-8
350
2.484375
2
[]
no_license
package com.kepler.trace; public class SpanContext { private static final ThreadLocal<Span> span = new ThreadLocal<Span>() { @Override protected Span initialValue() { return new Span(); } }; public static void set(Span span) { SpanContext.span.set(span); } public static Span get() { return SpanContext.span.get(); } }
true
4300efe2aa2ba5d399790b7c4cf347e699ef319e
Java
ildar66/WSAD_NRI
/2005/webcommon/com/hps/july/project/valueobject/ProjectActionObject.java
WINDOWS-1251
9,473
2.296875
2
[]
no_license
package com.hps.july.project.valueobject; import com.hps.july.persistence.*; import java.util.*; /** * -wrapper . * Creation date: (29.05.2003 12:04:46) * @author: Dmitry Dneprov */ public class ProjectActionObject { private int divcode; private java.lang.String comment; private java.lang.String objtype; private java.lang.String usercolval; private int projectaction; private java.lang.Boolean completed; private java.lang.Boolean agreement; private boolean hasproblems; private java.sql.Date factdate; private java.sql.Date plandate; private java.sql.Date suggplandate; private java.lang.Boolean isNewplandate; private java.lang.String headername; private int divcol; private int projectactiontype; private java.lang.String notes; private int projectcode; /** * ProjectActionObject constructor comment. */ public ProjectActionObject(int argProjectaction, int argDivCode) { super(); //System.out.println("SETTING projectaction=" + argProjectaction); setProjectaction(argProjectaction); setObjtype("P"); setDivcode(argDivCode); } /** * ProjectActionObject constructor comment. */ public ProjectActionObject(int argDivCol, int argDivCode, int argProject) { super(); setDivcol(argDivCol); setDivcode(argDivCode); setObjtype("K"); setProjectcode(argProject); /* // Determine user column value try { ProjectDivColValAccessBean colvalab = new ProjectDivColValAccessBean(); colvalab.setInitKey_project_project(new Integer(argProject)); colvalab.setInitKey_projectDivColumn_divcolid(new Integer(argDivCol)); colvalab.refreshCopyHelper(); setUsercolval(colvalab.getColvalue()); } catch (Exception e) { setUsercolval(""); } */ } /** * Confirm / Reject new plan date for projectaction. * Creation date: (13.10.2003 15:34:40) * @return boolean * @param argPrjAction int * @param isConfirm boolean */ public static void changeAllPlanDates(boolean isConfirm, Integer argProject) throws Exception { java.util.Enumeration en = new ProjectActionAccessBean().findByProjectOrderByOrderAsc(argProject); while (en.hasMoreElements()) { ProjectActionAccessBean pab = (ProjectActionAccessBean)en.nextElement(); if (isConfirm) pab.setPlandate(pab.getSuggplandate()); else pab.setSuggplandate(pab.getPlandate()); pab.setIsNewplandate(Boolean.FALSE); pab.commitCopyHelper(); } } /** * Confirm / Reject new plan date for projectaction. * Creation date: (13.10.2003 15:34:40) * @return boolean * @param argPrjAction int * @param isConfirm boolean */ public static void changePlanDate(int argPrjAction, boolean isConfirm) throws Exception { ProjectActionAccessBean pab = new ProjectActionAccessBean(); pab.setInitKey_projectaction(argPrjAction); pab.refreshCopyHelper(); if (isConfirm) pab.setPlandate(pab.getSuggplandate()); else pab.setSuggplandate(pab.getPlandate()); pab.setIsNewplandate(Boolean.FALSE); pab.commitCopyHelper(); } /** * Insert the method's description here. * Creation date: (29.09.2003 18:52:03) * @return java.lang.Boolean */ public java.lang.Boolean getAgreement() { return agreement; } /** * Insert the method's description here. * Creation date: (29.05.2003 12:09:40) * @return java.lang.String */ public java.lang.String getComment() { return comment; } /** * Insert the method's description here. * Creation date: (29.09.2003 18:51:42) * @return java.lang.Boolean */ public java.lang.Boolean getCompleted() { return completed; } /** * Insert the method's description here. * Creation date: (29.05.2003 12:07:29) * @return int */ public int getDivcode() { return divcode; } /** * Insert the method's description here. * Creation date: (14.11.2003 14:52:35) * @return int */ public int getDivcol() { return divcol; } /** * Insert the method's description here. * Creation date: (29.09.2003 18:53:01) * @return java.sql.Date */ public java.sql.Date getFactdate() { return factdate; } /** * Insert the method's description here. * Creation date: (13.10.2003 12:02:39) * @return java.lang.String */ public java.lang.String getHeadername() { return headername; } /** * Insert the method's description here. * Creation date: (13.10.2003 11:10:36) * @return java.lang.Boolean */ public java.lang.Boolean getIsNewplandate() { return isNewplandate; } /** * Insert the method's description here. * Creation date: (05.01.2004 12:29:15) * @return java.lang.String */ public java.lang.String getNotes() { return notes; } /** * Insert the method's description here. * Creation date: (18.06.2003 12:06:06) * @return java.lang.String */ public java.lang.String getObjtype() { return objtype; } /** * Insert the method's description here. * Creation date: (29.09.2003 18:53:15) * @return java.sql.Date */ public java.sql.Date getPlandate() { return plandate; } /** * Insert the method's description here. * Creation date: (29.09.2003 18:51:00) * @return int */ public int getProjectaction() { return projectaction; } /** * Insert the method's description here. * Creation date: (26.12.2003 16:35:32) * @return int */ public int getProjectactiontype() { return projectactiontype; } /** * Insert the method's description here. * Creation date: (05.01.2004 16:01:29) * @return int */ public int getProjectcode() { return projectcode; } /** * Insert the method's description here. * Creation date: (13.10.2003 11:09:40) * @return java.sql.Date */ public java.sql.Date getSuggplandate() { return suggplandate; } /** * Insert the method's description here. * Creation date: (18.06.2003 14:02:53) * @return java.lang.String */ public java.lang.String getUsercolval() { return usercolval; } /** * Insert the method's description here. * Creation date: (29.09.2003 18:52:34) * @return boolean */ public boolean isHasproblems() { return hasproblems; } /** * Insert the method's description here. * Creation date: (29.09.2003 18:52:03) * @param newAgreement java.lang.Boolean */ public void setAgreement(java.lang.Boolean newAgreement) { agreement = newAgreement; } /** * Insert the method's description here. * Creation date: (29.05.2003 12:09:40) * @param newComment java.lang.String */ public void setComment(java.lang.String newComment) { comment = newComment; } /** * Insert the method's description here. * Creation date: (29.09.2003 18:51:42) * @param newCompleted java.lang.Boolean */ public void setCompleted(java.lang.Boolean newCompleted) { completed = newCompleted; } /** * Insert the method's description here. * Creation date: (29.05.2003 12:07:29) * @param newDivcode int */ public void setDivcode(int newDivcode) { divcode = newDivcode; } /** * Insert the method's description here. * Creation date: (14.11.2003 14:52:35) * @param newDivcol int */ public void setDivcol(int newDivcol) { divcol = newDivcol; } /** * Insert the method's description here. * Creation date: (29.09.2003 18:53:01) * @param newFactdate java.sql.Date */ public void setFactdate(java.sql.Date newFactdate) { factdate = newFactdate; } /** * Insert the method's description here. * Creation date: (29.09.2003 18:52:34) * @param newHasproblems boolean */ public void setHasproblems(boolean newHasproblems) { hasproblems = newHasproblems; } /** * Insert the method's description here. * Creation date: (13.10.2003 12:02:39) * @param newHeadername java.lang.String */ public void setHeadername(java.lang.String newHeadername) { headername = newHeadername; } /** * Insert the method's description here. * Creation date: (13.10.2003 11:10:36) * @param newIsNewplandate java.lang.Boolean */ public void setIsNewplandate(java.lang.Boolean newIsNewplandate) { isNewplandate = newIsNewplandate; } /** * Insert the method's description here. * Creation date: (05.01.2004 12:29:15) * @param newNotes java.lang.String */ public void setNotes(java.lang.String newNotes) { notes = newNotes; } /** * Insert the method's description here. * Creation date: (18.06.2003 12:06:06) * @param newObjtype java.lang.String */ public void setObjtype(java.lang.String newObjtype) { objtype = newObjtype; } /** * Insert the method's description here. * Creation date: (29.09.2003 18:53:15) * @param newPlandate java.sql.Date */ public void setPlandate(java.sql.Date newPlandate) { plandate = newPlandate; } /** * Insert the method's description here. * Creation date: (29.09.2003 18:51:00) * @param newProjectaction int */ public void setProjectaction(int newProjectaction) { projectaction = newProjectaction; } /** * Insert the method's description here. * Creation date: (26.12.2003 16:35:32) * @param newProjectactiontype int */ public void setProjectactiontype(int newProjectactiontype) { projectactiontype = newProjectactiontype; } /** * Insert the method's description here. * Creation date: (05.01.2004 16:01:29) * @param newProjectcode int */ public void setProjectcode(int newProjectcode) { projectcode = newProjectcode; } /** * Insert the method's description here. * Creation date: (13.10.2003 11:09:40) * @param newSuggplandate java.sql.Date */ public void setSuggplandate(java.sql.Date newSuggplandate) { suggplandate = newSuggplandate; } /** * Insert the method's description here. * Creation date: (18.06.2003 14:02:53) * @param newUsercolval java.lang.String */ public void setUsercolval(java.lang.String newUsercolval) { usercolval = newUsercolval; } }
true
581fdcc20504fba1d1cf7273f1f032385172f47b
Java
colin314/FamilyMapServer
/src/Result/EventIDResponse.java
UTF-8
306
1.929688
2
[]
no_license
package Result; import Model.Event; import com.sun.java.accessibility.util.EventID; public class EventIDResponse extends Event { public EventIDResponse() { super(); } public EventIDResponse(Event event) { super(event); success = true; } boolean success; }
true
d868f308d4174aa1a56eabf0f137693a1ff8a44a
Java
ganguixu/videos
/src/test/java/cn/ggx/test/UserDaoTest.java
UTF-8
2,394
2.234375
2
[]
no_license
package cn.ggx.test; import cn.ggx.dao.UserDao; import cn.ggx.entity.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring/*.xml"}) public class UserDaoTest { @Autowired UserDao userDao; // @Test // public void test1() { // // User user = new User(); // user.setCreateTime(new Date()); // user.setMobile("13262900562"); // user.setEmail("ganguixu@fescoadecco.com"); // user.setPassword("123"); // user.setVipFlag(0); // // int code = userDao.addUser(user); // System.out.println(code); // // } // // @Test // public void test2() { // // HashMap<String, Object> map = new HashMap<String, Object>(); // map.put("password", "123"); // // List<User> user = userDao.findUserAll(); // System.out.println(user); // } // @Test // public void test3(){ // HashMap<String,String> map = new HashMap<String, String>(); // map.put("email","ganguixu@fescoadecco.com"); // List<User> userByEmail = userDao.findUserByEmail(map); // System.out.println(userByEmail); // } @Test public void test4(){ List<User> list = new ArrayList<User>(); User user1 = new User("zhouxiaolong@fescoadecco.com","1234","13278121254",0,new Date()); User user2 = new User("yinyangyang@fescoadecco.com","4567","15878121254",0,new Date()); list.add(user1); list.add(user2); int i = userDao.addUsers(list); System.out.println(i); } // @Test // public void test5(){ // List<User> list = new ArrayList<User>(); // User user = new User(1,"zhuyuanji@fescoadecco.com","999",null,null,null); // list.add(user); // int i = userDao.updateUsers(list); // System.out.println(i); // } // @Test // public void test3() { // // HashMap<String, Object> map = new HashMap<String, Object>(); // map.put("password", "321456"); // map.put("id", "1"); // // int code = userDao.updateUser(map); // System.out.println(code); // } }
true
b602fa8d17b7e2c40b18abd5e172bc3e43d69f31
Java
chenxiaozj/oddjob
/src/main/java/org/oddjob/beanbus/mega/MegaBeanBusInterceptor.java
UTF-8
1,068
2.03125
2
[ "BSD-2-Clause" ]
permissive
package org.oddjob.beanbus.mega; import org.oddjob.arooa.ArooaConfigurationException; import org.oddjob.arooa.ArooaSession; import org.oddjob.arooa.ParsingInterceptor; import org.oddjob.arooa.life.ClassResolverClassLoader; import org.oddjob.arooa.parsing.ArooaContext; import org.oddjob.arooa.parsing.SessionOverrideContext; /** * A {@link ParsingInterceptor} provided by a {@link MegaBeanBus} to * provide specialised parsing of the configuration to * allow bean bus elements to be used. * * @author rob * */ public class MegaBeanBusInterceptor implements ParsingInterceptor { @Override public ArooaContext intercept(ArooaContext suggestedContext) throws ArooaConfigurationException { ArooaSession existingSession = suggestedContext.getSession(); ArooaSession session = new MegaBusSessionFactory().createSession( existingSession, new ClassResolverClassLoader( existingSession.getArooaDescriptor( ).getClassResolver())); return new SessionOverrideContext(suggestedContext, session); } }
true
f15207e8bc1e9ac63fc9ecadf4ee164d5ccf7ee3
Java
Sdreamery/Eyuan
/src/com/eyuan/filter/LoginIntercept.java
UTF-8
4,160
2.8125
3
[]
no_license
package com.eyuan.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.eyuan.po.UserInfoPo; import com.eyuan.util.StringUtil; /** * 非法拦截与自动登录 * 什么时候该放行 * 1、指定资源 放行 (静态资源html、js、css、images) * 2、指定页面 放行 (登录页面、注册页面 --- 不需要登录就能访问的页面都放行) * 3、指定行为 放行 (登录操作、自动登录操作、注册操作) * 4、登录状态 放行 (对应的session作用域中是否有值 user对象) * 5、判断cookie是否为空 * 如果cookie不为空,得到用户名和密码,调用登录方法 * 拦截之后做什么 * 跳转到登录页面 * @author 威威 * */ @WebFilter("/*") public class LoginIntercept implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("拦截器初始化~~~"); } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { //基于HTTP协议,所以先转化类型 HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; // 得到请求的路径,得到站点名+资源路径 String requestUri = request.getRequestURI(); //放行无需登陆就能查看的界面 if (requestUri.contains("/mall") || requestUri.contains("/index") || requestUri.contains("/product") || requestUri.contains("other")) { chain.doFilter(request, response); return ; } //放行鼠标移入购物车请求详情 if ("cartList".equals(request.getParameter("action"))) { chain.doFilter(request, response); return ; } // 放行指定资源 (静态资源 html、js、css、images) if (requestUri.contains("/statics")) { chain.doFilter(request, response); return ; } // 放行指定页面 (登录页面、注册页面 --- 不需要登录就能访问的页面都放行) if (requestUri.indexOf("/login.jsp") != -1||requestUri.indexOf("/register.jsp") != -1) { chain.doFilter(request, response); return ; } // 放行指定行为 action (登录操作、自动登录操作) String action = request.getParameter("action"); if (requestUri.contains("/user")&&!requestUri.contains("/user.jsp")) { if (!requestUri.contains("/userOrder")){ chain.doFilter(request, response); return ; } } // 登录状态 放行 (session作用域中的user对象不为空) UserInfoPo user = (UserInfoPo) request.getSession().getAttribute("user"); if (user != null) { chain.doFilter(request, response); return ; } /** 判断cookie是否为空 如果cookie不为空, * 得到用户名和密码,调用自动登录方法 * 获取Cookie对象,可能不止一个 * 判断cookies是否为空 */ Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length >0) { for (Cookie cookie : cookies) {//遍历一个个Cookie对象 //拿到cookie名为user的cookie String uname = cookie.getName(); if ("user".equals(uname)) { String value = cookie.getValue(); if (StringUtil.isEmpty(value)) { response.sendRedirect("login.jsp"); return ; } else { //获取用户名和密码 String userName = value.split("-")[0]; String userPwd = value.split("-")[1]; //调用自动登录方法 request.getRequestDispatcher("user?action=login&userName=" + userName + "&userPwd=" + userPwd).forward(request, response); return ; } } } } //拦截跳转到登录页面 response.sendRedirect("login.jsp"); } @Override public void destroy() { System.out.println("拦截器被销毁~~~"); } }
true