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
497e9a5c73ec61c4f9564c847a616909525d6905
Java
Samrus-10/Sber_second
/src/main/java/sam/rus/MyHttpServer/model/Rules.java
UTF-8
687
2.75
3
[]
no_license
package sam.rus.MyHttpServer.model; public enum Rules { VISITOR("visitor"), USER("user"), ADMIN("admin"); private java.lang.String rule; Rules(java.lang.String rule) { this.rule = rule; } public boolean chek(String str){ boolean result = false; if(str.equals("visitor")){ if (this.rule.equals("visitore")) { result = true; } }else if(str.equals("user")){ if (this.rule.equals("visitore") || this.rule.equals("user")) { result = true; } }else if(str.equals("admin")){ result = true; } return result; } }
true
b5d602618802703af1be50d94659e64584fc8855
Java
Agnieszka-Kulig/weight
/src/Animal.java
UTF-8
880
3.734375
4
[]
no_license
public class Animal { final static Double MIN_WEIGHT = 2.0; private Double weight = 6.0; final public String species; public Boolean isAlive = true; public Animal(String species) { this.species = species; } void feed(Double foodWeight) { if (this.isAlive) { this.weight += foodWeight; System.out.println("It was for good. It will be fat"); } else { System.out.println("Too late, the dog dead"); } } void takeForAWalk() { if (this.isAlive) { this.weight--; System.out.println("The walks are great"); if (this.weight < MIN_WEIGHT) { this.isAlive = false; } } else { System.out.println("Not have power"); } } Double getWeight() { return weight; } }
true
a9639e965b2458a03a159cfb807c047d477c1b26
Java
mboysan/jbizur
/jbizur-bizur/src/main/java/ee/ut/jbizur/protocol/commands/net/ApiSet_NC.java
UTF-8
736
2.03125
2
[ "MIT" ]
permissive
package ee.ut.jbizur.protocol.commands.net; import java.io.Serializable; public class ApiSet_NC extends MapRequest_NC { {setRequest(true);} private Serializable key; private Serializable val; public Serializable getKey() { return key; } public ApiSet_NC setKey(Serializable key) { this.key = key; return this; } public Serializable getVal() { return val; } public ApiSet_NC setVal(Serializable val) { this.val = val; return this; } @Override public String toString() { return "ApiSet_NC{" + "key='" + key + '\'' + ", val='" + val + '\'' + "} " + super.toString(); } }
true
7e675fc2e7b3793a4d29b313f2985ba316f80fed
Java
guo224/LeavePlatform
/LeavePlatform-Web/src/test/java/leave/test/areaTest.java
UTF-8
557
2.0625
2
[]
no_license
package leave.test; import leave.interfaces.IAreaService; import leave.model.object.Area; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; /** * Created by 白嘿嘿黑 on 2018/4/8. */ public class areaTest extends TestBase { @Autowired private IAreaService iAreaService; @Test public void test1(){ Area area = new Area(); area.setId("234"); area.setAreaName("12"); area.setAreaId("23"); iAreaService.insert(area); System.out.println("Over"); } }
true
671ba1a785b727283270079796cfc6bebfcc6b2f
Java
zloff007/javaJunior15012019
/src/lesson15/SetUtils.java
UTF-8
1,691
3.59375
4
[]
no_license
package lesson15; import java.util.Collection; import java.util.Set; import java.util.SortedSet; /** * Утилитный класс для работы с множествами * * @author nedis * @version 1.0 */ public interface SetUtils { /** * Возвращает отсортированное множество в обратном порядке (по убыванию) как объединение двух коллекций * collection1 - коллекция чисел (Нужно привести каждое число к строковому представлению) и set2 - множество * неотсортированных строк * * @param colection1 коллекция чисел * @param set2 множество неотсортированных строк * @return отсортированное множество в обратном порядке * @throws NullPointerException если collection1 или set2 == null */ SortedSet<String> orderedSet(Collection<Integer> collection1, Set<String> set2) throws NullPointerException; /** * Возвращает множество чисел val1,val2,val3,val4,val5 в таком же порядке * * @param val1 аргумент функции * @param val2 аргумент функции * @param val3 аргумент функции * @param val4 аргумент функции * @param val5 аргумент функции * @return упорядоченное множество в заданном порядке */ Set<Integer> customOrderSet(int val1, int val2, int val3, int val4, int val5); }
true
55e8e45aed4c14b9c61940ae22b884fdbfa481eb
Java
fr0stf0x/Air-Messenger
/app/src/main/java/it/tdt/edu/vn/airmessenger/fragments/UserListFragment.java
UTF-8
12,213
1.765625
2
[]
no_license
package it.tdt.edu.vn.airmessenger.fragments; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.support.v7.view.ActionMode; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.Query; import com.google.firebase.firestore.QuerySnapshot; import java.util.List; import java.util.Locale; import it.tdt.edu.vn.airmessenger.AllUsersActivity; import it.tdt.edu.vn.airmessenger.App; import it.tdt.edu.vn.airmessenger.ChatActivity; import it.tdt.edu.vn.airmessenger.MainActivity; import it.tdt.edu.vn.airmessenger.R; import it.tdt.edu.vn.airmessenger.UserInfoActivity; import it.tdt.edu.vn.airmessenger.adapters.UserAdapter; import it.tdt.edu.vn.airmessenger.interfaces.OnUserClickListener; import it.tdt.edu.vn.airmessenger.models.Conversation; import it.tdt.edu.vn.airmessenger.models.User; public class UserListFragment extends Fragment implements OnUserClickListener { public static String COLLECTION_NAME = "friends"; public static final String TAG = "User_list_fragment"; public static final int USERS_FLAG = 1; public static final int FRIENDS_FLAG = 0; private int flag = FRIENDS_FLAG; private ActionMode mActionMode; public static final int LIMIT = 50; FirebaseUser user; FirebaseFirestore db; RecyclerView rvContacts; TextView tvEmptyList; UserAdapter adapter; Query mQuery; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onAttach(Context context) { super.onAttach(context); user = FirebaseAuth.getInstance().getCurrentUser(); db = FirebaseFirestore.getInstance(); if (context instanceof AllUsersActivity) { flag = USERS_FLAG; } } @Override public void onStart() { super.onStart(); if (adapter != null) { adapter.startListening(); } } @Override public void onStop() { super.onStop(); if (adapter != null) { adapter.stopListening(); } } @Override public void onItemSelected(int position) { adapter.toggleSelection(position);//Toggle the selection Toast.makeText(App.getContext(), "Selected " + position, Toast.LENGTH_SHORT).show(); boolean hasCheckedItems = adapter.getSelectedCount() > 0;//Check if any items are already selected or not if (hasCheckedItems && mActionMode == null) // there are some selected items, start the actionMode mActionMode = ((MainActivity) getContext()).startSupportActionMode(new UserActionModeCallBack() { @Override public void onDestroyActionMode(ActionMode mode) { adapter.removeSelection(); Log.d(TAG, "onDestroyActionMode: setNullToActionMode"); setNullToActionMode(); } }); else if (!hasCheckedItems && mActionMode != null) // there no selected items, finish the actionMode mActionMode.finish(); if (mActionMode != null) //set action mode title on item selection mActionMode.setTitle(String.valueOf(adapter .getSelectedCount())); } @Override public void onUserClick(int position) { Log.d(TAG, "onMessageClicked: At " + position); if (mActionMode != null) { onItemSelected(position); } else { startActivity(adapter.getSnapshot(position)); } } private void startActivity(DocumentSnapshot user) { String userId = user.getId(); Intent intent; switch (flag) { case USERS_FLAG: intent = new Intent(getContext(), UserInfoActivity.class); startIntentWithExtra(intent, userId); break; default: // jump to chat activity intent = new Intent(getContext(), ChatActivity.class); putExtrasAndStart(intent, userId); break; } } @Override public boolean onUserLongClick(int position) { Log.d(TAG, "onUserLongClick: At " + position); onItemSelected(position); return true; } public void setNullToActionMode() { if (mActionMode != null) { Log.d(TAG, "setNullToActionMode: Completed"); mActionMode = null; } } class UserActionModeCallBack implements ActionMode.Callback, DialogInterface.OnClickListener { final String TAG = "ActionModeCallBack"; SparseBooleanArray selected; int selectedItemSize; public UserActionModeCallBack() { } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { mode.getMenuInflater().inflate(R.menu.conversation_menu, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return true; } @Override public boolean onActionItemClicked(final ActionMode mode, MenuItem item) { selected = adapter.getSelectedIds(); selectedItemSize = selected.size(); switch (item.getItemId()) { case R.id.action_delete: String arg = selectedItemSize > 1 ? getString(R.string.arg_users) : getString(R.string.arg_user); createDialog( String.format(Locale.getDefault(), getString(R.string.delete_alert), arg)).show(); mode.finish(); break; case R.id.action_fav: Toast.makeText(App.getContext(), "Function 'favorite' is WIP", Toast.LENGTH_SHORT) .show(); mode.finish(); break; } return true; } private void deleteSelected() { for (int i = (selected.size() - 1); i >= 0; i--) { if (selected.valueAt(i)) { //get selected data in Model Log.d(TAG, "onActionItemClicked: index " + i); DocumentSnapshot conversation = adapter.getSnapshot(i); Conversation.deleteConversation( conversation.getId(), user.getUid(), conversation.getString(User.FIELD_CHAT_WITH) ); } } } private AlertDialog createDialog(String alertString) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); AlertDialog dialog; dialog = builder .setMessage(alertString) .setPositiveButton( R.string.delete_okay, this) .setNegativeButton( R.string.cancel, this) .create(); return dialog; } @Override public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_NEGATIVE) { dialog.dismiss(); } else if (which == DialogInterface.BUTTON_POSITIVE) { deleteSelected(); dialog.dismiss(); } } @Override public void onDestroyActionMode(ActionMode mode) { } } private void startIntentWithExtra(Intent intent, String userId) { intent.putExtra(User.USER_ID_KEY, userId); startActivity(intent); } private void putExtrasAndStart(final Intent intent, final String receiverId) { db.collection(User.COLLECTION_NAME) .document(this.user.getUid()) .collection(Conversation.COLLECTION_NAME) .whereEqualTo(User.FIELD_CHAT_WITH, receiverId) .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { List<DocumentSnapshot> result = task.getResult().getDocuments(); if (result.size() > 1) { Log.d(TAG, "onComplete: ERROR - More than 1 conversation"); return; } if (result.size() == 1) { String chatId = result.get(0).getId(); intent.putExtra(Conversation.CONVERSATION_ID_KEY, chatId); Log.d(TAG, "onComplete: There 1 conversation: " + chatId); } startIntentWithExtra(intent, receiverId); } } }); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.contact_list_layout, container, false); } @Override public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); tvEmptyList = view.findViewById(R.id.tvEmptyList); rvContacts = view.findViewById(R.id.userList); if (user != null) { switch (flag) { case FRIENDS_FLAG: mQuery = db.collection(User.COLLECTION_NAME) .document(user.getUid()).collection(COLLECTION_NAME); Log.d(TAG, "Case friends"); break; case USERS_FLAG: mQuery = db.collection(User.COLLECTION_NAME); Log.d(TAG, "Case users"); break; } adapter = new UserAdapter(mQuery, this, flag) { @Override protected void onDataChanged() { if (flag == FRIENDS_FLAG) { if (getItemCount() == 0) { rvContacts.setVisibility(View.GONE); tvEmptyList.setVisibility(View.VISIBLE); } else { rvContacts.setVisibility(View.VISIBLE); tvEmptyList.setVisibility(View.GONE); } } } @Override protected void onError(FirebaseFirestoreException e) { Log.d(TAG, "Error: check logs for info."); rvContacts.setVisibility(View.GONE); tvEmptyList.setVisibility(View.GONE); } }; rvContacts.setAdapter(adapter); rvContacts.setLayoutManager(new LinearLayoutManager(getContext())); } } }
true
e74f2b8cad8fa5d1260996abda4c73f22c6417fe
Java
Slycir/DukeTIPAI
/Otto/Fun.java
UTF-8
371
3.09375
3
[]
no_license
import java.util.Scanner; public class fun { public static void main(String[] args) { Scanner in; in = new Scanner(System.in); System.out.println("Enter a word:"); String response = in.nextString(); lineSpace(); System.ou.println(response); }//main public static void lineSpace() { System.out.println(" "); }//lineSpace }//Fun
true
f0b0dde049afce77827f9d984096176cf2eaf894
Java
rparias/restaurante-is2
/restaurante-backend/src/main/java/com/ronaldarias/ppmtool/services/ParametroService.java
UTF-8
1,533
2.546875
3
[]
no_license
package com.ronaldarias.ppmtool.services; import com.ronaldarias.ppmtool.domain.Parametro; import com.ronaldarias.ppmtool.exceptions.ProjectIdException; import com.ronaldarias.ppmtool.repositories.ParametroRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class ParametroService { @Autowired private ParametroRepository parametroRepository; public Parametro saveOrUpdateParametro(Parametro parametro) { try { return parametroRepository.save(parametro); } catch (Exception ex) { throw new ProjectIdException("Parametro ID " + parametro.getIdParametro() + " already exists"); } } public Parametro findParametroById(Integer parametroId) { Parametro parametro = parametroRepository.findById(parametroId) .orElse(null); if (parametro == null) { throw new ProjectIdException("Parametro ID " + parametroId + " does not exist"); } return parametro; } public Iterable<Parametro> findAllParametros() { return parametroRepository.findAll(); } public void deleteParametroById(Integer parametroId) { Parametro parametro = parametroRepository.findById(parametroId) .orElse(null); if (parametro == null) { throw new ProjectIdException("Parametro ID " + parametroId + " does not exist"); } parametroRepository.delete(parametro); } }
true
49124e4cb8295827c2434abfa00bf3511b2e33ac
Java
kralovek/kkr.ktm
/src/main/java/kkr/ktm/domains/excel/components/structureloader/base/SystemParameter.java
UTF-8
171
1.679688
2
[]
no_license
package kkr.ktm.domains.excel.components.structureloader.base; public enum SystemParameter { ACTIVE, CODE, DESCRIPTION, NAME, ORDER, GROUP, STATUS, DYNSTATUS }
true
13b04a2ee7c428fe315d50a49cd70256c0f185c4
Java
SanyaKolesnik/Exam
/src/test/java/imdb/Constants.java
UTF-8
254
2.015625
2
[]
no_license
package imdb; /** * Created by stale on 20.11.2016. */ public class Constants { public static final int DEFAULT_WAIT_TIME = 50; public static final int DEFAULT_WAIT_SHORT_TIME = 5; public static final int DEFAULT_WAIT_LONG_TIME = 120; }
true
a3bbc93a5c1b04761ee4563a03610bdf065e29a2
Java
Projecto2/PFII
/SIG_HDP_Master/SIG_HDP_Master-ejb/src/java/entidade/SupiSupervisorHasEscala.java
UTF-8
5,801
1.828125
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 entidade; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.UniqueConstraint; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author amed */ @Entity @Table(name = "supi_supervisor_has_escala", catalog = "sigh_db", schema = "public", uniqueConstraints = { @UniqueConstraint(columnNames = {"data", "fk_id_escala", "fk_id_funcionario"})}) @XmlRootElement @NamedQueries({ @NamedQuery(name = "SupiSupervisorHasEscala.findAll", query = "SELECT s FROM SupiSupervisorHasEscala s"), @NamedQuery(name = "SupiSupervisorHasEscala.findByPkIdFuncionarioSupervisionaEscala", query = "SELECT s FROM SupiSupervisorHasEscala s WHERE s.pkIdFuncionarioSupervisionaEscala = :pkIdFuncionarioSupervisionaEscala"), @NamedQuery(name = "SupiSupervisorHasEscala.findByObservacao", query = "SELECT s FROM SupiSupervisorHasEscala s WHERE s.observacao = :observacao"), @NamedQuery(name = "SupiSupervisorHasEscala.findByData", query = "SELECT s FROM SupiSupervisorHasEscala s WHERE s.data = :data")}) public class SupiSupervisorHasEscala implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "pk_id_funcionario_supervisiona_escala", nullable = false) private Integer pkIdFuncionarioSupervisionaEscala; @Size(max = 2147483647) @Column(name = "observacao", length = 2147483647) private String observacao; @Basic(optional = false) @NotNull @Column(name = "data", nullable = false) @Temporal(TemporalType.DATE) private Date data; @JoinColumn(name = "fk_id_enfermaria", referencedColumnName = "pk_id_enfermaria") @ManyToOne private InterEnfermaria fkIdEnfermaria; @JoinColumn(name = "fk_id_funcionario", referencedColumnName = "pk_id_funcionario", nullable = false) @ManyToOne(optional = false) private RhFuncionario fkIdFuncionario; @JoinColumn(name = "fk_id_escala", referencedColumnName = "pk_id_escala", nullable = false) @ManyToOne(optional = false) private SupiEscala fkIdEscala; @JoinColumn(name = "fk_id_turno", referencedColumnName = "pk_id_turno") @ManyToOne private SupiTurno fkIdTurno; public SupiSupervisorHasEscala() { } public SupiSupervisorHasEscala(Integer pkIdFuncionarioSupervisionaEscala) { this.pkIdFuncionarioSupervisionaEscala = pkIdFuncionarioSupervisionaEscala; } public SupiSupervisorHasEscala(Integer pkIdFuncionarioSupervisionaEscala, Date data) { this.pkIdFuncionarioSupervisionaEscala = pkIdFuncionarioSupervisionaEscala; this.data = data; } public Integer getPkIdFuncionarioSupervisionaEscala() { return pkIdFuncionarioSupervisionaEscala; } public void setPkIdFuncionarioSupervisionaEscala(Integer pkIdFuncionarioSupervisionaEscala) { this.pkIdFuncionarioSupervisionaEscala = pkIdFuncionarioSupervisionaEscala; } public String getObservacao() { return observacao; } public void setObservacao(String observacao) { this.observacao = observacao; } public Date getData() { return data; } public void setData(Date data) { this.data = data; } public InterEnfermaria getFkIdEnfermaria() { return fkIdEnfermaria; } public void setFkIdEnfermaria(InterEnfermaria fkIdEnfermaria) { this.fkIdEnfermaria = fkIdEnfermaria; } public RhFuncionario getFkIdFuncionario() { return fkIdFuncionario; } public void setFkIdFuncionario(RhFuncionario fkIdFuncionario) { this.fkIdFuncionario = fkIdFuncionario; } public SupiEscala getFkIdEscala() { return fkIdEscala; } public void setFkIdEscala(SupiEscala fkIdEscala) { this.fkIdEscala = fkIdEscala; } public SupiTurno getFkIdTurno() { return fkIdTurno; } public void setFkIdTurno(SupiTurno fkIdTurno) { this.fkIdTurno = fkIdTurno; } @Override public int hashCode() { int hash = 0; hash += (pkIdFuncionarioSupervisionaEscala != null ? pkIdFuncionarioSupervisionaEscala.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof SupiSupervisorHasEscala)) { return false; } SupiSupervisorHasEscala other = (SupiSupervisorHasEscala) object; if ((this.pkIdFuncionarioSupervisionaEscala == null && other.pkIdFuncionarioSupervisionaEscala != null) || (this.pkIdFuncionarioSupervisionaEscala != null && !this.pkIdFuncionarioSupervisionaEscala.equals(other.pkIdFuncionarioSupervisionaEscala))) { return false; } return true; } @Override public String toString() { return "entidade.SupiSupervisorHasEscala[ pkIdFuncionarioSupervisionaEscala=" + pkIdFuncionarioSupervisionaEscala + " ]"; } }
true
4ae9ad0e8e88570a252b1d19057794cc75399cff
Java
parthrai/ajmer_java
/A1Q2.java
UTF-8
848
3
3
[]
no_license
/** Assignment 1 Question 2 * COMP 1006/1406 - Fall 2021 * * Peaks */ public class A1Q2{ public static double[][] peaks(double[] data, double epsilon){ /* All input arguments must satisfy. We will only use valid input arguments when testing your code. data: 0 <= data.length <= Integer.MAX_VALUE epsilon: epsilon > 0.0 */ // this will be your output array double[][] out = null; // add your code here! return out; } // You are NOT asked to write a program so this following main // method is not needed. However, you CAN write code here to help // test your methods. Just be sure that whatever you add here does not // public static void main(String[] args){ } }
true
630ae2f2433adbe78c55ebee118abf618b1b8c1b
Java
mwilliams7197/calcite-kudu
/adapter/src/main/java/com/twilio/kudu/sql/rules/KuduNestedJoinRule.java
UTF-8
6,954
1.835938
2
[ "Apache-2.0" ]
permissive
/* Copyright 2020 Twilio, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twilio.kudu.sql.rules; import java.util.EnumSet; import com.twilio.kudu.sql.KuduQuery; import com.twilio.kudu.sql.rel.KuduFilterRel; import com.twilio.kudu.sql.rel.KuduLimitRel; import com.twilio.kudu.sql.rel.KuduNestedJoin; import com.twilio.kudu.sql.rel.KuduProjectRel; import com.twilio.kudu.sql.rel.KuduSortRel; import com.twilio.kudu.sql.rel.KuduToEnumerableRel; import org.apache.calcite.plan.RelOptRule; import org.apache.calcite.plan.RelOptRuleCall; import org.apache.calcite.plan.RelOptRuleOperand; import org.apache.calcite.rel.core.Join; import org.apache.calcite.rel.core.JoinRelType; import org.apache.calcite.rex.RexCall; import org.apache.calcite.rex.RexInputRef; import org.apache.calcite.rex.RexNode; import org.apache.calcite.rex.RexVisitor; import org.apache.calcite.rex.RexVisitorImpl; import org.apache.calcite.sql.SqlKind; import org.apache.calcite.tools.RelBuilderFactory; public class KuduNestedJoinRule extends RelOptRule { public final static EnumSet<SqlKind> VALID_CALL_TYPES = EnumSet.of(SqlKind.EQUALS, SqlKind.GREATER_THAN, SqlKind.GREATER_THAN_OR_EQUAL, SqlKind.LESS_THAN, SqlKind.LESS_THAN_OR_EQUAL); public static final int DEFAULT_BATCH_SIZE = 100; private int batchSize; public KuduNestedJoinRule(final RelOptRuleOperand op, RelBuilderFactory relBuilderFactory, final String name, final int batchSize) { super(op, relBuilderFactory, name); this.batchSize = DEFAULT_BATCH_SIZE; } @Override public boolean matches(final RelOptRuleCall call) { final Join join = call.rel(0); if (join.getJoinType() != JoinRelType.INNER && join.getJoinType() != JoinRelType.LEFT) { return false; } final RexNode condition = join.getCondition(); final RexVisitor<Boolean> validateJoinCondition = new RexVisitorImpl<Boolean>(true) { @Override public Boolean visitCall(final RexCall rexCall) { final SqlKind callType = rexCall.getOperator().getKind(); if (callType == SqlKind.OR) { return Boolean.FALSE; } else if (callType == SqlKind.AND) { for (final RexNode operand : rexCall.operands) { final Boolean opResult = operand.accept(this); if (opResult == null || opResult.equals(Boolean.FALSE)) { return Boolean.FALSE; } } } else if (!VALID_CALL_TYPES.contains(callType)) { return Boolean.FALSE; } return Boolean.TRUE; } @Override public Boolean visitInputRef(final RexInputRef inputRef) { return Boolean.TRUE; } }; final Boolean isValid = condition.accept(validateJoinCondition); // @TODO: Hack for the moment. final boolean containsActorSid = join.getRight().getRowType().getFieldList().stream() .anyMatch(fl -> fl.getName().equalsIgnoreCase("actor_sid")); return isValid && containsActorSid; } @Override public void onMatch(final RelOptRuleCall call) { final Join join = call.rel(0); final JoinRelType joinType = join.getJoinType(); final KuduNestedJoin newJoin = KuduNestedJoin.create(join.getLeft(), join.getRight(), join.getCondition(), joinType, this.batchSize); call.transformTo(newJoin); } /** * Because our current cost calculation is so poor, we have to write rules that * target specific plans. These three rule target those plans. */ public static final class KuduNestedOverFilter extends KuduNestedJoinRule { public KuduNestedOverFilter(final RelBuilderFactory factory) { super( operand(Join.class, some( operand(KuduToEnumerableRel.class, some(operand(KuduProjectRel.class, some(operand(KuduFilterRel.class, some(operand(KuduQuery.class, none()))))))), operand(KuduToEnumerableRel.class, some(operand(KuduProjectRel.class, some(operand(KuduQuery.class, none()))))))), factory, "KuduNestedOverFilter", DEFAULT_BATCH_SIZE); } } public static final class KuduNestedOverSortAndFilter extends KuduNestedJoinRule { public KuduNestedOverSortAndFilter(final RelBuilderFactory factory) { super( operand(Join.class, some( operand(KuduToEnumerableRel.class, some(operand(KuduProjectRel.class, some(operand(KuduSortRel.class, some(operand(KuduFilterRel.class, some(operand(KuduQuery.class, none()))))))))), operand(KuduToEnumerableRel.class, some(operand(KuduProjectRel.class, some(operand(KuduQuery.class, none()))))))), factory, "KuduNestedOverSortAndFilter", DEFAULT_BATCH_SIZE); } } public static final class KuduNestedOverLimitAndFilter extends KuduNestedJoinRule { public KuduNestedOverLimitAndFilter(final RelBuilderFactory factory) { super( operand(Join.class, some( operand(KuduToEnumerableRel.class, some(operand(KuduProjectRel.class, some(operand(KuduLimitRel.class, some(operand(KuduFilterRel.class, some(operand(KuduQuery.class, none()))))))))), operand(KuduToEnumerableRel.class, some(operand(KuduProjectRel.class, some(operand(KuduQuery.class, none()))))))), factory, "KuduNestedOverLimitAndFilter", DEFAULT_BATCH_SIZE); } } public static final class KuduNestedOverLimitAndSortAndFilter extends KuduNestedJoinRule { public KuduNestedOverLimitAndSortAndFilter(final RelBuilderFactory factory) { super( operand(Join.class, some( operand(KuduToEnumerableRel.class, some(operand(KuduProjectRel.class, some(operand(KuduLimitRel.class, some(operand(KuduSortRel.class, some(operand(KuduFilterRel.class, some(operand(KuduQuery.class, none()))))))))))), operand(KuduToEnumerableRel.class, some(operand(KuduProjectRel.class, some(operand(KuduQuery.class, none()))))))), factory, "KuduNestedOverLimitAndSortAndFilter", DEFAULT_BATCH_SIZE); } } }
true
f3bd4d823cbde9c86155a27b0bd2deea8a17fca3
Java
Amro97/LMS
/LMS/src/View/Login.java
UTF-8
4,637
2.4375
2
[]
no_license
package View; import java.awt.EventQueue; import Model.Book; import Model.BookService; import Model.PanelService; import Model.Person; import Model.Subscriber; import Model.sqliteConnection; import java.sql.*; import java.util.List; import javax.swing.*; import Controller.LoginController; import java.awt.Font; import java.awt.Image; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Color; import java.awt.Button; public class Login { public JRadioButton rdbtnLibrarian; JRadioButton rdbtnSubscriber; public JFrame frame; public JTextField usernameField; public JPasswordField passwordField; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedLookAndFeelException e) { // TODO Auto-generated catch block e.printStackTrace(); } Login window = new Login(); window.frame.setVisible(true); } }); } //images Image img_login = new ImageIcon(this.getClass().getResource("/secrecy-icon.png")).getImage(); Image img_radioSubsc = new ImageIcon(this.getClass().getResource("/Subscriber.png")).getImage(); Image img_radiolibrarian = new ImageIcon(this.getClass().getResource("/Librarian.png")).getImage(); Image img_cover = new ImageIcon(this.getClass().getResource("/cover.jpg")).getImage(); /** * Create the application. */ public Login() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { LoginController controller = new LoginController(this);//this=login object frame = new JFrame("MA-Library Managment System"); frame.getContentPane().setBackground( new java.awt.Color(242, 244, 245) ); frame.setBounds(600, 300, 697, 428);//600, 300, 697, 428 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.getContentPane().setLayout(null); //User name text JLabel lblNewLabel = new JLabel("User name"); lblNewLabel.setForeground(Color.DARK_GRAY); lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 20)); //lblNewLabel.setForeground(Color.white); lblNewLabel.setBounds(330, 127, 122, 43); frame.getContentPane().add(lblNewLabel); //Password text JLabel lblNewLabel_1 = new JLabel("Password"); lblNewLabel_1.setForeground(Color.DARK_GRAY); lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 20)); lblNewLabel_1.setBounds(330, 175, 109, 50); frame.getContentPane().add(lblNewLabel_1); usernameField = new JTextField(); usernameField.setBounds(448, 127, 216, 43); frame.getContentPane().add(usernameField); usernameField.setColumns(10); JButton btnNewButton = new JButton("Login"); btnNewButton.setForeground(Color.DARK_GRAY); btnNewButton.setIcon(new ImageIcon(img_login)); btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 17)); btnNewButton.addActionListener(controller); btnNewButton.setBounds(448, 280, 216, 43); frame.getContentPane().add(btnNewButton); passwordField = new JPasswordField(); passwordField.setBounds(448, 183, 216, 40); frame.getContentPane().add(passwordField); rdbtnLibrarian = new JRadioButton("Librarian"); rdbtnLibrarian.setBounds(580, 69, 155, 29); frame.getContentPane().add(rdbtnLibrarian); rdbtnSubscriber = new JRadioButton("Subscriber"); rdbtnSubscriber.setSelected(true); rdbtnSubscriber.setBounds(450, 69, 155, 29); frame.getContentPane().add(rdbtnSubscriber); ButtonGroup bg1 = new ButtonGroup( );//group radio buttons bg1.add(rdbtnSubscriber); bg1.add(rdbtnLibrarian); //subscriber image JLabel lblNewLabel_2 = new JLabel(""); lblNewLabel_2.setForeground(Color.WHITE); lblNewLabel_2.setIcon(new ImageIcon(img_radioSubsc)); lblNewLabel_2.setBounds(450, 52, 80, 20);//354, 52, 69, 20 frame.getContentPane().add(lblNewLabel_2); JLabel label = new JLabel(""); label.setIcon(new ImageIcon(img_radiolibrarian)); label.setBounds(580, 52, 69, 20); frame.getContentPane().add(label); //Cover photo JLabel ImgLable = new JLabel(""); ImgLable.setIcon(new ImageIcon(img_cover)); ImgLable.setBounds(-20, 0, 711,428); frame.getContentPane().add(ImgLable); } }
true
fca620df0cda5185896cef38ed6debf2fffd4d86
Java
daanvdh/JavaForger
/src/test/java/common/AbstractFileChangingTest.java
UTF-8
6,118
2.609375
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2018 by Daan van den Heuvel. * * This file is part of JavaForger. * * 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 common; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Scanner; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import configuration.StaticJavaForgerConfiguration; /** * This abstract class creates a new file before each test which the extending test class can change within the test, so that the original file is not changed. * The newly created file is removed after the test is run. * * @author Daan */ public abstract class AbstractFileChangingTest { private static final String ORIGINAL_CLASS = "src/test/java/inputClassesForTests/ClassWithEverything.java"; private static final String ORIGINAL_TEST_CLASS = "src/test/java/inputClassesForTests/ClassWithEverythingTest.java"; protected static final String INPUT_CLASS = "src/test/resources/temporaryTestResults/ClassWithEverything.java"; protected static final String INPUT_TEST_CLASS = "src/test/resources/temporaryTestResults/ClassWithEverythingTest.java"; @Before public void setup() throws IOException { StaticJavaForgerConfiguration.reset(); SymbolSolverSetup.setup(); tearDown(); copyClass(getOriginalClass(), INPUT_CLASS); copyClass(getOriginalTestClass(), INPUT_TEST_CLASS); } @After public void tearDown() { StaticJavaForgerConfiguration.reset(); removeTestClassIfExists(INPUT_CLASS); removeTestClassIfExists(INPUT_TEST_CLASS); } protected void removeTestClassIfExists(String input) { File f = new File(input); if (f.exists() && !f.isDirectory()) { f.delete(); } } protected void copyClass(String input, String copyLocation) throws IOException, FileNotFoundException { File src = new File(input); File dest = new File(copyLocation); FileUtils.copyFile(src, dest); } protected String fileToString(String path) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded, StandardCharsets.UTF_8); } /** * Writes the content to the file given by path. * * @param path The path to the file to write to * @param content The content to fill the file with * @throws IOException */ protected void stringToFile(String path, String content) throws IOException { try (PrintWriter writer = new PrintWriter(path, "UTF-8")) { writer.write(content); } } protected void verifyFileEqual(String expectedPath, String actualPath) throws IOException { try (LineNumberReader reader1 = new LineNumberReader(new FileReader(expectedPath)); LineNumberReader reader2 = new LineNumberReader(new FileReader(actualPath))) { String line1 = reader1.readLine(); String line2 = reader2.readLine(); boolean equal = true; while (equal && line1 != null) { equal = line1.equals(line2); line1 = reader1.readLine(); line2 = reader2.readLine(); } equal = equal && line1 == null && line2 == null; if (!equal) { System.err.println("Actual file " + actualPath + ":"); printFile(new File(actualPath)); System.err.println("Expected file " + expectedPath + ":"); printFile(new File(expectedPath)); } Assert.assertTrue("Was not equal on line " + reader1.getLineNumber() + " expected: " + line1 + " actual: " + line2, equal); } } protected void printFile(File file) throws FileNotFoundException { try (Scanner input = new Scanner(file)) { while (input.hasNextLine()) { System.out.println(input.nextLine()); } } } protected String getOriginalClass() { return ORIGINAL_CLASS; } protected String getOriginalTestClass() { return ORIGINAL_TEST_CLASS; } /** * Method for precisely indicating which char in the two strings is the first that is not equal. Created because of the endless debugging for the different * line-endings. */ protected void verifyEquals(String expect, String result) { char[] e = expect.toCharArray(); char[] r = result.toCharArray(); byte[] eb = expect.getBytes(); byte[] rb = result.getBytes(); int i = 0; int ej = 1; int ei = 1; int rj = 1; int ri = 1; if (e.length != r.length) { System.out.println("expected as length " + e.length + " but actual as length " + r.length); } for (; i < e.length && i < r.length; i++) { if (!(e[i] == r[i]) && !((e[i] == '\r' || e[i] == '\n') && (r[i] == '\r' || r[i] == '\n'))) { System.out.println("first occurance of not equal string at index " + i + ":"); System.out.println("at line " + ej + " and column " + ei + " expect char: " + e[i]); System.out.println("at line " + rj + " and column " + ri + " actual char: " + r[i]); System.out.println("at line " + ej + " and column " + ei + " expect byte: " + eb[i]); System.out.println("at line " + rj + " and column " + ri + " actual byte: " + rb[i]); System.out.println("actual: "); break; } ej = e[i] == '\n' || e[i] == '\r' ? ej + 1 : ej; rj = r[i] == '\n' || r[i] == '\r' ? rj + 1 : rj; ei = e[i] == '\n' || e[i] == '\r' ? 1 : ei + 1; ri = r[i] == '\n' || r[i] == '\r' ? 1 : ri + 1; } } }
true
30439de204282fc3d59bafb8273a6a968dae0794
Java
desstiony/LeetCodePractice
/234. Palindrome Linked List/Solution_234.java
UTF-8
2,430
3.78125
4
[]
no_license
/** * @author: Mr. Gong * @date: 2020/4/4 * @description: 234. 回文链表 * * 请判断一个链表是否为回文链表。 * 示例 1: * * 输入: 1->2 * 输出: false * 示例 2: * * 输入: 1->2->2->1 * 输出: true * 进阶: * 你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题? * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/palindrome-linked-list * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class Solution_234 { static class ListNode { int val; ListNode next; ListNode(int x) { val = x; } @Override public String toString() { return val + "->" + (next == null ? "NULL" : next); } } public boolean isPalindrome(ListNode head) { if (head == null || head.next == null) { return true; } ListNode fast = head, slow = head, prev = null, curr; while (fast != null && fast.next != null) { // 当前节点即为慢指针指向节点 curr = slow; // 快指针后移两位, 判断何时跳出循环 fast = fast.next.next; // 慢指针后移一位 slow = slow.next; // 翻转 // 当前节点下next 指向 上一个节点 curr.next = prev; // 当前节点赋值给上一个节点, prev 前移 prev = curr; } System.out.println("swap: \n " + prev); // 奇数情况,跳过中位数 if (fast != null) { // 跳过 slow = slow.next; } while (prev != null) { if (prev.val != slow.val) { return false; } prev = prev.next; slow = slow.next; } return true; } public static void main(String[] args) { ListNode l1 = new ListNode(1); l1.next = new ListNode(2); l1.next.next = new ListNode(3); l1.next.next.next = new ListNode(2); l1.next.next.next.next = new ListNode(1); System.out.println("in: \n " + l1); Solution_234 pl = new Solution_234(); System.out.println("isPalindrome: \n " + pl.isPalindrome(l1)); System.out.println("in: \n " + l1); } }
true
7af2940261b0af2eb1f3709c95cb539058ac40eb
Java
XiePengLearn/refactor-frontend-android
/main/src/main/java/com/sxjs/jd/composition/main/MainActivity.java
UTF-8
13,575
1.625
2
[ "Apache-2.0" ]
permissive
package com.sxjs.jd.composition.main; import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.FragmentManager; import android.text.TextUtils; import android.view.KeyEvent; import android.widget.FrameLayout; import android.widget.Toast; import com.alibaba.android.arouter.facade.annotation.Route; import com.alibaba.android.arouter.launcher.ARouter; import com.sxjs.common.base.BaseActivity; import com.sxjs.common.util.LogUtil; import com.sxjs.common.util.PrefUtils; import com.sxjs.common.util.ResponseCode; import com.sxjs.common.util.ToastUtil; import com.sxjs.common.util.statusbar.StatusBarUtil; import com.sxjs.common.widget.bottomnavigation.BadgeItem; import com.sxjs.common.widget.bottomnavigation.BottomNavigationBar; import com.sxjs.common.widget.bottomnavigation.BottomNavigationItem; import com.sxjs.jd.MainDataManager; import com.sxjs.jd.R; import com.sxjs.jd.R2; import com.sxjs.jd.composition.main.befor.BeforePageFragment; import com.sxjs.jd.composition.main.home.HomePageFragment; import com.sxjs.jd.composition.main.middle.MiddlePageFragment; import com.sxjs.jd.composition.main.mine.MinePageFragment; import com.sxjs.jd.entities.LoginResponse; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; @Route(path = "/main/MainActivity") public class MainActivity extends BaseActivity implements MainContract.View, BottomNavigationBar.OnTabSelectedListener { @Inject MainPresenter presenter; @BindView(R2.id.bottom_navigation_bar1) BottomNavigationBar bottomNavigationBar; @BindView(R2.id.main_container) FrameLayout mainContainer; // private MainHomeFragment mMainHomeFragment; private HomePageFragment mMainHomeFragment; // private ClassificationFragment mClassificationFragment; private MiddlePageFragment mClassificationFragment; private FragmentManager mFragmentManager; // private FindFragment mFindFragment; private BeforePageFragment mFindFragment; // private MyFragment mMyFragment; private MinePageFragment mMyFragment; @SuppressLint("StaticFieldLeak") public static MainActivity instance;//关闭当前页面的instance private final String MESSAGE_ACTION = "com.jkx.message"; // 消息通知的广播名称 @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); StatusBarUtil.setImmersiveStatusBar(this, true); unbinder = ButterKnife.bind(this); mFragmentManager = getSupportFragmentManager(); initView(); initData(); //在oncreate中添加 instance = this; registerMessageBroadcast(); } /** * 注册消息广播 */ private void registerMessageBroadcast() { IntentFilter filter = new IntentFilter(MESSAGE_ACTION); registerReceiver(mSystemMessageReceiver, filter);// 注册广播 } private BroadcastReceiver mSystemMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (MESSAGE_ACTION.equals(action)) { initMoreState(); } } }; private void initMoreState() { LogUtil.e(TAG, "-----MainActivity收到信鸽的服务推送消息-----"); //初始化首页数据 initLogin(); } private void initLogin() { String lAccount = PrefUtils.readUserNameDefault(this.getApplicationContext()); String lPassword = PrefUtils.readPasswordDefault(this.getApplicationContext()); String mXinGeToken = PrefUtils.readXinGeToken(this.getApplicationContext()); Map<String, Object> mapParameters = new HashMap<>(6); mapParameters.put("MOBILE", lAccount); mapParameters.put("PASSWORD", lPassword); mapParameters.put("SIGNIN_TYPE", "1"); mapParameters.put("USER_TYPE", "1"); mapParameters.put("MOBILE_TYPE", "1"); mapParameters.put("XINGE_TOKEN", mXinGeToken); LogUtil.e(TAG, "-------mXinGeToken-------" + mXinGeToken); Map<String, String> mapHeaders = new HashMap<>(1); mapHeaders.put("ACTION", "S002"); // mapHeaders.put("SESSION_ID", TaskManager.SESSION_ID); presenter.getLoginData(mapHeaders, mapParameters); } public void initView() { mMainHomeFragment = (HomePageFragment) mFragmentManager.findFragmentByTag("home_fg"); mClassificationFragment = (MiddlePageFragment) mFragmentManager.findFragmentByTag("class_fg"); mFindFragment = (BeforePageFragment) mFragmentManager.findFragmentByTag("find_fg"); mMyFragment = (MinePageFragment) mFragmentManager.findFragmentByTag("my_fg"); if (mMainHomeFragment == null) { mMainHomeFragment = HomePageFragment.newInstance(); addFragment(R.id.main_container, mMainHomeFragment, "home_fg"); } //更改位置,初始化在 点击底部导航栏 position 为1 初始化 /*if(mClassificationFragment == null){ mClassificationFragment = ClassificationFragment.newInstance(); addFragment(R.id.main_container, mClassificationFragment, "class_fg"); }*/ //更改位置,初始化在 点击底部导航栏 position 为2 初始化 /*if(mFindFragment == null){ mFindFragment = FindFragment.newInstance(); addFragment(R.id.main_container, mFindFragment, "find_fg"); }*/ //更改位置,初始化在 点击底部导航栏 position 为3 初始化 /*if(mMyFragment == null){ mMyFragment = MyFragment.newInstance(); addFragment(R.id.main_container, mMyFragment, "my_fg"); }*/ mFragmentManager.beginTransaction().show(mMainHomeFragment) .commitAllowingStateLoss(); hideClassificationFragmnt(); hideFindFragment(); hideMyFragment(); DaggerMainActivityComponent.builder() .appComponent(getAppComponent()) .mainPresenterModule(new MainPresenterModule(this, MainDataManager.getInstance(mDataManager))) .build() .inject(this); initBottomNavigation(); } @Override public void onTabSelected(int position) { if (position == 0) { if (mMainHomeFragment == null) { mMainHomeFragment = HomePageFragment.newInstance(); addFragment(R.id.main_container, mMainHomeFragment, "home_fg"); } hideClassificationFragmnt(); hideFindFragment(); hideMyFragment(); mFragmentManager.beginTransaction() .show(mMainHomeFragment) .commitAllowingStateLoss(); } else if (position == 1) { if (mClassificationFragment == null) { mClassificationFragment = MiddlePageFragment.newInstance(); addFragment(R.id.main_container, mClassificationFragment, "class_fg"); } hideHomeFragment(); hideFindFragment(); hideMyFragment(); mFragmentManager.beginTransaction() .show(mClassificationFragment) .commitAllowingStateLoss(); } else if (position == 2) { if (mFindFragment == null) { mFindFragment = BeforePageFragment.newInstance(); addFragment(R.id.main_container, mFindFragment, "find_fg"); } hideHomeFragment(); hideClassificationFragmnt(); hideMyFragment(); mFragmentManager.beginTransaction() .show(mFindFragment) .commitAllowingStateLoss(); } else if (position == 3) { if (mMyFragment == null) { mMyFragment = MinePageFragment.newInstance(); addFragment(R.id.main_container, mMyFragment, "my_fg"); } hideHomeFragment(); hideClassificationFragmnt(); hideFindFragment(); mFragmentManager.beginTransaction() .show(mMyFragment) .commitAllowingStateLoss(); } } private void hideHomeFragment() { if (mMainHomeFragment != null) { mFragmentManager.beginTransaction().hide(mMainHomeFragment).commitAllowingStateLoss(); } } private void hideMyFragment() { if (mMyFragment != null) { mFragmentManager.beginTransaction().hide(mMyFragment).commitAllowingStateLoss(); } } private void hideFindFragment() { if (mFindFragment != null) { mFragmentManager.beginTransaction().hide(mFindFragment).commitAllowingStateLoss(); } } private void hideClassificationFragmnt() { if (mClassificationFragment != null) { mFragmentManager.beginTransaction().hide(mClassificationFragment).commitAllowingStateLoss(); } } private void initBottomNavigation() { BadgeItem numberBadgeItem = new BadgeItem() .setBorderWidth(4) .setBackgroundColorResource(R.color.colorAccent) .setText("99+") .setHideOnSelect(false); bottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED); //bottomNavigationBar.setMode(BottomNavigationBar.MODE_SHIFTING); bottomNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC); //bottomNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_RIPPLE); //bottomNavigationBar.setAutoHideEnabled(true); bottomNavigationBar .addItem(new BottomNavigationItem(R.drawable.axh, "").setInactiveIconResource(R.drawable.axg).setActiveColorResource(R.color.colorAccent)) .addItem(new BottomNavigationItem(R.drawable.axd, "").setInactiveIconResource(R.drawable.axc).setActiveColorResource(R.color.colorAccent)) .addItem(new BottomNavigationItem(R.drawable.axf, "").setInactiveIconResource(R.drawable.axe).setActiveColorResource(R.color.colorAccent)) // .addItem(new BottomNavigationItem(R.drawable.axb, "").setInactiveIconResource(R.drawable.axa).setActiveColorResource(R.color.colorAccent).setBadgeItem(numberBadgeItem)) .addItem(new BottomNavigationItem(R.drawable.axj, "").setInactiveIconResource(R.drawable.axi).setActiveColorResource(R.color.colorAccent)) .setFirstSelectedPosition(0) .initialise(); bottomNavigationBar.setTabSelectedListener(this); } private static final String TAG = "MainActivity"; public void initData() { // presenter.getText(); } private String text; private String loginData; @Override public void setLoginData(LoginResponse loginResponse) { try { String code = loginResponse.getCode(); String msg = loginResponse.getMsg(); if (code.equals(ResponseCode.SUCCESS_OK)) { LogUtil.e(TAG, "----------用户默认登录了-------------: "); String SESSION_ID = loginResponse.getData(); PrefUtils.writeSESSION_ID(SESSION_ID, this.getApplicationContext()); } else if (code.equals(ResponseCode.SEESION_ERROR)) { //SESSION_ID为空别的页面 要调起登录页面 } else { if (!TextUtils.isEmpty(msg)) { ToastUtil.showToast(this.getApplicationContext(), msg); } } } catch (Exception e) { ToastUtil.showToast(this.getApplicationContext(), "解析数据失败"); } } @Override public void showProgressDialogView() { showProgressDialog(); } @Override public void hiddenProgressDialogView() { hiddenProgressDialog(); } @Override public void onTabUnselected(int position) { } @Override public void onTabReselected(int position) { } @Override protected void onStart() { super.onStart(); } @Override protected void onDestroy() { super.onDestroy(); if (presenter != null) { presenter.destory(); } if (mSystemMessageReceiver != null) { unregisterReceiver(mSystemMessageReceiver); } } private long timeMillis; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { if ((System.currentTimeMillis() - timeMillis) > 2000) { Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show(); timeMillis = System.currentTimeMillis(); } else { finish(); System.exit(0); } return true; } return super.onKeyDown(keyCode, event); } }
true
7819f4b912672d9808745f5595517b868d06ba99
Java
rohinagrawal/User-Service
/src/main/java/dev/rohin/userservice/dto/ResetPasswordDto.java
UTF-8
253
1.914063
2
[ "MIT" ]
permissive
package dev.rohin.userservice.dto; import lombok.Getter; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; @Getter public class ResetPasswordDto { @NotEmpty @Size(min = 3) private String password; }
true
373e3b73bfc51563cec70a699182b5054e79f7bc
Java
arnaidu/WebVision_CSC207_Project
/WebvisionWebapp/src/main/java/com/csc/spring/db/UserRepo.java
UTF-8
336
1.976563
2
[ "Unlicense" ]
permissive
package com.csc.spring.db; import com.csc.spring.models.User; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface UserRepo extends JpaRepository<User, Long> { // User database model User findByEmail(String email); List<User> findByRole(String role); }
true
98e66a1c9a8a13816ef085656ee3161244b4e341
Java
Jahrens/MCTCG
/src/com/teammetallurgy/mctcg/card/CardList.java
UTF-8
684
2.8125
3
[]
no_license
package com.teammetallurgy.mctcg.card; import net.minecraft.util.Icon; public enum CardList { CREEPER("Creepr", 1, 0, null); private String name; private int attack, defence; private Icon texture; CardList(String cardName, int cardDefence, int cardAttack, Icon cardTexture) { name = cardName; defence = cardDefence; attack = cardAttack; texture = cardTexture; } public String getName() { return name; } public int getAttack() { return attack; } public int getDefence() { return defence; } public Icon getTexture() { return texture; } }
true
0c09c7c6b50b125969eb5f4a72affdff35a95bc6
Java
hujun519191086/AndroidDesignWidgetsSample
/app/src/main/java/com/ddmeng/appbarlayoutsample/behavior/FloatingActionButtonBehaviorActivity.java
UTF-8
1,056
2
2
[ "Apache-2.0" ]
permissive
package com.ddmeng.appbarlayoutsample.behavior; import android.os.Bundle; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.view.ViewGroup; import com.ddmeng.appbarlayoutsample.R; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class FloatingActionButtonBehaviorActivity extends AppCompatActivity { @BindView(R.id.container) CoordinatorLayout coordinatorLayout; @BindView(R.id.fab) FloatingActionButton floatingActionButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_floating_action_button_behavior); ButterKnife.bind(this); } @OnClick(R.id.show_button) void onShowButtonClick() { Snackbar.make(coordinatorLayout, "Hey there!", Snackbar.LENGTH_LONG).show(); } }
true
37f8b3f48764e0e0fed4466096664cf4d4441567
Java
juanra1997/Programacion
/Practicas/Practica03/Ejercicio04/Fecha.java
ISO-8859-10
8,250
3.40625
3
[]
no_license
package Ejercicio04; import java.util.Scanner; public class Fecha { private int dia; private int mes; private int anno; private void valida() { if(this.anno<1900||this.anno>2050) { System.out.println("Ao incorrecto"); this.anno=1900; } if(this.mes<1||this.mes>12) { System.out.println("Mes incorrecto"); this.mes=1; } if((this.anno%400==0||this.anno%4==0&&this.anno%100!=0)==true&&this.mes==2&&this.dia>29){ System.out.println("Dia incorrecto"); this.dia=1; } if((this.anno%400==0||this.anno%4==0&&this.anno%100!=0)==false&&this.mes==2&&this.dia>28) { System.out.println("Dia incorrecto"); this.dia=1; } if(this.mes==2||this.mes==4||this.mes==6||this.mes==9||this.mes==11&&this.dia>30) { System.out.println("Dia incorrecto"); this.dia=1; } if(this.mes==1||this.mes==3||this.mes==5||this.mes==7||this.mes==8||this.mes==10||this.mes==12&&dia>31) { System.out.println("Dia incorrecto"); this.dia=1; } } public Fecha() { this.dia=1; this.mes=1; this.anno=1900; valida(); } public Fecha(int dia, int mes, int anno) { this.dia=dia; this.mes=mes; this.anno=anno; } public void leer() { Scanner teclado=new Scanner(System.in); System.out.println("Introduce dia (1-31)"); this.dia=teclado.nextInt(); System.out.println("Introduce mes (1-12)"); this.mes=teclado.nextInt(); System.out.println("Introduce ao (1900-2050)"); this.anno=teclado.nextInt(); teclado.close(); valida(); } public String bisiesto() { if (anno%400==0||anno%4==0&&anno%100!=0==true) { return "El ao es bisiesto"; } else { return "El ao no es bisiesto"; } } public String diasMes(int mes) { if (mes<0||mes>12) { return "No es un mes valido"; } else if(mes==4||mes==6||mes==9||mes==11) { return 30+" dias"; } else if(mes==2&&(anno%400==0||anno%4==0&&anno%100!=0)==true) { return 29+" dias"; } else if(mes==2&&(anno%400==0||anno%4==0&&anno%100!=0)==false) { return 28+" dias"; } else { return 31+" dias"; } } public int getDia() { return this.dia; } public int getMes() { return this.mes; } public int getAnno() { return this.anno; } public void setDia(int dia) { this.dia=dia; } public void setMes(int mes) { this.mes=mes; } public void setAnno(int anno) { this.anno=anno; } public String corta() { String mss; mss=this.dia+"-"+this.mes+"-"+this.anno; return mss; } public String diasTranscurridos() { int sumDias=0, x=1900, m=1, d=1; while(x<this.anno) { if((anno%400==0||anno%4==0&&anno%100!=0)==true) { sumDias=sumDias+366; } else { sumDias=sumDias+365; } x++; } while(m<this.mes) { if(m==2&&(anno%400==0||anno%4==0&&anno%100!=0)==true) { sumDias=sumDias+29; } if(m==2&&(anno%400==0||anno%4==0&&anno%100!=0)==false) { sumDias=sumDias+28; } if(m==4||m==6||m==9||m==11) { sumDias=sumDias+30; } if(m==1||m==3||m==5||m==7||m==8||m==10||m==12) { sumDias=sumDias+31; } m++; } while(d<this.dia) { sumDias=sumDias+1; d++; } return "Han transcurrido "+sumDias+" dias desde el 1-1-1900"; } public String diaSemana() { int y, x, m, d; String diaSemana="dia"; y=anno-(14-this.mes)/12; x=y+y/4-y/100+y/400; m=this.mes+12*((14-mes)/12)-2; d=(this.dia+x+(31*m)/12)%7; if (d==1) { diaSemana="Domingo"; } if (d==2) { diaSemana="Lunes"; } if (d==3) { diaSemana="Martes"; } if (d==4) { diaSemana="Miercoles"; } if (d==5) { diaSemana="Jueves"; } if (d==6) { diaSemana="Viernes"; } if (d==0) { diaSemana="Sabado"; } return diaSemana; } public String larga() { String mss, mes="mes"; if(this.mes==1) { mes="Enero"; } if(this.mes==2) { mes="Febrero"; } if(this.mes==3) { mes="Marzo"; } if(this.mes==4) { mes="Abril"; } if(this.mes==5) { mes="Mayo"; } if(this.mes==6) { mes="Junio"; } if(this.mes==7) { mes="Julio"; } if(this.mes==8) { mes="Agosto"; } if(this.mes==9) { mes="Septiembre"; } if(this.mes==10) { mes="Octubre"; } if(this.mes==11) { mes="Noviembre"; } if(this.mes==12) { mes="Diciembre"; } mss=diaSemana()+" "+this.dia+" de "+mes+" de "+this.anno; return mss; } public Fecha fechaTras(long dias) { while (dias > 0) { this.dia++; if((this.anno%400==0||this.anno%4==0&&this.anno%100!=0)==true&&this.mes==2&&this.dia>29) { this.mes=this.mes+1; this.dia=1; } if((this.anno%400==0||this.anno%4==0&&this.anno%100!=0)==false&&this.mes==2&&this.dia>28) { this.mes=this.mes+1; this.dia=1; } if(this.mes==2||this.mes==4||this.mes==6||this.mes==9||this.mes==11&&this.dia>30) { this.mes=this.mes+1; this.dia=1; } if(this.mes==1||this.mes==3||this.mes==5||this.mes==7||this.mes==8||this.mes==10&&dia>31);{ this.mes=this.mes+1; this.dia=1; } if(this.mes==12&&this.dia>31) { this.anno=this.anno+1; this.mes=1; this.dia=1; } dias--; } Fecha fecha = new Fecha(dia, mes, anno); return fecha; } public String diasEntre(Fecha f) { int sumDias=0; while(f.anno<this.anno) { if((anno%400==0||anno%4==0&&anno%100!=0)==true) { sumDias=sumDias+366; } else { sumDias=sumDias+365; } f.anno++; } while(f.mes<this.mes) { if(f.mes==2&&(anno%400==0||anno%4==0&&anno%100!=0)==true) { sumDias=sumDias+29; } if(f.mes==2&&(anno%400==0||anno%4==0&&anno%100!=0)==false) { sumDias=sumDias+28; } if(f.mes==4||f.mes==6||f.mes==9||f.mes==11) { sumDias=sumDias+30; } if(f.mes==1||f.mes==3||f.mes==5||f.mes==7||f.mes==8||f.mes==10||f.mes==12) { sumDias=sumDias+31; } f.mes++; } while(f.dia<this.dia) { sumDias=sumDias+1; f.dia++; } return "Han transcurrido "+sumDias+" dias entre las fechas"; } public Fecha diaSiguiente() { this.dia=this.dia+1; if((this.anno%400==0||this.anno%4==0&&this.anno%100!=0)==true&&this.mes==2&&this.dia>29) { this.mes=this.mes+1; this.dia=1; } if((this.anno%400==0||this.anno%4==0&&this.anno%100!=0)==false&&this.mes==2&&this.dia>28) { this.mes=this.mes+1; this.dia=1; } if(this.mes==2||this.mes==4||this.mes==6||this.mes==9||this.mes==11&&this.dia>30) { this.mes=this.mes+1; this.dia=1; } if(this.mes==1||this.mes==3||this.mes==5||this.mes==7||this.mes==8||this.mes==10&&dia>31);{ this.mes=this.mes+1; this.dia=1; } if(this.mes==12&&this.dia>31) { this.anno=this.anno+1; this.mes=1; this.dia=1; } Fecha fecha=new Fecha(this.dia, this.mes, this.anno); return fecha; } public Fecha diaAnterior() { this.dia=this.dia-1; if((this.anno%400==0||this.anno%4==0&&this.anno%100!=0)==true&&this.mes==3&&this.dia<1) { this.mes=this.mes-1; this.dia=29; } if((this.anno%400==0||this.anno%4==0&&this.anno%100!=0)==false&&this.mes==2&&this.dia<1) { this.mes=this.mes-1; this.dia=28; } if(this.mes==2||this.mes==4||this.mes==6||this.mes==9||this.mes==11&&this.dia<1) { this.mes=this.mes-1; this.dia=31; } if(this.mes==1||this.mes==3||this.mes==5||this.mes==7||this.mes==8||this.mes==10&&dia<1);{ this.mes=this.mes-1; this.dia=30; } if(this.mes==12&&this.dia>31) { this.anno=this.anno+1; this.mes=1; this.dia=1; } Fecha fecha=new Fecha(this.dia, this.mes, this.anno); return fecha; } public Fecha copia() { Fecha fecha=new Fecha(this.dia, this.mes, this.anno); return fecha; } public String igualQue(Fecha f) { if(f.dia==this.dia&&f.mes==this.mes&&f.anno==this.anno) { return "Las dos fechas son iguales"; } else { return "Las dos fechas no son iguales"; } } public String menorQue(Fecha f) { if(this.anno<f.anno||this.anno==f.anno&&this.mes<f.mes||this.anno==f.anno&&this.mes==f.mes&&this.dia<f.dia) { return "La fecha es anterior a la proporcionada"; } else { return "La fecha no es anterior a la proporcionada"; } } public String mayorQue(Fecha f) { if (this.anno>f.anno||this.anno==f.anno&&this.mes>f.mes||this.anno==f.anno&&this.mes==f.mes&&this.dia>f.dia) { return "La fecha es posterior a la proporcionada"; } else { return "La fecha no es posterior a la proporcionada"; } } }
true
fe6e9683d53917a504571d4bc356d6a6f3ebbe23
Java
sk6786/SocialFeed
/app/src/main/java/com/example/ikhan/socialfeed/Feed.java
UTF-8
1,276
2
2
[]
no_license
package com.example.ikhan.socialfeed; import android.app.Activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Window; import android.widget.TextView; import com.facebook.AccessToken; import com.facebook.GraphRequest; import com.facebook.GraphResponse; import com.facebook.HttpMethod; import org.json.JSONObject; import java.util.Arrays; public class Feed extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_feed); AccessToken accessToken = AccessToken.getCurrentAccessToken(); final TextView txt=(TextView)findViewById(R.id.Token); //txt.setText(""+accessToken); new GraphRequest(accessToken,"/me/feed",null, HttpMethod.GET, new GraphRequest.Callback() { public void onCompleted(GraphResponse response) { /* handle the result */ JSONObject json = response.getJSONObject(); txt.setText(json.toString()); // txt.setText(response.toString()); } } ).executeAsync(); } }
true
4173119cb8dd13eba0cc97744bddbbbe7852c177
Java
farble1670/android-ninja-temp
/NinjaTempProject/NinjaTemp/src/main/java/org/jtb/ninjatemp/Response.java
UTF-8
362
2.46875
2
[ "Apache-2.0" ]
permissive
package org.jtb.ninjatemp; import org.json.JSONException; import org.json.JSONObject; abstract class Response { protected final JSONObject data; int getResult() { return data.optInt("result", -1); } Response(String content) throws JSONException { data = new JSONObject(content); } Response(JSONObject data) { this.data = data; } }
true
ec4b8287bd1138b88ad7bf405d60967a1c03afd5
Java
bhojanesnehal/OnlineProject
/OnlineProject/src/main/java/com/jbkclass/qa/pages/DashboardPage.java
UTF-8
510
1.992188
2
[]
no_license
package com.jbkclass.qa.pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import com.jbkclass.qa.base.TestBase; public class DashboardPage extends TestBase { @FindBy(xpath="//span[text()='Top 10 customers in fiscal year']") WebElement customersLabel; public DashboardPage() { PageFactory.initElements(driver, this); } public String checklabelsOfDashboardPage () { return customersLabel.getText(); } }
true
f483616400b1d97f09c6849ef48f418b381a7722
Java
RichardCx11/sistema-bancario
/sistemabancario-backend/src/main/java/com/pe/compartamosfinanciera/sistemabancario/entity/Sucursal.java
UTF-8
2,069
2.078125
2
[]
no_license
package com.pe.compartamosfinanciera.sistemabancario.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @Entity @Table(name = "sucursal") @JsonIgnoreProperties({"hibernateLazyInitializer","handler"}) public class Sucursal implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "idSucursal") private Integer idSucursal; private String nombre; private String direccion; @Column(name = "fechaRegistro") private Date fechaRegistro; @JoinColumn(name = "idBanco") @JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" }) @ManyToOne(fetch = FetchType.LAZY) private Banco banco; @JoinColumn(name = "idOrdenPago") @JsonIgnoreProperties({"sucursales", "hibernateLazyInitializer", "handler" }) @ManyToOne(fetch = FetchType.LAZY) private OrdenPago ordenPago; public Integer getIdSucursal() { return idSucursal; } public void setIdSucursal(Integer idSucursal) { this.idSucursal = idSucursal; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public Date getFechaRegistro() { return fechaRegistro; } public void setFechaRegistro(Date fechaRegistro) { this.fechaRegistro = fechaRegistro; } public Banco getBanco() { return banco; } public void setBanco(Banco banco) { this.banco = banco; } public OrdenPago getOrdenPago() { return ordenPago; } public void setOrdenPago(OrdenPago ordenPago) { this.ordenPago = ordenPago; } }
true
be38a718ce08e7fc561404e6f8d9ca79cd5debc6
Java
educ-nc-spring-19/mailing-service
/src/main/java/com/educ_nc_spring_19/mailing_service/pattern_engine/controller/request/TemplateRequest.java
UTF-8
273
1.601563
2
[]
no_license
package com.educ_nc_spring_19.mailing_service.pattern_engine.controller.request; import lombok.Data; import java.util.UUID; @Data public class TemplateRequest { public UUID creator_id; public String type; public String header; public String text; }
true
03ffba6ff4d27cac4ca2c744f6d21e3fa765681a
Java
chhai-chivon-springframework/spring-boot-RESTfull-hibernate
/src/main/java/com/chhaichivon/springbootRESTfullhibernate/utils/BaseServiceHelper.java
UTF-8
403
1.953125
2
[]
no_license
package com.chhaichivon.springbootRESTfullhibernate.utils; import java.util.List; /** * AUTHOR : CHHAI CHIVON * EMAIL : chhaichivon1995@gmail.com * DATE : 8/26/2017 * TIME : 12:53 PM */ public interface BaseServiceHelper<T> { public T findById(long id); public Boolean save(T entity); public Boolean update(T entity); public Boolean delete(Long id); public List<T> get(Pagination pagination); }
true
1dc84b5abd3e5beed9651d0e46dcaf4e02166c53
Java
BlackNetCat/test
/c03/TestSerial.java
UTF-8
143
1.726563
2
[]
no_license
package c03; import java.io.Serializable; class TestSerial implements Serializable { public byte version = 100; public byte count = 0; }
true
9dd204b2977d208be38097bb4b838a4253ff30d5
Java
jthoover-github/Snake
/src/TextObject.java
UTF-8
2,054
3.171875
3
[]
no_license
import java.util.ArrayList; import java.awt.*; public class TextObject { private ArrayList<Coords> cca = new ArrayList<Coords>(); private static final int blockSize = GameObject.getGameBlockSize(); private static final int scale = GameObject.getGameScale(); public TextObject(ArrayList<Coords> cca) { this.cca = cca; } public static int getScale() { return scale; } public static int getBlockSize() { return blockSize; } public void draw(Graphics g, int x, int y, Color c) { Color d = c.darker(); for (int i = 0; i < cca.size(); i++) { Coords xy = cca.get(i); if (scale == 1) { g.setColor(c); g.fillRect(x*getBlockSize()+xy.getX()*getScale(), y*getBlockSize()+xy.getY()*getScale(), 1, 1); } else { g.setColor(c); g.fillRect(x*getBlockSize()+xy.getX()*getScale(), y*getBlockSize()+xy.getY()*getScale(), getScale(), getScale()-1); g.setColor(d); g.fillRect(x*getBlockSize()+xy.getX()*getScale(), y*getBlockSize()+(xy.getY()+1)*getScale() - 1, getScale(), 1); } } } public void draw(Graphics g, int x, int y, Color c, int size) { Color d = c.darker(); for (int i = 0; i < cca.size(); i++) { Coords xy = cca.get(i); if (scale == 1) { g.setColor(c); g.fillRect(x*getBlockSize()+(xy.getX()*getScale()) * size, y*getBlockSize()+(xy.getY()*getScale()) * size, getScale()*size, getScale()*size); } else { g.setColor(c); g.fillRect(x*getBlockSize()+(xy.getX()*getScale()) * size, y*getBlockSize()+(xy.getY()*getScale()) * size, getScale()*size, (getScale()-1)*size); g.setColor(d); g.fillRect(x*getBlockSize()+(xy.getX()*getScale()) * size, y*getBlockSize()+((xy.getY()+1)*getScale() - 1) * size, getScale()*size, size); } } } }
true
50943f3fccce209ffd205d1fbea68e71d092cb52
Java
fengluandll/freedom
/WorkspacePlayCity/TSJDF_HE_Sistema/src/mx/gob/tsjdf/cfdi/service/RecibosService.java
ISO-8859-1
18,321
1.90625
2
[]
no_license
package mx.gob.tsjdf.cfdi.service; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import org.apache.log4j.Logger; import mx.gob.tsjdf.cfdi.bo.RecibosBo; import mx.gob.tsjdf.cfdi.dao.PagoDao; import mx.gob.tsjdf.cfdi.dao.PagoEmpleadoDao; import mx.gob.tsjdf.cfdi.dto.CampoRubroDto; import mx.gob.tsjdf.cfdi.dto.DescripcionPagoDto; import mx.gob.tsjdf.cfdi.dto.PagoEmpleadoDto; import mx.gob.tsjdf.cfdi.dto.PercepcionDeduccionDto; import mx.gob.tsjdf.cfdi.dto.ReciboDto; import mx.gob.tsjdf.cfdi.dto.RecibosEmpleadoDto; import mx.gob.tsjdf.cfdi.recibos.logger.LoggerSingleton; import mx.gob.tsjdf.cfdi.view.CfdisView; import mx.gob.tsjdf.util.Funciones; public class RecibosService { private PagoDao pagoDao; Funciones funciones; // private static Logger logger; private static org.apache.log4j.Logger logger = Logger.getLogger(RecibosService.class); public RecibosService(){ funciones = new Funciones(); this.pagoDao = new PagoDao(); // logger = LoggerSingleton.getInstance(); } public RecibosEmpleadoDto getRecibos(HashMap<String, CampoRubroDto> hmapCampos, String query, String numeroEmpleado, String fechaPaga, String metodoPago, String tipoNomina) { RecibosEmpleadoDto recibosEmpleadoDto = new RecibosEmpleadoDto(); for (Integer periodo : this.pagoDao.consultaPeriodosEmpleado(numeroEmpleado, fechaPaga,tipoNomina)) { recibosEmpleadoDto.getListaRecibos().add(generaRecibo(hmapCampos, query, numeroEmpleado, fechaPaga, periodo.intValue(), metodoPago,tipoNomina)); } return recibosEmpleadoDto; } public ReciboDto generaRecibo(HashMap<String, CampoRubroDto> hmapCampos, String query, String numeroEmpleado, String fechaPaga, int idPeriodo, String metodoPago,String tipoNomina) { ReciboDto reciboDto = new ReciboDto(); reciboDto.setNumeroEmpleado(numeroEmpleado); reciboDto.setIdPeriodo(idPeriodo); this.pagoDao.llenaConceptosRecibo(reciboDto, query, fechaPaga, hmapCampos,tipoNomina); this.pagoDao.llenaDatosGenerales(reciboDto, reciboDto.getFechaInicioPeriodo(), fechaPaga, metodoPago,tipoNomina); Double perTotalGravado = Double.valueOf(0.0D); Double perTotalExento = Double.valueOf(0.0D); HashSet<String> hsPercepciones = new HashSet(); HashSet<String> hsDeducciones = new HashSet(); for (Map.Entry<String, PercepcionDeduccionDto> p : reciboDto.getHmapPercepciones().entrySet()) { if ((((PercepcionDeduccionDto)p.getValue()).getImporte().doubleValue() == 0.0D) && (!((PercepcionDeduccionDto)p.getValue()).getDespliegaConCero())) { hsPercepciones.add((String)p.getKey()); } else { if ((((PercepcionDeduccionDto)p.getValue()).getExento() == 1) || (((PercepcionDeduccionDto)p.getValue()).getExento() == 2)) { ((PercepcionDeduccionDto)p.getValue()).setImporteExento( ((PercepcionDeduccionDto)p.getValue()).getImporte()); } if (((PercepcionDeduccionDto)p.getValue()).getExento() == 0) { ((PercepcionDeduccionDto)p.getValue()).setImporteGravado(((PercepcionDeduccionDto)p.getValue()).getImporte()); } if ((((PercepcionDeduccionDto)p.getValue()).getDespliega().equals("T")) || (((PercepcionDeduccionDto)p.getValue()).getDespliega().equals("C"))) { perTotalGravado = Double.valueOf(perTotalGravado.doubleValue() + ((PercepcionDeduccionDto)p.getValue()).getImporteGravado().doubleValue()); perTotalExento = Double.valueOf(perTotalExento.doubleValue() + ((PercepcionDeduccionDto)p.getValue()).getImporteExento().doubleValue()); } } } for (Map.Entry<String, PercepcionDeduccionDto> d : reciboDto.getHmapDeducciones().entrySet()) { if ((((PercepcionDeduccionDto)d.getValue()).getImporte().doubleValue() == 0.0D) && (!((PercepcionDeduccionDto)d.getValue()).getDespliegaConCero())) { hsDeducciones.add((String)d.getKey()); } else { if ((((PercepcionDeduccionDto)d.getValue()).getExento() == 1) || (((PercepcionDeduccionDto)d.getValue()).getExento() == 2)) { ((PercepcionDeduccionDto)d.getValue()).setImporteExento( ((PercepcionDeduccionDto)d.getValue()).getImporte()); } if (((PercepcionDeduccionDto)d.getValue()).getExento() == 0) { ((PercepcionDeduccionDto)d.getValue()).setImporteGravado( ((PercepcionDeduccionDto)d.getValue()).getImporte()); } } } for (Iterator<String> iterator = hsPercepciones.iterator(); iterator.hasNext();) { String key = (String)iterator.next(); reciboDto.getHmapPercepciones().remove(key); } for (Iterator<String> iterator = hsDeducciones.iterator(); iterator.hasNext();) { String key = (String)iterator.next(); reciboDto.getHmapDeducciones().remove(key); } reciboDto.setTotalGravadoPercepciones(RecibosBo.Redondear(perTotalGravado.doubleValue())); reciboDto.setTotalExentoPercepciones(RecibosBo.Redondear(perTotalExento.doubleValue())); reciboDto.setTotalGravadoDeducciones(0.0D); reciboDto.setTotalExentoDeducciones(RecibosBo.Redondear(reciboDto.getTotalDescuentos())); if ((reciboDto.getHorasExtraDobles() > 0.0D) || (reciboDto.getHorasExtraTriples() > 0.0D)) { reciboDto.setDiasHorasExtra(10); } return reciboDto; } public ArrayList<PagoEmpleadoDto> getPagosEmpleado(String numeroEmpleado, int anio) { PagoEmpleadoDao dao = new PagoEmpleadoDao(); return dao.consultarPagosEmpleado(numeroEmpleado, Integer.toString(anio)); } public ArrayList<DescripcionPagoDto> getDescripcionPagos(String anio,String tipoNomina) { return this.pagoDao.consultarDescripcionesPago(anio,tipoNomina); } public int generaTxt(HashMap<String, CampoRubroDto> hmapCampos, String query, String idRfc, String numeroEmpleado, String fechaPaga, String pagoDescripcion, String fechaEmision, String token, String fechaSistema, String dirTxt, String periodicidadPago, String fechaEjecucion, String metodoPago, String tipoNomina) { RecibosEmpleadoDto recibosEmpleadoDto = getRecibos(hmapCampos, query, numeroEmpleado, fechaPaga, metodoPago,tipoNomina); if (recibosEmpleadoDto.getListaRecibos().size() > 0) { int numRecibos = 1; for (ReciboDto reciboDto : recibosEmpleadoDto.getListaRecibos()) { String pathAbsoluto = dirTxt + numeroEmpleado + "-" + numRecibos++ + ".txt"; StringBuffer contenido = new StringBuffer(); ArchivoService bo = new ArchivoService(); StringBuffer strPerComplementos = new StringBuffer(""); StringBuffer strPerAddenda = new StringBuffer(""); StringBuffer strDesComplementos = new StringBuffer(""); StringBuffer strDesAddenda = new StringBuffer(""); int numPerC = 1; int numPerA = 1; for (Map.Entry<String, PercepcionDeduccionDto> p : reciboDto.getHmapPercepciones().entrySet()) { if ((((PercepcionDeduccionDto)p.getValue()).getDespliega().equals("T")) || (((PercepcionDeduccionDto)p.getValue()).getDespliega().equals("C"))) { String identificadorC = RecibosBo.intToStr(numPerC++); strPerComplementos.append("COM010|PE0001|PER" + identificadorC + "|" + ((PercepcionDeduccionDto)p.getValue()).getClaveSat() + "|" + ((PercepcionDeduccionDto)p.getValue()).getClaveTsjdf() + "|" + ((PercepcionDeduccionDto)p.getValue()).getDescripcionSat() + "|" + ((PercepcionDeduccionDto)p.getValue()).getImporteGravadoFormat() + "|" + ((PercepcionDeduccionDto)p.getValue()).getImporteExentoFormat() + "|\n"); } if ((((PercepcionDeduccionDto)p.getValue()).getDespliega().equals("T")) || (((PercepcionDeduccionDto)p.getValue()).getDespliega().equals("A"))) { String identificadorA = RecibosBo.intToStr(numPerA++); strPerAddenda.append("A 0001|PE0001|PER" + identificadorA + "|" + ((PercepcionDeduccionDto)p.getValue()).getDescripcionTsjdf() + "|" + ((PercepcionDeduccionDto)p.getValue()).getImporteFormat() + "|" + ((PercepcionDeduccionDto)p.getValue()).getClaveTsjdf() + "|\n"); } } int numDesC = 1; int numDesA = 1; for (Map.Entry<String, PercepcionDeduccionDto> d : reciboDto.getHmapDeducciones().entrySet()) { if ((((PercepcionDeduccionDto)d.getValue()).getDespliega().equals("T")) || (((PercepcionDeduccionDto)d.getValue()).getDespliega().equals("C"))) { String identificadorC = RecibosBo.intToStr(numDesC++); //Empleados especiales String claveSAT = "null"; String descSAT = "null"; if(reciboDto.getNumeroEmpleado().equals("2174578") || reciboDto.getNumeroEmpleado().equals("2404000") || reciboDto.getNumeroEmpleado().equals("8003305") || reciboDto.getNumeroEmpleado().equals("7563425") || reciboDto.getNumeroEmpleado().equals("2049907") || reciboDto.getNumeroEmpleado().equals("1964335") || reciboDto.getNumeroEmpleado().equals("0037897")){ if(tipoNomina.equals("tribunal")){ if(((PercepcionDeduccionDto)d.getValue()).getClaveTsjdf().equals("8580")){ claveSAT = "004"; descSAT = "Otros"; //Funciones.variableLog.append("Cambio 004 y descripcion Otros al empleado****** "+reciboDto.getNumeroEmpleado() +"\n"); logger.info("Cambio 004 y descripcion Otros al empleado****** "+reciboDto.getNumeroEmpleado()); }else{ claveSAT = ((PercepcionDeduccionDto)d.getValue()).getClaveSat(); descSAT = ((PercepcionDeduccionDto)d.getValue()).getDescripcionSat(); } }else{ claveSAT = ((PercepcionDeduccionDto)d.getValue()).getClaveSat(); descSAT = ((PercepcionDeduccionDto)d.getValue()).getDescripcionSat(); } }else{ claveSAT = ((PercepcionDeduccionDto)d.getValue()).getClaveSat(); descSAT = ((PercepcionDeduccionDto)d.getValue()).getDescripcionSat(); } strDesComplementos.append("COM010|DE0001|DED" + identificadorC + "|" + claveSAT + "|" + ((PercepcionDeduccionDto)d.getValue()).getClaveTsjdf() + "|" + descSAT + "|" + ((PercepcionDeduccionDto)d.getValue()).getImporteGravadoFormat() + "|" + ((PercepcionDeduccionDto)d.getValue()).getImporteExentoFormat() + "|\n"); //Termina Empleados especiales /* Se comenta para que haga los cambios sobre los empleados especiales * strDesComplementos.append("COM010|DE0001|DED" + identificadorC + "|" + ((PercepcionDeduccionDto)d.getValue()).getClaveSat() + "|" + ((PercepcionDeduccionDto)d.getValue()).getClaveTsjdf() + "|" + ((PercepcionDeduccionDto)d.getValue()).getDescripcionSat() + "|" + ((PercepcionDeduccionDto)d.getValue()).getImporteGravadoFormat() + "|" + ((PercepcionDeduccionDto)d.getValue()).getImporteExentoFormat() + "|\n");*/ } if ((((PercepcionDeduccionDto)d.getValue()).getDespliega().equals("T")) || (((PercepcionDeduccionDto)d.getValue()).getDespliega().equals("C"))) { String identificadorA = RecibosBo.intToStr(numDesA++); strDesAddenda.append("A 0001|DE0001|DED" + identificadorA + "|" + ((PercepcionDeduccionDto)d.getValue()).getDescripcionTsjdf() + "|" + ((PercepcionDeduccionDto)d.getValue()).getImporteFormat() + "|" + ((PercepcionDeduccionDto)d.getValue()).getClaveTsjdf() + "|\n"); } } contenido.append("H00000|" + idRfc + "|1|" + fechaSistema + "|\n"); contenido.append("OPE001|1|" + token + "|\n"); contenido.append("C10001|3.2|" + fechaEmision + "|PAGO EN UNA SOLA EXHIBICION|\n"); contenido.append("C30003||" + reciboDto.getTotalPercepcionesFormat() + "|" + reciboDto.getDescuentoLayoutFormat() + "|DEDUCCIONES NOMINA|1.0|MXN|" + reciboDto.getLiquidoCobrarFormat() + "|" + reciboDto.getMetodoPago() + "||||||RECIBO DE NMINA|" + reciboDto.getNumArea() + "||\n"); if(tipoNomina.equals("tribunal")){ contenido.append("E00001|41|\n"); }else if(tipoNomina.equals("consejo")){ contenido.append("E00001|50|\n"); } contenido.append("R00001|" + reciboDto.getRfc() + "|" + reciboDto.getNombreCompleto() + "|||\n"); contenido.append("D00001|||||||||MXICO||\n"); contenido .append("I00001|1.00|SERVICIO||PAGO DE NMINA|" + reciboDto.getTotalPercepcionesFormat() + "|" + reciboDto.getTotalPercepcionesFormat() + "|0|\n"); contenido.append("COM010|1.1|" + reciboDto.getNumeroEmpleado() + "||" + reciboDto.getCurp() + "|2||" + fechaEjecucion + "|" + reciboDto.getFechaInicioPeriodo() + "|" + reciboDto.getFechaFinPeriodo() + "|" + reciboDto.getDiasPagados() + "|" + reciboDto.getDescripcionArea() + "||014|||" + reciboDto.getPuesto() + "|||" + periodicidadPago + "||||\n"); contenido.append("COM010|PERC01|" + reciboDto.getTotalGravadoPercepcionesFormat() + "|" + reciboDto.getTotalExentoPercepcionesFormat() + "|\n"); contenido.append(strPerComplementos); contenido.append("COM010|DEDU01|" + reciboDto.getTotalGravadoDeduccionesFormat() + "|" + reciboDto.getTotalExentoDeduccionesFormat() + "|\n"); contenido.append(strDesComplementos); contenido.append("T10001|" + reciboDto.getIsrFormat() + "|\n"); contenido.append("T20001|ISR|" + reciboDto.getIsrFormat() + "|\n"); contenido.append("A 0001|1.0|\n"); contenido.append("A 0001|FBA001|||||||||||\n"); contenido.append("A 0001|NODOC1||\n"); contenido.append("A 0001|NOM001|" + reciboDto.getTn() + "|" + reciboDto.getZp() + "|" + reciboDto.getNumArea() + "|" + reciboDto.getCodigo() + "|" + reciboDto.getNivelSalarial() + "|" + reciboDto.getUniverso() + "|" + reciboDto.getNumeroPlaza() + "|" + reciboDto.getSeccionSindical() + "|" + pagoDescripcion + "|\n"); contenido.append("A 0001|PERC01|" + reciboDto.getTotalGravadoPercepcionesFormat() + "|" + reciboDto.getTotalExentoPercepcionesFormat() + "|\n"); contenido.append(strPerAddenda); contenido.append("A 0001|DEDU01|" + reciboDto.getTotalGravadoDeduccionesFormat() + "|" + reciboDto.getTotalExentoDeduccionesFormat() + "|\n"); contenido.append(strDesAddenda); contenido.append("A 0001|NOTGEN|" + reciboDto.getMensaje() + "|\n"); contenido.append("OPEEND|\n"); bo.creaArchivo(pathAbsoluto, contenido); } return recibosEmpleadoDto.getListaRecibos().size(); } Funciones.variableLog.append("El empleado " + numeroEmpleado + " no tiene recibos en la fecha de pago especificada" +"\n"); logger.info("El empleado " + numeroEmpleado + " no tiene recibos en la fecha de pago especificada"); return 0; } public HashMap<String, CampoRubroDto> getHmapCampos(String tipoNomina) { return this.pagoDao.llenaListasCampos(tipoNomina); } public int generacionMasivaTodos(ArrayList<String> listaEmpleados, HashMap<String, CampoRubroDto> hmapCampos, String query, String idRfc, String fechaPaga, String strSerie, String pagoDescripcion, String fechaRecibo, String fechaSistema, String dirTxt, String periodicidadPago, String fechaEjecucion, String metodoPago,ArrayList<String> listaEmpleadosArchivo, String tipoNomina) { String token = "token"; logger.info("Fecha de Paga = " + fechaPaga); logger.info("Descripcion de la nomina = " + pagoDescripcion); logger.info("Se procesaran un total de empleados = " + listaEmpleados.size()); System.out.println("Creando recibos, por favor espere ..."); int contador = 0; if (listaEmpleados.size() > 0) { for (String numeroEmpleado : listaEmpleados) { if(listaEmpleadosArchivo.contains(numeroEmpleado)){ logger.info("El empleado "+numeroEmpleado + " Fue omitido en la nomina"); }else{ contador = contador + generaTxt(hmapCampos, query, idRfc, numeroEmpleado, fechaPaga, pagoDescripcion, fechaRecibo, token, fechaSistema, dirTxt, periodicidadPago, fechaEjecucion, metodoPago,tipoNomina); if (contador % 100 == 0) { System.out.println("Archivos generados = " + contador); } } } } else { logger.info("No hay empleados en la fecha de paga proporcionada : " + fechaPaga); Funciones.variableLog.append("No hay empleados en la fecha de paga proporcionada : " + fechaPaga+"\n"); } return contador; } public ArrayList<String> getListaTodosEmpleados(String fechaPaga,String tipoNomina) { return this.pagoDao.consultaEmpleadosPorPeriodo(fechaPaga,tipoNomina); } public DescripcionPagoDto getFechaEjecucion(String fechaPaga,String tipoNomina) { return this.pagoDao.consultaFechaEjecucionYdescripcionPago(fechaPaga,tipoNomina); } }
true
2584ceac7fb5508a3d10738d573ef5ec7786902e
Java
VU-libtech/OLE-INST
/ole-app/olefs/src/main/java/org/kuali/ole/fp/document/web/struts/CreditCardReceiptAction.java
UTF-8
5,731
1.789063
2
[ "ECL-2.0" ]
permissive
/* * Copyright 2006 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.ole.fp.document.web.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.kuali.ole.fp.businessobject.CreditCardDetail; import org.kuali.ole.fp.document.CreditCardReceiptDocument; import org.kuali.ole.fp.document.validation.impl.CreditCardReceiptDocumentRuleUtil; import org.kuali.ole.sys.OLEConstants; import org.kuali.ole.sys.OLEPropertyConstants; import org.kuali.ole.sys.context.SpringContext; import org.kuali.ole.sys.service.BankService; import org.kuali.rice.kew.api.exception.WorkflowException; import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase; import org.kuali.rice.krad.util.GlobalVariables; /** * This is the action class for the CreditCardReceiptDocument. */ public class CreditCardReceiptAction extends CapitalAccountingLinesActionBase { /** * Adds handling for credit card receipt amount updates. * * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CreditCardReceiptForm ccrForm = (CreditCardReceiptForm) form; if (ccrForm.hasDocumentId()) { CreditCardReceiptDocument ccrDoc = ccrForm.getCreditCardReceiptDocument(); ccrDoc.setTotalCreditCardAmount(ccrDoc.calculateCreditCardReceiptTotal()); // recalc b/c changes to the amounts could // have happened //set bank ccrDoc.setBank(SpringContext.getBean(BankService.class).getByPrimaryId(ccrDoc.getCreditCardReceiptBankCode())); } // proceed as usual return super.execute(mapping, form, request, response); } /** * Adds a CreditCardDetail instance created from the current "new creditCardReceipt" line to the document * * @param mapping * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public ActionForward addCreditCardReceipt(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CreditCardReceiptForm ccrForm = (CreditCardReceiptForm) form; CreditCardReceiptDocument ccrDoc = ccrForm.getCreditCardReceiptDocument(); CreditCardDetail newCreditCardReceipt = ccrForm.getNewCreditCardReceipt(); ccrDoc.prepareNewCreditCardReceipt(newCreditCardReceipt); // creditCardReceipt business rules boolean rulePassed = validateNewCreditCardReceipt(newCreditCardReceipt); if (rulePassed) { // add creditCardReceipt ccrDoc.addCreditCardReceipt(newCreditCardReceipt); // clear the used creditCardReceipt ccrForm.setNewCreditCardReceipt(new CreditCardDetail()); } return mapping.findForward(OLEConstants.MAPPING_BASIC); } /** * Deletes the selected creditCardReceipt (line) from the document * * @param mapping * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public ActionForward deleteCreditCardReceipt(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CreditCardReceiptForm ccrForm = (CreditCardReceiptForm) form; CreditCardReceiptDocument ccrDoc = ccrForm.getCreditCardReceiptDocument(); int deleteIndex = getLineToDelete(request); // delete creditCardReceipt ccrDoc.removeCreditCardReceipt(deleteIndex); return mapping.findForward(OLEConstants.MAPPING_BASIC); } /** * This method validates a new credit card receipt detail record. * * @param creditCardReceipt * @return boolean */ protected boolean validateNewCreditCardReceipt(CreditCardDetail creditCardReceipt) { GlobalVariables.getMessageMap().addToErrorPath(OLEPropertyConstants.NEW_CREDIT_CARD_RECEIPT); boolean isValid = CreditCardReceiptDocumentRuleUtil.validateCreditCardReceipt(creditCardReceipt); GlobalVariables.getMessageMap().removeFromErrorPath(OLEPropertyConstants.NEW_CREDIT_CARD_RECEIPT); return isValid; } /** * Do initialization for a new credit card receipt * * @see org.kuali.rice.kns.web.struts.action.KualiDocumentActionBase#createDocument(org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase) */ @Override protected void createDocument(KualiDocumentFormBase kualiDocumentFormBase) throws WorkflowException { super.createDocument(kualiDocumentFormBase); ((CreditCardReceiptDocument) kualiDocumentFormBase.getDocument()).initiateDocument(); } }
true
ee60e24343f2d8500cae30cb2d6070b2bde90654
Java
TheStudyGroup/Sokoban
/src/com/c0destudy/sokoban/ui/helper/RichJButton.java
UTF-8
692
2.90625
3
[ "MIT" ]
permissive
package com.c0destudy.sokoban.ui.helper; import javax.swing.*; import java.awt.*; public class RichJButton extends JButton { public RichJButton(final String text) { super(text); } @Override public void setBackground(Color color) { super.setBackground(color); if (color.getAlpha() < 255) { setOpaque(false); } } @Override protected void paintComponent(Graphics g) { if (!isOpaque() && getBackground().getAlpha() < 255) { g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(getForeground()); } super.paintComponent(g); } }
true
2947f6a39bb79f75ff24f2b72b85e2fbab43e251
Java
27house/CrazyAlarm
/android/app/src/main/java/com/sunn/xhui/crazyalarm/ui/adapter/VoiceListAdapter.java
UTF-8
4,936
2.03125
2
[]
no_license
package com.sunn.xhui.crazyalarm.ui.adapter; import android.content.Context; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.sunn.xhui.crazyalarm.Constant; import com.sunn.xhui.crazyalarm.R; import com.sunn.xhui.crazyalarm.data.Voice; import com.sunn.xhui.crazyalarm.mpv.contract.DownloadContract; import com.sunn.xhui.crazyalarm.mpv.presenter.DownloadPresenter; import com.sunn.xhui.crazyalarm.ui.alarm.AddAlarmActivity; import com.sunn.xhui.crazyalarm.ui.widget.ProgressButton; import com.sunn.xhui.crazyalarm.utils.FileUtils; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * 音频列表 * * @author XHui.sun * created at 2018/5/17 0017 10:44 */ public class VoiceListAdapter extends BaseRecycleAdapter { private SelectCallback callback; public VoiceListAdapter(Context context, SelectCallback callback) { super(context); this.callback = callback; } public void setVoiceList(List<Voice> list) { setDataList(list); } @NonNull @Override public BaseRecViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { if (viewType == BaseRecycleAdapter.V_TYPE_DATA) { View view = LayoutInflater.from(context).inflate(R.layout.item_create_voice, parent, false); return new VoiceViewHolder(view); } return super.onCreateViewHolder(parent, viewType); } public class VoiceViewHolder extends BaseRecViewHolder implements ProgressButton.OnProgressButtonClickListener { @BindView(R.id.iv_icon) ImageView ivIcon; @BindView(R.id.tv_title) TextView tvTitle; @BindView(R.id.btn_voice) ProgressButton btnVoice; private Voice voice; VoiceViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } @Override public void setData(Object item) { super.setData(item); voice = (Voice) item; switch (voice.getType()) { case Voice.TYPE_RING_TONE: // 铃声 case Voice.TYPE_DOWNLOAD: // 已下载 btnVoice.setText(R.string.used); break; case Voice.TYPE_ONLINE: // 在线 btnVoice.setText(R.string.download); break; default: break; } if (context instanceof AddAlarmActivity) { AddAlarmActivity activity = (AddAlarmActivity) context; if (activity.currentVoice != null && activity.currentVoice.getTitle().equals(voice.getTitle())) { btnVoice.setText(R.string.already_used); btnVoice.setForeground(ContextCompat.getColor(context, R.color.gray_cd)); } } else { btnVoice.setForeground(ContextCompat.getColor(context, R.color.colorPrimary)); } if (voice.isUsed()) { // 正在拨放中 tvTitle.setTextColor(ContextCompat.getColor(context, R.color.colorPrimaryDark)); ivIcon.setVisibility(View.VISIBLE); } else { // 没有被选中播放 tvTitle.setTextColor(ContextCompat.getColor(context, R.color.gray_33)); ivIcon.setVisibility(View.GONE); } tvTitle.setText(voice.getTitle()); btnVoice.setOnProgressButtonClickListener(this); } @OnClick(R.id.ll_content) public void clickItem(View view) { // 播放 callback.play(voice); } @Override public void onClickListener() { switch (voice.getType()) { case Voice.TYPE_RING_TONE: case Voice.TYPE_DOWNLOAD: // 铃声 、已下载 -- 确定选择 callback.used(voice); break; case Voice.TYPE_ONLINE: // 在线 -- 下载(下载成功后改为使用) final String fpn = FileUtils.getFilesPath(context, Constant.FILE_NAME_RINGTONE) + "/" + voice.getTitle() + ".mp3"; DownloadPresenter presenter = new DownloadPresenter(new DownloadContract.View() { @Override public void downloadSuccess() { btnVoice.setText("使用"); btnVoice.setProgress(100); voice.setPath(fpn); voice.setType(Voice.TYPE_DOWNLOAD); callback.download(voice); } @Override public void downloadProcess(int progress) { btnVoice.setText("正在下载..."); btnVoice.setProgress(progress); } @Override public void downloadFailed(String error) { btnVoice.setText("下载"); } @Override public String filePathName() { // 下载保存地址 return fpn; } }); presenter.downloadFile(voice.getUrl()); break; default: break; } } } public interface SelectCallback { /** * 选中-去播放 * * @param voice Voice */ void play(Voice voice); /** * 选中-确定使用,关闭页面并返回 * * @param voice Voice */ void used(Voice voice); /** * 选中-去下载,并在本地中显示 * * @param voice Voice */ void download(Voice voice); } }
true
f42218ec8e529f52f7a53ca9053fdcde79ee491a
Java
hml763/JAVA-practice
/20.05.03/enumeration_열거형.java
WINDOWS-1252
607
3.65625
4
[]
no_license
enum Color{ Red, Green, Blue } public class enumeration_ { public static void main(String[] args) { for(Color col : Color.values()) { System.out.println(col); } Color c = Color.Red; System.out.println( c + "'s value is : " + c.ordinal()); System.out.println( c + "'s value is : " + c + "\n"); c = Color.valueOf("Blue"); System.out.println( c + "'s value is : " + c.ordinal()); System.out.println( c + "'s value is : " + c + "\n\n"); c = Color.valueOf("Yellow"); System.out.println( c + "'s value is : " + c.ordinal()); } }
true
e5e6d42e02b327d364826c2966e96667f799a542
Java
RakibHassanIDB/Buy-Sell
/src/java/service/course_RS.java
UTF-8
1,590
2.15625
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 service; import dao.course_Dao; import entity.Course; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; /** * * @author SAM */ @Path("/courses") public class course_RS { course_Dao dao = new course_Dao(); @GET @Produces(MediaType.APPLICATION_JSON) public List<Course> get2Course() { List<Course> listofCourse = dao.getAllCoursenew(); return listofCourse; } @GET @Path("/{cid}") @Produces(MediaType.APPLICATION_JSON) public List<Course> getCoursesByIDnew(@PathParam("cid") int cid) { return dao.getCourseByIDnew(cid); } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Course add2Course(Course c) { return dao.add2Coursenew(c); } @PUT @Produces(MediaType.APPLICATION_JSON) public Course update2Course(Course c) { return dao.updateCourseew(c); } @DELETE @Path("/{cid}") @Produces(MediaType.APPLICATION_JSON) public void delete2Course(@PathParam("cid") int cid) { dao.deleteCourseInfonew(cid); } }
true
772939b4e2e3b3f75b81fa9e659c3a1eef1931b4
Java
evertoncamacho/teste-docket
/src/main/java/br/com/docket/teste/cartorio/rest/GerenciaCartorioResource.java
UTF-8
2,129
1.914063
2
[]
no_license
package br.com.docket.teste.cartorio.rest; import br.com.docket.teste.cartorio.model.Cartorio; import br.com.docket.teste.cartorio.model.Certidao; import br.com.docket.teste.cartorio.service.CartorioServiceImpl; import br.com.docket.teste.cartorio.service.CertidaoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; @RestController @RequestMapping(value = "/api") public class GerenciaCartorioResource { @Autowired private CartorioServiceImpl cartorioService; @Autowired private CertidaoService certidaoService; @GetMapping("/listaCertidoesRelacionadasComCartorios") public ResponseEntity<List<Certidao>> relacionaCertidoesComCartorios() { return ResponseEntity.ok(certidaoService.buscaCertidoesECartoriosRelacionados()); } @GetMapping("/cartorios") public ResponseEntity<List<Cartorio>> exibeCartorios() { return ResponseEntity.ok(cartorioService.buscaTodos()); } @GetMapping("/cartorios/{id}") public ResponseEntity<Cartorio> buscaCartorio(@PathVariable("id") Long id) { return ResponseEntity.ok(cartorioService.procuraPorId(id).get()); } @PostMapping("/cartorios/salvar") public ResponseEntity<Cartorio> salvaCartorio(@Valid @RequestBody Cartorio cartorio) { return new ResponseEntity<>(cartorioService.salvaOuAtualiza(cartorio), HttpStatus.CREATED); } @PutMapping("/cartorios/editar/{id}") public ResponseEntity<Cartorio> editaCartorio(@Valid @RequestBody Cartorio cartorioRequisicao, @PathVariable("id") Long id) { return ResponseEntity.ok(cartorioService.atualizaCartorioApi(cartorioRequisicao, id)); } @DeleteMapping("/cartorios/remove/{id}") public ResponseEntity<Void> removeCartorio(@PathVariable("id") Long id) { cartorioService.remove(cartorioService.buscaApenasCartorioPorId(id).get()); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } }
true
30576808daea6eb05dcde53eae40f38e1446235d
Java
DiegoGranadosLy/ConstruTEC
/app/src/main/java/com/tec/diegogranados/construtec/Buscar_Proyecto.java
UTF-8
2,737
2.25
2
[]
no_license
package com.tec.diegogranados.construtec; import android.content.Intent; import android.os.Build; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; public class Buscar_Proyecto extends AppCompatActivity { String Nombre_Usuario; String Nivel_de_Acceso; String Busqueda; ArrayAdapter adapter; ListView listview; String[] values; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.buscar__proyecto); Nombre_Usuario = (String) getIntent().getExtras().getSerializable(String.valueOf(R.string.Nombre_Paso_Parametros)); Nivel_de_Acceso= (String) getIntent().getExtras().getSerializable(String.valueOf(R.string.Acceso_Paso_Parametros)); Busqueda= (String) getIntent().getExtras().getSerializable(String.valueOf(R.string.Busqueda_Paso_Parametros)); this.Crear_List_Adapter(); } private void Crear_List_Adapter(){ listview = (ListView) findViewById(R.id.list_View_Buscar_Proyecto); values = new String[] { "Casa Enzo", "Casa Diego", "Abastecedor el Aguila", "El Halcon", "Vista Hermosa", "San Juan de Dios", "Tecnologico", "HP", "Teradyne", "UCR", "UNA", "ULICORI", "UCA", "UNED", "Biblioteca"}; final ArrayList<String> list = new ArrayList<String>(); for (int i = 0; i < values.length; ++i) { list.add(values[i]); } adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list); listview.setAdapter(adapter); this.Agregar_Accion(listview); } private void Agregar_Accion(ListView listview){ listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { Intent siguiente; final String item = (String) parent.getItemAtPosition(position); siguiente = new Intent(Buscar_Proyecto.this, Info_Obra.class); siguiente.putExtra(String.valueOf(R.string.Nombre_Paso_Parametros),Nombre_Usuario); siguiente.putExtra(String.valueOf(R.string.Acceso_Paso_Parametros),Nivel_de_Acceso); siguiente.putExtra("Obra", item); startActivity(siguiente); } }); } }
true
c8c2cdebe6786c97f9ffe0f40f0d563eeb0e8587
Java
ganzhiping/peony-newTancms
/peony-tancms/src/main/java/com/peony/newPeony/page/service/PageService.java
UTF-8
410
1.578125
2
[]
no_license
package com.peony.newPeony.page.service; import com.peony.core.base.pojo.PageParameter; import com.peony.newPeony.page.model.Page; /** * Created by Administrator on 2017/8/18. */ public interface PageService { String thinkInfoPage(PageParameter pageParameter, String str, String s); Page SubjectPage(PageParameter pageParameter, int str, int s); Page ESSearchPage(String queryid,int pageNo); }
true
7155fa4b43e510505d44418a8ff7620dc47bfa07
Java
ppuczka/practicereactor
/src/test/java/FluxTest.java
UTF-8
1,115
2.765625
3
[]
no_license
import org.junit.jupiter.api.Test; import reactor.core.publisher.Flux; import java.time.Duration; import java.util.Arrays; public class FluxTest { @Test void firstFlux() { Flux.just("A", "B", "C") .log() .subscribe(); } @Test void fluxFromIterable() { Flux.fromIterable(Arrays.asList("A", "B", "C") ) .log() .subscribe(); } @Test void fluxFromRange() { Flux.range(10, 5) .log() .subscribe(); } @Test void fluxFromInterval() throws InterruptedException { Flux.interval(Duration.ofSeconds(1)) .log() .take(2) .subscribe(); Thread.sleep(5000); } @Test void fluxRequest() { Flux.range(10, 5) .log() .subscribe(null, null, null, s-> s.request(3)); } @Test void fluxLimit() { Flux.range(10, 5) .log() .limitRate(3) .subscribe(); } }
true
cf22b14651d6f48f73d74cce25ca647a27ba2056
Java
Andxtorres/POO-Agosto_Diciembre_2019
/MiniProyecto/mapa/Mapa.java
UTF-8
245
2.359375
2
[]
no_license
package mapa; public class Mapa{ public Casilla[][] casillas; public Mapa(){ casillas=new Casilla[50][50]; for(int i=0;i<casillas.length;i++){ for(int j=0;j<casillas[i].length;j++){ casillas[i][j]=new Casilla(); } } } }
true
2d640b31c19ccd7aa678a7424369c17082514f34
Java
Chate328/Bank-savings-menagement-systems
/银行储蓄管理界面/src/银行储蓄管理界面/JPanelForUserselect.java
GB18030
3,057
2.125
2
[]
no_license
package д; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.math.BigDecimal; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; public class JPanelForUserselect { JButton HQ,DQ,HQMX,DQMX,ZH; JPanel m,w; TextBorderUtlis Border2,Border1,Border3; DateChooserJButton button,button2; JComboBox JC; public static String User_id; JLabel J1,J2; JPanelForUserselect(JPanel n,JPanel m,String str){ this.w=m; this.m=n; this.User_id=str; HQ=new JButton(); HQMX=new JButton("ڴȡ¼"); ZH=new JButton("ת˼¼"); DQMX=new JButton("ڴȡ¼"); button=new DateChooserJButton(); button2=new DateChooserJButton(); JC=new JComboBox(); JC.addItem("ڴ¼"); JC.addItem("ڴ¼"); JC.addItem("תϸ¼"); JC.addItem("ڴȡ¼"); JC.addItem("ڴȡ¼"); Border2=new TextBorderUtlis(new Color(255,255,255),1,true); Border1=new TextBorderUtlis(new Color(0,191,255),1,true); Border3=new TextBorderUtlis(new Color(255,255,255),1,true); J1=new JLabel("ֹ:"); J2=new JLabel("--"); } public void setUserSelect() { m.add(J1); J1.setBounds(160, 30, 100, 25); m.add(J2); J2.setBounds(350, 25, 20, 25); m.add(JC); JC.setBounds(0,0, 105, 23); JC.setBorder(Border2); JC.setBackground(Color.white); m.add(button); button.setBounds(220, 30, 130, 20); button.setBorder(Border1); button.setBackground(Color.white); m.add(button2); button2.setBounds(360,30,130,20); button2.setBorder(Border1); button2.setBackground(Color.white); m.add(HQ); HQ.setBounds(550,30,40, 25); ImageIcon Iconu = new ImageIcon("src/images/CX.jpg"); HQ.setIcon(Iconu); HQ.setBorder(Border2); HQ.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub String str=JC.getSelectedItem().toString().trim(); String start=button.getText().toString(); String end=button2.getText().toString(); if(str.equals("ڴ¼")) { UserforHQ U=new UserforHQ(User_id); U.ActionListenerforHQ(w, start, end); }else if(str.equals("ڴ¼")) { UserForDQ U=new UserForDQ(User_id); U.ActionListenerforDQ(w, start, end); }else if(str.equals("תϸ¼")) { UserforZH U=new UserforZH(User_id); U.ActionListenerforZH(w, start, end); }else if(str.equals("ڴȡ¼")) { UserforDQMX U=new UserforDQMX(User_id); U.ActionListenerforDQMX(w, start, end); }else if(str.equals("ڴȡ¼")){ UserforHQMX U=new UserforHQMX(User_id); U.ActionListenerforDQMX(w, start, end); } } }); } }
true
1cf18a3478e11fbe41b5e95ac6d4e17f3726dba2
Java
moutainhigh/tohome
/95_SC/sc-master/src/main/java/cn/com/bbut/iy/itemmaster/dao/receipt/warehouse/WarehouseMapper.java
UTF-8
1,783
1.90625
2
[]
no_license
package cn.com.bbut.iy.itemmaster.dao.receipt.warehouse; import cn.com.bbut.iy.itemmaster.dto.base.GridDataDTO; import cn.com.bbut.iy.itemmaster.dto.od0000_t.OD0000TDTO; import cn.com.bbut.iy.itemmaster.dto.receipt.warehouse.WarehouseDetailsGridDTO; import cn.com.bbut.iy.itemmaster.dto.receipt.warehouse.WarehouseDetailsParamDTO; import cn.com.bbut.iy.itemmaster.dto.receipt.warehouse.WarehouseReceiptGridDTO; import cn.com.bbut.iy.itemmaster.dto.receipt.warehouse.WarehouseReceiptParamDTO; import org.springframework.stereotype.Repository; import java.util.List; /** * 仓库配送验收DAO * */ @Repository public interface WarehouseMapper { /** * 查询仓库配送验收头档 */ List<WarehouseReceiptGridDTO> selectReceipt(WarehouseReceiptParamDTO param); /** * 查询满足条件的记录条数 */ int selectReceiptCount(WarehouseReceiptParamDTO param); /** * 查询记录 */ WarehouseReceiptGridDTO selectByKey(WarehouseReceiptParamDTO param); /** * 查询仓库配送验收详情 */ List<WarehouseDetailsGridDTO> selectDetail(WarehouseDetailsParamDTO param); /** * 查询满足条件的记录条数 */ int selectDetailCount(WarehouseDetailsParamDTO param); /** * 主键查询记录详情 */ WarehouseDetailsGridDTO selectDetailByKey(WarehouseDetailsGridDTO param); int modifyReviewStatus(String orderId); /** * 修改收货数量 */ int modifyQty(WarehouseDetailsGridDTO param); /** * 修改订单状态 */ int updateStatus(WarehouseReceiptParamDTO param); /** * 打印功能 * @param param * @return */ List<WarehouseReceiptGridDTO> getPrintData(WarehouseReceiptParamDTO param); }
true
3f0c6925a8250e880c86d525139234e4d660ce6d
Java
luchongbin/luchongwen
/app/src/main/java/com/luchongbin/mycashbook/greendao/DaoSession.java
UTF-8
2,345
2.0625
2
[]
no_license
package com.luchongbin.mycashbook.greendao; import java.util.Map; import org.greenrobot.greendao.AbstractDao; import org.greenrobot.greendao.AbstractDaoSession; import org.greenrobot.greendao.database.Database; import org.greenrobot.greendao.identityscope.IdentityScopeType; import org.greenrobot.greendao.internal.DaoConfig; import com.luchongbin.mycashbook.bean.CashBook; import com.luchongbin.mycashbook.bean.CheQueLog; import com.luchongbin.mycashbook.bean.User; import com.luchongbin.mycashbook.greendao.CashBookDao; import com.luchongbin.mycashbook.greendao.CheQueLogDao; import com.luchongbin.mycashbook.greendao.UserDao; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * {@inheritDoc} * * @see org.greenrobot.greendao.AbstractDaoSession */ public class DaoSession extends AbstractDaoSession { private final DaoConfig cashBookDaoConfig; private final DaoConfig cheQueLogDaoConfig; private final DaoConfig userDaoConfig; private final CashBookDao cashBookDao; private final CheQueLogDao cheQueLogDao; private final UserDao userDao; public DaoSession(Database db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig> daoConfigMap) { super(db); cashBookDaoConfig = daoConfigMap.get(CashBookDao.class).clone(); cashBookDaoConfig.initIdentityScope(type); cheQueLogDaoConfig = daoConfigMap.get(CheQueLogDao.class).clone(); cheQueLogDaoConfig.initIdentityScope(type); userDaoConfig = daoConfigMap.get(UserDao.class).clone(); userDaoConfig.initIdentityScope(type); cashBookDao = new CashBookDao(cashBookDaoConfig, this); cheQueLogDao = new CheQueLogDao(cheQueLogDaoConfig, this); userDao = new UserDao(userDaoConfig, this); registerDao(CashBook.class, cashBookDao); registerDao(CheQueLog.class, cheQueLogDao); registerDao(User.class, userDao); } public void clear() { cashBookDaoConfig.clearIdentityScope(); cheQueLogDaoConfig.clearIdentityScope(); userDaoConfig.clearIdentityScope(); } public CashBookDao getCashBookDao() { return cashBookDao; } public CheQueLogDao getCheQueLogDao() { return cheQueLogDao; } public UserDao getUserDao() { return userDao; } }
true
68bfe32f77844b78f08e39a7388cbb69e7c2c635
Java
devtadiyal/Tabon
/app/src/main/java/com/saffron/tabon/contacts/AddOfferGetter.java
UTF-8
505
2.1875
2
[]
no_license
package com.saffron.tabon.contacts; /** * Created by saffron on 3/29/2018. */ public class AddOfferGetter { private int img; private String no; private String banner; public AddOfferGetter(int img, String banner, String no) { this.img = img; this.banner = banner; this.no = no; } public int getImg() { return img; } public String getBanner() { return banner; } public String getNo() { return no; } }
true
bc7508f0fc549362b269405774b81a7ba5d8f479
Java
salt-hai/salt-blog
/src/main/java/com/salthai/blog/config/TextViewConfig.java
UTF-8
741
1.90625
2
[]
no_license
package com.salthai.blog.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @Author: SaltHai * @Date: 2020/3/12 21:48 * @Version 1.0 */ @Configuration public class TextViewConfig implements WebMvcConfigurer { /** * 用于页面测试 * * @param registry */ @Override public void addViewControllers(ViewControllerRegistry registry) { // registry.addViewController("/admin/adminInfo").setViewName("/admin/adminInfo"); // registry.setOrder(Ordered.HIGHEST_PRECEDENCE); // WebMvcConfigurer.super.addViewControllers(registry); } }
true
01d2e585d50d566e50d75f0efb6ab8671385535f
Java
Nunocky/ActionViewStudy01
/app/src/main/java/org/nunocky/actionviewstudy01/MySeekBar.java
UTF-8
1,781
2.34375
2
[]
no_license
package org.nunocky.actionviewstudy01; import android.content.Context; import android.support.v7.view.CollapsibleActionView; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.TextView; /** * TODO: document your custom view class. */ public class MySeekBar extends LinearLayout implements CollapsibleActionView { public MySeekBar(Context context) { super(context); setGravity(Gravity.CENTER_VERTICAL); LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT); setLayoutParams(params); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View child = inflater.inflate(R.layout.actionview_seekbar, this, true); final SeekBar seekBar = (SeekBar) child.findViewById(R.id.seekbar); final TextView seekValue = (TextView) child.findViewById(R.id.seek_value); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { seekValue.setText(progress + ""); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); seekBar.setProgress(50); seekValue.setText("50"); } @Override public void onActionViewExpanded() { } @Override public void onActionViewCollapsed() { } }
true
bd2ced85ea93e14be4549fdbd0b5a58b1e673252
Java
C2P1/Monopoly
/src/main/java/monopoly/GameLogic.java
UTF-8
9,416
2.96875
3
[]
no_license
package monopoly; public class GameLogic { private Square[] squares = { new Square("GO", 200, 658, 658), new Square(new Property("Mediterranean Avenue", 60, 2, 50, 50, 0, 2), 569, 658), new Square("Community Chest", 0, 511, 658), new Square(new Property("Baltic Avenue", 60, 4, 50, 50, 0, 2), 453, 658), new Square("Income Tax", -200, 395, 658), new Square(new Property("Reading Railroad", 200, 25, 0, 0, 8,4), 337, 658), new Square(new Property("Oriental Avenue", 100, 6, 50, 50, 1, 3), 279, 658), new Square("Chance", 0, 221, 658), new Square(new Property("Vermont Avenue", 100, 6, 50, 50, 1,3),163, 658), new Square(new Property("Connecticut Avenue", 120, 8, 50, 50, 1, 3), 105, 658), new Square("Just Visiting", 0, 31, 658), new Square(new Property("St. Charles Place", 140, 10, 100, 100, 2,3), 31, 569), new Square(new Property("Electric Company", 150, 4, 0, 0, 9,2), 31, 511), new Square(new Property("States Avenue", 140, 10, 100, 100, 2,3), 31, 453), new Square(new Property("Virginia Avenue", 160, 12, 100, 100, 2,3), 31, 395), new Square(new Property("Pennsylvania Railroad", 200, 25, 0, 0, 8,4),31, 337), new Square(new Property("St. James Place", 180, 14, 100, 100, 3,3),31, 279), new Square("Community Chest", 0, 31, 221), new Square(new Property("Tennesse Avenue", 180, 14, 100, 100, 3, 3), 31, 163), new Square(new Property("New York Avenue", 200, 16, 100, 100, 3, 3), 31, 105), new Square("Free Parking", 0, 31, 31), new Square(new Property("Kentucky Avenue", 220, 18, 150, 150, 4, 3), 105, 31), new Square("Chance", 0, 163, 31), new Square(new Property("Indiana Avenue", 220, 18, 150, 150, 4, 3),221, 31), new Square(new Property("Illinois Avenue", 240, 20, 150, 150, 4, 3),279, 31), new Square(new Property("B & O Railroad", 200, 25, 0, 0, 8, 4),337, 31), new Square(new Property("Atlantic Avenue", 260, 22, 150, 150, 5, 3),395, 31), new Square(new Property("Ventnor Avenue", 260, 22, 150, 150, 5, 3), 453, 31), new Square(new Property("Water Works", 150, 4, 0, 0, 9, 2), 511, 31), new Square(new Property("Marvin Gardens", 280, 24, 150, 150, 5, 3), 569, 31), new Square("Go To Jail", 0, 658,31), new Square(new Property("Pacific Avenue", 300, 28, 200, 200, 6, 3), 658, 105), new Square(new Property("North Carolina Avenue", 300, 26, 200, 200, 6, 3), 658, 163), new Square("Community Chest", 0, 658, 221), new Square(new Property("Pennsylvania Avenue", 320, 28, 200, 200, 6, 3), 658, 279), new Square(new Property("Short Line Railroad", 200, 25, 0, 0, 8, 4),658, 337), new Square("Chance", 0, 658, 395), new Square(new Property("Park Place", 350, 35, 200, 200, 7, 2), 658, 453), new Square("Luxury Tax", -100, 658, 511), new Square(new Property("Boardwalk", 400, 50, 200, 200, 7, 2), 658, 569) }; private Player[] players; private Player turn; private int whoseturn; private int playerLoc; //the current Player's location on the board private int xCoord, yCoord; private double paidValue; private boolean compPlayer; public GameLogic(Player[] p) { whoseturn=0; players=p; paidValue=0; } //method to determine if the current Player is the computer public boolean isComputer() { if (turn.getOrder() == 0 && Prompt.isCompPlayer()) { return true; } else { return false; } } //method to set the compPlayer public void setCompPlayer(boolean x) { compPlayer = x; } //method to determine if there is a compPlayer public boolean isCompPlayer() { return compPlayer; } //method to determine if the Player has been in the jail for 3 turns public boolean clearToLeave() { if (turn.getAttempts() < 2) { turn.updateAttempts(); return false; } else { return true; } } //method to determine if the Player has sufficient funds for a Property public boolean hasFunds() { if (turn.getBalance() < squares[playerLoc].getProperty().getPrice()) { return false; } else { return true; } } public void nextTurn() { // turn=players[whoseturn]; // whoseturn = (whoseturn + 1)%(players.length); turn=players[whoseturn]; whoseturn++; if(whoseturn>3||players[whoseturn]==null) { whoseturn=0; } } public boolean buyproperty(){ //get the current Property, buy it, make the button invisible, change the text Property toBuy = squares[playerLoc].getProperty(); return turn.buyDeed(toBuy); } public boolean isUtilorRail(Property p) { if(p.getSetNum()==8||p.getSetNum()==9) { return true; } else { return false; } } public boolean isFullSet(Player player, Property myproperty) { if (myproperty != null) { int numInSet=myproperty.getNumInSet(); int count=player.getProperties().get(myproperty.getSetNum()).size(); if(isUtilorRail(myproperty)) { return false; } if(count==numInSet) { return true; } else { return false; } } else { return false; } // int numInSet=myproperty.getNumInSet(); // int count=player.getProperties().get(myproperty.getSetNum()).size(); // if(isUtilorRail(myproperty)) { // return false; // } // if(count==numInSet) { // return true; // } // else { // return false; // } } public boolean passedGo(int sum) { if((turn.getLocation()+sum)>=40) { return true; } else { return false; } } public void moveplayer(int sum) { playerLoc= (sum+turn.getLocation())%40; turn.setLocation(playerLoc); xCoord=squares[playerLoc].getX(); //CHANGED FROM i yCoord=squares[playerLoc].getY(); //CHANGED FROM i } public int getX() { return xCoord; } public int getY() { return yCoord; } public Player getTurn() { return turn; } public int getTurnIndex() { return whoseturn; } public boolean isValidProperty() { if(squares[playerLoc].getProperty()!=null && !squares[playerLoc].getProperty().getIsOwned()) { return true; } else { return false; } } //method to determine if the current Player is also the owner of the current Property public boolean isOwner() { if (turn == squares[playerLoc].getProperty().getOwner()) { return true; } else { return false; } } public int handleSquare(int sum) { Square current=squares[playerLoc]; if(playerLoc==4||playerLoc==38) { handleTax(); return 0; } else if (playerLoc==30) { handleJail(); return 1; } else if(isValidProperty()) { return 2; } else if(current.getProperty()!=null) { if(playerLoc==12||playerLoc==28) { handleUtil(sum); } else if(current.getProperty().getNumInSet()==4) { handleRail(); } else{ handleProp(); } //check if the current Player is also the owner if (isOwner()) { //System.out.println("Player has landed on their own property."); return 4; } else //can only return 3 i.e. an owned Property, if the current Player is not the owner { return 3; } } else { return 4; } } public void handleProp() { //the current Player is also the owner of the current Property if (isOwner()) { //System.out.println("Player has landed on their own property."); } else { //handle the player owning the entire set; rent is doubled if (isFullSet(squares[playerLoc].getProperty().getOwner(), squares[playerLoc].getProperty())) { paidValue = squares[playerLoc].getProperty().getRent() * 2; turn.updateBalance(-paidValue); squares[playerLoc].getProperty().getOwner().updateBalance(paidValue); } else //handle the player not owning the entire set { paidValue=squares[playerLoc].getProperty().getRent(); turn.updateBalance(-paidValue); squares[playerLoc].getProperty().getOwner().updateBalance(paidValue); } } } public void handleRail(){ Player owner=squares[playerLoc].getProperty().getOwner(); int count=owner.getProperties().get(squares[playerLoc].getProperty().getSetNum()).size(); switch (count) { case 1: paidValue=25; break; case 2: paidValue=50; break; case 3: paidValue=100; break; case 4: paidValue=200; break; } //the current Player is also the owner of the current Property if (isOwner()) { System.out.println("Player has landed on their own property."); } else { turn.updateBalance(-paidValue); owner.updateBalance(paidValue); } } public void handleUtil(int sum) { Player owner=squares[playerLoc].getProperty().getOwner(); if(isFullSet(squares[playerLoc].getProperty().getOwner(), squares[playerLoc].getProperty())) { paidValue=sum*10; } else { paidValue=sum*4; } //the current Player is also the owner of the current Property if (isOwner()) { System.out.println("Player has landed on their own property."); } else { turn.updateBalance(-paidValue); owner.updateBalance(paidValue); } } public void handleJail() { turn.setJailed(true); turn.setLocation(10); playerLoc=10; xCoord=squares[playerLoc].getX(); //CHANGED FROM i yCoord=squares[playerLoc].getY(); //CHANGED FROM i } public void handleTax() { switch(playerLoc) { case 4:turn.updateBalance((-200)); paidValue=200; break; default:turn.updateBalance((-100)); paidValue=100; break; } } public Square getCurrentSquare() { return squares[playerLoc]; } public double getPaidValue() { return paidValue; } }
true
984693b5707703b21e9f0bd3551ba87631cad73a
Java
fengt/akl
/src/cn/com/akl/ccgl/cgrk/rtclass/StepNo4TransactionAfter.java
GB18030
1,762
2.0625
2
[]
no_license
package cn.com.akl.ccgl.cgrk.rtclass; import java.sql.Connection; import java.util.Hashtable; import java.util.Vector; import cn.com.akl.ccgl.cgrk.cnt.CgrkCnt; import cn.com.akl.u8.senddata.SendPurchaseOrderData; import cn.com.akl.util.DAOUtil; import cn.com.akl.util.StrUtil; import com.actionsoft.awf.organization.control.UserContext; import com.actionsoft.awf.util.DBSql; import com.actionsoft.loader.core.WorkFlowStepRTClassA; import com.actionsoft.sdk.local.level0.BOInstanceAPI; public class StepNo4TransactionAfter extends WorkFlowStepRTClassA { private static final String QUERY_KHDM = "SELECT TOP 1 KHDM FROM BO_AKL_CCB_RKD_ZCXX WHERE BINDID =?"; private Connection conn = null; private UserContext uc; public StepNo4TransactionAfter() { // TODO Auto-generated constructor stub } public StepNo4TransactionAfter(UserContext uc) { super(uc); this.uc = uc; setProvider("fengtao"); setDescription("U8ӿڴݡ"); } @Override public boolean execute() { int bindid = this.getParameter(PARAMETER_INSTANCE_ID).toInt(); Hashtable<String, String> head = BOInstanceAPI.getInstance().getBOData(CgrkCnt.tableName0, bindid);//ͷ Vector<Hashtable<String, String>> body = BOInstanceAPI.getInstance().getBODatas(CgrkCnt.tableName1, bindid);// try{ conn = DBSql.open(); String khdm = StrUtil.returnStr(DAOUtil.getStringOrNull(conn, QUERY_KHDM, bindid));//ȡͻ if(khdm.equals(CgrkCnt.khdm0)){//ϲɹ SendPurchaseOrderData sendData = new SendPurchaseOrderData(); sendData.sendData(head, body); } }catch(Exception e){ e.printStackTrace(); }finally{ DBSql.close(conn, null, null); } return true; } }
true
053e7dd9eaee26b8b16ed06b14467a00d445011c
Java
Nickstar2020/smarsh-cop3330-assignment2
/src/test/java/ex35/AppTest.java
UTF-8
294
2.15625
2
[]
no_license
/* * UCF COP3330 Fall 2021 Assignment 2 Solution * Copyright 2021 Nicholas Smarsh */ package ex35; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class AppTest { @Test void pickWinner() { assertEquals("The winner is Nick", "Nick"); } }
true
9295ec259e2e6cbd33ee912b246ba14100d195af
Java
ACGaming/AquaMunda
/src/main/java/mcjty/aquamunda/blocks/cooker/CookerHandle.java
UTF-8
2,436
2.171875
2
[ "MIT" ]
permissive
package mcjty.aquamunda.blocks.cooker; import mcjty.aquamunda.items.ItemDish; import mcjty.aquamunda.items.ModItems; import mcjty.aquamunda.recipes.CookerRecipeRepository; import mcjty.immcraft.api.handles.DefaultInterfaceHandle; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.Vec3d; import net.minecraft.util.text.TextFormatting; class CookerHandle extends DefaultInterfaceHandle<DefaultInterfaceHandle> { private final CookerTE cookerTE; public CookerHandle(CookerTE cookerTE, String id) { super(id); this.cookerTE = cookerTE; } @Override public int getInsertAmount(boolean sneak) { return 1; } @Override public Vec3d getRenderOffset() { long t = System.currentTimeMillis(); float offset = (t % 3000) / 3000.0f; if (offset > .5) { offset = 1.0f - offset; } float dy = cookerTE.getContentsHeight() - .6f; return new Vec3d(0, (offset - 0.5f) / 20.0f + dy, 0); } @Override public ItemStack extractOutput(TileEntity genericTE, EntityPlayer player, int amount) { ItemStack stack = super.extractOutput(genericTE, player, amount); if (isItemThatNeedsExtractionItem(stack)) { String dishName = ((ICookerResult) stack.getItem()).getDishName(); stack = new ItemStack(ModItems.dish, stack.getCount(), ItemDish.getDishMeta(dishName)); } return stack; } @Override public boolean acceptAsInput(ItemStack stack) { if (!cookerTE.getSoup().isEmpty()) { return false; } return CookerRecipeRepository.getRecipe(stack) != null; } @Override public boolean isOutputWithItem() { return true; } @Override public boolean isItemThatNeedsExtractionItem(ItemStack item) { if (!item.isEmpty()) { return item.getItem() instanceof ICookerResult; } return false; } @Override public boolean isSuitableExtractionItem(ItemStack item) { if (!item.isEmpty()) { return item.getItem() == Items.BOWL; } return false; } @Override public String getExtractionMessage() { return TextFormatting.YELLOW + "You need a bowl to get the food out"; } }
true
d3ea9ce482e44283219bda474612658616b59c2b
Java
joelsousa/KCX-Mapping-Convert
/KCX-Mapping-Convert/src/com/kewill/kcx/component/mapping/db/CustomerDataDTO.java
UTF-8
967
2.3125
2
[]
no_license
package com.kewill.kcx.component.mapping.db; /** * Modul : CustomerDataDTO<br> * Erstellt : 17.06.2009<br> * Beschreibung : Data Transfer Object for the "customer_data" database table. * * @author schmidt * @version 1.0.00 */ public class CustomerDataDTO { private String kcxId = ""; private String pdfOutFormat = ""; private String bobName = ""; //EI20130215 public String getKcxId() { return kcxId; } public void setKcxId(String kcxId) { this.kcxId = kcxId; } public String getPdfOutFormat() { return pdfOutFormat; } public void setPdfOutFormat(String pdfOutFormat) { this.pdfOutFormat = pdfOutFormat; } public String getBobName() { if (bobName != null) { //EI20130902 bobName = bobName.trim(); } return bobName; } public void setBobName(String bob) { this.bobName = bob; } }
true
7fb79718b3e2ce4e217987411156872cc3de93a4
Java
liXXX-ops/JVMProjects
/src/jvm1/LoadBytecode.java
UTF-8
1,421
2.859375
3
[]
no_license
package jvm1; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Stack; import jvm1.ToBytecode; //装载器 public class LoadBytecode{ private static Stack<Map<Integer,String>> stack = new Stack<>(); private static String[][] form; private static int pc; public static Stack<Map<Integer,String>> Loading() throws IOException { pc=ToBytecode.Translate(); //获取PC的最大值,即字节码的个数 form=ToBytecode.WriteToTxt(); //获取字节码的数组 /* * 前期测试代码 Map<Integer,String> map = new HashMap<>(); map.put(1, "lzx"); stack.push(map); Map<Integer,String> maping= new HashMap<>(); maping=stack.pop(); Set<Integer> set = maping.keySet(); //Set获得到键值 String integer=maping.get(1); //get(k)获得到键值为key的String值 System.out.println(set+"???"+integer); */ //由于栈的结构性质,逆序装入,保证执行时顺序 Map<Integer,String> map = new HashMap<>(); for(int i=pc/5-1;i>=0;i--) //逆序装载 for(int j=4;j>=0;j--) { map.put(5*i+j, form[i][j]); stack.push(map); //PC与对应的值进栈 map = new HashMap<>(); } //for(int k=map.size()-1;k>=0;k--) //stack.push(map); //for(int k=map.size()-1;k>0;k--) //System.out.println(stack.pop()); //否则enginecode中返回过去的栈顶已经出栈 return stack; } }
true
6b69a25a2a8af19be91dc974cbb0533d64262b55
Java
tectronics/ephec-hackfiltration
/Hackfiltration/src/be/ephec/git/first/SocketServerBis.java
UTF-8
494
2.8125
3
[]
no_license
import java.net.*; import java.io.*; public class SocketServerBis { public static void main(String[] args) throws IOException, ClassNotFoundException { ServerSocket server = new ServerSocket(8080); System.out.println("Le serveur est démarré sur le port 8080 !"); //server.setSoTimeout(15000); Socket socket = server.accept(); ObjectInputStream input = new ObjectInputStream(socket.getInputStream()); System.out.println(input.readObject()); socket.close(); System.exit(0); } }
true
854418639752b84ea62f2ba9638fe9daa7be494b
Java
spoganshev/justfolio
/Folio/src/com/example/folio/client/component/CustomAnchor.java
UTF-8
761
2.21875
2
[]
no_license
package com.example.folio.client.component; import com.google.gwt.event.dom.client.MouseOutEvent; import com.google.gwt.event.dom.client.MouseOutHandler; import com.google.gwt.event.dom.client.MouseOverEvent; import com.google.gwt.event.dom.client.MouseOverHandler; import com.google.gwt.user.client.ui.Anchor; public class CustomAnchor extends Anchor { public CustomAnchor(String text) { super(text); setStyleName("anchor"); addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent arg0) { addStyleName("anchor_over"); } }); addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent arg0) { removeStyleName("anchor_over"); } }); } }
true
74266f47d6b160ba6014c8668ab392a9f34651d3
Java
emimontesdeoca/2DAW
/2017/DSW/Segundo trimestre/Practicas/Netbeans/sakilaRS_Emiliano/src/main/java/es/cifpcm/sakilars_emiliano/services/rest/ActorRest.java
UTF-8
1,907
2.125
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 es.cifpcm.sakilars_emiliano.services.rest; import es.cifpcm.sakilars_emiliano.Actor; import es.cifpcm.sakilars_emiliano.dao.ActorDao; import es.cifpcm.sakilars_emiliano.dao.ActorDaoImpl; import java.util.List; import java.util.ArrayList; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import java.lang.*; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; import org.primefaces.json.*; /** * * @author emont */ @Path("actor") public class ActorRest { public ActorRest() { } @GET @Path("allActors") @Produces(MediaType.APPLICATION_JSON) public String getAllActores() { ActorDao a = new ActorDaoImpl(); JSONArray json = new JSONArray(a.selectAll()); return json.toString(); } @POST @Path("/create") @Consumes({MediaType.APPLICATION_JSON}) public Response setActor(String json) { JSONObject jsonObj = new JSONObject(json); Actor a = new Actor(); a.setFirstName(jsonObj.getString("firstName")); a.setLastName(jsonObj.getString("lastName")); ActorDao dao = new ActorDaoImpl(); dao.insert(a); return Response.status(200).entity(jsonObj).build(); } @GET @Path("{data}") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response getActor(@PathParam("data") String data) { ActorDao a = new ActorDaoImpl(); JSONObject j = new JSONObject(a.selectAll().get(Integer.parseInt(data))); return Response.status(200).entity(j.toString()).build(); } }
true
0fca9841cd6ab714af94e2bc342257feae697dc9
Java
ivaifua/SoftServeTasks
/search_points_in_the_radius/VasylDanylyuk/src/main/java/App.java
UTF-8
802
2.90625
3
[]
no_license
import java.util.Collection; import java.util.HashSet; import java.util.Random; /** * Created by Vasyl Danylyuk on 15.10.2014. */ public class App { public static void main(String[] args){ Collection<IPoint> points = new HashSet<IPoint>(200,1); Random random = new Random(); for(int i = 0; i < 200; i++){ points.add(new PointByGeoCoordinates(random.nextDouble() / 10 + 48.86, random.nextDouble() / 10 + 24.63)); //48.9133962,24.9172989 } IPointsFinder pointsOnMap = new PointsOnMap(points); IPoint myPosition = new PointByGeoCoordinates(48.9120,24.68753527258d); int radius = 800; for(IPoint currentPoint : pointsOnMap.getPointsNearMe(myPosition, radius)){ System.out.println(currentPoint); } } }
true
c7c35270fc726fe7e4f98cd1b732cea6410ee2ba
Java
havingfunq/Asteroids3D
/main/java/com/github/havingfunq/asteroids3d/Dodecahedron.java
UTF-8
3,112
2.953125
3
[]
no_license
package com.github.havingfunq.asteroids3d; import java.util.ArrayList; /** * Created by Vince on 4/22/2017. */ public class Dodecahedron { float[][] dodec = new float[20][3]; float[] verts = new float[500]; ArrayList<Float> dodecahedron = new ArrayList<Float>(); public Dodecahedron(){ float alpha = (float) Math.sqrt(2.0 / (3.0 + Math.sqrt(5.0))); float beta = 1.0f + (float) Math.sqrt(6.0 / (3.0 + Math.sqrt(5.0)) - 2.0 + 2.0 * Math.sqrt(2.0 / (3.0 + Math.sqrt(5.0)))); dodec[0][0] = -alpha; dodec[0][1] = 0f; dodec[0][2] = beta; dodec[1][0] = alpha; dodec[1][1] = 0f; dodec[1][2] = beta; dodec[2][0] = -1f; dodec[2][1] = -1f; dodec[2][2] = -1f; dodec[3][0] = -1f; dodec[3][1] = -1f; dodec[3][2] = 1f; dodec[4][0] = -1f; dodec[4][1] = 1f; dodec[4][2] = -1f; dodec[5][0] = -1f; dodec[5][1] = 1f; dodec[5][2] = 1f; dodec[6][0] = 1f; dodec[6][1] = -1f; dodec[6][2] = -1f; dodec[7][0] = 1f; dodec[7][1] = -1f; dodec[7][2] = 1f; dodec[8][0] = 1f; dodec[8][1] = 1f; dodec[8][2] = -1f; dodec[9][0] = 1f; dodec[9][1] = 1f; dodec[9][2] = 1f; dodec[10][0] = beta; dodec[10][1] = alpha; dodec[10][2] = 0f; dodec[11][0] = beta; dodec[11][1] = -alpha; dodec[11][2] = 0f; dodec[12][0] = -beta; dodec[12][1] = alpha; dodec[12][2] = 0f; dodec[13][0] = -beta; dodec[13][1] = -alpha; dodec[13][2] = 0f; dodec[14][0] = -alpha; dodec[14][1] = 0f; dodec[14][2] = -beta; dodec[15][0] = alpha; dodec[15][1] = 0f; dodec[15][2] = -beta; dodec[16][0] = 0f; dodec[16][1] = beta; dodec[16][2] = alpha; dodec[17][0] = 0f; dodec[17][1] = beta; dodec[17][2] = -alpha; dodec[18][0] = 0f; dodec[18][1] = -beta; dodec[18][2] = alpha; dodec[19][0] = 0f; dodec[19][1] = -beta; dodec[19][2] = -alpha; pentagon(0, 1, 9, 16, 5); pentagon(1, 0, 3, 18, 7); pentagon(1, 7, 11, 10, 9); pentagon(11, 7, 18, 19, 6); pentagon(8, 17, 16, 9, 10); pentagon(2, 14, 15, 6, 19); pentagon(2, 13, 12, 4, 14); pentagon(2, 19, 18, 3, 13); pentagon(3, 0, 5, 12, 13); pentagon(6, 15, 8, 10, 11); pentagon(4, 17, 8, 15, 14); pentagon(4, 12, 5, 16, 17); for(int i = 0; i < dodecahedron.size(); i++){ verts[i] = dodecahedron.get(i); } } void pentagon(int a, int b, int c, int d, int e){ dodecahedron.add(dodec[a][0]); dodecahedron.add(dodec[a][1]); dodecahedron.add(dodec[a][2]); dodecahedron.add(dodec[b][0]); dodecahedron.add(dodec[b][1]); dodecahedron.add(dodec[b][2]); dodecahedron.add(dodec[c][0]); dodecahedron.add(dodec[c][1]); dodecahedron.add(dodec[c][2]); dodecahedron.add(dodec[d][0]); dodecahedron.add(dodec[d][1]); dodecahedron.add(dodec[d][2]); dodecahedron.add(dodec[e][0]); dodecahedron.add(dodec[e][1]); dodecahedron.add(dodec[e][2]); } float[] getVerts(){ return verts; } }
true
c0617f50ff552973bbc8452204130ca3b3cc11d4
Java
littlejedi/zeedoo-commons
/src/main/java/com/zeedoo/commons/mybatis/DateTimeTypeHandler.java
UTF-8
1,785
2.78125
3
[]
no_license
package com.zeedoo.commons.mybatis; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.TypeHandler; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; /** * MyBatis {@link DateTime} handler to convert MySQL UNIX timestamp <-> Joda DateTime objects * * @author nzhu * */ public class DateTimeTypeHandler implements TypeHandler<DateTime> { @Override public void setParameter(PreparedStatement ps, int i, DateTime parameter, JdbcType jdbcType) throws SQLException { if (parameter != null) { // Divide by 1000 to get to Unix epoch time ps.setLong(i, parameter.getMillis() / 1000L); } else { ps.setTimestamp(i, null); } } @Override public DateTime getResult(ResultSet rs, String columnName) throws SQLException { long timestamp = rs.getLong(columnName); // We are already storing UTC timestamps in database, we don't need Joda to convert to a different timezone return new DateTime(timestamp * 1000L).withZone(DateTimeZone.UTC); } @Override public DateTime getResult(ResultSet rs, int columnIndex) throws SQLException { long timestamp = rs.getLong(columnIndex); // We are already storing UTC timestamps in database, we don't need Joda to convert to a different timezone return new DateTime(timestamp * 1000L).withZone(DateTimeZone.UTC); } @Override public DateTime getResult(CallableStatement cs, int columnIndex) throws SQLException { long timestamp = cs.getLong(columnIndex); // We are already storing UTC timestamps in database, we don't need Joda to convert to a different timezone return new DateTime(timestamp * 1000L).withZone(DateTimeZone.UTC); } }
true
739c09bdcd8c4fa1f7f5d92c43b951c11e2e6ee5
Java
ericbv/spring-data-jpa-datatables
/src/main/java/org/springframework/data/jpa/datatables/qrepository/QDataTablesRepositoryImpl.java
UTF-8
2,599
2.15625
2
[ "Apache-2.0" ]
permissive
package org.springframework.data.jpa.datatables.qrepository; import static org.springframework.data.jpa.datatables.repository.DataTablesUtils.getPageable; import static org.springframework.data.jpa.datatables.repository.DataTablesUtils.getPredicate; import java.io.Serializable; import javax.persistence.EntityManager; import org.springframework.data.domain.Page; import org.springframework.data.jpa.datatables.mapping.DataTablesInput; import org.springframework.data.jpa.datatables.mapping.DataTablesOutput; import org.springframework.data.jpa.repository.support.JpaEntityInformation; import org.springframework.data.jpa.repository.support.QueryDslJpaRepository; import org.springframework.data.querydsl.EntityPathResolver; import org.springframework.data.querydsl.SimpleEntityPathResolver; import com.mysema.query.BooleanBuilder; import com.mysema.query.types.EntityPath; import com.mysema.query.types.Predicate; import com.mysema.query.types.path.PathBuilder; /** * Repository implementation * * @author Damien Arrachequesne */ public class QDataTablesRepositoryImpl<T, ID extends Serializable> extends QueryDslJpaRepository<T, ID> implements QDataTablesRepository<T, ID> { private static final EntityPathResolver DEFAULT_ENTITY_PATH_RESOLVER = SimpleEntityPathResolver.INSTANCE; private final EntityPath<T> path; private final PathBuilder<T> builder; public QDataTablesRepositoryImpl(JpaEntityInformation<T, ID> entityInformation, EntityManager entityManager) { this(entityInformation, entityManager, DEFAULT_ENTITY_PATH_RESOLVER); } public QDataTablesRepositoryImpl(JpaEntityInformation<T, ID> entityInformation, EntityManager entityManager, EntityPathResolver resolver) { super(entityInformation, entityManager); this.path = resolver.createPath(entityInformation.getJavaType()); this.builder = new PathBuilder<T>(path.getType(), path.getMetadata()); } @Override public DataTablesOutput<T> findAll(DataTablesInput input) { return findAll(input, null); } @Override public DataTablesOutput<T> findAll(DataTablesInput input, Predicate additionalPredicate) { DataTablesOutput<T> output = new DataTablesOutput<T>(); output.setDraw(input.getDraw()); try { output.setRecordsTotal(count()); Page<T> data = findAll( new BooleanBuilder().and(getPredicate(this.builder, input)).and(additionalPredicate).getValue(), getPageable(input)); output.setData(data.getContent()); output.setRecordsFiltered(data.getTotalElements()); } catch (Exception e) { output.setError(e.toString()); output.setRecordsFiltered(0L); } return output; } }
true
7db8d3cc594453e86d3afbd91a7f366d51ec2bdf
Java
projudice/test
/test/test/calTest.java
UTF-8
281
2.296875
2
[]
no_license
package test; import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.Test; import add.Cal; public class calTest { @Test public void addTest() { Cal cal = new Cal(); assertEquals(5, cal.add(2, 3)); } }
true
2b5a00fc6954ade6b5c396014f6a704f63002528
Java
oGabrielArruda/airport-data-structures-I
/src/main/java/Janelas/InitialWindow.java
UTF-8
3,659
2.734375
3
[]
no_license
package Janelas; import Aeroporto.Aeroporto; import AirportManager.AirportManager; import ListaDuplaDesordenada.ListaDuplaDesordenada; import Voo.Voo; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class InitialWindow extends AirportManager { AirportManager manager; private JFrame frame; private JButton btnAddAeroporto; private JPanel panelAddAirport; private JButton cadastrarVooButton; private JButton removerVooButton; private JButton listaVooDeDeterminadoButton; private JButton listarTodosOsVoosButton; public InitialWindow(AirportManager manager) { this.manager = manager; initialize(); } private void initialize() { frame = new JFrame("App"); frame.setContentPane(panelAddAirport); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.pack(); frame.setSize(600, 400); frame.setVisible(true); btnAddAeroporto.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFrame addAirport = new JFrame("AddAirport"); addAirport.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); addAirport.setContentPane(new AdicionarAeroporto(manager).PainelAdd); addAirport.pack(); addAirport.setSize(600, 400); addAirport.setVisible(true); } }); cadastrarVooButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFrame addVoo = new JFrame("CadastrarVoo"); addVoo.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); addVoo.setContentPane(new CadastrarVoo(manager).PanelAdd); addVoo.pack(); addVoo.setSize(600, 400); addVoo.setVisible(true); } }); removerVooButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFrame removerVoo = new JFrame("RemoverVoo"); removerVoo.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); removerVoo.setContentPane(new RemoverVoo(manager).panelRemove); removerVoo.pack(); removerVoo.setSize(600, 400); removerVoo.setVisible(true); } }); listaVooDeDeterminadoButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFrame listarVoos = new JFrame("ListarVoosDeAeroporto"); listarVoos.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); listarVoos.setContentPane(new ListarVoosDeAeroporto(manager).panelListar); listarVoos.pack(); listarVoos.setSize(600, 400); listarVoos.setVisible(true); } }); listarTodosOsVoosButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFrame listarVoos = new JFrame("ListarVoos"); listarVoos.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); listarVoos.setContentPane(new ListarTodosVoos(manager).panelListar); listarVoos.pack(); listarVoos.setSize(600, 400); listarVoos.setVisible(true); } }); } }
true
bc312e10a4f821d6d57d4452b1ad4b5a4ab3db25
Java
FitzgeraldMouseton/blog-webflux
/src/main/java/com/cheeseind/blogenginewebflux/models/dto/blogdto/CalendarDto.java
UTF-8
401
1.734375
2
[]
no_license
package com.cheeseind.blogenginewebflux.models.dto.blogdto; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Map; @Data @AllArgsConstructor @NoArgsConstructor public class CalendarDto { private Integer[] years; @JsonProperty("posts") private Map<String, Long> postsPerDate; }
true
510fef796a3d3bd84f4f1ebc84cb5f3a068ca7da
Java
szdksconan/seawar
/seawar_1.3_ly/app/foxu/fight/FightScene.java
GB18030
14,684
2.4375
2
[]
no_license
package foxu.fight; import java.util.ArrayList; import java.util.List; import foxu.sea.fight.FightSceneFactory; import foxu.sea.fight.LimitNumSkill; import mustang.event.ChangeListener; import mustang.log.LogFactory; import mustang.log.Logger; import mustang.math.Random; import mustang.math.Random1; import mustang.set.Comparator; import mustang.util.SampleFactory; /** * ս * * @author ZYT */ abstract public class FightScene implements Cloneable { /** ־¼ */ private static final Logger log=LogFactory.getLogger(FightScene.class); /* static fields */ /** * ¼ GET_SCENE=201õս,SCENE_ADD_FIGHTER=202Ҽս * SKII_SPRING=203ÿغϴ,FIGHT_START=210սʼ,ROUND_START=220غϿʼ, * ROUND_OVER * =229غϽ,ACTION_START=230жʼ,SPREAD_STRAT=231ʼʩ,ADD_ABILITY * =232ؼ, * EXEMPT=233,HURT=234˺,IMMUNITY=235,RESIST=236ֿ,DEAD=237ɫ, * SPREAD_OVER * =238ʩŽ,REMOVE_FIGHTER=239Ƴһfighter,CLEAN_ABILITY=240Ч, * ACTION_OVER * =250,TOUCH_SPREAD_START=241ʩſʼ,TOUCH_SPREAD_OVER=242ͷŽ, * FIGHT_START * =210սʼ,FIGHTER_OVER=219ս,ERUPT=251,NEXT_TARGET=252һĿ, * ATTACK_ONCE * =253һ,ABILITY_TIME_OUT=254ܳʱ,INTERVAL_EFFECT=255Чһ * NEXT_FIGHTER=256һfighterж,EXECUTE_AILITY=257ִһЧ,LIMIT_HURT=258 * ˺FLUSH_BUFF=259ˢ³OTHER_HURT=260 ֵתƵ˺,ADD_TIME=261ʱ * FIGHT_CONTINUE Ϲؿݲ */ public enum FightEvent { /**õս*/ GET_SCENE, /**Ҽս*/ SCENE_ADD_FIGHTER, /**սʼ*/ FIGHT_START, /**ս*/ FIGHT_OVER, /**غϿʼ*/ ROUND_START, /**ÿغϴ*/ SKII_SPRING, READY, /**غϽ*/ ROUND_OVER, /**жʼ*/ ACTION_START, /**ʼʩ*/ SPREAD_START, /**ؼ*/ ADD_ABILITY, /***/ EXEMPT, /**˺**/ HURT, /****/ IMMUNITY, /**ֿ*/ RESIST, /**ɫ*/ DEAD, /**ʩŽ*/ SPREAD_OVER, /**ɫ Ƴһfighter*/ REMOVE_FIGHTER, /**Ч*/ CLEAN_ABILITY, /**ʩſʼ*/ TOUCH_SPREAD_START, /**ʩŽ*/ TOUCH_SPREAD_OVER, /** нɫ*/ ACTION_OVER, /***/ ERUPT, /**һĿ*/ NEXT_TARGET, /**һ*/ ATTACK_ONCE, /**ܳʱ*/ ABILITY_TIME_OUT, /**Чһ*/ INTERVAL_EFFECT, /**һfighterж**/ NEXT_FIGHTER, /**ִһЧ*/ EXECUTE_AILITY, /**˺*/ LIMIT_HURT, /**ˢ³*/ FLUSH_BUFF, /** ֵתƵ˺*/ OTHER_HURT, /**ʱ*/ ADD_TIME, ATTACK_CONTINUE, FIGHT_CONTINUE, ACTIVE_STATE }; /** ޳ */ public static final int RANDOM_MAX=10001,RANDOM_MINI=0,OLD_TIMES=100; /** ս߹ */ public static SampleFactory fighterFactory; /** ܹ */ public static SampleFactory abilityFactory; public static int MAX_ROUND=41; /* fields */ /** ʽ */ Formula[] formulas; /** ɫ */ private FighterContainer container; /** ǰغ */ int currentRound; /** غ */ int maxRound=MAX_ROUND; /** Fighter㷨 */ Comparator comparator; /** */ ChangeListener listener; /** Ƽܼ*/ List<LimitNumSkill> limitNumSkillList = new ArrayList<LimitNumSkill>(); private Random rd=new Random1(); /** ʼΪ0 սɺ󷵻ʤ߱ */ int successTeam; /** ز */ boolean defend=false; /** Ƽܼ*/ public List<LimitNumSkill> getLimitNumSkillList() { return limitNumSkillList; } /** Ƽܼ*/ public void setLimitNumSkillList(List<LimitNumSkill> limitNumSkillList) { this.limitNumSkillList=limitNumSkillList; } /* properties */ /** 㷨 */ public void setComparator(Comparator comparator) { this.comparator=comparator; } /** սغ */ public int getMaxRound() { return maxRound; } /** սغ */ public void setMaxRound(int maxRound) { this.maxRound=maxRound; } /** fighter */ public void setFighterContainer(FighterContainer team) { this.container=team; } /** ü */ public ChangeListener getChangeListener() { return listener; } /** ü */ public void setChangeListener(ChangeListener listener) { this.listener=listener; } /** ùʽ */ public void setFormula(Formula[] formula) { formulas=formula; } /** */ public void setSeed(int seed) { rd.setSeed(seed); } /** */ public Random getRandom() { return rd; } /** Fighter */ public FighterContainer getFighterContainer() { return container; } /** ָ͵Ĺʽ */ public Formula getFormula(int type) { return formulas[type]; } /** õǰغ */ public int getCurrentRound() { return currentRound; } /* abstract methods */ /** * սǷ * * @return ʤţսδInteger.MAX_VALUE,ƽַ0 */ abstract public int checkOver(); /** * ׼ж * * @param f ҪжFighter */ abstract public void fighterReady(Fighter f); /* methods */ /** ʼ */ public void init() { currentRound=0; } /** * һɫ * * @param f һFighter * @return Ƿɹ */ public boolean addFighter(int team,Fighter[] f) { if(f==null) return false; for(int i=f.length-1;i>=0;i--) { if(f[i]!=null) { f[i].setScene(this); f[i].setTeam(team); container.addFighter(team,f[i]); } } ChangeListener listener=this.listener; if(listener!=null) listener.change(this,FightEvent.SCENE_ADD_FIGHTER.ordinal(), new Integer(team),f); return true; } /** * ӽɫ * * @param f Fighter * @param location ǷԶλ * @return ӳɹ */ public boolean addFighter(int teamId,Fighter f) { if(f==null) return false; container.addFighter(teamId,f); f.setTeam(teamId); f.setScene(this); ChangeListener listener=this.listener; if(listener!=null) listener.change(this,FightEvent.SCENE_ADD_FIGHTER.ordinal(), new Integer(teamId),f); return true; } /** * ˢfighterϵļ * * @param time ʱ,жϼǷʱ * @param code У,жϼǷ */ public int flushFighterAbility(int time,ChangeListener listener) { Fighter[] fighters=container.getAllFighter(); // FighterϵЧһ for(int i=fighters.length-1;i>=0;i--) { if(!fighters[i].isDead()) { fighters[i].flushAbility(time,listener); // ˢЧ,fighterп if(fighters[i].isDead()) { fighters[i].deadClear(); removeHalo(fighters[i],fighters); } else { fighters[i].flushHalo(fighters); } } } return checkOver(); } /** * нɫս * </p> * ˢ¹⻷ */ public void fightStart() { ChangeListener listener=this.listener; if(listener!=null) listener.change(this,FightEvent.FIGHT_START.ordinal()); int team; while(currentRound<maxRound) { team=roundStart(); roundOver(team); if(team!=Integer.MAX_VALUE) { fightOver(team); break; } } } /** * غ׼׶ * </p> * ʼʱ */ public int roundStart() { currentRound++; ChangeListener listener=this.listener; if(listener!=null) listener.change(this,FightEvent.ROUND_START.ordinal()); int team=flushFighterAbility(currentRound,listener); if(team==Integer.MAX_VALUE) return actionStart(comparator); return team; } /** * ĿǷ,ڶfighterж϶fighterӰ * * @param fighters ǰеfighter */ public void checkOutTargetDead(Fighter[] fighters) { removeHalo(fighters,fighters); } /** ˢ¹⻷ */ public void flushHalo(Fighter[] fighters) { for(int i=0;i<fighters.length;i++) { fighters[i].flushHalo(fighters); } } /** ȡǰֵfighter nullΪû teamID */ public Fighter selectFighter(Fighter[] fighters,int teamID, int otherTeamId,int teamIndex0,int teamIndex1) { Fighter selectFighter=null; if(teamIndex0>FightSceneFactory.MAX_INDEX &&teamIndex1>FightSceneFactory.MAX_INDEX) return null; int location=teamIndex0; if(teamID==1) location=teamIndex1; for(int i=0;i<fighters.length;i++) { if(fighters[i]==null) continue; // 鿴ӦֵĶ selectFighter=findFighterByTeamId(fighters,teamID,location); // 鿴һֻ黹ûгֵfighter if(selectFighter==null) { int otherLocation=teamIndex0; if(otherTeamId==1) otherLocation=teamIndex1; selectFighter=findFighterByTeamId(fighters,otherTeamId, otherLocation); } } return selectFighter; } /** ijһֻ ҳһչfighter */ public Fighter findFighterByTeamId(Fighter[] fighters,int teamId, int location) { if(location>FightSceneFactory.MAX_INDEX) return null; for(int i=0;i<fighters.length;i++) { if(fighters[i]==null) continue; if(fighters[i].getTeam()==teamId &&fighters[i].getLocation()==location) { if(fighters[i].isDead()) return findFighterByTeamId(fighters,teamId,location+1); return fighters[i]; } } return findFighterByTeamId(fighters,teamId,location+1); } /** ʼ */ public int actionStart(Comparator comparator) { int over=Integer.MAX_VALUE; Ability ability; // Fighter[] fighters=container.sort(comparator); Fighter[] fighters=container.getAllFighter(); ChangeListener listener=this.listener; if(listener!=null) listener.change(this,FightEvent.ACTION_START.ordinal(),fighters); // ǰغϳֵ± int teamIndex0=0; // ǰغϳֵ± int teamIndex1=0; // ǰֶ int teamID=0; Fighter fighterNow=selectFighter(fighters,teamID,1,teamIndex0, teamIndex1); if(defend) { fighterNow=selectFighter(fighters,1,0,teamIndex0,teamIndex1); } while(fighterNow!=null) { // õǰֵϢ teamID=fighterNow.getTeam(); int nextTeamId=0; if(teamID==0) { teamIndex0=fighterNow.getLocation()+1; nextTeamId=1; } else teamIndex1=fighterNow.getLocation()+1; // ʼ if(listener!=null) listener.change(this,FightEvent.NEXT_FIGHTER.ordinal(), fighterNow); if(fighterNow.isAttackFighter()) { fighterReady(fighterNow); ability=fighterNow.getAbility(); if(ability==null) { fighterNow=selectFighter(fighters,nextTeamId,teamID, teamIndex0,teamIndex1); continue; } // 鼼ܷȷʩ if(ability.checkUsed(fighterNow,fighterNow.getTarget())==0) ability.used(fighterNow,fighterNow.getTarget()); // ڹ Ͻ //checkOutTargetDead(fighters); // ˢ¹⻷ flushHalo(fighters); fighterNow.clearTarget(); } over=checkOver(); if(over!=Integer.MAX_VALUE) break; fighterNow=selectFighter(fighters,nextTeamId,teamID,teamIndex0, teamIndex1); } return actionOver(over); } /** * нɫ * * @param over սǷıʾ * @return رʾ */ public int actionOver(int over) { ChangeListener listener=this.listener; if(listener!=null) listener.change(this,FightEvent.ACTION_OVER.ordinal()); return over; } /** * غϽ * * @param over սǷıʾ * @return رʾ */ public void roundOver(int over) { ChangeListener listener=this.listener; if(listener!=null) listener.change(this,FightEvent.ROUND_OVER.ordinal(),over); } /** * ս * * @param team ʤ */ public void fightOver(int team) { ChangeListener listener=this.listener; if(listener!=null) listener.change(this,FightEvent.FIGHT_OVER.ordinal(),team); clear(); successTeam=team; } /** * Ƴfighterһfigher()ʩŵĹ⻷ * * @param fighter ͷŹ⻷fighter * @param fighters ȫfighter */ public void removeHalo(Fighter fighter,Fighter[] fighters) { if(fighter==null) return; for(int i=fighters.length-1;i>=0;i--) { if(fighter==fighters[i]) continue; fighters[i].removePerennityAbility(fighter); } } /** * fighterˢһfighterĹ⻷ * * @param fighters Ҫжϵfighter * @param allFighters ȫfighter */ public void removeHalo(Fighter[] fighters,Fighter[] allFighters) { Fighter f; for(int i=fighters.length-1;i>=0;i--) { f=container.getFighter(fighters[i].getTeam(),fighters[i] .getLocation()); if(f!=null&&fighters[i].isDead()) // ˢһδfighterϵĹ⻷ { fighters[i].deadClear(); removeHalo(fighters[i],allFighters); } } } /** Ƴijfighter */ public void removeFighter(Fighter fighter) { if(fighter==null) return; // if(fighter.isDead()) fighter.deadClear(); fighter.clear(); Fighter[] fighters=container.getAllFighter(); for(int i=fighters.length-1;i>=0;i--) { if(fighters[i]!=fighter) fighters[i].removePerennityAbility(fighter); } container.removeFighter(fighter); fighter.setScene(null); ChangeListener listener=this.listener; if(listener!=null) listener .change(this,FightEvent.REMOVE_FIGHTER.ordinal(),fighter); } /** ս */ public void clear() { Fighter[] fighters=container.getAllFighter(); for(int i=fighters.length-1;i>=0;i--) { fighters[i].clear(); } container.clear(); } /** * @return successTeam */ public int getSuccessTeam() { return successTeam; } /** * @param successTeam Ҫõ successTeam */ public void setSuccessTeam(int successTeam) { this.successTeam=successTeam; } public boolean isDefend() { return defend; } public void setDefend(boolean defend) { this.defend=defend; } }
true
0af22b02d19a9549992cb6bed72225b8e78a99db
Java
nadul/smafira
/src/java/db/AssessmentDBReader.java
UTF-8
2,905
2.703125
3
[]
no_license
package db; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import db.SQLConnector.DBType; public class AssessmentDBReader { private Connection conn; private Statement selectAssessments; public AssessmentDBReader() { init(); } public HashMap<String, String> getRelevanceAssessments(String assessmentValue){ return getColumnAssessment(ResultDbColNames.RELEVANCE.path, assessmentValue); } public HashMap<String, String> getSimilarityAssessments(String assessmentValue){ return getColumnAssessment(ResultDbColNames.SIMILARITY.path, assessmentValue); } public HashMap<String, String> getAnimalTestAssessments(String assessmentValue){ return getColumnAssessment(ResultDbColNames.ANIMALTEST.path, assessmentValue); } private HashMap<String, String> getColumnAssessment(String targetColumnName, String assessmentValue){ String sqlQuery = "SELECT " + ResultDbColNames.PMID.path + ", " + targetColumnName + " FROM pubmed_result_document"; HashMap<String, String> columnAssess = new HashMap<String, String>(); String pmid, targetAttribute; if(assessmentValue != null && !assessmentValue.isEmpty()){ sqlQuery += " WHERE " + targetColumnName + "='" + assessmentValue + "'"; } try { ResultSet assessments = selectAssessments.executeQuery(sqlQuery); while(assessments.next()){ pmid = assessments.getString(ResultDbColNames.PMID.path); targetAttribute = assessments.getString(targetColumnName); // System.out.println("pmid: " + pmid + "; " + targetColumnName + ": " + targetAttribute); columnAssess.put(pmid, targetAttribute); } } catch (SQLException e) { e.printStackTrace(); } return columnAssess; } public String getRefDocID(String refDocPmid){ String refDocID = null; String sqlQuery = "SELECT " + ReferenceDbColNames.ID.path + " FROM pubmed_reference_document WHERE " + ReferenceDbColNames.PMID.path + " = '" + refDocPmid + "'"; try { Statement selectRefDoc = conn.createStatement(); ResultSet assessments = selectRefDoc.executeQuery(sqlQuery); if(assessments.next()){ refDocID = assessments.getString(ResultDbColNames.ID.path); } } catch (SQLException e) { e.printStackTrace(); } return refDocID; } private void init(){ this.conn = (new SQLConnector(DBType.MYSQL)).getConnection(); try { selectAssessments = conn.createStatement(); } catch (SQLException e) { e.printStackTrace(); } } public void closeConnection(){ try { this.conn.close(); } catch (SQLException e) { e.printStackTrace(); } } public static void main(String[] args) { AssessmentDBReader adbr = new AssessmentDBReader(); // adbr.getRelevanceAssessments(null); // adbr.getSimilarityAssessments(null); adbr.getAnimalTestAssessments(null); } }
true
d9c31e3e84d936ef9f6749d6c2360d84a012467a
Java
aiveejoy/studentEnrollmentWdDBjava
/src/ivydbjava/paccounts.java
UTF-8
4,989
2.75
3
[]
no_license
package ivydbjava; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /* * 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. */ /** * * @author 2ndyrGroupC */ public class paccounts { private String Uname; private String Pass; Scanner scan = new Scanner(System.in); static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/devilleres"; static final String USER = "root"; static final String PASS = ""; private Connection conn = null; private Statement stmt = null; public paccounts() { } public paccounts(String Uname, String Pass) { this.Uname = Uname; this.Pass = Pass; } public String getUname() { return Uname; } public void setUname(String Uname) { this.Uname = Uname; } public String getPass() { return Pass; } public void setPass(String Pass) { this.Pass = Pass; } public void connectdb() throws SQLException { try { Class.forName(JDBC_DRIVER); //STEP 3: Open a connection System.out.println("Connecting to database..."); } catch (ClassNotFoundException ex) { Logger.getLogger(paccounts.class.getName()).log(Level.SEVERE, null, ex); } } public void createAccounts() throws SQLException { conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println(".... Personal Account Form ...."); try { System.out.print("USERNAME: "); Uname = scan.next(); System.out.print("PASSWORD: "); Pass = scan.next(); while (Pass.length() < 8) { System.out.println("Password less than 8, please re-enter."); System.out.println(" Password: "); Pass = scan.next(); } System.out.print("CONFIRM PASSWORD: "); String finalPass = scan.next(); while (!Pass.matches(finalPass)) { System.out.println("---------------> ERROR DETECTED!!! :( \n----> PASSWORD MISMATCH <----"); System.out.print("CONFIRM PASSWORD: "); finalPass = scan.next(); } if (Pass.matches(finalPass)) { Pass = finalPass; System.out.println("---------------> Information SAVED!!!! :)"); try { //STEP 4: Execute a query // System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "INSERT INTO `accounts`(`username`, `password`) VALUES ('" + Uname + "','" + Pass + "')"; stmt.executeUpdate(sql); } catch (Exception e) { e.printStackTrace(); } } else { throw new IOException("wrong"); } } catch (IOException e) { System.out.println(e); } } public void updateAccount() throws SQLException { conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.print("ID: "); int ID = scan.nextInt(); System.out.print("New Username: "); String Nuname = scan.next(); System.out.print("New Password: "); String Npass = scan.next(); try { stmt = conn.createStatement(); String sql; sql = "UPDATE `accounts` SET `username`='" + Nuname + "',`password`='" + Npass + "' WHERE id=" + ID; stmt.executeUpdate(sql); } catch (Exception e) { } System.out.println("---------------> Account UPDATED!!!! :)"); } public void retrieveAllAcc() throws SQLException { conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("********-- List of Accounts --********"); try { stmt = conn.createStatement(); String sql; sql = "SELECT * FROM accounts"; ResultSet rs = stmt.executeQuery(sql); System.out.println(""); while (rs.next()) { //Retrieve by column name int id = rs.getInt("id"); String first = rs.getString("username"); String last = rs.getString("password"); //Display values System.out.print(id); System.out.print("\t\t" + first); System.out.println("\t\t" + last); } } catch (Exception e) { } } }
true
ba93cef6f079537dbdc20122f734fa6630f72b73
Java
radtek/ad-aws-ausync
/ad-ausync-server/src/main/java/com/upsmart/ausync/process/slave/FileProcessor.java
UTF-8
8,914
2.453125
2
[]
no_license
package com.upsmart.ausync.process.slave; import com.upsmart.ausync.awss3.AwsS3FileInfo; import com.upsmart.ausync.awss3.AwsS3Wrapper; import com.upsmart.ausync.common.Constant; import com.upsmart.ausync.model.BrotherFiles; import com.upsmart.ausync.model.TransData; import com.upsmart.server.common.codec.MD5; import com.upsmart.server.common.utils.StringUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.zip.GZIPInputStream; /** * Created by yuhang on 17-11-7. */ public abstract class FileProcessor implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(FileProcessor.class); /** * 文在在aws的s3路径 */ protected abstract String getAwsS3FilePath(); /** * 文件下载到本地的路径 */ protected abstract String getLocalFilePath(); protected Map<String, BrotherFiles> downloadFile(TransData.Task task) { if(null == task){ return null; } Map<String, BrotherFiles> map = new HashMap<>(); AwsS3Wrapper awsS3Wrapper = new AwsS3Wrapper(); String awsFolder = String.format("%s/%s", getAwsS3FilePath(), task.taskId); List<AwsS3FileInfo> list = awsS3Wrapper.getAllFilesPath(awsFolder); for (AwsS3FileInfo awsS3FileInfo : list) { String name = awsS3FileInfo.path.substring(awsS3FileInfo.path.lastIndexOf("/") + 1); String localFile = String.format("%s/%s/%s", getLocalFilePath(), task.taskId, name); File file = new File(localFile); awsS3Wrapper.downloadFile(awsS3FileInfo.path, file); LOGGER.warn(String.format("download (%s) => (%s)", awsS3FileInfo.path, localFile)); String prefix = name.substring(0, name.indexOf(".")); String suffix = name.substring(name.lastIndexOf(".")); if (suffix.equals(".md5")) { if (!map.containsKey(prefix)) { map.put(prefix, new BrotherFiles()); } map.get(prefix).md5FilePath = localFile; } else if (suffix.equals(".gz")) { if (!map.containsKey(prefix)) { map.put(prefix, new BrotherFiles()); } map.get(prefix).gzipFilePath = localFile; } else { // 其它后缀的文件 // map.get(prefix).filePath = localFile; } } return map; } protected void gzipDecompress(String oldFile, String newFile) throws Exception { LOGGER.info(String.format("decompress (%s) to (%s)", oldFile, newFile)); File file = new File(oldFile); FileInputStream fis = null; FileOutputStream fos = null; try{ fis = new FileInputStream(file); fos = new FileOutputStream(newFile); decompress(fis, fos); fos.flush(); } finally { if(null != fis) { fis.close(); } if(null != fos) { fos.close(); } } } protected void decompress(InputStream is, OutputStream os) throws IOException { GZIPInputStream gis = null; try{ gis = new GZIPInputStream(is); int count; byte data[] = new byte[1024]; while ((count = gis.read(data, 0, 1024)) != -1) { os.write(data, 0, count); } } finally { if(null != gis){ gis.close(); } } } protected boolean del(String filePath){ File f = new File(filePath); if(f.isDirectory()){ for(File s : f.listFiles()){ del(s.getAbsolutePath()); } } boolean delStatus = f.delete(); LOGGER.info(String.format("delete (%s)", filePath, delStatus)); return delStatus; } protected boolean VerifyMd5(Map<String, BrotherFiles> map) throws IOException, NoSuchAlgorithmException { boolean ret = true; Iterator<Map.Entry<String, BrotherFiles>> iter = map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, BrotherFiles> entry = iter.next(); String prefix = entry.getKey(); BrotherFiles brotherFiles = entry.getValue(); String gzMD5 = readMD5(brotherFiles.gzipFilePath); String fileMD5 = readFileToStr(brotherFiles.md5FilePath); if (!StringUtil.isNullOrEmpty(gzMD5) && !StringUtil.isNullOrEmpty(fileMD5)) { if (gzMD5.equals(fileMD5)) { brotherFiles.verify = true; LOGGER.info(String.format("(%s) MD5 is pass (%s).", prefix, gzMD5)); } else { ret = false; LOGGER.warn(String.format("(%s) MD5 is invalid (%s)-(%s).", prefix, gzMD5, fileMD5)); } } else { brotherFiles.verify = true; LOGGER.warn(String.format("(%s) no files to verify.", prefix)); } } return ret; } protected String readMD5(String filePath) throws NoSuchAlgorithmException, IOException { if (StringUtil.isNullOrEmpty(filePath)) { return null; } File file = new File(filePath); if (!file.isDirectory()) { FileInputStream in = null; FileChannel channel = null; List<MappedByteBuffer> listBuff = new ArrayList<>(); try { MessageDigest md = MessageDigest.getInstance("MD5"); in = new FileInputStream(file); channel = in.getChannel(); // 文件块数量,可能还有结余 long blockNum = file.length() / Constant.MAX_MAPPING_BUFF_SIZE; for(int i=0; i<blockNum; i++){ MappedByteBuffer byteBuffer = null; try{ byteBuffer = channel.map(FileChannel.MapMode.READ_ONLY, i*Constant.MAX_MAPPING_BUFF_SIZE, Constant.MAX_MAPPING_BUFF_SIZE); md.update(byteBuffer); // listBuff.add(byteBuffer); } finally { if(null != byteBuffer){ Constant.releaseBuff(byteBuffer); // 释放内存 } } } long remainByte = file.length() - (blockNum * Constant.MAX_MAPPING_BUFF_SIZE); if(remainByte > 0){ MappedByteBuffer byteBuffer = null; try{ byteBuffer = channel.map(FileChannel.MapMode.READ_ONLY, (blockNum)*Constant.MAX_MAPPING_BUFF_SIZE, remainByte); md.update(byteBuffer); // listBuff.add(byteBuffer); } finally { if(null != byteBuffer){ Constant.releaseBuff(byteBuffer); // 释放内存 } } } return MD5.byteToString(md.digest()); } finally { if(null != listBuff && !listBuff.isEmpty()){ for(MappedByteBuffer buff : listBuff){ Constant.releaseBuff(buff); // 释放内存 } } if(null != channel){ channel.close(); } if (null != in) { in.close(); } } } return null; } protected String readFileToStr(String filePath) throws IOException { if (StringUtil.isNullOrEmpty(filePath)) { return null; } String ret = ""; File file = new File(filePath); if (!file.isDirectory()) { InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try { inputStreamReader = new InputStreamReader(new FileInputStream(file.getAbsolutePath()), "UTF-8"); bufferedReader = new BufferedReader(inputStreamReader); String line; while ((line = bufferedReader.readLine()) != null) { ret += line; } } finally { if (null != bufferedReader) { bufferedReader.close(); } if (null != inputStreamReader) { inputStreamReader.close(); } } } return ret; } }
true
5be27561a4fa25b85d49185a5a611b87dec04e8d
Java
VivienFei/UtilitySystem
/powerorigin/src/com/interceptor/AuthenticUser.java
UTF-8
1,373
2.046875
2
[]
no_license
package com.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.java.po.Admin; import com.java.po.User; /** * 拦截需要登录的页面 */ public class AuthenticUser implements HandlerInterceptor { public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { } public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { } public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception { String path = request.getContextPath(); String uri = request.getRequestURI(); // System.out.println("uri--preHandle"+uri); HttpSession session = (HttpSession) request.getSession(); User user = (User) request.getSession().getAttribute("user"); Admin admin=(Admin)request.getSession().getAttribute("admin"); if (uri.equals("/power/login.do") || uri.equals("/power")) { return true; } else if (user == null||admin==null) { response.sendRedirect(request.getContextPath() + "/login.do"); return false; } else { return true; } } }
true
91962ba9e77af7d8b4dd1214987fc266a48d15b4
Java
wubi517/AceBird
/app/src/main/java/com/kds/gold/acebird/dialog/AccountDlg.java
UTF-8
1,727
2.109375
2
[]
no_license
package com.kds.gold.acebird.dialog; import android.app.Dialog; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.support.annotation.NonNull; import android.view.KeyEvent; import android.view.Window; import android.widget.TextView; import com.kds.gold.acebird.R; import com.kds.gold.acebird.apps.Constants; import com.kds.gold.acebird.apps.MyApp; import com.kds.gold.acebird.models.LoginModel; /** * Created by RST on 7/27/2017. */ public class AccountDlg extends Dialog { private LoginModel loginModel = (LoginModel) MyApp.instance.getPreference().get(Constants.LOGIN_INFO); public AccountDlg(@NonNull Context context, final DialogMacListener listener) { super(context); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.dlg_account); getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); TextView txt_mac = (TextView)findViewById(R.id.txt_mac); txt_mac.setText(loginModel.getMac_address()); TextView txt_expired = findViewById(R.id.txt_expired); txt_expired.setText((String ) MyApp.instance.getPreference().get(Constants.PROFILE)); } public interface DialogMacListener { public void OnYesClick(Dialog dialog); } @Override public boolean dispatchKeyEvent(@NonNull KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_BACK) { dismiss(); } if(event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_DPAD_CENTER){ dismiss(); } return super.dispatchKeyEvent(event); } }
true
b495dc0cb40ca67dc603bc4af7d7c133cf463fe3
Java
artiomsher/sentence-analysis
/src/main/java/com/example/junior/Form.java
UTF-8
4,066
2.8125
3
[]
no_license
package com.example.junior; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; public class Form { private String contentTextInput; private String contentFileInput; private Map<Character, Result> results = new HashMap<Character, Result>(); private String filePath; /* Formats textarea data from hasmap in a form of how it was asked in the spec */ public String getResultsTextInput() { if (contentTextInput.isEmpty()) { return ""; } else { computeResults(contentTextInput); TreeMap<Character, Result> sortedHM = new TreeMap<Character, Result>(); sortedHM.putAll(results); String formattedResult = ""; for (Map.Entry<Character, Result> entry : sortedHM.entrySet()) { formattedResult += entry.getKey() + " " + entry.getValue().getNumberOfWords() + " " + entry.getValue().getWords() + '\n'; } writePreviousRequest(contentTextInput, formattedResult, "textarea"); return formattedResult; } } /* Formats file data from hasmap in a form of how it was asked in the spec * Redundant to previous method, cannot think of how to combine them */ public String getResultsFileInput() { results.clear(); if (contentFileInput == null) { return ""; } else { computeResults(contentFileInput); TreeMap<Character, Result> sortedHM = new TreeMap<Character, Result>(); sortedHM.putAll(results); String formattedResult = ""; for (Map.Entry<Character, Result> entry : sortedHM.entrySet()) { formattedResult += entry.getKey() + " " + entry.getValue().getNumberOfWords() + " " + entry.getValue().getWords() + '\n'; } writePreviousRequest(contentFileInput, formattedResult, "text file"); return formattedResult; } } public String getContentTextInput() { return contentTextInput; } public void setContentTextInput(String contentTextInput) { this.contentTextInput = contentTextInput; } public String getContentFileInput() { readFromFile(filePath); return contentFileInput; } public void setContentFileInput(String contentFileInput) { this.contentFileInput = contentFileInput; } /* Arranges data to hashmap */ private void computeResults(String content) { String[] trimmed = content.trim().split(" "); for (String singleWord : trimmed) { if (isOnlyLatin(singleWord)) { if (results.get(getLastCharacter(singleWord)) != null) { results.get(getLastCharacter(singleWord)).populateWords(singleWord); } else { results.put(getLastCharacter(singleWord), new Result(singleWord)); } } } } /* Checks if the word contains any non-latin characters with RegEx */ private Boolean isOnlyLatin(String splittedContent) { return splittedContent.matches("^[a-zA-Z]*$"); } private Character getLastCharacter(String splittedContent) { return splittedContent.toLowerCase().charAt(splittedContent.length() - 1); } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } private void readFromFile(String filePath) { String content = ""; try { File file = new File(filePath); Scanner myReader = new Scanner(file); while (myReader.hasNextLine()) { String data = myReader.nextLine(); content += data + " "; } myReader.close(); setContentFileInput(content); } catch (FileNotFoundException e) { } } /* Writes data to log.txt file to perform history tracking */ private void writePreviousRequest(String content, String result, String fileOrInput) { File log = new File("./history/log.txt"); try { if (log.exists() == false) { log.createNewFile(); } PrintWriter out = new PrintWriter(new FileWriter(log, true)); out.append("Requested text from " + fileOrInput + " : " + content + "\n" + "Result: " + result + "\n\n"); out.close(); } catch (IOException e) { System.out.println("Failed to write request history"); } } }
true
0428a1bd663170d0b31449751e6c19958828dfde
Java
rasu3094/CodingProblems
/src/hackthaton/SmallestPositiveIntegerIndentification.java
UTF-8
720
3.171875
3
[]
no_license
package hackthaton; public class SmallestPositiveIntegerIndentification { public static void main(String[] args) { //int arr[] = {-10,-3,1,29,-2}; int arr[] = {1,3,5,0,2}; int smallestPositive = findSmallestPositiveIntegerInUnsortedArray(arr, arr.length); System.out.println("Smallest Positive Integer In Unsorted Array : "+ smallestPositive); } private static int findSmallestPositiveIntegerInUnsortedArray(int[] arr, int size) { boolean[] present = new boolean[size+1]; for (int i = 0; i < size; i++) { if(arr[i] > 0 && arr[i]<=size) { present[arr[i]] = true; } } for (int i = 1; i < size; i++) { if(!present[i]) { return i; } } return size+1; } }
true
0094678de551b30cccf2ee227d54a1f2b5e2af9d
Java
greatstudy/zyjy
/src/com/zyjy/dao/base/BaseDao.java
UTF-8
2,804
2.5625
3
[]
no_license
package com.zyjy.dao.base; import com.mchange.v2.c3p0.ComboPooledDataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * @ClassName BaseDao * @Description 只做连接和关闭资源,同时获得表的前缀 * @Author 清Great * @Date 2020/10/13 10:50 */ public class BaseDao { private static BaseDao baseDao = new BaseDao(); private static ComboPooledDataSource ds = new ComboPooledDataSource(); public static BaseDao getBaseDao() { return baseDao; } public String getTableFirstName() { //表的前缀 String tableFirstName = "C"; return tableFirstName; } /** * 获取连接 * 获取连接并设置成非自动commit * * @return */ public static Connection getConnection() throws SQLException { Connection connection = ds.getConnection(); connection.setAutoCommit(false); return connection; } public static void commit(Connection connection) throws SQLException { connection.commit(); } public static void rollback(Connection connection) { try { if (connection != null) { connection.rollback(); } } catch (SQLException e) { e.printStackTrace(); } } /** * 获取连接并设置成非自动commit * * @return */ public Connection getConnAutoCommit() throws SQLException { Connection connection = ds.getConnection(); connection.setAutoCommit(true); return connection; } /** * 关闭资源 * * @param rs * @param ps */ public void closeResource(ResultSet rs, PreparedStatement ps) throws SQLException { if (rs != null) { rs.close(); } if (ps != null) { ps.close(); } } public static void closeConnection(Connection connection) { try { if (connection != null) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } public static void dsState() { System.out.println("最大连接数:" + ds.getMaxPoolSize());// 最大连接数 System.out.println("最小连接数:" + ds.getMinPoolSize());// 最小连接数 try { System.out.println("正在使用连接数:" + ds.getNumBusyConnections());// 正在使用连接数 System.out.println("空闲连接数:" + ds.getNumIdleConnections());// 空闲连接数 System.out.println("总连接数:" + ds.getNumConnections());// 总连接数 } catch (SQLException e) { e.printStackTrace(); } } }
true
b256bd9da250e1080418dd3f75c9b72fbe04f57b
Java
Garfield-Lucky/hospital
/src/main/java/org/wu/work/repository/impl/DoctorWorkRepository.java
UTF-8
19,231
2.359375
2
[]
no_license
package org.wu.work.repository.impl; import java.util.List; import java.util.Map; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Repository; import org.wu.work.entity.DoctorWork; import org.wu.work.repository.RepositorySupport; @Repository("doctorWorkRepository") public class DoctorWorkRepository extends RepositorySupport<DoctorWork> { /** * @param userName * @return */ // 查询所有检查项目名 public List<DoctorWork> queryAllDoctorWork(){ return this.findAll(); } // 查询检查 public DoctorWork queryDoctorWorkById(String id){ DetachedCriteria detachedCriteria = DetachedCriteria.forClass(DoctorWork.class); detachedCriteria.add(Restrictions.eq("id", id)); System.out.println("id="+id); return this.findOne(detachedCriteria); } // 查询检查 public List<DoctorWork> queryDoctorWorkByCode(String code){ DetachedCriteria detachedCriteria = DetachedCriteria.forClass(DoctorWork.class); detachedCriteria.add(Restrictions.eq("doctorCode", code)); System.out.println("doctorCode="+code); return this.findAll(detachedCriteria); } // 预约挂号时检查该医生是否可以挂号 public List<Map<String,String>> queryDoctorWorkByCodeAndDate(String code,String date){ String sql = "select dw.id,dw.doctorCode,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw where dw.doctorCode =:code and dw.workDate =:date and dw.status =0" ; List<Map<String,String>> list = this.executeSql(sql,new String[]{"code","date"},code,date); return list; } public List<Map<String,String>> queryDoctorWorkByCode(int page,int pageSize,String code){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.doctorCode =:code and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSqlPage(sql, page, pageSize,new String[]{"code"},code); return list; } public List<Map<String,String>> queryDoctorWorkList(int page,int pageSize){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0 and dw.workDate >= date_format(curdate(),'%Y-%m-%d' )" ; List<Map<String,String>> list = this.executeSqlPage(sql, page, pageSize); return list; } // 保存检查 public DoctorWork saveDoctorWork(DoctorWork work) { try { return this.save(work); } catch (Exception e) { return null; } } //删除检查 public boolean deleteDoctorWork(DoctorWork work) { if (work == null) { return false; } try { this.delete(work); } catch (Exception e) { return false; } return true; } //医生值班列表查询 //1 public List<Map<String,String>> queryDoctorWorkByD(int page,int pageSize,String code){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.doctorCode =:code and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSqlPage(sql, page, pageSize,new String[]{"code"},code); return list; } //2 public List<Map<String,String>> queryDoctorWorkByR(int page,int pageSize,String count){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.registerCount =:count and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSqlPage(sql, page, pageSize,new String[]{"count"},count); return list; } //3 public List<Map<String,String>> queryDoctorWorkByW(int page,int pageSize,String date){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.workDate =:date and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSqlPage(sql, page, pageSize,new String[]{"date"},date); return list; } //4 public List<Map<String,String>> queryDoctorWorkByT(int page,int pageSize,String time){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.workTime =:time and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSqlPage(sql, page, pageSize,new String[]{"time"},time); return list; } //5 public List<Map<String,String>> queryDoctorWorkByRW(int page,int pageSize,String count,String date){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.registerCount =:count and dw.workDate =:date and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSqlPage(sql, page, pageSize,new String[]{"count","date"},count,date); return list; } //6 public List<Map<String,String>> queryDoctorWorkByRT(int page,int pageSize,String count,String time){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.registerCount =:count and dw.workTime =:time and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSqlPage(sql, page, pageSize,new String[]{"count","time"},count,time); return list; } //7 public List<Map<String,String>> queryDoctorWorkByWT(int page,int pageSize,String date,String time){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.workDate =:date and dw.workTime =:time and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSqlPage(sql, page, pageSize,new String[]{"date","time"},date,time); return list; } //8 public List<Map<String,String>> queryDoctorWorkByDR(int page,int pageSize,String code,String count){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.doctorCode =:code and dw.registerCount =:count and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSqlPage(sql, page, pageSize,new String[]{"code","count"},code,count); return list; } //9 public List<Map<String,String>> queryDoctorWorkByDW(int page,int pageSize,String code,String date){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.doctorCode =:code and dw.workDate =:date and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSqlPage(sql, page, pageSize,new String[]{"code","date"},code,date); return list; } //10 public List<Map<String,String>> queryDoctorWorkByDT(int page,int pageSize,String code,String time){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.doctorCode =:code and dw.workTime =:time and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSqlPage(sql, page, pageSize,new String[]{"code","time"},code,time); return list; } //11 public List<Map<String,String>> queryDoctorWorkByDRW(int page,int pageSize,String code,String count,String date){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.doctorCode =:code and dw.registerCount =:count and dw.workDate =:date and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSqlPage(sql, page, pageSize,new String[]{"code","count","date"},code,count,date); return list; } //12 public List<Map<String,String>> queryDoctorWorkByDRT(int page,int pageSize,String code,String count,String time){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.doctorCode =:code and dw.registerCount =:count and dw.workTime =:time and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSqlPage(sql, page, pageSize,new String[]{"code","count","time"},code,count,time); return list; } //13 public List<Map<String,String>> queryDoctorWorkByDWT(int page,int pageSize,String code,String date,String time){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.doctorCode =:code and dw.workDate =:date and dw.workTime =:time and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSqlPage(sql, page, pageSize,new String[]{"code","date","time"},code,date,time); return list; } //14 public List<Map<String,String>> queryDoctorWorkByRWT(int page,int pageSize,String count,String date,String time){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.registerCount =:count and dw.workDate =:date and dw.workTime =:time and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSqlPage(sql, page, pageSize,new String[]{"count","date","time"},count,date,time); return list; } //15 public List<Map<String,String>> queryDoctorWorkByDRWT(int page,int pageSize,String code,String count,String date,String time){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.doctorCode =:code and dw.registerCount =:count and dw.workDate =:date and dw.workTime =:time and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSqlPage(sql, page, pageSize,new String[]{"code","count","date","time"},code,count,date,time); return list; } //分页 public List<Map<String,String>> queryDateNum(){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0 and dw.workDate >= date_format(curdate(),'%Y-%m-%d' )" ; List<Map<String,String>> list = this.executeSql(sql); return list; } //1 public List<Map<String,String>> queryDataNumByD(String code){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.doctorCode =:code and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSql(sql, new String[]{"code"},code); return list; } //2 public List<Map<String,String>> queryDataNumByR(String count){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.registerCount =:count and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSql(sql,new String[]{"count"},count); return list; } //3 public List<Map<String,String>> queryDataNumByW(String date){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.workDate =:date and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSql(sql,new String[]{"date"},date); return list; } //4 public List<Map<String,String>> queryDataNumByT(String time){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.workTime =:time and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSql(sql,new String[]{"time"},time); return list; } //5 public List<Map<String,String>> queryDataNumByRW(String count,String date){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.registerCount =:count and dw.workDate =:date and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSql(sql,new String[]{"count","date"},count,date); return list; } //6 public List<Map<String,String>> queryDataNumByRT(String count,String time){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.registerCount =:count and dw.workTime =:time and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSql(sql,new String[]{"count","time"},count,time); return list; } //7 public List<Map<String,String>> queryDataNumByWT(String date,String time){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.workDate =:date and dw.workTime =:time and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSql(sql,new String[]{"date","time"},date,time); return list; } //8 public List<Map<String,String>> queryDataNumByDR(String code,String count){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.doctorCode =:code and dw.registerCount =:count and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSql(sql,new String[]{"code","count"},code,count); return list; } //9 public List<Map<String,String>> queryDataNumByDW(String code,String date){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.doctorCode =:code and dw.workDate =:date and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSql(sql,new String[]{"code","date"},code,date); return list; } //10 public List<Map<String,String>> queryDataNumByDT(String code,String time){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.doctorCode =:code and dw.workTime =:time and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSql(sql,new String[]{"code","time"},code,time); return list; } //11 public List<Map<String,String>> queryDataNumByDRW(String code,String count,String date){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.doctorCode =:code and dw.registerCount =:count and dw.workDate =:date and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSql(sql,new String[]{"code","count","date"},code,count,date); return list; } //12 public List<Map<String,String>> queryDataNumByDRT(String code,String count,String time){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.doctorCode =:code and dw.registerCount =:count and dw.workTime =:time and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSql(sql,new String[]{"code","count","time"},code,count,time); return list; } //13 public List<Map<String,String>> queryDataNumByDWT(String code,String date,String time){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.doctorCode =:code and dw.workDate =:date and dw.workTime =:time and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSql(sql,new String[]{"code","date","time"},code,date,time); return list; } //14 public List<Map<String,String>> queryDataNumByRWT(String count,String date,String time){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.registerCount =:count and dw.workDate =:date and dw.workTime =:time and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSql(sql,new String[]{"count","date","time"},count,date,time); return list; } //15 public List<Map<String,String>> queryDataNumByDRWT(String code,String count,String date,String time){ String sql = "select dw.id,dw.doctorCode,d.doctorName,o.officeType,dw.workDate,dw.workTime,dw.registerCount,dw.reaminCount from tb_doctorWork dw,tb_office o,tb_doctor d where dw.doctorCode =:code and dw.registerCount =:count and dw.workDate =:date and dw.workTime =:time and dw.doctorCode =d.doctorCode and d.officeCode = o.officeCode and dw.status =0" ; List<Map<String,String>> list = this.executeSql(sql,new String[]{"code","count","date","time"},code,count,date,time); return list; } }
true
83500a2abdd193830c0830fc6f3d8a17bb71c41d
Java
huynhquanhht/BKDrive-App
/FTP_Code/FTP_Code/src/Model/Bean/Account.java
UTF-8
1,245
2.328125
2
[]
no_license
package Model.Bean; import java.io.Serializable; public class Account implements Serializable { /** * */ private static final long serialVersionUID = -7065249758248316953L; int id; String username; String password; String name; String ipAddress; int idFolder; public Account(int id, String username, String password, String name, String ipAddress, int idFolder) { this.id = id; this.username = username; this.password = password; this.name = name; this.ipAddress = ipAddress; this.idFolder = idFolder; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getIdFolder() { return idFolder; } public void setIdFolder(int idFolder) { this.idFolder = idFolder; } }
true
9f98a61910c2bcc84392f14b5a40abf37d8e6c0b
Java
dknitk/programs
/java/projects/KWInterviewQA/src/com/knowledgewala/interviewqa/NumberOfIslands.java
UTF-8
1,179
3.578125
4
[]
no_license
package com.knowledgewala.interviewqa; public class NumberOfIslands { private int h; private int w; public static void main(String[] args) { char[][] grid = { { '1', '1', '1' }, { '1', '0', '0' }, { '1', '0', '1' } }; System.out.println("Number of islands is " + new NumberOfIslands().numIslands(grid)); } public int numIslands(char[][] grid) { h = grid.length; if (h == 0) return 0; w = grid[0].length; boolean[][] visited = new boolean[h][w]; int islandCount = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { System.out.print("("+i+" , "+j+") :"+grid[i][j]+" "); if (!visited[i][j] && grid[i][j] == '1') { markNeigbors(grid, visited, i, j); ++islandCount; } } System.out.println(); } return islandCount; } private void markNeigbors(char[][] grid, boolean[][] visited, int x, int y) { if (x < 0 || x >= h || y < 0 || y >= w || visited[x][y] || grid[x][y] != '1') return; visited[x][y] = true; markNeigbors(grid, visited, x + 1, y); markNeigbors(grid, visited, x - 1, y); markNeigbors(grid, visited, x, y + 1); markNeigbors(grid, visited, x, y - 1); } }
true
3f5a665c312b7e56d5b5e306353c5c8253f7e5b5
Java
kimyundung/misssimple
/mss-domain/src/main/java/com/misssimple/domain/Goods.java
UTF-8
2,713
2.25
2
[]
no_license
package com.misssimple.domain; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; import java.util.List; /** * 商品表 */ @Data @NoArgsConstructor public class Goods { /* goods_id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键id', goods_name VARCHAR(32) NOT NULL COMMENT '商品名称', goods_price DECIMAL(10,2) NOT NULL DEFAULT '0.00' COMMENT '商品价格', cat_id INT(11) UNSIGNED NOT NULL COMMENT '类型id', goods_introduce TEXT COMMENT '商品详情介绍', goods_big_logo CHAR(128) NOT NULL DEFAULT '' COMMENT '图片logo大图', goods_small_logo CHAR(128) NOT NULL DEFAULT '' COMMENT '图片logo小图', cat_one_id INT(11) UNSIGNED NOT NULL COMMENT '一级分类id', cat_two_id INT(11) UNSIGNED NOT NULL COMMENT '二级分类id', hot_number INT(11) UNSIGNED DEFAULT '0' COMMENT '热卖数量', is_promote INT(11) DEFAULT '0' COMMENT '是否促销', status INT(11) DEFAULT '0' COMMENT '商品状态 0下架 1上架', is_del TINYINT(1) DEFAULT '0' COMMENT '0:正常 1:删除', create_time DATETIME NOT NULL COMMENT '记录生成时间', update_time DATETIME NOT NULL COMMENT '记录修改时间', delete_time DATETIME DEFAULT NULL COMMENT '删除时间标志', created_by VARCHAR(100) NOT NULL COMMENT '创建人', updated_by VARCHAR(100) NOT NULL COMMENT '更新人', deleted_by VARCHAR(100) DEFAULT NULL COMMENT '删除人',*/ private Integer goodsId; // 主键id private String goodsName; // 商品名称 private Double goodsPrice; // 商品价格 private Integer catId; // 类型id private String goodsIntroduce; // 商品详情介绍 private String goodsBigLogo; // 图片logo大图 private String goodsSmallLogo; // 图片logo小图 private Integer catOneId; // 一级分类id private Integer caTwoId; // 二级分类id private Integer hotNumber; // 热卖数量 private Integer isPromote; // 是否促销 private Integer status; // 商品状态 0下架 1上架 private Integer isDel; // 是否删除 private Date createTime; // 记录生成时间 private Date updateTime; // 记录修改时间 private Date deleteTime; // 删除时间标志 private String createdBy; // 创建人 private String updatedBy; // 更新人 private String deletedBy; // 删除人 // 该商品拥有的相册集合 private List<GoodsPics> pics; }
true
932ddfff44d02a5885ce98077f19a3540a844a67
Java
KuntanSutar/Home-PC-Practice
/Home PC Practice/Fire1.java
UTF-8
217
2.765625
3
[]
no_license
class Fire1 { static public void main(String... Kuntan) { System.out.println("Parent Main"); } } class Fire2 extends Fire1 { static public void main(String... Kuntan) { System.out.println("Child Main"); } }
true
98d618bb9f03ef536612e7d235e916aaf8208233
Java
amwfarid/Wrapper-Droid
/app/src/main/java/com/fariddev/wrapperdroid/FileIO/FileIO.java
UTF-8
1,260
2.765625
3
[]
no_license
package com.fariddev.wrapperdroid.FileIO; import android.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * Created by Ahmed on 3/11/16. */ public class FileIO { private File file; private boolean append; private FileOutputStream oStream; private FileInputStream iStream; public FileIO(String path, String fileName, boolean append){ this.append = append; file = new File(path, fileName); } public void write(String payload){ try { oStream = new FileOutputStream(file,append); oStream.write(payload.getBytes()); oStream.close(); } catch (IOException e) { Log.e("FileIO error", e.getMessage()); } } public String read(){ try { int length = (int) file.length(); byte[] payload = new byte[length]; iStream = new FileInputStream(file); iStream.read(payload); iStream.close(); return new String(payload); } catch (IOException e) { Log.e("FileIO error", e.getMessage()); } return null; } }
true
411b984e4f1604347c7e65ade201826f6b82f9a9
Java
onap/policy-drools-pdp
/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheck.java
UTF-8
4,201
1.882813
2
[ "CC-BY-4.0", "Apache-2.0" ]
permissive
/* * ============LICENSE_START======================================================= * ONAP * ================================================================================ * Copyright (C) 2017-2019, 2021-2022 AT&T Intellectual Property. 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. * ============LICENSE_END========================================================= */ package org.onap.policy.drools.healthcheck; import java.util.ArrayList; import java.util.List; import lombok.Data; import lombok.NoArgsConstructor; import org.onap.policy.common.capabilities.Startable; import org.onap.policy.common.endpoints.http.client.HttpClient; import org.onap.policy.drools.system.PolicyController; /** * Healthcheck. */ public interface HealthCheck extends Startable { /** * Healthcheck Report. */ @Data @NoArgsConstructor class Report { /** * Named Entity in the report. */ private String name; /** * URL queried. */ private String url; /** * healthy. */ private boolean healthy; /** * return code. */ private long code; /** * start time. */ private long startTime = System.currentTimeMillis(); /** * end time. */ private long endTime; /** * elapsed time. */ private long elapsedTime; /** * Message from remote entity. */ private String message; /** * Create a report. * * @param report the report to create */ public Report(Report report) { this.startTime = report.startTime; this.code = report.code; this.elapsedTime = report.elapsedTime; this.endTime = report.endTime; this.healthy = report.healthy; this.message = report.message; this.name = report.name; this.url = report.url; } /** * Set the end time on the report as now. * * @return the report */ public Report setEndTime() { setEndTime(System.currentTimeMillis()); setElapsedTime(endTime - startTime); return this; } } /** * Report aggregation. */ @Data class Reports { private boolean healthy; private final long startTime = System.currentTimeMillis(); private long endTime; private long elapsedTime; private List<Report> details = new ArrayList<>(); /** * Set the end time on the report as now. * * @return the report */ public Reports setEndTime() { this.endTime = System.currentTimeMillis(); this.elapsedTime = this.endTime - this.startTime; return this; } } /** * Process engine open status. */ void open(); /** * System healthcheck. */ Reports healthCheck(); /** * Engine only healthcheck. */ Reports engineHealthcheck(); /** * Controllers only healthcheck. */ Reports controllerHealthcheck(); /** * Healthcheck on a controller. */ Reports controllerHealthcheck(PolicyController controller); /** * HTTP Clients only healthcheck. */ Reports clientHealthcheck(); /** * Healthcheck on an HTTP Client. */ Reports clientHealthcheck(HttpClient client); }
true
831fdceca7b7c41b85e8fb27d9dbd4dace888cf7
Java
gustavliu/sleep-test-center
/src/main/java/com/gustav/entity/UserDTO.java
UTF-8
808
2.46875
2
[]
no_license
package com.gustav.entity; import java.io.Serializable; import com.gustav.enums.UserSexEnum; import lombok.Data; @Data public class UserDTO implements Serializable { private static final long serialVersionUID = 1L; private Long id; private String userName; private String passWord; private UserSexEnum userSex; private String nickName; public UserDTO() { super(); } public UserDTO(String userName, String passWord, UserSexEnum userSex) { super(); this.passWord = passWord; this.userName = userName; this.userSex = userSex; } @Override public String toString() { // TODO Auto-generated method stub return "userName " + this.userName + ", pasword " + this.passWord + "sex " + userSex.name(); } }
true
820e612e4a83ab831f2e7dbac9cce3ecfaded564
Java
wyzfzu/myframe
/myframe-core/src/main/java/com/myframe/core/util/ExcelUtils.java
UTF-8
4,480
2.671875
3
[ "MIT" ]
permissive
package com.myframe.core.util; import com.google.common.base.Optional; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.OutputStream; import java.lang.reflect.Method; import java.util.Date; import java.util.List; /** * Excel导出工具。 * * @author wyzfzu (wyzfzu@qq.com) */ public final class ExcelUtils { public static <T> Workbook export(final List<T> datas, List<Pair<String, String>> valueDescs) { return export(datas, valueDescs, null); } public static <T> Workbook export(final List<T> datas, List<Pair<String, String>> valueDescs, OutputStream os) { return export(datas, valueDescs, os, false); } public static <T> Workbook exportOld(final List<T> datas, List<Pair<String, String>> valueDescs) { return exportOld(datas, valueDescs, null); } /** * 导出数据到excel, xls格式。 * * @param datas 要导出的数据。 * @param valueDescs 字段和描述键值对。 * @param os 输出流。 * @param <T> 类类型 * @return 工作簿对象 */ public static <T> Workbook exportOld(final List<T> datas, List<Pair<String, String>> valueDescs, OutputStream os) { return export(datas, valueDescs, os, true); } /** * 导出数据到excel, xlsx格式。 * * @param datas 要导出的数据。 * @param valueDescs 字段和描述键值对。 * @param os 输出流。 * @param <T> 类类型 * @return 工作簿对象 */ public static <T> Workbook export(final List<T> datas, List<Pair<String, String>> valueDescs, OutputStream os, boolean old) { if (CollectUtils.isEmpty(datas)) { throw new RuntimeException("导出数据不能为空!"); } if (CollectUtils.isEmpty(valueDescs)) { throw new RuntimeException("导出字段和描述映射不能为空!"); } Class<?> classType = null; Workbook workbook; if (old) { workbook = new HSSFWorkbook(); } else { workbook = new XSSFWorkbook(); } Sheet sheet = workbook.createSheet(); // 生成头行 int i = 0; Row header = sheet.createRow(0); for (Pair<String, String> entry : valueDescs) { Cell cell = header.createCell(i); String fieldDesc = entry.getValue(); cell.setCellValue(fieldDesc); cell.setCellType(CellType.STRING); i++; } for (int rownum = 0, len = datas.size(); rownum < len; ++rownum) { T data = datas.get(rownum); if (null == classType) { classType = data.getClass(); } Row row = sheet.createRow(rownum + 1); int colNum = 0; for (Pair<String, String> entry : valueDescs) { Cell cell = row.createCell(colNum); colNum++; String fieldName = entry.getKey(); Object cellValue = ReflectUtils.invokeGetter(data, fieldName); if (null == cellValue) { cell.setCellValue(""); continue; } Optional<Method> field = ReflectUtils.getAccessibleMethod(data, "set" + StringUtils.capitalize(fieldName)); if (!field.isPresent()) { cell.setCellValue(cellValue.toString()); } else { Class<?> returnType = field.get().getReturnType(); if (returnType.equals(Boolean.class)) { cell.setCellValue(cellValue.toString()); } else if (returnType.equals(Date.class)) { cell.setCellValue(DateUtils.formatDateTime((Date) cellValue)); } else { cell.setCellValue(cellValue.toString()); } } } } if (null != os) { try { workbook.write(os); os.flush(); os.close(); } catch (Exception e) { throw new RuntimeException(e); } } return workbook; } }
true
cae9af62982503bf9b37354b7248af30d403a37a
Java
fj2008/java
/src/test/Ex1.java
UHC
1,110
3.609375
4
[]
no_license
package test; import chapter3.TV; public class Ex1 { public static void main(String[] args) { TV LG_TV = new TV(); LG_TV.setColor("red"); // ü(߽) α׷ ߽ α׷ ϴ // ü ϴ ʿ ü ϴ ɸ ؾѴ. LG_TV.power(); LG_TV.channelUp(); // ԵǸ ν (߽)α׷ . //߽ ϰԵǸ ԵǸ ʹ 䱸Ѵ //׷ ü ֵ private ؼ Ѵ //ܺη ϸ ȵǴ ͸ ߴ ȭ, LG_TV.channelDown(); // äιȣ ˷ְ ʹ //1. Ѱ //2.äιȣ ˷ش //ο ɹ System.out.println(" ä ȣ" + LG_TV.getChannel()+" Դϴ."); } }
true
dc49624fbde5f61b31e22e03254aeefb26c630c4
Java
freckie/Winter-Is-End
/freckie/week3/src/main/java/com/freckie/week3/service/logic/ArticleServiceLogic.java
UTF-8
4,460
2.375
2
[]
no_license
package com.freckie.week3.service.logic; import com.freckie.week3.model.*; import com.freckie.week3.payload.article.*; import com.freckie.week3.payload.board.PutBoardResponse; import com.freckie.week3.repository.ArticleRepository; import com.freckie.week3.repository.BoardRepository; import com.freckie.week3.repository.UserRepository; import com.freckie.week3.service.ArticleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.time.LocalDateTime; import java.util.List; import java.util.NoSuchElementException; import java.util.ArrayList; import java.util.stream.Collectors; @Service public class ArticleServiceLogic implements ArticleService { @Autowired private ArticleRepository articleRepo; @Autowired private BoardRepository boardRepo; @Autowired private UserRepository userRepo; public GetArticleListResponse getArticleList(Long boardId) throws NoSuchElementException { // raise exception if no Board exists boardRepo.findById(boardId).orElseThrow(() -> new NoSuchElementException("No specific board exists")); Board board = boardRepo.getById(boardId); // Create DTO list List<Article> articles = articleRepo.findAllByBoard(board); ArrayList<ArticleDTO> dtoList = articles.stream() .map(ArticleDTO::of) .collect(Collectors.toCollection(ArrayList<ArticleDTO>::new)); // Make a response containing the Article List return new GetArticleListResponse(BoardDTO.of(board), dtoList); } public GetArticleResponse getArticle(Long boardId, Long articleId) throws NoSuchElementException { // raise exception if no Board exists boardRepo.findById(boardId).orElseThrow(() -> new NoSuchElementException("No specific board exists")); articleRepo.findById(articleId).orElseThrow(() -> new NoSuchElementException("No specific article exists")); // Get the Article Article article = articleRepo.getById(articleId); // Make a response containing the Article return new GetArticleResponse(ArticleDTO.of(article)); } @Transactional public PostArticleResponse createArticle(Long boardId, PostArticleRequest req) throws NoSuchElementException { // raise exception if no Board exists Long userId = req.getCreatedBy(); userRepo.findById(userId).orElseThrow(() -> new NoSuchElementException("No specific user exists")); boardRepo.findById(boardId).orElseThrow(() -> new NoSuchElementException("No specific board exists")); // Create a new Post User user = userRepo.getById(userId); Board board = boardRepo.getById(boardId); Article article = new Article(req.getTitle(), req.getContents(), LocalDateTime.now(), user, board); ArticleDTO dto = ArticleDTO.of(articleRepo.save(article)); // Make a response containing the ArticleDTO return new PostArticleResponse(dto); } @Transactional public PutArticleResponse updateArticle(Long boardId, Long articleId, PutArticleRequest req) throws NoSuchElementException { // raise exception if no Article exists boardRepo.findById(boardId).orElseThrow(() -> new NoSuchElementException("No specific board exists")); articleRepo.findById(boardId).orElseThrow(() -> new NoSuchElementException("No specific article exists")); // Get the Article Article article = articleRepo.getById(articleId); // Update the Article if (req.getTitle().isPresent()) { article.setTitle(req.getTitle().get()); } if (req.getContents().isPresent()) { article.setContents(req.getContents().get()); } ArticleDTO dto = ArticleDTO.of(articleRepo.save(article)); // Make a response containing the BoardDTO return new PutArticleResponse(dto); } @Transactional public Boolean deleteArticle(Long boardId, Long articleId) throws NoSuchElementException { // raise exception if no Board exists boardRepo.findById(boardId).orElseThrow(() -> new NoSuchElementException("No specific board exists")); articleRepo.findById(boardId).orElseThrow(() -> new NoSuchElementException("No specific article exists")); articleRepo.deleteById(articleId); return true; } }
true
8d43a68dc52642226c5a933d57f37ac83b08cf18
Java
TobyDrane/Java-3D-Voxel-Game
/Block Game/src/com/idkstudios/game/rendering/ChunkMeshBuilder.java
UTF-8
7,234
2.359375
2
[]
no_license
package com.idkstudios.game.rendering; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; import com.idkstudios.game.blocks.Block; import com.idkstudios.game.blocks.BlockManager; import com.idkstudios.game.blocks.BlockType; import com.idkstudios.game.math.MathHelper; import com.idkstudios.game.math.Vec3f; import com.idkstudios.game.math.Vec3i; import com.idkstudios.game.utils.IntList; import com.idkstudios.game.world.Chunk; import com.idkstudios.game.world.ChunkData; import com.idkstudios.game.world.LightBuffer; public class ChunkMeshBuilder { private static final boolean DEBUG = false; public static final Vec3f COLOR_WHITE = new Vec3f(1, 1, 1); public static final int STRIDE = 8; public static final int POSITION_SIZE = 3; public static final int POSITION_OFFSET = 0; public static final int COLOR_SIZE = 3; public static final int COLOR_OFFSET = POSITION_OFFSET + POSITION_SIZE; public static final int TEX_COORD_SIZE = 2; public static final int TEX_COORD_OFFSET = COLOR_OFFSET + COLOR_SIZE; public static final int FLOAT_SIZE = 4; public static enum MeshType { OPAQUE, TRANSLUCENT } private static BlockManager _blockManager = BlockManager.getInstance(); private static int USED_SIZE = 0; private static boolean SMOOTH_LIGHTING = true; public static void generateChunkMesh(Chunk chunk, MeshType meshType) { if (DEBUG) System.out.println("Building " + meshType.name() + " Mesh for " + chunk.toString() + "..."); /* Make sure there are no list edits anymore */ chunk.performListChanges(); ChunkMesh mesh = chunk.getMesh(); mesh.destroy(meshType); /* Compute vertex count */ int vertexCount = chunk.getVertexCount(meshType); if (DEBUG) System.out.println("\tVertex Count = " + vertexCount); /* * If there are no faces visible yet (because of generating busy), don't * create a buffer */ if (vertexCount == 0) { return; } mesh.setVertexCount(meshType, vertexCount); /* Create a buffer */ int vbo = BufferManager.getInstance().createBuffer(); mesh.setVBO(meshType, vbo); /* Bind the buffer */ GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); /* Allocate size for the buffer */ int size = vertexCount * STRIDE * FLOAT_SIZE; GL15.glBufferData(GL15.GL_ARRAY_BUFFER, size, GL15.GL_STATIC_DRAW); if (DEBUG) System.out.println("\tCreate VBO: " + vbo + " with size = " + size + " (ERROR: " + GL11.glGetError() + ")"); /* Get the native buffer to write to */ ByteBuffer byteBuffer = GL15.glMapBuffer(GL15.GL_ARRAY_BUFFER, GL15.GL_WRITE_ONLY, size, null); if (byteBuffer == null) { System.out .println("\tCouldn't create a native VBO!: GL Error Code = " + GL11.glGetError()); GL15.glUnmapBuffer(GL15.GL_ARRAY_BUFFER); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); mesh.destroy(meshType); Thread.dumpStack(); mesh.setVBO(meshType, -1); mesh.setVertexCount(meshType, 0); return; } FloatBuffer vertexBuffer = byteBuffer.asFloatBuffer(); /* Store all vertices in the buffer */ USED_SIZE = 0; /* Local temporary variables, used to speed up */ IntList blockList = chunk.getVisibleBlocks(); int blockIndex = -1; byte blockType = 0; boolean special = false; Vec3i vec = new Vec3i(); BlockType type; Block block = null; LightBuffer lightBuffer = chunk.getLightBuffer(); byte faceMask = 0; /* Iterate over the blocks */ for (int i = 0; i < blockList.size(); ++i) { blockIndex = blockList.get(i); blockType = chunk.getChunkData().getBlockType(blockIndex); if (blockType == 0) continue; special = chunk.getChunkData().isSpecial(blockIndex); type = _blockManager.getBlockType(blockType); if ((meshType == MeshType.OPAQUE && !type.isTranslucent() && type .hasNormalAABB()) || (meshType == MeshType.TRANSLUCENT && (type .isTranslucent() || !type.hasNormalAABB()))) { ChunkData.indexToPosition(blockIndex, vec); /* Build the light buffer */ vec.setX(vec.x() + chunk.getAbsoluteX()); vec.setZ(vec.z() + chunk.getAbsoluteZ()); lightBuffer.setReferencePoint(vec.x(), vec.y(), vec.z()); if (special) { block = chunk.getChunkData().getSpecialBlock(blockIndex); if (block.isVisible()) { block.storeInVBO(vertexBuffer, lightBuffer); } } else { if (type.isCrossed()) { type.getCrossedBlockBrush().storeInVBO(vertexBuffer, vec.x() + 0.5f, vec.y() + 0.5f, vec.z() + 0.5f, lightBuffer); } else { faceMask = chunk.getChunkData().getFaceMask(blockIndex); type.getDefaultBlockBrush().setFaceMask(faceMask); type.getBrush().storeInVBO(vertexBuffer, vec.x() + 0.5f, vec.y() + 0.5f, vec.z() + 0.5f, lightBuffer); } } } } /* Perform a check */ if (USED_SIZE != STRIDE * FLOAT_SIZE * mesh.getVertexCount(meshType)) { System.out.println("\t[WARNING!]: Used size = " + USED_SIZE); System.out.println("\t[WARNING!]: Vertex count = " + USED_SIZE / STRIDE / FLOAT_SIZE); mesh.setVertexCount(meshType, USED_SIZE / STRIDE / FLOAT_SIZE); } byteBuffer.flip(); GL15.glUnmapBuffer(GL15.GL_ARRAY_BUFFER); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); } public static void putColorWithLight4(FloatBuffer vertexBuffer, Vec3f vec, byte light, byte light1, byte light2, byte light3) { float value; if (SMOOTH_LIGHTING) { value = light + light1 + light2 + light3; value /= 120.0001f; } else { value = light / 30.001f; } value = MathHelper.sin(value * MathHelper.f_PI_div_2); vertexBuffer.put(vec.x() * value); vertexBuffer.put(vec.y() * value); vertexBuffer.put(vec.z() * value); USED_SIZE += 3 * FLOAT_SIZE; } public static void putColorWithLight3(FloatBuffer vertexBuffer, Vec3f vec, byte light, byte light1, byte light2) { float value; if (SMOOTH_LIGHTING) { value = light + light1 + light2; value /= 90.0001f; } else { value = light / 30.001f; } value = MathHelper.sin(value * MathHelper.f_PI_div_2); vertexBuffer.put(vec.x() * value); vertexBuffer.put(vec.y() * value); vertexBuffer.put(vec.z() * value); USED_SIZE += 3 * FLOAT_SIZE; } public static void putColorWithLight(FloatBuffer vertexBuffer, Vec3f vec, byte light) { float value; value = light / 30.001f; vertexBuffer.put(vec.x() * value); vertexBuffer.put(vec.y() * value); vertexBuffer.put(vec.z() * value); USED_SIZE += 3 * FLOAT_SIZE; } public static void putVec3f(FloatBuffer vertexBuffer, Vec3f vec) { vertexBuffer.put(vec.x()); vertexBuffer.put(vec.y()); vertexBuffer.put(vec.z()); USED_SIZE += 3 * FLOAT_SIZE; } public static void put3f(FloatBuffer vertexBuffer, float f0, float f1, float f2) { vertexBuffer.put(f0); vertexBuffer.put(f1); vertexBuffer.put(f2); USED_SIZE += 3 * FLOAT_SIZE; } public static void put2f(FloatBuffer vertexBuffer, float f0, float f1) { vertexBuffer.put(f0); vertexBuffer.put(f1); USED_SIZE += 2 * FLOAT_SIZE; } public static void generateChunkMeshes(Chunk chunk) { chunk.getLightBuffer().buffer(chunk); generateChunkMesh(chunk, MeshType.OPAQUE); generateChunkMesh(chunk, MeshType.TRANSLUCENT); } }
true
0caf2efbb3437b5c81bdf599d71e1c6956b7f98e
Java
dan7800/Research
/Research_Bucket/Completed_Archived/dropboxbackup_9_1_18/AndroidData/old/Notsure/data/realvsfake/coinpirates/realcoinpirates_1%0%6%apk/com/tapjoy/TapjoyFeaturedAppWebView.java
UTF-8
5,217
1.898438
2
[]
no_license
package com.tapjoy; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; public class TapjoyFeaturedAppWebView extends Activity { final String TAPJOY_FEATURED_APP = "Featured App"; private String clientPackage = ""; private String fullScreenAdURL = ""; private ProgressBar progressBar; private String userID = ""; private WebView webView = null; public TapjoyFeaturedAppWebView() { } private void finishActivity() { finish(); } private void showOffers() { TapjoyConnect.getTapjoyConnectInstance(this).showOffers(this, this.userID); } public void onConfigurationChanged(Configuration paramConfiguration) { super.onConfigurationChanged(paramConfiguration); if (this.webView != null) new RefreshTask(null).execute(new Void[0]); } protected void onCreate(Bundle paramBundle) { Bundle localBundle = getIntent().getExtras(); this.userID = localBundle.getString("USER_ID"); this.clientPackage = localBundle.getString("CLIENT_PACKAGE"); this.fullScreenAdURL = localBundle.getString("FULLSCREEN_AD_URL"); this.fullScreenAdURL = this.fullScreenAdURL.replaceAll(" ", "%20"); super.onCreate(paramBundle); requestWindowFeature(1); setContentView(getApplicationContext().getResources().getIdentifier("tapjoy_featured_app_web_view", "layout", this.clientPackage)); this.webView = ((WebView)findViewById(getApplicationContext().getResources().getIdentifier("FeaturedAppWebView", "id", this.clientPackage))); this.webView.setWebViewClient(new TapjoyWebViewClient(null)); this.webView.getSettings().setJavaScriptEnabled(true); this.progressBar = ((ProgressBar)findViewById(getResources().getIdentifier("FeaturedAppProgressBar", "id", this.clientPackage))); this.progressBar.setVisibility(0); this.webView.loadUrl(this.fullScreenAdURL); TapjoyLog.i("Featured App", "Opening Full Screen AD URL = [" + this.fullScreenAdURL + "]"); } private class RefreshTask extends AsyncTask<Void, Void, Boolean> { private RefreshTask() { } protected Boolean doInBackground(Void[] paramArrayOfVoid) { try { Thread.sleep(200L); return Boolean.valueOf(true); } catch (InterruptedException localInterruptedException) { while (true) localInterruptedException.printStackTrace(); } } protected void onPostExecute(Boolean paramBoolean) { if (TapjoyFeaturedAppWebView.this.webView != null) TapjoyFeaturedAppWebView.this.webView.loadUrl("javascript:window.onorientationchange();"); } } private class TapjoyWebViewClient extends WebViewClient { private TapjoyWebViewClient() { } public void onPageFinished(WebView paramWebView, String paramString) { TapjoyFeaturedAppWebView.this.progressBar.setVisibility(8); } public boolean shouldOverrideUrlLoading(WebView paramWebView, String paramString) { TapjoyLog.i("Featured App", "URL = [" + paramString + "]"); if (paramString.contains("showOffers")) { TapjoyLog.i("Featured App", "show offers"); TapjoyFeaturedAppWebView.this.showOffers(); return true; } if (paramString.contains("dismiss")) { TapjoyLog.i("Featured App", "dismiss"); TapjoyFeaturedAppWebView.this.finishActivity(); return true; } if (paramString.indexOf("market") > -1) { TapjoyLog.i("Featured App", "Market URL = [" + paramString + "]"); try { String[] arrayOfString = paramString.split("q="); String str = "http://market.android.com/search?q=pname:" + arrayOfString[1] + "&referrer=" + TapjoyFeaturedAppWebView.this.clientPackage; Intent localIntent2 = new Intent("android.intent.action.VIEW", Uri.parse(str)); TapjoyFeaturedAppWebView.this.startActivity(localIntent2); TapjoyLog.i("Featured App", "Open URL of application = [" + str + "]"); return true; } catch (Exception localException) { TapjoyLog.i("Featured App", "Android market is unavailable at this device. To view this link install market."); return true; } } if (paramString.contains("ws.tapjoyads.com")) { TapjoyLog.i("Featured App", "Open redirecting URL = [" + paramString + "]"); paramWebView.loadUrl(paramString); return true; } TapjoyLog.i("Featured App", "Opening URL in new browser = [" + paramString + "]"); Intent localIntent1 = new Intent("android.intent.action.VIEW", Uri.parse(paramString)); TapjoyFeaturedAppWebView.this.startActivity(localIntent1); return true; } } } /* Location: * Qualified Name: com.tapjoy.TapjoyFeaturedAppWebView * Java Class Version: 6 (50.0) * JD-Core Version: 0.6.1-SNAPSHOT */
true
01293e2146d08714b467fa16d7d057418f5bc732
Java
cga2351/code
/DecompiledViberSrc/app/src/main/java/com/google/android/gms/common/api/internal/OptionalPendingResultImpl.java
UTF-8
2,543
1.921875
2
[]
no_license
package com.google.android.gms.common.api.internal; import com.google.android.gms.common.annotation.KeepForSdk; import com.google.android.gms.common.api.OptionalPendingResult; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.PendingResult.StatusListener; import com.google.android.gms.common.api.Result; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.ResultTransform; import com.google.android.gms.common.api.TransformedResult; import java.util.concurrent.TimeUnit; @KeepForSdk public final class OptionalPendingResultImpl<R extends Result> extends OptionalPendingResult<R> { private final BasePendingResult<R> zajp; public OptionalPendingResultImpl(PendingResult<R> paramPendingResult) { this.zajp = ((BasePendingResult)paramPendingResult); } public final void addStatusListener(PendingResult.StatusListener paramStatusListener) { this.zajp.addStatusListener(paramStatusListener); } public final R await() { return this.zajp.await(); } public final R await(long paramLong, TimeUnit paramTimeUnit) { return this.zajp.await(paramLong, paramTimeUnit); } public final void cancel() { this.zajp.cancel(); } public final R get() { if (isDone()) return await(0L, TimeUnit.MILLISECONDS); throw new IllegalStateException("Result is not available. Check that isDone() returns true before calling get()."); } public final boolean isCanceled() { return this.zajp.isCanceled(); } public final boolean isDone() { return this.zajp.isReady(); } public final void setResultCallback(ResultCallback<? super R> paramResultCallback) { this.zajp.setResultCallback(paramResultCallback); } public final void setResultCallback(ResultCallback<? super R> paramResultCallback, long paramLong, TimeUnit paramTimeUnit) { this.zajp.setResultCallback(paramResultCallback, paramLong, paramTimeUnit); } public final <S extends Result> TransformedResult<S> then(ResultTransform<? super R, ? extends S> paramResultTransform) { return this.zajp.then(paramResultTransform); } public final Integer zam() { return this.zajp.zam(); } } /* Location: E:\Study\Tools\apktool2_2\dex2jar-0.0.9.15\classes_viber_2_dex2jar.jar * Qualified Name: com.google.android.gms.common.api.internal.OptionalPendingResultImpl * JD-Core Version: 0.6.2 */
true
06d5e516fed2381d2616c677241aa7fea25f98c5
Java
andresetiawan95/m-lelangapa
/app/src/main/java/com/lelangapa/android/fragments/userpublic/riwayat/RiwayatMainFragment.java
UTF-8
5,564
2.09375
2
[]
no_license
package com.lelangapa.android.fragments.userpublic.riwayat; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import com.lelangapa.android.R; import com.lelangapa.android.apicalls.singleton.RequestController; import com.lelangapa.android.apicalls.userpublic.UserPublicAPI; import com.lelangapa.android.interfaces.DataReceiver; import com.lelangapa.android.resources.RiwayatResources; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; /** * Created by andre on 29/03/17. */ public class RiwayatMainFragment extends Fragment { private ArrayList<RiwayatResources> listRiwayat; private String userID; private DataReceiver dataReceiver; private ProgressBar progressBar_loadingData; private EmptyFragment emptyFragment; private NoEmptyFragment noEmptyFragment; public RiwayatMainFragment() { initializeConstants(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initializeFragments(); initializeDataReceiver(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_detail_user_public_riwayat_layout, container, false); initializeViews(view); getIntentData(); getRiwayatItems(); return view; } private void initializeConstants() { listRiwayat = new ArrayList<>(); } private void getIntentData() { userID = getActivity().getIntent().getStringExtra("id_user"); } private void initializeViews(View view) { progressBar_loadingData = (ProgressBar) view.findViewById(R.id.fragment_detail_user_public_riwayat_layout_progress_bar); } private void initializeFragments() { emptyFragment = new EmptyFragment(); noEmptyFragment = new NoEmptyFragment(); } private void initializeDataReceiver() { dataReceiver = new DataReceiver() { @Override public void dataReceived(Object output) { String response = output.toString(); try { JSONObject jsonResponse = new JSONObject(response); JSONArray responseArray = jsonResponse.getJSONArray("data"); listRiwayat.clear(); for (int i=0;i<responseArray.length();i++) { JSONObject jsonArrayObject = responseArray.getJSONObject(i); RiwayatResources riwayatResources = new RiwayatResources(); riwayatResources.setIdBid(jsonArrayObject.getString("id_bid_return")); riwayatResources.setIdItem(jsonArrayObject.getString("id_item_return")); riwayatResources.setIdAuctioneer(jsonArrayObject.getString("id_user_return")); riwayatResources.setNamaAuctioneer(jsonArrayObject.getString("nama_user_return")); riwayatResources.setNamaItem(jsonArrayObject.getString("nama_item_return")); riwayatResources.setBidStatus(jsonArrayObject.getInt("bid_status_return")); riwayatResources.setBidTime(jsonArrayObject.getInt("bid_time_return")); riwayatResources.setWinStatus(jsonArrayObject.getBoolean("win_status_return")); riwayatResources.setHargaBid(jsonArrayObject.getString("price_bid_return")); riwayatResources.setBidStatus(jsonArrayObject.getInt("bid_status_return")); listRiwayat.add(riwayatResources); } setupFragment(); } catch (JSONException e) { e.printStackTrace(); } } }; } private void getAndRemoveFragment() { Fragment currentFragment = getChildFragmentManager().findFragmentById(R.id.fragment_detail_user_public_riwayat_layout); if (currentFragment != null) { getChildFragmentManager().beginTransaction() .remove(currentFragment) .commit(); } } private void enableProgressBar() { this.progressBar_loadingData.setVisibility(View.VISIBLE); } private void disableProgressBar() { this.progressBar_loadingData.setVisibility(View.GONE); } private void setupFragment() { disableProgressBar(); if (listRiwayat.isEmpty()) { getChildFragmentManager().beginTransaction() .replace(R.id.fragment_detail_user_public_riwayat_layout, emptyFragment) .commit(); } else { noEmptyFragment.setListRiwayat(listRiwayat); getChildFragmentManager().beginTransaction() .replace(R.id.fragment_detail_user_public_riwayat_layout, noEmptyFragment) .commit(); } } private void getRiwayatItems() { getAndRemoveFragment(); enableProgressBar(); UserPublicAPI.GetRiwayatAPI getRiwayatAPI = UserPublicAPI.instanceRiwayatAPI(userID, dataReceiver); RequestController.getInstance(getActivity()).addToRequestQueue(getRiwayatAPI); } }
true
6762304f0aab0a03259bd542a1b22bf9e4bfb000
Java
rachmat2110/BMI
/app/src/main/java/com/example/myapplication/send_email.java
UTF-8
1,298
2.3125
2
[]
no_license
package com.example.myapplication; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class send_email extends AppCompatActivity { EditText mSubject, mMessage, email_sender; TextView mEmail; Button kirimID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_send_email); mEmail = findViewById(R.id.mailID); mMessage = findViewById(R.id.messageID); mSubject = findViewById(R.id.subjectID); kirimID = findViewById(R.id.kirimID); //email_sender = findViewById(R.id.email_sender); kirimID.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendMail(); } }); } private void sendMail() { String mail = mEmail.getText().toString(); String message = mMessage.getText().toString(); String subject = mSubject.getText().toString(); JavaMailAPI javaMailAPI = new JavaMailAPI(this, mail,subject,message); javaMailAPI.execute(); } }
true
a05b35df6cb3337bfee5bc8cf4efafe50e939e44
Java
dario-ca/horse-fever
/trunk/src/test/java/it/polimi/provafinale2013/dario/casula_alessandro/chetta/AppTest.java
UTF-8
989
2.375
2
[]
no_license
/****************************************************************** * @date: Milan, 18/06/2013 * @title: Horse Fever * @school: Politecnico di Milano * @course: Prova Finale 2013 * @author: Alessandro Chetta 758461 * @author: Dario Casula 757731 ******************************************************************/ package it.polimi.provafinale2013.dario.casula_alessandro.chetta; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
true
6402d39b346ecea49e8899cb2c81d6950d950113
Java
Marto37/CodeSamples
/Sort.java
UTF-8
7,792
3.546875
4
[]
no_license
import java.util.Comparator; import java.util.LinkedList; import java.util.Random; public class Sort { public static <T> void cocktailSort(T[] arr, Comparator<T> comparator) { if (arr == null || comparator == null) { throw new IllegalArgumentException("Array nor comparator can be " + "null. Please insert non-null comparator and array."); } boolean swapped = true; boolean upDown = true; int lastUp = 0; int lastDown = arr.length - 1; int finalSwapInd; while (swapped) { swapped = false; if (upDown) { upDown = false; finalSwapInd = lastDown - 1; for (int i = lastUp; i < lastDown; i++) { if (comparator.compare(arr[i], arr[i + 1]) > 0) { T data = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = data; finalSwapInd = i; swapped = true; } } lastDown = finalSwapInd; } else { upDown = true; finalSwapInd = lastUp + 1; for (int i = lastDown; i > lastUp; i--) { if (comparator.compare(arr[i - 1], arr[i]) > 0) { T data = arr[i - 1]; arr[i - 1] = arr[i]; arr[i] = data; finalSwapInd = i; swapped = true; } } lastUp = finalSwapInd; } } } public static <T> void insertionSort(T[] arr, Comparator<T> comparator) { if (arr == null || comparator == null) { throw new IllegalArgumentException("Array nor comparator can be " + "null. Please insert non-null comparator and array."); } for (int i = 1; i < arr.length; i++) { int currInd = i; while (currInd > 0 && comparator.compare(arr[currInd], arr[currInd - 1]) < 0) { T data = arr[currInd - 1]; arr[currInd - 1] = arr[currInd]; arr[currInd] = data; currInd--; } } } public static <T> void selectionSort(T[] arr, Comparator<T> comparator) { if (arr == null || comparator == null) { throw new IllegalArgumentException("Array nor comparator can be " + "null. Please insert non-null comparator and array."); } for (int i = 0; i < arr.length - 1; i++) { int minInd = i; for (int j = i + 1; j < arr.length; j++) { if (comparator.compare(arr[j], arr[minInd]) < 0) { minInd = j; } } T data = arr[minInd]; arr[minInd] = arr[i]; arr[i] = data; } } public static <T> void mergeSort(T[] arr, Comparator<T> comparator) { if (arr == null || comparator == null) { throw new IllegalArgumentException("Array nor comparator can be " + "null. Please insert non-null comparator and array."); } if (arr.length <= 1) { return; } int midInd = arr.length / 2; T[] leftArr = (T[]) new Object[arr.length / 2]; T[] rightArr = (T[]) new Object[arr.length - (arr.length / 2)]; for (int i = 0; i < midInd; i++) { leftArr[i] = arr[i]; } for (int i = midInd; i < arr.length; i++) { rightArr[i - midInd] = arr[i]; } mergeSort(leftArr, comparator); mergeSort(rightArr, comparator); int leftInd = 0; int rightInd = 0; int currInd = 0; while (leftInd < leftArr.length && rightInd < rightArr.length) { if (comparator.compare(leftArr[leftInd], rightArr[rightInd]) <= 0) { arr[currInd] = leftArr[leftInd]; leftInd++; } else { arr[currInd] = rightArr[rightInd]; rightInd++; } currInd++; } if (leftInd < leftArr.length) { for (int i = leftInd; i < leftArr.length; i++) { arr[currInd] = leftArr[i]; currInd++; } } else if (rightInd < rightArr.length) { for (int i = rightInd; i < rightArr.length; i++) { arr[currInd] = rightArr[i]; currInd++; } } } public static void lsdRadixSort(int[] arr) { if (arr == null) { throw new IllegalArgumentException("Cannot sort null array. " + "Please input non-null array."); } LinkedList<Integer>[] counter; counter = (LinkedList<Integer>[]) new LinkedList[19]; for (int i = 0; i < 19; i++) { counter[i] = new LinkedList<>(); } int mod = 10; int dev = 1; boolean cont = true; while (cont) { cont = false; for (int i = 0; i < arr.length; i++) { int beforeMod = arr[i] / dev; if (beforeMod != 0) { cont = true; } int bucket = beforeMod % mod + 9; counter[bucket].add(arr[i]); } int idx = 0; for (int i = 0; i < counter.length; i++) { while (!counter[i].isEmpty()) { arr[idx] = counter[i].remove(); idx++; } } dev = dev * 10; } } public static <T> T kthSelect(int k, T[] arr, Comparator<T> comparator, Random rand) { if (arr == null || comparator == null || rand == null) { throw new IllegalArgumentException("Array nor comparator nor " + "random object " + "can be " + "null. Please insert non-null comparator, array and " + "random object" + "."); } if (k < 1 || k > arr.length) { throw new IllegalArgumentException("Inputted k is not in the " + "range of 1 to array.length. Please insert k in proper " + "range."); } return kthSelectHelper(k, arr, comparator, rand, 0, arr.length - 1); } private static <T> T kthSelectHelper(int k, T[] arr, Comparator<T> comparator, Random rand, int start, int end) { int pivotInd = rand.nextInt(end - start + 1) + start; T pivot = arr[pivotInd]; arr[pivotInd] = arr[start]; arr[start] = arr[pivotInd]; int i = start + 1; int j = end; while (i <= j) { while (i < j && comparator.compare(pivot, arr[i]) >= 0) { i++; } while (j >= i && comparator.compare(pivot, arr[j]) <= 0) { j--; } if (i == j) { i++; } if (i < j) { T data = arr[j]; arr[j] = arr[i]; arr[i] = data; i++; j--; } } arr[start] = arr[j]; arr[j] = pivot; if (j == k - 1) { return arr[j]; } else if (j > k - 1) { return kthSelectHelper(k, arr, comparator, rand, start, j - 1); } else { return kthSelectHelper(k, arr, comparator, rand, j + 1, end); } } }
true
de9bae3762e7cc34c045e2acb90a291ff219adc4
Java
JMaltat/cqrs-ecommerce-exercise
/src/main/java/com/margo/sample/cqrs/ecommerce/Basket.java
UTF-8
1,869
2.5
2
[]
no_license
package com.margo.sample.cqrs.ecommerce; import com.google.common.collect.Maps; import com.margo.sample.cqrs.ecommerce.commands.AddProduct; import com.margo.sample.cqrs.ecommerce.commands.Command; import com.margo.sample.cqrs.ecommerce.commands.RemoveProduct; import com.margo.sample.cqrs.ecommerce.commands.Validate; import com.margo.sample.cqrs.ecommerce.events.Event; import com.margo.sample.cqrs.ecommerce.events.ProductAdded; import java.util.List; import java.util.Map; public class Basket { private final EventStore eventStore; Basket(final EventStore eventStore) { this.eventStore = eventStore; } void addProduct(final Command<AddProduct> addProduct) { Event event = Event.builderFor(ProductAdded.class) .withAggregateId(addProduct.getAggregateId()) .withCommandId(addProduct.getId()) .withData(ProductAdded.builder() .withProductId(addProduct.getData().getProductId()) .withQuantity(addProduct.getData().getQuantity()) .build()) .build(); eventStore.save(event); } void removeProduct(final Command<RemoveProduct> removeProduct) { } void validate(final Command<Validate> validate) { Decision decision = new Decision(eventStore.getHistory(validate.getAggregateId())); if (!decision.canValidate()){ //store reject event return; } // store validated event } class Decision { private Map<String, Integer> quantityByProduct = Maps.newConcurrentMap(); private Decision(final List<Event> history){ history.forEach(this::apply); } void apply(Event event){ if (event.getType().equals(ProductAdded.class)){ ProductAdded data = (ProductAdded) event.getData(); quantityByProduct.compute(data.getProductId(), (key, value) -> value != null ? value + data.getQuantity() : data.getQuantity()); } } boolean canValidate(){ return !quantityByProduct.isEmpty(); } } }
true
69c4299104061b4cdcfba5774473f7b7178568fd
Java
meniossin/src
/third_party/robolectric/robolectric/shadows/framework/src/main/java/org/robolectric/shadows/ShadowQueuedWork.java
UTF-8
699
1.882813
2
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
package org.robolectric.shadows; import android.app.QueuedWork; import android.os.Build; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Implements; import org.robolectric.annotation.Resetter; import org.robolectric.util.ReflectionHelpers; @Implements(value = QueuedWork.class, isInAndroidSdk = false) public class ShadowQueuedWork { @Resetter public static void reset() { QueuedWork.waitToFinish(); if (RuntimeEnvironment.getApiLevel() >= Build.VERSION_CODES.O) { ReflectionHelpers.setStaticField(QueuedWork.class, "sHandler", null); } else { ReflectionHelpers.setStaticField(QueuedWork.class, "sSingleThreadExecutor", null); } } }
true
43f49620a8c2cb6f178a21d430ecf634ee6d1216
Java
jack15177089002/mybcz_5_0_1
/app/src/androidTest/java/brut/util/DataInputDelegate.java
UTF-8
1,519
2.671875
3
[]
no_license
package brut.util; import java.io.DataInput; public abstract class DataInputDelegate implements DataInput { protected final DataInput mDelegate; public DataInputDelegate(DataInput dataInput) { this.mDelegate = dataInput; } public int skipBytes(int i) { return this.mDelegate.skipBytes(i); } public int readUnsignedShort() { return this.mDelegate.readUnsignedShort(); } public int readUnsignedByte() { return this.mDelegate.readUnsignedByte(); } public String readUTF() { return this.mDelegate.readUTF(); } public short readShort() { return this.mDelegate.readShort(); } public long readLong() { return this.mDelegate.readLong(); } public String readLine() { return this.mDelegate.readLine(); } public int readInt() { return this.mDelegate.readInt(); } public void readFully(byte[] bArr, int i, int i2) { this.mDelegate.readFully(bArr, i, i2); } public void readFully(byte[] bArr) { this.mDelegate.readFully(bArr); } public float readFloat() { return this.mDelegate.readFloat(); } public double readDouble() { return this.mDelegate.readDouble(); } public char readChar() { return this.mDelegate.readChar(); } public byte readByte() { return this.mDelegate.readByte(); } public boolean readBoolean() { return this.mDelegate.readBoolean(); } }
true
e92c15ac2cb37514ae42186ee5d22884c28358c3
Java
harjeet88/datastructures
/data_structures/src/com/mycomp/leetcode/medium/SubArrayproductLessThank.java
UTF-8
2,776
3.375
3
[]
no_license
package com.mycomp.leetcode.medium; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.mycomp.leetcode.utils.NumberUtils; /** * https://leetcode.com/problems/subarray-product-less-than-k/description/ * @author Harjeet *Your are given an array of positive integers nums. Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k. Example 1: Input: nums = [10, 5, 2, 6], k = 100 Output: 8 Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]. Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k. Note: 0 < nums.length <= 50000. 0 < nums[i] < 1000. 0 <= k < 10^6. */ public class SubArrayproductLessThank { public static void main(String[] args) { int k=100; int[] nums= {10,5,2,6}; Set<Set<Integer>> result=new HashSet<>(); List<Integer> combi=new ArrayList<>(); int level=0; int prod=1; //getSubArryLessk(nums,result,combi,k,prod,level); getContigiousSubArryLessk(nums,result,k); System.out.println(result); } private static void getContigiousSubArryLessk(int[] nums, Set<Set<Integer>> result, int k) { int count=0; int[][] temp=new int[nums.length][nums.length]; for(int i=0; i<nums.length;i++) { if(nums[i]<k) { temp[i][i]=nums[i]; count++; } } Set<Integer> combi=new HashSet<>(); //Set<Set<Integer>> res=new HashSet<>(); for(int i=0;i<nums.length;i++) { combi=new HashSet<>(); for(int j=i+1;j<nums.length;j++) { int prod=temp[i][j-1]*nums[j]; if(prod!=0 && prod<k) { combi.add(nums[j]); result.add(new HashSet<>(combi)); //System.out.println(); temp[i][j]=prod; count++; } System.out.println("======================================"); NumberUtils.print2dArray(temp); } } System.out.println(count); } private static void getSubArryLessk(int[] nums, Set<Set<Integer>> result, List<Integer> combi, int k,int prod,int level) { if(level == nums.length && prod<k) { System.out.println("Adding : "+combi); System.out.println("====================================="); result.add(new HashSet<>(combi)); return; } for(int i=0;i<nums.length;i++) { System.out.println("Checking : "+nums[i]); int cur=nums[i]; if(nums[i] ==0) { continue; } int updatedProd=prod*cur; nums[i]=0; combi.add(cur); if(updatedProd<k) { result.add(new HashSet<>(combi)); } getSubArryLessk(nums, result, combi,k, updatedProd, level+1); nums[i]=cur; combi.remove(combi.size()-1); } } }
true
b14d7414b62d25579398ea4c2107234a9eeb158f
Java
dangolbeeker/dgs-newfeatures-demo
/src/main/java/com/example/featuredemo/dataloader/ReviewsDataLoader.java
UTF-8
867
2.0625
2
[]
no_license
package com.example.featuredemo.dataloader; import com.example.demo.generated.types.Review; import com.example.featuredemo.services.ReviewsService; import com.netflix.graphql.dgs.DgsDataLoader; import org.dataloader.MappedBatchLoader; import org.springframework.beans.factory.annotation.Autowired; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; @DgsDataLoader(name = "reviews") public class ReviewsDataLoader implements MappedBatchLoader<Integer, List<Review>> { @Autowired ReviewsService reviewsService; @Override public CompletionStage<Map<Integer, List<Review>>> load(Set<Integer> keys) { return CompletableFuture.supplyAsync(() -> reviewsService.reviewsForShows(new ArrayList<>(keys))); } }
true
1b6b3d18cf2516257d87e470c0f4c197fbb2881b
Java
JustBru00/MeaningfullCurrency
/src/com/gmail/justbru00/meaningfull/currency/listeners/BankHandler.java
UTF-8
3,015
2.375
2
[ "MIT" ]
permissive
/** The MIT License (MIT) Copyright (c) 2016 Justin "JustBru00" Brubaker Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ package com.gmail.justbru00.meaningfull.currency.listeners; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.inventory.Inventory; import com.gmail.justbru00.meaningfull.currency.main.Main; import com.gmail.justbru00.meaningfull.currency.utils.Debug; import com.gmail.justbru00.meaningfull.currency.utils.ItemWorth; import com.gmail.justbru00.meaningfull.currency.utils.Messager; public class BankHandler implements Listener { Main main; public BankHandler(Main main) { this.main = main; } @EventHandler public void onPlayerJoin(PlayerLoginEvent e) { if (e.getPlayer().getName().equalsIgnoreCase("JustBru00")) { e.getPlayer().sendMessage(Main.PREFIX + Messager.color("&bThis Server uses Meaningfull Currency.")); } } @EventHandler public void onInventoryClose(InventoryCloseEvent e) { Inventory inv = e.getInventory(); Player player = (Player) e.getPlayer(); if (inv.getName().equals(main.getConfigString("commands.bank.gui.title").replace("{PLAYERNAME}", player.getName()))) { int i = 0; Debug.send("Starting to save inventory."); while(i<54) { main.config.set("store." + player.getUniqueId().toString() + ".bank." + i, inv.getItem(i)); i++; } main.saveConfig(); Debug.send("Success."); i = 0; int newbal = 0; while(i<54) { if (inv.getItem(i) != null) { newbal = newbal + ItemWorth.calc(inv.getItem(i)); Debug.send("Item number: " + i + " Total is: " + newbal); } i++; } Debug.send("Try to save balance."); Main.econ.withdrawPlayer(player, Main.econ.getBalance(player)); Main.econ.depositPlayer(player, newbal); Debug.send("Done."); return; } } }
true
fbcd7e91073d69d8ebec5d0029ca8df85116dcd5
Java
seeminglyjs/GookB_Data
/국비16일차/java09_api_15day/RandomEx.java
UHC
516
3.71875
4
[]
no_license
package java09_api_15day; import java.util.Random; public class RandomEx { public static void main(String[] args) { Random ran = new Random(); // System.out.println(ran.nextInt()); //int // System.out.println(ran.nextBoolean()); // true // false // System.out.println(ran.nextDouble()); // 0.0 ~ 0.99999999999 System.out.println(ran.nextInt(100)); // 0 ~ 99 System.out.println(ran.nextInt(100) + 1); // 1 ~ 100 } }
true
f79ab98131b12d37f2059cd4ed4ead33e8a731e8
Java
ParanoidUser/codewars-handbook
/kata/8-kyu/pillars/test/SolutionTest.java
UTF-8
296
2.453125
2
[ "MIT" ]
permissive
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class SolutionTest { @Test void sample() { assertEquals(0, Kata.pillars(1, 10, 10)); assertEquals(2000, Kata.pillars(2, 20, 25)); assertEquals(15270, Kata.pillars(11, 15, 30)); } }
true
7a258c99d8535e9c440be63a638dc1b686682063
Java
fugeritaetas/morozko-lib
/java16-fugerit/fj-core-legacy/src/main/java/org/fugerit/java/core/web/servlet/filter/HttpFilter.java
UTF-8
2,189
1.796875
2
[ "Apache-2.0" ]
permissive
/***************************************************************** <copyright> Morozko Java Library org.fugerit.java.core.ent Copyright (c) 2006 Morozko All rights reserved. This program and the accompanying materials are made available under the terms of the Apache License v2.0 which accompanies this distribution, and is available at http://www.apache.org/licenses/ (txt version : http://www.apache.org/licenses/LICENSE-2.0.txt html version : http://www.apache.org/licenses/LICENSE-2.0.html) This product includes software developed at The Apache Software Foundation (http://www.apache.org/). </copyright> *****************************************************************/ /* * @(#)HttpFilter.java * * @project : org.fugerit.java.core.ent * @package : org.fugerit.java.core.web.servlet.filter * @creation : 12-lug-2005 8.28.19 */ package org.fugerit.java.core.web.servlet.filter; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.fugerit.java.core.web.log.helpers.LogObjectFilter; public abstract class HttpFilter extends LogObjectFilter { public abstract void init(FilterConfig config) throws ServletException; public abstract void doFilter( HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException; public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if ( request instanceof HttpServletRequest && response instanceof HttpServletResponse ) { this.getLogger().debug( "Http request and response : doFilter http" ); this.doFilter( (HttpServletRequest)request, (HttpServletResponse)response, chain ); } else { this.getLogger().debug( "Not http request and response : proceeding with chain" ); chain.doFilter( request, response ); } } public abstract void destroy(); }
true
cf8530225de4db7596137720ec6e1ed4fda44b72
Java
matmaq1/CP_summer_2017-1
/src/Maps.java
UTF-8
740
2.875
3
[]
no_license
import shapes.Circle; import shapes.Rectangle; import shapes.Shape; import java.util.HashMap; import java.util.Map; /** * Created by Mateusz on 19.04.2017. */ public class Maps { public static void main(String[] args) { Map<String, Shape> shapeMap = new HashMap<>(); shapeMap.put("Circle", new Circle(4)); shapeMap.put("Rectangle", new Rectangle(4,5)); System.out.println(shapeMap.get("Circle")); for(String string: shapeMap.keySet()){ System.out.println(string + " = " + shapeMap.get(string)); } //print list of words in a random text and a number of times it appeared das Hausaudgabe //shapeMap.keySet();//no two same keys } //mapos sdidictiosndar }
true