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
69a72a53a265dbd3043f3bc9cbf281fb4440d293
Java
saya-ac-cn/java-utils
/java/src/test/java/ac/cn/saya/lambda/LambdaUtil1.java
UTF-8
585
2.609375
3
[ "Apache-2.0" ]
permissive
package ac.cn.saya.lambda; import org.junit.Test; /** * @Title: LambdaUtil1 * @ProjectName java-utils * @Description: TODO * @Author liunengkai * @Date: 2019-05-01 22:19 * @Description: */ public class LambdaUtil1 { @Test public void test1(){ Runnable r1 = new Runnable() { @Override public void run() { System.out.println("线程执行"); } }; r1.run(); System.out.println("------------"); Runnable r2 = () -> System.out.println("线程执行"); r2.run(); } }
true
1369d4dd1653d573ba20bb0cda54c2fb20d3af24
Java
gearkim0614/GT_Trader
/app/src/test/java/com/example/gttrader/JasonTests.java
UTF-8
2,547
2.671875
3
[]
no_license
package com.example.gttrader; import com.example.gttrader.Entity.Firearms; import com.example.gttrader.Entity.Narcotics; import com.example.gttrader.Entity.Water; import com.example.gttrader.Entity.Player; import com.example.gttrader.Entity.Scooter; import org.junit.Test; import java.util.HashMap; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class JasonTests { Narcotics narcotics1 = new Narcotics (); Narcotics narcotics2 = new Narcotics (); Firearms firearm1 = new Firearms(); Player player1 = new Player("Jason",4,4,4,4); Scooter scooter1 = player1.getScooter(); Player player2 = new Player("Peggy",4,4,4,4); Scooter scooter2 = player2.getScooter(); HashMap<Integer, Integer> scooter_hold = new HashMap<Integer, Integer>(); @Test public void narcotics_test1() { assertTrue(narcotics1.equals(narcotics2)); } @Test public void narcotics_test2() { assertFalse(narcotics1.equals(firearm1)); } @Test public void battery_test1() { scooter1.setBatteryLife ( 75.5 ); scooter2.setBatteryLife ( 75.5 ); assertEquals (scooter1.getBatteryLife (),scooter2.getBatteryLife (),0.01); } @Test public void battery_test2() { scooter1.setBatteryLife ( 0.0 ); assertNotEquals (scooter1.getBatteryLife (),scooter1.getBatteryLife () - 1.0,0.1); } @Test public void scooter_test1() { for (int i = 1; i < 11; i++) { scooter_hold.put(i, 0); } scooter_hold.put(10, 1); scooter_hold.put(1, 2); scooter_hold.put(7, 1); scooter1.addToHold ( new Water() ); scooter1.addToHold ( new Firearms () ); scooter1.addToHold ( new Firearms () ); scooter1.addToHold ( new Firearms () ); scooter1.removeFromHold2 ( new Firearms () ); scooter1.addToHold ( new Narcotics () ); assertEquals ( scooter1.getScooter_hold (), scooter_hold ); } @Test public void scooter_test2() { for (int i = 1; i < 11; i++) { scooter_hold.put(i, 0); } scooter_hold.put(10, 100); scooter_hold.put(1, 2); scooter_hold.put(7, 1); scooter1.removeFromHold2 ( new Firearms () ); scooter1.addToHold ( new Narcotics () ); assertNotEquals ( scooter1.getScooter_hold (), scooter_hold ); } }
true
201cdd8aeca4fee59d8a802b6a3a40131f4f473e
Java
veerakilaparthi/esurvey_android
/app/src/main/java/com/anyasoft/es/surveyapp/details/PersonDetailsFragment.java
UTF-8
8,690
2.03125
2
[]
no_license
package com.anyasoft.es.surveyapp.details; import android.content.Context; import android.os.Bundle; import android.support.design.widget.TextInputLayout; import android.support.v4.app.Fragment; import android.support.v7.widget.AppCompatSpinner; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.anyasoft.es.surveyapp.R; import com.anyasoft.es.surveyapp.logger.L; import com.anyasoft.es.surveyapp.question.QuestionModel; import org.json.JSONException; import org.json.JSONObject; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link PersonDetailsFragment.OnFragmentInteractionListener} interface * to handle interaction events. */ public class PersonDetailsFragment extends Fragment implements View.OnClickListener { private Button btnReset, btnSubmit; private TextInputLayout txtInputName; private TextInputLayout txtInputRelativeName; private TextInputLayout txtInputAge; //private TextInputLayout txtInputCast; private TextInputLayout txtInputCorpName; private TextInputLayout txtInputWardNum; private TextInputLayout txtInputWardName; private TextInputLayout txtInputReligion; private TextInputLayout txtInputSubcaste; private TextInputLayout txtInputProfession; private TextInputLayout txtInputPlace; private TextInputLayout txtInputNumOfChildren; private AppCompatSpinner spnGender; private AppCompatSpinner edtCaste; private OnFragmentInteractionListener mListener; public PersonDetailsFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view =inflater.inflate(R.layout.content_person_details, container, false); txtInputAge = (TextInputLayout) view.findViewById(R.id.textLayoutAge); //txtInputCast = (TextInputLayout) view.findViewById(R.id.textLayoutCaste); txtInputName = (TextInputLayout) view.findViewById(R.id.textLayoutName); txtInputCorpName = (TextInputLayout) view.findViewById(R.id.textLayoutMunicipality); txtInputWardName = (TextInputLayout) view.findViewById(R.id.textLayoutWardName); txtInputWardNum = (TextInputLayout) view.findViewById(R.id.textLayoutWardNum); txtInputReligion = (TextInputLayout) view.findViewById(R.id.textLayoutReligion); txtInputSubcaste = (TextInputLayout) view.findViewById(R.id.textLayoutSubcaste); txtInputProfession = (TextInputLayout) view.findViewById(R.id.textLayoutprofession); txtInputPlace = (TextInputLayout) view.findViewById(R.id.textLayoutplace); txtInputRelativeName = (TextInputLayout) view.findViewById(R.id.textLayoutRelativeName); txtInputNumOfChildren = (TextInputLayout) view.findViewById(R.id.textLayoutNumOfChildren); spnGender = (AppCompatSpinner) view.findViewById(R.id.spnGender); edtCaste = (AppCompatSpinner) view.findViewById(R.id.edtCaste); btnSubmit = (Button) view.findViewById(R.id.btnSubmit); btnReset = (Button) view.findViewById(R.id.btnReset); btnSubmit.setOnClickListener(this); btnReset.setOnClickListener(this); return view; } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed() { if (mListener != null) { mListener.onSubmit(); }//if()... } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onClick(View v) { if (v == btnReset) { mListener.gotoBack(); /*txtInputName.getEditText().setText(""); txtInputCast.getEditText().setText(""); txtInputAge.getEditText().setText(""); txtInputNumOfChildren.getEditText().setText(""); txtInputWardName.getEditText().setText(""); txtInputWardName.getEditText().toString(); txtInputCorpName.getEditText().setText(""); txtInputWardNum.getEditText().setText(""); // String txtInputWardName.getEditText().getText().toString();; txtInputReligion.getEditText().setText(""); txtInputSubcaste.getEditText().setText(""); txtInputProfession.getEditText().setText(""); txtInputPlace.getEditText().setText(""); txtInputNumOfChildren.getEditText().setText(""); spnGender.setSelection(0);*/ }// if (v == btnSubmit) { sendRequest(); }// } private void sendRequest() { String name = txtInputName.getEditText().getText().toString(); // String cast = txtInputCast.getEditText().getText().toString(); String age = txtInputAge.getEditText().getText().toString(); String wardName = txtInputWardName.getEditText().getText().toString(); String corpName = txtInputCorpName.getEditText().getText().toString(); String wardNum = txtInputWardNum.getEditText().getText().toString(); // String txtInputWardName.getEditText().getText().toString();; String religion = txtInputReligion.getEditText().getText().toString(); String subCaste = txtInputSubcaste.getEditText().getText().toString(); String profession = txtInputProfession.getEditText().getText().toString(); String place = txtInputPlace.getEditText().getText().toString(); String relativeName = txtInputRelativeName.getEditText().getText().toString(); String numOfChildren = txtInputNumOfChildren.getEditText().getText().toString(); String gender = spnGender.getSelectedItem().toString(); String cast = edtCaste.getSelectedItem().toString(); if (name == null || name.equals("")) { txtInputName.setError("Can't be left blank"); return; }// if (cast == null || cast.equals("")) { //txtInputCast.setError("Can't be left blank"); return; }// if (age == null || age.equals("")) { //txtInputCast.setError("Can't be left blank"); return; }// //int position = QuestionModel.questionList.size()-1; // QuestionModel model = QuestionModel.questionList.get(position); JSONObject jsonDetails = new JSONObject(); L.d("WardName = " + wardName); try { jsonDetails.put("Name",name); jsonDetails.put("cast",cast); jsonDetails.put("age",age); jsonDetails.put("wardName",wardName+""); jsonDetails.put("corpName",corpName+""); jsonDetails.put("religion",religion+""); jsonDetails.put("wardNum",wardNum+""); jsonDetails.put("subCaste",subCaste+""); jsonDetails.put("profession",profession+""); jsonDetails.put("place",place+""); jsonDetails.put("numOfChildren",numOfChildren+""); jsonDetails.put("gender",gender+""); jsonDetails.put("fName",relativeName+""); } catch (JSONException e) { e.printStackTrace(); L.e("sendRequest()::Creating json "+e.getLocalizedMessage()); }//catch().... //model.setAnswer("Attached"); QuestionModel.details = jsonDetails.toString(); L.d("PersonDeatailActivity:: SendRequest():: answer"+ jsonDetails.toString()); onButtonPressed(); }// /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onMarked(boolean marked); void gotoBack(); void onSubmit(); } }
true
c8686666ad92aefdfaf91e336dd58e26ed0a5569
Java
thetwobear/FastEC
/x-core/src/main/java/com/x/x_core/wechat/template/WXEntryTemplate.java
UTF-8
625
1.984375
2
[]
no_license
package com.x.x_core.wechat.template; import com.x.x_core.wechat.BaseWXEntryActivity; import com.x.x_core.wechat.XWeChat; /** * Created by 熊猿猿 on 2017/8/16/016. */ public class WXEntryTemplate extends BaseWXEntryActivity { @Override protected void onResume() { super.onResume(); //登录成功后实际进入的Activity,直接finish() finish(); //设置不需要动画 overridePendingTransition(0, 0); } @Override protected void signInSuccess(String ueserInfo) { XWeChat.getInstance().getmSignInCallback().onSignInSuccess(ueserInfo); } }
true
e6f8bbfa45beb4a35860f7a1847767565ab8d373
Java
0Kirby/JavaLearning
/New/src/exception/TestThrow.java
GB18030
570
3.03125
3
[ "Apache-2.0" ]
permissive
package exception; public class TestThrow { static void pop() throws NegativeArraySizeException { // 巽׳NegativeArraySizeException쳣 int[] arr = new int[-1]; arr[1] = 1; // } public static void main(String[] args) { // try { // try䴦쳣Ϣ pop();// pop() } catch (NegativeArraySizeException e) { System.out.println("pop()׳쳣");// 쳣Ϣ } } }
true
75ae38ab2289727c4308466377837263b926fd5e
Java
YanaKrukovska/payment-system-servlet
/src/main/java/com/krukovska/paymentsystem/persistence/mapper/UnblockRequestMapper.java
UTF-8
1,722
2.328125
2
[]
no_license
package com.krukovska.paymentsystem.persistence.mapper; import com.krukovska.paymentsystem.persistence.Field; import com.krukovska.paymentsystem.persistence.model.Account; import com.krukovska.paymentsystem.persistence.model.Client; import com.krukovska.paymentsystem.persistence.model.UnblockRequest; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; public class UnblockRequestMapper extends AbstractMapper<UnblockRequest> { protected UnblockRequest mapObject(ResultSet rs) throws SQLException { Objects.requireNonNull(rs, "ResultSet must be not null"); UnblockRequest request = new UnblockRequest(); request.setId(rs.getLong("id")); if (rs.getDate("action_date") != null) { request.setActionDate(rs.getDate("action_date").toLocalDate()); } request.setCreationDate(rs.getDate("creation_date").toLocalDate()); Account account = new Account(); account.setId(rs.getLong("account_id")); request.setAccount(account); Client client = new Client(); client.setId(rs.getLong("client_id")); request.setClient(client); return request; } @Override public Set<Field> getFields(UnblockRequest p) { Objects.requireNonNull(p, "Entity must be not null"); Set<Field> fields = new LinkedHashSet<>(); fields.add(new Field("account_id", p.getAccount().getId())); fields.add(new Field("client_id", p.getClient().getId())); fields.add(new Field("creation_date", p.getCreationDate())); return Collections.unmodifiableSet(fields); } }
true
6bf2a436915c0e4d58fc07bd6f2e865c093d88da
Java
wofxuan/yunjing
/星河/com.agdress.api/src/test/java/com/agdress/commons/utils/MD5UtilTest.java
UTF-8
501
1.890625
2
[]
no_license
package com.agdress.commons.utils; import org.junit.Test; import static org.junit.Assert.*; /** * Created by Administrator on 2017/8/25. */ public class MD5UtilTest { @Test public void getMD5() throws Exception { String str = MD5Util.getMD5Str("amount=50.0&attach=11&notify_url=http://192.168.1.43/payment/notify&order_no=R150364693661840655&partner_id=108674&pay_type=0002&version=V1.0&ff0471e8e42494c482f1a2a797ed616b"); System.out.println(str); } }
true
23925b3a3d76cc4a5a6f61b9c043502190b238ae
Java
yangrui110/asunerp
/framework/base/src/com/hanlin/fadp/base/util/collections/GenericMapSet.java
UTF-8
815
2.734375
3
[]
no_license
package com.hanlin.fadp.base.util.collections; import java.util.Map; import java.util.Set; public abstract class GenericMapSet<K, V, M extends Map<K, V>, I> extends GenericMapCollection<K, V, M, I> implements Set<I> { public GenericMapSet(M source) { super(source); } @Override public final boolean equals(Object o) { if (!(o instanceof Set<?>)) return false; Set<?> other = (Set<?>) o; if (source.size() != other.size()) return false; for (I item: this) { if (!other.contains(item)) return false; } return true; } @Override public final int hashCode() { int h = 0; for (I item: this) { if (item == null) continue; h += item.hashCode(); } return h; } }
true
2aa72d2c951427ed82f713de449e7f1659abb2fe
Java
ant-tools/wood
/src/js/wood/PreviewServlet.java
UTF-8
12,179
1.953125
2
[]
no_license
package js.wood; import java.io.IOException; import java.io.Reader; import java.io.StringWriter; import java.security.Principal; import java.util.HashMap; import java.util.Locale; import java.util.Map; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import js.container.ContainerSPI; import js.core.Factory; import js.http.ContentType; import js.json.Json; import js.lang.Callback; import js.rmi.BusinessException; import js.servlet.RequestContext; import js.servlet.TinyContainer; import js.util.Classes; import js.util.Files; import js.util.Strings; /** * Preview servlet allows access from browser to project components and related files. This allows to use browser for * components preview by simple refreshing loaded page. A file is returned as it is but component layout is aggregated * and preview HTML code is generated on the fly; uses {@link Preview} for that. * <p> * In order to work preview servlet should be properly declared into web.xml file: * * <pre> * &lt;context-param&gt; * &lt;param-name&gt;PROJECT_DIR&lt;/param-name&gt; * &lt;param-value&gt;path/to/project&lt;/param-value&gt; * &lt;/context-param&gt; * * &lt;listener&gt; * &lt;listener-class&gt;js.wood.PreviewServlet&lt;/listener-class&gt; * &lt;/listener&gt; * * &lt;servlet&gt; * &lt;servlet-name&gt;development&lt;/servlet-name&gt; * &lt;servlet-class&gt;js.wood.PreviewServlet&lt;/servlet-class&gt; * &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; * &lt;/servlet&gt; * * &lt;servlet-mapping&gt; * &lt;servlet-name&gt;development&lt;/servlet-name&gt; * &lt;url-pattern&gt;/&lt;/url-pattern&gt; * &lt;/servlet-mapping&gt; * </pre> * * Preview WAR archive is actually empty; it contains only <code>web.xml</code> descriptor, that is, no Java classes nor * static content. * * @author Iulian Rotaru */ public final class PreviewServlet extends HttpServlet implements ReferenceHandler { /** Java serialization ID, */ private static final long serialVersionUID = -2971057399517075118L; /** Servlet context init parameter for project directory. */ private static final String PROJECT_DIR_PARAM = "PROJECT_DIR"; /** Context parameter for naming strategy. */ private static final String NAMING_STRATEGY_PARAM = "NAMING_STRATEGY"; private static final String PREVIEW_CALLBACK_PARAM = "PREVIEW_CALLBACK"; /** Parent container. */ private ContainerSPI container; /** Project instance initialized from Servlet context parameter on Servlet initialization. */ private Project project; /** Preview callback defined by user code. */ private Callback<ContainerSPI> previewCallback; /** * Preview layout is a special layout used for component unit test. It is returned instead of component; preview * layout uses component layout as widget. */ private static final String LAYOUT_PREVIEW = "preview.htm"; /** Variables cache initialized before every component preview processing. */ private static VariablesCache variablesCache = new VariablesCache(); private Json json; /** * Servlet instance initialization. This hook is invoked by Servlet container when first create preview Servlet * instance. Since this Servlet is declared <code>load-on-startup</code> this initialization occurs at application * deployment. * <p> * For every deployed preview context/application, Servlet container creates exactly one instance of this preview * Servlet and invoke this method once. This method takes care to create {@link #project} instance with proper root * directory loaded from initialization parameters. */ @Override public void init(ServletConfig config) throws ServletException { ServletContext context = config.getServletContext(); container = (ContainerSPI)context.getAttribute(TinyContainer.ATTR_INSTANCE); project = new Project(context.getInitParameter(PROJECT_DIR_PARAM)); String namingStrategyValue = context.getInitParameter(NAMING_STRATEGY_PARAM); if(namingStrategyValue == null) { project.setNamingStrategy(NamingStrategy.XMLNS); } else { project.setNamingStrategy(NamingStrategy.valueOf(namingStrategyValue)); } String previewCallbackValue = context.getInitParameter(PREVIEW_CALLBACK_PARAM); if(previewCallbackValue != null) { previewCallback = Classes.newInstance(previewCallbackValue); } json = Classes.loadService(Json.class); } /** * Servlet service routine just delegates {@link #doService(HttpServletRequest, HttpServletResponse)} and print * exception stack. * * @param httpRequest HTTP request, * @param httpResponse HTTP response. */ @Override protected void service(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException, IOException { try { Factory.bind(container); RequestContext context = Factory.getInstance(RequestContext.class); context.attach(httpRequest, httpResponse); if(!container.isAuthenticated()) { container.login(new PreviewUser()); } if(previewCallback != null) { previewCallback.handle(container); } doService(httpRequest, httpResponse); } catch(BusinessException e) {} catch(Throwable e) { if(e.getCause() instanceof BusinessException) { sendThrowable(httpResponse, HttpServletResponse.SC_BAD_REQUEST, e.getCause()); return; } throw new ServletException(e); } } /** * Process requests from browser for component layout and all dependent files. * * @param httpRequest HTTP request, * @param httpResponse HTTP response. * @throws Exception exceptions from preview process are thrown to caller. */ private void doService(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws Exception { httpResponse.setCharacterEncoding("UTF-8"); // request path is request URI without context; it does not starts with a path separator String requestPath = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length() + 1); if(RmiRequestHandler.accept(requestPath)) { RmiRequestHandler handler = new RmiRequestHandler(project, requestPath); handler.service(httpRequest, httpResponse); return; } if(RestRequestHandler.accept(requestPath)) { RestRequestHandler handler = new RestRequestHandler(project, requestPath); handler.service(httpRequest, httpResponse); return; } if(ResourceRequestHandler.accept(requestPath)) { ResourceRequestHandler handler = new ResourceRequestHandler(project, httpRequest); handler.service(httpRequest, httpResponse); return; } if(CompoPath.accept(requestPath)) { CompoPath compoPath = new CompoPath(project, requestPath); FilePath layoutPath = compoPath.getLayoutPath(); // if component has preview layout uses it instead of component layout // preview layout should use component as widget FilePath layoutPreview = compoPath.getFilePath(LAYOUT_PREVIEW); if(layoutPreview.exists()) { layoutPath = layoutPreview; } // rescan project script files and update variables cache every time a component is requested project.previewScriptFiles(); variablesCache.update(project); // create component with support for preview script Component component = new Component(layoutPath, this); component.scan(true); Preview preview = new Preview(component); preview.serialize(httpResponse.getWriter()); return; } FilePath filePath = project.getFile(requestPath); if(filePath.isStyle()) { if(!filePath.hasVariants()) { Reader reader = new SourceReader(new StyleReader(filePath), filePath, this); Files.copy(reader, httpResponse.getWriter()); } return; } if(filePath.isScript()) { Reader reader = new SourceReader(filePath, this); Files.copy(reader, httpResponse.getWriter()); return; } // all other files are just sent back to browser if(!filePath.exists() && filePath.isMedia()) { filePath = filePath.getVariant("en"); if(!filePath.exists()) { } } Files.copy(filePath.toFile(), httpResponse.getOutputStream()); } /** * Handler for resource references takes care of variables injection and media file processing. * * @param reference resource references, * @param source source containing the resource references. * @return resource variable values or media file source. */ @Override public String onResourceReference(Reference reference, FilePath source) { Locale previewLocale = new Locale("en"); if(reference.isVariable()) { String value = variablesCache.getVariables(project, source).get(previewLocale, reference, source, this); if(value == null) { value = reference.toString(); } return value; } // discover media file and returns its absolute URL path FilePath mediaFile = project.getMediaFile(previewLocale, reference, source); if(mediaFile == null) { throw new WoodException("Missing media file for reference |%s| from source |%s|.", reference, source); } return Strings.concat(Path.SEPARATOR, project.getName(), Path.SEPARATOR, mediaFile.getDirPath().value(), mediaFile.getName()); } /** * Send throwable back to preview browser. * * @param httpResponse HTTP response, * @param responseCode HTTP response code, * @param throwable throwable instance. * @throws IOException if sending throwable fails. */ private void sendThrowable(HttpServletResponse httpResponse, int responseCode, Throwable throwable) throws IOException { httpResponse.setStatus(responseCode); httpResponse.setContentType(ContentType.APPLICATION_JSON.getValue()); StringWriter buffer = new StringWriter(); json.stringify(buffer, throwable); byte[] bytes = buffer.toString().getBytes("UTF-8"); httpResponse.setContentLength(bytes.length); httpResponse.getOutputStream().write(bytes); httpResponse.getOutputStream().flush(); } /** * Variable caches used to speed up preview process. Cache life span last for a component preview session. * * @author Iulian Rotaru */ private static class VariablesCache { /** Components variables. */ private Map<Path, Variables> compoVariables = new HashMap<Path, Variables>(); /** Project asset variables. */ private Variables assetVariables; /** Theme variables. */ private Variables themeVariables; /** * Initialize variables cache by cleaning component variables hash and rescanning assets and site styles * directories. * * @param project parent project. */ public synchronized void update(Project project) { compoVariables.clear(); assetVariables = new Variables(project, project.getAssetsDir()); themeVariables = new Variables(project, project.getThemeDir()); } /** * Return cached component variables. If variables are not already on hash create new instance and store before * return it. Component to return variables for is identified by given source file. * * @param sourcePath component source file. * @return component variables. */ public synchronized Variables getVariables(Project project, FilePath sourcePath) { Variables variables = compoVariables.get(sourcePath.getDirPath()); if(variables == null) { variables = new Variables(project, sourcePath.getDirPath()); variables.setAssetVariables(assetVariables); variables.setThemeVariables(themeVariables); compoVariables.put(sourcePath.getDirPath(), variables); } return variables; } } private static class PreviewUser implements Principal { @Override public String getName() { return "preview-user"; } } }
true
bbecb8a2e199f7c7456981d79995a1816fe6fa74
Java
YunusCag/StokTakipOtomasyonu
/src/data/Stok.java
UTF-8
2,178
2.328125
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 data; import java.util.Date; /** * * @author Yunus */ public class Stok { private int stokNo; private int malzemeNo; private int calisanNo; private Date kayitTarihi; private int miktar; public Calisan calisan; public Malzeme malzeme; public Stok(int stokNo, int malzemeNo, int calisanNo, Date kayitTarihi, int miktar, Calisan calisan, Malzeme malzeme) { this.stokNo = stokNo; this.malzemeNo = malzemeNo; this.calisanNo = calisanNo; this.kayitTarihi = kayitTarihi; this.miktar = miktar; this.calisan = calisan; this.malzeme = malzeme; } public Stok(int stokNo, int malzemeNo, int calisanNo, Date kayitTarihi, int miktar) { this.stokNo = stokNo; this.malzemeNo = malzemeNo; this.calisanNo = calisanNo; this.kayitTarihi = kayitTarihi; this.miktar = miktar; } public Stok(int malzemeNo, int calisanNo, Date kayitTarihi, int miktar) { this.malzemeNo = malzemeNo; this.calisanNo = calisanNo; this.kayitTarihi = kayitTarihi; this.miktar = miktar; } public int getStokNo() { return stokNo; } public void setStokNo(int stokNo) { this.stokNo = stokNo; } public int getMalzemeNo() { return malzemeNo; } public void setMalzemeNo(int malzemeNo) { this.malzemeNo = malzemeNo; } public int getCalisanNo() { return calisanNo; } public void setCalisanNo(int calisanNo) { this.calisanNo = calisanNo; } public Date getKayitTarihi() { return kayitTarihi; } public void setKayitTarihi(Date kayitTarihi) { this.kayitTarihi = kayitTarihi; } public int getMiktar() { return miktar; } public void setMiktar(int miktar) { this.miktar = miktar; } }
true
a3c5b3d317cfd06deb59b0bb14273efd9f785ad7
Java
Super02/Tickr-bot
/src/main/java/me/enscivwy/ticketbot/Commands/Basic/MentionTag.java
UTF-8
1,301
2.390625
2
[]
no_license
package me.enscivwy.ticketbot.Commands.Basic; import me.enscivwy.ticketbot.CommandHandler.Command; import me.enscivwy.ticketbot.TicketBot; import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import net.dv8tion.jda.core.hooks.ListenerAdapter; import java.awt.*; import java.time.OffsetDateTime; public class MentionTag extends ListenerAdapter { @Override public void onMessageReceived(MessageReceivedEvent e) { if(e.getAuthor().isBot()) return; if(e.getMessage().getContentRaw().equalsIgnoreCase("<@470564628443955202>")) { StringBuilder sb = new StringBuilder(); for(Command cmd : TicketBot.getCommands()) { sb.append(TicketBot.getPrefix()).append("**").append(cmd.getCommand()).append("**").append(" - ").append(cmd.getDescription()).append("\n"); } e.getChannel().sendMessage(new EmbedBuilder() .setTitle("Help Menu", null) .setDescription("Need help with the bot? Right here! \n\n" + sb.toString().trim() + "\n\n") .setTimestamp(OffsetDateTime.now()) .setColor(Color.decode("#ffffff")) .build()).queue(); } } }
true
7afacf3c2c2b6ac97785b90a4aae5964d0a91494
Java
luxiaotao1123/CoolBlog
/back-end/src/main/java/cn/blog/utils/R1.java
UTF-8
1,082
3.09375
3
[]
no_license
package cn.blog.utils; import java.util.HashMap; import java.util.Map; public class R1 extends HashMap<String,Object>{ //构造 public R1(){ put("code",200); //初始值 } //错误 public static R1 error(int code, String msg){ R1 r1 = new R1(); r1.put("code",code); r1.put("msg",msg); return r1; } //成功 public static R1 success(int code,String msg){ R1 r1 = new R1(); r1.put("code",code); r1.put("msg",msg); return r1; } //返回多个对象存进map public static R1 ok(Map<String,Object> map){ R1 r1 = new R1(); r1.putAll(map); return r1; } public static R1 ok(){ return new R1(); } //返回一个对象存进map,key为对象名,key自己命名 public static R1 add(String key,Object value){ R1 r1 = new R1(); r1.put(key,value); r1.ok(r1); return r1; } public R1 put(String key,Object value){ super.put(key,value); return this; } }
true
da4a1bab796a55fd725714fc6be286c77680be0b
Java
macmaton/probable-potato-player
/test/abc/music/SectionTest.java
UTF-8
1,008
2.546875
3
[]
no_license
package abc.music; import org.junit.Test; public class SectionTest extends TestBase { Section s1; Section s2; Section s3; public void setup() { s1 = createSection(); s2 = createSection(); s3 = createSection(createVoicePart()); } @Test public void testEquals() { setup(); assert s1.equals(s2); assert !(s2.equals(s3)); } @Test public void testHashCode() { setup(); assert s1.hashCode() == s2.hashCode(); } @Test public void testToString() { setup(); Body b1 = parseBody(s1.toString()); Section test1 = b1.getSections().get(0); Body b2 = parseBody(s3.toString()); Section test2 = b2.getSections().get(0); assert s1.equals(test1); assert s3.equals(test2); } @Test (expected = UnsupportedOperationException.class) public void testGetElements() { setup(); s1.getElements().set(0, createLine()); } }
true
b8c7f16054dfa7af8df21177d495a1d263205f03
Java
moutainhigh/server-3
/service-share/activity-srv/src/test/java/com/lawu/eshop/activity/srv/ActivitySrvApplicationTest.java
UTF-8
851
1.78125
2
[]
no_license
package com.lawu.eshop.activity.srv; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.FilterType; /** * 活动服务测试启动类 * @author jiangxinjun * @createDate 2017年12月28日 * @updateDate 2017年12月28日 */ @MapperScan({"com.lawu.eshop.activity.srv.mapper"}) @ComponentScan(value = {"com.lawu"}, excludeFilters = {@ComponentScan.Filter(value = {ActivitySrvApplication.class}, type = FilterType.ASSIGNABLE_TYPE)}) @SpringBootApplication public class ActivitySrvApplicationTest { public static void main(String[] args) { SpringApplication.run(ActivitySrvApplicationTest.class, args); } }
true
aeffd343f523446290a4d146e11b466b7906f883
Java
cei-dda/rmi-app
/server/src/main/java/net/franciscovillegas/cei/obligatorio/server/App.java
UTF-8
2,537
2.671875
3
[]
no_license
package net.franciscovillegas.cei.obligatorio.server; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; import net.franciscovillegas.cei.obligatorio.common.Server; import net.franciscovillegas.cei.obligatorio.server.entities.Address; import net.franciscovillegas.cei.obligatorio.server.entities.Task; import net.franciscovillegas.cei.obligatorio.server.entities.User; /** * Hello world! * */ public class App { public static void main(String[] args) { EntityManager em = null; try { System.setProperty("java.security.policy", "file:///Users/fvillegas/Projects/cei/java.policy"); LocateRegistry.createRegistry(1099); ServerImpl obj = new ServerImpl(); Server stub = (Server) UnicastRemoteObject.exportObject(obj, 0); // Bind the remote object's stub in the registry Registry registry = LocateRegistry.getRegistry(1099); registry.bind("server", stub); // JDBC System.out.println("Server ready"); // new Memento(); // JPA EntityManagerFactory emf; emf = Persistence.createEntityManagerFactory("jpaDS"); em = (EntityManager) emf.createEntityManager(); em.getTransaction().begin(); User user = new User(); Address address = new Address("la direccion"); em.persist(address); em.persist(user); user.setAddress(address); em.getTransaction().commit(); User u = em.find(User.class, user.getId()); // u esta manejado por el EM em.close(); // u deja de estar manejado por el EM em = (EntityManager) emf.createEntityManager(); em.getTransaction().begin(); u = em.merge(u); // u vuelve a estar manejado por un EM u.setName("algo"); System.out.println(u.getTareas()); if (u.getTareas() == null) { u.setTareas(new ArrayList<Task>()); } Task task = new Task(); u.getTareas().add(task); em.persist(task); em.getTransaction().commit(); u = em.find(User.class, user.getId()); Query query = em.createNamedQuery("findUserByName"); query.setParameter("name", "algo"); u = (User) query.getSingleResult(); u.getTareas(); System.out.println("---->2"); } catch (Exception e) { System.err.println("Server exception: " + e.toString()); e.printStackTrace(); } finally { if (em != null) { em.close(); } } // System.exit(0); } }
true
be5b7ae74fb09dce10e16b71bc65bb38c043be27
Java
kangzhenkang/puma
/puma/puma-core/src/main/java/com/dianping/puma/core/sync/model/task/SyncTask.java
UTF-8
602
2.09375
2
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
package com.dianping.puma.core.sync.model.task; import com.google.code.morphia.annotations.Entity; @Entity public class SyncTask extends AbstractTask { private static final long serialVersionUID = 2359517002901314187L; // 状态 private SyncTaskStatusAction syncTaskStatusAction; public SyncTask() { super(Type.SYNC); } public SyncTaskStatusAction getSyncTaskStatusAction() { return syncTaskStatusAction; } public void setSyncTaskStatusAction(SyncTaskStatusAction taskStatusAction) { this.syncTaskStatusAction = taskStatusAction; } }
true
bc6d97597d009ae9d2332a66af6c858bd214647c
Java
ykhorosh/mera_se_2020
/Lineva/2/LessonTwoTaskOne.java
UTF-8
773
3.71875
4
[]
no_license
import java.util.Random; public class LessonTwoTaskOne { public static void main(String[] args) { final int SIZE = 10, BOUND = 100; int[] array = new int[SIZE]; Random random = new Random(); array[0] = random.nextInt(BOUND); int sum = array[0]; int minIndex = 0; System.out.print("Array: " + array[0]); for (int i = 1; i < SIZE; i++) { array[i] = random.nextInt(BOUND); sum += array[i]; if (array[i] < array[minIndex]) { minIndex = i; } System.out.print(" " + array[i]); } System.out.println("\nSum is " + sum); System.out.println("Min is " + array[minIndex] + " with index " + minIndex); } }
true
e7e78c20f6c9fb05bc123693f23fdebea4663653
Java
UCSB-CS-RACELab/eager-appscale
/Eager/roots/core/src/main/java/edu/ucsb/cs/roots/ManagedService.java
UTF-8
1,036
2.40625
2
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
package edu.ucsb.cs.roots; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; public abstract class ManagedService { protected final RootsEnvironment environment; protected final Logger log = LoggerFactory.getLogger(getClass()); private State state; public ManagedService(RootsEnvironment environment) { checkNotNull(environment); this.environment = environment; this.state = State.STANDBY; } public final void init() throws Exception { checkState(state == State.STANDBY); doInit(); state = State.INITIALIZED; } public final void destroy() { checkState(state == State.INITIALIZED); doDestroy(); state = State.DESTROYED; } public final State getState() { return state; } protected abstract void doInit() throws Exception; protected abstract void doDestroy(); }
true
41acc794ce74de7637485a22e8a21ffa2537d3bf
Java
JBajracharya/data-structures-and-algorithms
/code401challenges/src/test/java/code401challenges/tree/BinarySearchTreeTest.java
UTF-8
2,964
3.46875
3
[]
no_license
package code401challenges.tree; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import static org.junit.Assert.*; public class BinarySearchTreeTest { @Test public void testEmptyTree() { Tree emptyTree = new Tree(); assertNull(emptyTree.root); } @Test public void testSingleRootNode() { Tree singleRootNodeTree = new Tree(); singleRootNodeTree.root = new Node<>(4); assertNotNull(singleRootNodeTree.root); } @Test public void testLeftChildRightChild() { Tree leftRightTree = new Tree(); leftRightTree.root = new Node<>(1); leftRightTree.root.left = new Node<>(5); leftRightTree.root.right = new Node<>(8); assertEquals("[1, 5, 8]", leftRightTree.preOrder(leftRightTree.root).toString()); } static Tree tree; static BinarySearchTree<Integer> searchTree; @Before public void initial() { tree = new Tree(); searchTree = new BinarySearchTree<>(); tree.insert(20); tree.insert(10); tree.insert(30); tree.insert(5); tree.insert(15); tree.insert(16); } @Test public void testPreOrder() { ArrayList<Integer> list = searchTree.preOrder(tree.root); for (int a : list) { System.out.println("a = " + a); } assertEquals("[20, 10, 5, 15, 16, 30]", list.toString()); } @Test public void testInOrder() { ArrayList<Integer> list = searchTree.inOrder(tree.root); assertEquals("[5, 10, 15, 16, 20, 30]", list.toString()); } @Test public void testPostOrder() { ArrayList<Integer> list = searchTree.postOrder(tree.root); assertEquals("[5, 16, 15, 10, 30, 20]", list.toString()); } @Test public void testContains() { assertTrue(searchTree.contains(tree.root, 15)); assertTrue(searchTree.contains(tree.root, 30)); assertFalse(searchTree.contains(tree.root, 50)); } @Test public void testBreadthFirst() { assertEquals("[20, 10, 30, 5, 15, 16]", searchTree.breadthFirst(tree.root).toString()); } @Test public void testMaxValueInTree() throws Exception { assertEquals(30, searchTree.getMaxValue(tree.root)); } @Test public void testNegativeMax() throws Exception { Tree tree1 = new Tree(); tree1.insert(-20); tree1.insert(-10); tree1.insert(-30); tree1.insert(-5); tree1.insert(-15); tree1.insert(-16); assertEquals(-5, searchTree.getMaxValue(tree1.root)); } @Test(expected = Exception.class) public void testWrongDataTypeError() throws Exception { BinarySearchTree<String> stringTree = new BinarySearchTree<>(); stringTree.root = new Node<>("Ball"); int actual = stringTree.getMaxValue(stringTree.root); assertEquals(5, actual); } }
true
bbed536597f4af9311c74cd0cde12ac6bc3d1494
Java
cempay/hms-cordova-plugin
/cordova-plugin-hms-ads/src/android/src/main/java/com/huawei/hms/cordova/ads/basef/handler/CorPack.java
UTF-8
2,574
1.882813
2
[ "Apache-2.0" ]
permissive
/* Copyright 2020. Huawei Technologies Co., Ltd. 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 https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.huawei.hms.cordova.ads.basef.handler; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; public class CorPack { private final HMSLogger hmsLogger; private final CordovaPlugin cordovaPlugin; private final CordovaWebView webView; private final CordovaInterface cordova; private final CordovaEventRunner eventRunner; CorPack(final HMSLogger hmsLogger, final CordovaPlugin cordovaPlugin, final CordovaEventRunner eventRunner) { this.hmsLogger = hmsLogger; this.cordovaPlugin = cordovaPlugin; this.webView = cordovaPlugin.webView; this.cordova = cordovaPlugin.cordova; this.eventRunner = eventRunner; } public void requestPermission(int requestCode, String permission) { cordova.requestPermission(cordovaPlugin, requestCode, permission); } public void requestPermissions(int requestCode, String[] permissions) { cordova.requestPermissions(cordovaPlugin, requestCode, permissions); } public boolean hasPermission(String permission) { return cordova.hasPermission(permission); } public void enableLogger() { hmsLogger.enableLogger(); } public void disableLogger() { hmsLogger.disableLogger(); } public void startMethodExecution(String methodName) { hmsLogger.startMethodExecutionTimer(methodName); } public void sendSingleEvent(String methodName) { hmsLogger.sendSingleEvent(methodName); } public void sendSingleEvent(String methodName, String errorCode) { hmsLogger.sendSingleEvent(methodName, errorCode); } public CordovaWebView getCordovaWebView() { return webView; } public CordovaInterface getCordova() { return cordova; } public CordovaEventRunner getEventRunner() { return eventRunner; } }
true
21ba8641d8c3903ad3ebde7e2f1d7d3795ba378d
Java
vaibhav16060/SmartHealthWeb
/src/Controller/deactivateForWeb.java
UTF-8
2,141
2.359375
2
[]
no_license
package Controller; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import Model.*; /** * Servlet implementation class deactivateForWeb */ @WebServlet("/deactivateForWeb") public class deactivateForWeb extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public deactivateForWeb() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String calling_URL = request.getRequestURL().toString(); String redirect_URL = calling_URL.substring(0, calling_URL.lastIndexOf('/')); String password = request.getParameter("tb_password").toString(); HttpSession hs = request.getSession(); LoginDetails cont = (LoginDetails)hs.getAttribute("LoggerObj"); PrintWriter output = response.getWriter(); if(cont.if_password_matches(password)){ cont.deactivate_account(); cont.update_data(); hs.setAttribute("LoggerObj", null); output.println("<script>"); output.println("location.href='" + redirect_URL + "';"); output.println("alert('You have been successfully deactivated !');"); output.println("</script>"); return; } else{ output.println("<script>"); output.println("location.href='" + redirect_URL + "/Deactivate.jsp';"); output.println("alert('The password you entered does not match your current password.');"); output.println("</script>"); return; } } }
true
d9630c489f68259630e647c5477902c3fbd2cf81
Java
radhakrishnan10192/impdata
/data/Task2/src/com/bizruntime/Task2/CopyOf.java
UTF-8
1,187
3.703125
4
[]
no_license
package com.bizruntime.Task2; import java.util.Scanner; public class CopyOf { public static void main(String[] args) { int size ; int[] array; int[] array1; int[] array2; Scanner in = new Scanner(System.in); System.out.println("Enter Size of method"); size = in.nextInt(); array = new int[size]; for (int pos = 0; pos < size; pos++) { array[pos] = in.nextInt(); } array1 = copyOf(array); for (int pos = 0; pos < array1.length; pos++) { if (pos >0) { System.out.print(","); } System.out.print(array1[pos]); } System.out.println("Enter new length"); int key = in.nextInt(); array2 = copyOfEx(array , key); for (int i = 0; i < array2.length; i++) { System.out.println(array2[i]); } in.close(); } public static int[] copyOfEx(int[] array, int key) { int[] array1 = new int[key]; for (int pos = 0; pos < key; pos++) { if (array.length < key) { array1[pos] = 0; }else { array1[pos] = array[pos]; } } return array1; } public static int[] copyOf(int[] array){ int[] array1 = new int[array.length]; for (int pos = 0; pos < array1.length; pos++) { array1[pos] = array[pos]; } return array1; } }
true
7bdf35182d9508f532812d0e0353a3192c7dde89
Java
metamodeler/CIM-CSS
/CIM3/src/context/impl/CongnitiveImpl.java
UTF-8
701
1.726563
2
[ "CC-BY-4.0" ]
permissive
/** */ package context.impl; import context.Congnitive; import context.ContextPackage; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Congnitive</b></em>'. * <!-- end-user-doc --> * * @generated */ public class CongnitiveImpl extends AtomicImpl implements Congnitive { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected CongnitiveImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return ContextPackage.Literals.CONGNITIVE; } } //CongnitiveImpl
true
a09336ab79c6c2447c4188ab7d16ef1ddaaf57c5
Java
jagrosh/JDA
/src/main/java/net/dv8tion/jda/internal/handle/GuildUpdateHandler.java
UTF-8
13,949
1.882813
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.dv8tion.jda.internal.handle; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.entities.VoiceChannel; import net.dv8tion.jda.api.events.guild.update.*; import net.dv8tion.jda.api.utils.data.DataArray; import net.dv8tion.jda.api.utils.data.DataObject; import net.dv8tion.jda.internal.JDAImpl; import net.dv8tion.jda.internal.entities.GuildImpl; import net.dv8tion.jda.internal.requests.WebSocketClient; import java.util.Collections; import java.util.Locale; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.StreamSupport; public class GuildUpdateHandler extends SocketHandler { public GuildUpdateHandler(JDAImpl api) { super(api); } @Override protected Long handleInternally(DataObject content) { final long id = content.getLong("id"); if (getJDA().getGuildSetupController().isLocked(id)) return id; GuildImpl guild = (GuildImpl) getJDA().getGuildById(id); if (guild == null) { EventCache.LOG.debug("Caching GUILD_UPDATE for guild with id: {}", id); getJDA().getEventCache().cache(EventCache.Type.GUILD, id, responseNumber, allContent, this::handle); return null; } //When member limits aren't initialized we don't fire an update event for them int maxMembers = content.getInt("max_members", 0); int maxPresences = content.getInt("max_presences", 5000); if (guild.getMaxMembers() == 0) { // Initialize member limits to avoid unwanted update events guild.setMaxPresences(maxPresences); guild.setMaxMembers(maxMembers); } long ownerId = content.getLong("owner_id"); int boostCount = content.getInt("premium_subscription_count", 0); int boostTier = content.getInt("premium_tier", 0); String description = content.getString("description", null); String vanityCode = content.getString("vanity_url_code", null); String bannerId = content.getString("banner", null); String name = content.getString("name"); String iconId = content.getString("icon", null); String splashId = content.getString("splash", null); Guild.VerificationLevel verificationLevel = Guild.VerificationLevel.fromKey(content.getInt("verification_level")); Guild.NotificationLevel notificationLevel = Guild.NotificationLevel.fromKey(content.getInt("default_message_notifications")); Guild.MFALevel mfaLevel = Guild.MFALevel.fromKey(content.getInt("mfa_level")); Guild.NSFWLevel nsfwLevel = Guild.NSFWLevel.fromKey(content.getInt("nsfw_level", -1)); Guild.ExplicitContentLevel explicitContentLevel = Guild.ExplicitContentLevel.fromKey(content.getInt("explicit_content_filter")); Guild.Timeout afkTimeout = Guild.Timeout.fromKey(content.getInt("afk_timeout")); Locale locale = Locale.forLanguageTag(content.getString("preferred_locale", "en-US")); VoiceChannel afkChannel = content.isNull("afk_channel_id") ? null : guild.getVoiceChannelsView().get(content.getLong("afk_channel_id")); TextChannel systemChannel = content.isNull("system_channel_id") ? null : guild.getTextChannelsView().get(content.getLong("system_channel_id")); TextChannel rulesChannel = content.isNull("rules_channel_id") ? null : guild.getTextChannelsView().get(content.getLong("rules_channel_id")); TextChannel communityUpdatesChannel = content.isNull("public_updates_channel_id") ? null : guild.getTextChannelsView().get(content.getLong("public_updates_channel_id")); Set<String> features; if (!content.isNull("features")) { DataArray featureArr = content.getArray("features"); features = StreamSupport.stream(featureArr.spliterator(), false).map(String::valueOf).collect(Collectors.toSet()); } else { features = Collections.emptySet(); } if (ownerId != guild.getOwnerIdLong()) { long oldOwnerId = guild.getOwnerIdLong(); Member oldOwner = guild.getOwner(); Member newOwner = guild.getMembersView().get(ownerId); if (newOwner == null) WebSocketClient.LOG.debug("Received {} with owner not in cache. UserId: {} GuildId: {}", allContent.get("t"), ownerId, id); guild.setOwner(newOwner); guild.setOwnerId(ownerId); getJDA().handleEvent( new GuildUpdateOwnerEvent( getJDA(), responseNumber, guild, oldOwner, oldOwnerId, ownerId)); } if (!Objects.equals(description, guild.getDescription())) { String oldDescription = guild.getDescription(); guild.setDescription(description); getJDA().handleEvent( new GuildUpdateDescriptionEvent( getJDA(), responseNumber, guild, oldDescription)); } if (!Objects.equals(bannerId, guild.getBannerId())) { String oldBanner = guild.getBannerId(); guild.setBannerId(bannerId); getJDA().handleEvent( new GuildUpdateBannerEvent( getJDA(), responseNumber, guild, oldBanner)); } if (!Objects.equals(vanityCode, guild.getVanityCode())) { String oldCode = guild.getVanityCode(); guild.setVanityCode(vanityCode); getJDA().handleEvent( new GuildUpdateVanityCodeEvent( getJDA(), responseNumber, guild, oldCode)); } if (maxMembers != guild.getMaxMembers()) { int oldMax = guild.getMaxMembers(); guild.setMaxMembers(maxMembers); getJDA().handleEvent( new GuildUpdateMaxMembersEvent( getJDA(), responseNumber, guild, oldMax)); } if (maxPresences != guild.getMaxPresences()) { int oldMax = guild.getMaxPresences(); guild.setMaxPresences(maxPresences); getJDA().handleEvent( new GuildUpdateMaxPresencesEvent( getJDA(), responseNumber, guild, oldMax)); } if (boostCount != guild.getBoostCount()) { int oldCount = guild.getBoostCount(); guild.setBoostCount(boostCount); getJDA().handleEvent( new GuildUpdateBoostCountEvent( getJDA(), responseNumber, guild, oldCount)); } if (Guild.BoostTier.fromKey(boostTier) != guild.getBoostTier()) { Guild.BoostTier oldTier = guild.getBoostTier(); guild.setBoostTier(boostTier); getJDA().handleEvent( new GuildUpdateBoostTierEvent( getJDA(), responseNumber, guild, oldTier)); } if (!Objects.equals(name, guild.getName())) { String oldName = guild.getName(); guild.setName(name); getJDA().handleEvent( new GuildUpdateNameEvent( getJDA(), responseNumber, guild, oldName)); } if (!Objects.equals(iconId, guild.getIconId())) { String oldIconId = guild.getIconId(); guild.setIconId(iconId); getJDA().handleEvent( new GuildUpdateIconEvent( getJDA(), responseNumber, guild, oldIconId)); } if (!features.equals(guild.getFeatures())) { Set<String> oldFeatures = guild.getFeatures(); guild.setFeatures(features); getJDA().handleEvent( new GuildUpdateFeaturesEvent( getJDA(), responseNumber, guild, oldFeatures)); } if (!Objects.equals(splashId, guild.getSplashId())) { String oldSplashId = guild.getSplashId(); guild.setSplashId(splashId); getJDA().handleEvent( new GuildUpdateSplashEvent( getJDA(), responseNumber, guild, oldSplashId)); } if (!Objects.equals(verificationLevel, guild.getVerificationLevel())) { Guild.VerificationLevel oldVerificationLevel = guild.getVerificationLevel(); guild.setVerificationLevel(verificationLevel); getJDA().handleEvent( new GuildUpdateVerificationLevelEvent( getJDA(), responseNumber, guild, oldVerificationLevel)); } if (!Objects.equals(notificationLevel, guild.getDefaultNotificationLevel())) { Guild.NotificationLevel oldNotificationLevel = guild.getDefaultNotificationLevel(); guild.setDefaultNotificationLevel(notificationLevel); getJDA().handleEvent( new GuildUpdateNotificationLevelEvent( getJDA(), responseNumber, guild, oldNotificationLevel)); } if (!Objects.equals(mfaLevel, guild.getRequiredMFALevel())) { Guild.MFALevel oldMfaLevel = guild.getRequiredMFALevel(); guild.setRequiredMFALevel(mfaLevel); getJDA().handleEvent( new GuildUpdateMFALevelEvent( getJDA(), responseNumber, guild, oldMfaLevel)); } if (!Objects.equals(explicitContentLevel, guild.getExplicitContentLevel())) { Guild.ExplicitContentLevel oldExplicitContentLevel = guild.getExplicitContentLevel(); guild.setExplicitContentLevel(explicitContentLevel); getJDA().handleEvent( new GuildUpdateExplicitContentLevelEvent( getJDA(), responseNumber, guild, oldExplicitContentLevel)); } if (!Objects.equals(afkTimeout, guild.getAfkTimeout())) { Guild.Timeout oldAfkTimeout = guild.getAfkTimeout(); guild.setAfkTimeout(afkTimeout); getJDA().handleEvent( new GuildUpdateAfkTimeoutEvent( getJDA(), responseNumber, guild, oldAfkTimeout)); } if (!Objects.equals(locale, guild.getLocale())) { Locale oldLocale = guild.getLocale(); guild.setLocale(locale.toLanguageTag()); getJDA().handleEvent( new GuildUpdateLocaleEvent( getJDA(), responseNumber, guild, oldLocale)); } if (!Objects.equals(afkChannel, guild.getAfkChannel())) { VoiceChannel oldAfkChannel = guild.getAfkChannel(); guild.setAfkChannel(afkChannel); getJDA().handleEvent( new GuildUpdateAfkChannelEvent( getJDA(), responseNumber, guild, oldAfkChannel)); } if (!Objects.equals(systemChannel, guild.getSystemChannel())) { TextChannel oldSystemChannel = guild.getSystemChannel(); guild.setSystemChannel(systemChannel); getJDA().handleEvent( new GuildUpdateSystemChannelEvent( getJDA(), responseNumber, guild, oldSystemChannel)); } if (!Objects.equals(rulesChannel, guild.getRulesChannel())) { TextChannel oldRulesChannel = guild.getRulesChannel(); guild.setRulesChannel(rulesChannel); getJDA().handleEvent( new GuildUpdateRulesChannelEvent( getJDA(), responseNumber, guild, oldRulesChannel)); } if (!Objects.equals(communityUpdatesChannel, guild.getCommunityUpdatesChannel())) { TextChannel oldCommunityUpdatesChannel = guild.getCommunityUpdatesChannel(); guild.setCommunityUpdatesChannel(communityUpdatesChannel); getJDA().handleEvent( new GuildUpdateCommunityUpdatesChannelEvent( getJDA(), responseNumber, guild, oldCommunityUpdatesChannel)); } if (content.hasKey("nsfw_level") && nsfwLevel != guild.getNSFWLevel()) { Guild.NSFWLevel oldNSFWLevel = guild.getNSFWLevel(); guild.setNSFWLevel(nsfwLevel); getJDA().handleEvent( new GuildUpdateNSFWLevelEvent( getJDA(), responseNumber, guild, oldNSFWLevel)); } return null; } }
true
c3cadabe7ab37af6292c4fe8a22d36a34d8d3149
Java
Nathan-Bisson/RBA-ATool
/src/model/RGBAModel.java
UTF-8
2,972
3.28125
3
[]
no_license
package model; import java.util.Observable; import android.graphics.Color; /** * The model holds the data. * * Model color. * Based on red, green, blue and alpha (transparency). * * RGB: integer values in the domain range of 0 to 255 (inclusive). * Alpha: integer value in the domain range of 0 to 255 (inclusive). * * @author Nathan Bisson (biss0180@algonquinlive.com) * @version 1.0 */ public class RGBAModel extends Observable { public static final Integer MAX_ALPHA = 100; public static final Integer MAX_RGB = 255; public static final Integer MIN_ALPHA = 0; public static final Integer MIN_RGB = 0; private Integer alpha; private Integer blue; private Integer green; private Integer red; public RGBAModel() { // TODO Auto-generated constructor stub this( MAX_RGB, MAX_RGB, MAX_RGB, MAX_ALPHA ); } public RGBAModel(Integer red, Integer green, Integer blue, Integer alpha) { super(); this.red = red; this.green = green; this.blue = blue; this.alpha = alpha; } public void asBlack() { this.setRGB(MIN_RGB, MIN_RGB, MIN_RGB); } public void asBlue() { this.setRGB(MIN_RGB, MIN_RGB, MAX_RGB); } public void asCyan() { this.setRGB(MIN_RGB, MAX_RGB, MAX_RGB); } public void asGreen() { this.setRGB(MIN_RGB, MAX_RGB, MIN_RGB); } public void asMagenta() { this.setRGB(MAX_RGB, MIN_RGB, MAX_RGB); } public void asRed() { this.setRGB(MAX_RGB, MIN_RGB, MIN_RGB); } public void asWhite() { this.setRGB(MAX_RGB, MAX_RGB, MAX_RGB); } public void asYellow() { this.setRGB(MAX_RGB, MAX_RGB, MIN_RGB); } public int getColor() { return Color.rgb(red, green, blue); } public int getRed() { return this.red; } public int getGreen() { return this.green; } public int getBlue() { return this.blue; } public int getAlpha() { return this.alpha; } public void setRed(Integer red) { this.red = red; this.updateObservers(); } public void setGreen(Integer green) { this.green = green; this.updateObservers(); } public void setBlue(Integer blue) { this.blue = blue; this.updateObservers(); } public void setAlpha(Integer alpha) { this.alpha = alpha; this.updateObservers(); } public void setRGB(Integer red, Integer green, Integer blue) { this.red = red; this.green = green; this.blue = blue; this.updateObservers(); } @Override public String toString() { return "RGB-A [r=" + red + " g=" + green + " b=" + blue + " alpha=" + alpha + "]"; } /** * The model's state has changed! * * Notify all registered observers that this model has changed * state, and the registered observers should change too. */ private void updateObservers() { this.setChanged(); this.notifyObservers(); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub RGBAModel model = new RGBAModel(127, 127, 127, 255); System.out.println(model); } }
true
05041dd3b98fecf6835febfc27fc45e9a1571655
Java
JuKu/mmo-engine-client
/game-view-layer/src/main/java/com/jukusoft/mmo/engine/gameview/renderer/IRenderer.java
UTF-8
761
2.21875
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package com.jukusoft.mmo.engine.gameview.renderer; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.jukusoft.mmo.engine.applayer.time.GameTime; import com.jukusoft.mmo.engine.gameview.camera.CameraHelper; /** * Created by Justin on 14.09.2017. */ public interface IRenderer { /** * update renderer * * @param time game time instance to get current game time */ public void update(GameTime time); /** * draw renderer * * @param time game time instance to get current game time * @param camera game camera * @param batch sprite batch */ public void draw(GameTime time, CameraHelper camera, SpriteBatch batch); /** * dispose renderer */ public void dispose(); }
true
a0698d7397925f1d019545b1ca25c051edf5077f
Java
niarehtni/nccode
/limsweb/qcco/src/public/nc/ui/qcco/commission/refmodel/UnitTypeRefModel.java
GB18030
1,131
1.945313
2
[]
no_license
package nc.ui.qcco.commission.refmodel; import nc.ui.bd.ref.AbstractRefModel; public class UnitTypeRefModel extends AbstractRefModel { public UnitTypeRefModel() { super(); this.setTableName("NC_RESULT_TYPE"); this.setMutilLangNameRef(false); } public java.lang.String[] getFieldCode() { return new String[] { "NC_RESULT_CODE", "NC_RESULT_NAMECN" }; } public java.lang.String[] getFieldName() { return new String[] { "ֵͱ", "ֵ" }; } public java.lang.String[] getHiddenFieldCode() { return new String[] { "PK_RESULT_TYPE" }; } public java.lang.String getPkFieldCode() { return "PK_RESULT_TYPE"; } public java.lang.String getOrderPart() { return "NC_RESULT_CODE"; } public int getDefaultFieldCount() { return 2; } public java.lang.String getRefTitle() { return "ѡֵ"; } protected String getSql(String strPatch, String[] strFieldCode, String[] hiddenFields, String strTableName, String strWherePart, String strGroupField, String strOrderField) { return "select NC_RESULT_CODE,NC_RESULT_NAMECN name, PK_RESULT_TYPE from NC_RESULT_TYPE "; } }
true
0137350ac26dc81f9ba20256781460180e046e1e
Java
portofrotterdam/hamis-fuse
/core/src/main/java/org/jdesktop/fuse/Definition.java
UTF-8
4,211
2.109375
2
[]
no_license
/** * Copyright (c) 2006, Sun Microsystems, Inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Fuse project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jdesktop.fuse; /** * <p>This is the superinterface of any definition provider classes. This * interface is used primarily as a contract assurance interface and not * in any fancy polymorphic magic. Unless one is defining a new definition * <i>provider</i> (not the definition itself), there should never be a need * to implement this interface.</p> * * <p>It is expected that all implementations of this interface will also provide * a static <code>load</code> method overloaded for the various instances * which may or may not be necessary to create the definition. This is not * required (obviously) but it is conventional with the definitions provided * by Fuse.</p> * * @see org.jdesktop.fuse.ResourceInjector#addDefinition(String, Definition) * @since 0.2 * @author Daniel Spiewak */ public interface Definition { /** * This method is called to determine if the field name in question * is a field which should be injected. If this method returns true, * the result is roughly analogous to tagging a field with the * <code>@InjectedResource</code> annotation. * * @param field The name of the declared field to mark for injection. * @return <code>true</code> if the field should be injected, * <code>false</code> if otherwise. */ public boolean isInjectedField(String field); /** * This method returns the value of the (optional) name * attribute of the field in question. This is roughly analogous * to the <code>@InjectedResource(name="...")</code> * attribute. * * @param field The name of the declared field for which to return the name attribute. * @return The value of the name attribute for the specified field. */ public String name(String field); /** * This method returns the value of the (optional) key * attribute of the field in question. This is roughly analogous * to the <code>@InjectedResource(key="...")</code> * attribute. * * @param field The name of the declared field for which to return the key attribute. * @return The value of the key attribute for the specified field. */ public String key(String field); /** * This method returns the value of the (optional) loader * attribute of the field in question. This is roughly analogous * to the <code>@InjectedResource(loader="...")</code> * attribute. * * @param field The name of the declared field for which to return the loader attribute. * @return The value of the loader attribute for the specified field. */ @SuppressWarnings("unchecked") public Class<? extends TypeLoader> loader(String field); }
true
afb6846f48a80b3b6627063ad88a08dc1616a4aa
Java
esposama/crcp3310
/Desktop/AliceInWonderland/build-tmp/source/AliceInWonderland.java
UTF-8
4,675
2.65625
3
[]
no_license
import processing.core.*; import processing.data.*; import processing.event.*; import processing.opengl.*; import java.util.HashMap; import java.util.ArrayList; import java.io.File; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; public class AliceInWonderland extends PApplet { //Amanda Esposito //Project 1: Visualiing text data //I took Alice in Wonderland Text and displayed the data in two different data visualizations. BufferedReader reader; final String FILENAME = "Alice.txt"; int state; final int DRAW_LETTER_STATE = 0; final int DRAW_FREQUENCIES_STATE = 1; final int LETTERS_IN_ALAPHABET = 26; final int ASCCII_OFFSET = 97; int[] frequencies = new int[LETTERS_IN_ALAPHABET]; int[] pallette = new int[LETTERS_IN_ALAPHABET]; PImage letterViz; int [] ellipsePositionX = new int [26]; int [] ellipsePositionY = new int [26]; int maxFrequency = 0; int minFrequency = Integer.MAX_VALUE; char leastFrequentLetter; char mostFrequentLetter; String possibleAlice = ""; int alice; public void setup() { for (int i = 0; i < LETTERS_IN_ALAPHABET; i++){ pallette[i] = color(random(255, 255)); } letterViz = createImage(1000, 1000, RGB); letterViz.loadPixels(); state = DRAW_LETTER_STATE; prepareFrequencies(); letterViz.updatePixels(); } public void draw() { background(100); fill(0); if (state == DRAW_LETTER_STATE){ drawLetterVisualization(); } else { drawFrequenciesGraph(); } } public void mousePressed() { state = (state + 1) % 2; } public void drawLetterVisualization() { fill(255, 100, 0); image(letterViz, 0, 0); } public void drawFrequenciesGraph() { background(255); text("Drawling all the letters.", 10, 20); text( "Max: " + maxFrequency + " Most Frequent Letter: " + mostFrequentLetter, 10, 40); text( "Min: " + minFrequency + " Least Frequent Letter: " + leastFrequentLetter, 10, 60); text( "Alice counter: " + alice, 10, 80); for (int i = 0; i < frequencies.length; ++i) { fill(pallette[i]); ellipse(ellipsePositionX[i] /2, ellipsePositionY[i]/2 , frequencies[i]/40, frequencies[i]/40); char letter = (char)(i + 97); fill(0); text(letter, ellipsePositionX[i], ellipsePositionY[i]); } } public void prepareFrequencies() { for (int i = 0; i < LETTERS_IN_ALAPHABET; i++){ frequencies[i] = 0; ellipsePositionX[i] = (int)random(width); ellipsePositionY[i] = (int)random(height); pallette[i] = color(random(0, 255), random(0, 255), random(0, 255), 150); } reader = createReader(FILENAME); int pixelPosition = 0; try { int character; while ((character = reader.read()) != -1) { if (!Character.isAlphabetic(character)) { if (possibleAlice.compareTo("alice") == 0){ alice++; } possibleAlice = ""; continue; } char letter = (char)Character.toLowerCase(character); //converts letter to lower case possibleAlice += letter; frequencies[letter - ASCCII_OFFSET]++; // lower case letter - asccii ASCCII_OFFSET for (int i = 0; i < LETTERS_IN_ALAPHABET; i++) { if (possibleAlice.compareTo("alice") == 1){ letterViz.pixels[pixelPosition] = pallette[0]; pallette[0] = color(0); } else { pallette[i] = color(random(0, 255), random(0, 255), random(0, 255), 150); letterViz.pixels[pixelPosition] = pallette[i]; } } pixelPosition++; if (frequencies[letter - ASCCII_OFFSET] > maxFrequency) { mostFrequentLetter = letter; maxFrequency = frequencies[letter - ASCCII_OFFSET]; } if (frequencies[letter - ASCCII_OFFSET] < minFrequency || leastFrequentLetter == letter) { leastFrequentLetter = letter; minFrequency = frequencies[letter - ASCCII_OFFSET]; } } } catch (IOException e) { println("Could not read data."); e.printStackTrace(); } println(frequencies); println( "max: " + maxFrequency + " Most Frequent Letter: " + mostFrequentLetter); println( "min: " + minFrequency + " Least Frequent Letter: " + leastFrequentLetter); println( "Alice counter: " + alice); } public void settings() { size (1000, 1000); } static public void main(String[] passedArgs) { String[] appletArgs = new String[] { "AliceInWonderland" }; if (passedArgs != null) { PApplet.main(concat(appletArgs, passedArgs)); } else { PApplet.main(appletArgs); } } }
true
87526853af1c5c4181da3310b1811ebbf1eda5c8
Java
zwtaitxl1314/Spring1
/src/main/java/ioc/beanCreation/constructor/Student.java
UTF-8
755
3.28125
3
[]
no_license
package ioc.beanCreation.constructor; import java.util.Date; public class Student { private Integer id; private String name; private char gender; public Student() { super(); } public Student(Integer id, String name) { super(); this.id = id; this.name = name; } public Student(Integer id, String name, Date birthdate, char gender) { super(); this.id = id; this.name = name; this.gender = gender; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public char getGender() { return gender; } public void setGender(char gender) { this.gender = gender; } }
true
b540020bb437fcbbcb885091255b4c4ef710827c
Java
darionyaphet/algorithms
/src/org/darion/yaphet/lintcode/ValidParentheses.java
UTF-8
1,436
3.65625
4
[]
no_license
package org.darion.yaphet.lintcode; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.Stack; /** * http://www.lintcode.com/zh-cn/problem/valid-parentheses/ * * @author darion.yaphet * */ public class ValidParentheses { /** * @param s * A string * @return whether the string is a valid parentheses */ public boolean isValidParentheses(String s) { if (s == null || s.length() == 0) { return false; } if (s.length() % 2 != 0) { return false; } Set<Character> set = new HashSet<Character>(); set.add('['); set.add('('); set.add('{'); Map<Character, Character> map = new HashMap<Character, Character>(); map.put(')', '('); map.put(']', '['); map.put('}', '{'); Stack<Character> stack = new Stack<Character>(); for (char element : s.toCharArray()) { if (!map.keySet().contains(element)) { stack.add(element); } else { Character topElement = stack.pop(); if (!map.get(element).equals(topElement)) { return false; } } } if (stack.size() == 0) { return true; } else { return false; } } public static void main(String[] args) { ValidParentheses instance = new ValidParentheses(); String s = "()[]{}"; s = "([)]"; s = "("; s = null; s = "({[()]})"; s = "([)"; s = "[({(())}[()])]"; s = "(("; System.out.println(instance.isValidParentheses(s)); } }
true
a93b5ea0b37aabee10367e3dec5614660b922c59
Java
andrey-ko/satori-composer
/composer/src/com/satori/composer/rtm/core/RtmRelaxingState.java
UTF-8
681
2.5625
3
[ "BSD-2-Clause" ]
permissive
package com.satori.composer.rtm.core; public class RtmRelaxingState extends RtmState<IRtmContext, RtmRelaxingState.Exit> { public final long delay; public RtmRelaxingState(IRtmContext ctx, long delay) { super(ctx); this.delay = delay; } @Override public boolean enter(Runnable exitHandler) { if (!super.enter(exitHandler)) { return false; } return true; } @Override public void onPulse(long timestamp) { if (checkNotCompleted() && age(timestamp) > delay) { succeed(Exit.started); } } @Override public void stop() { succeed(Exit.stopped); } public enum Exit { started, stopped } }
true
aa45bbfc75242fd59f229b694e3f2431cde2b25d
Java
MorningSage/Mekanism-Fabric
/src/api/java/mekanism/api/providers/IPigmentProvider.java
UTF-8
372
2.328125
2
[ "MIT" ]
permissive
package mekanism.api.providers; import mekanism.api.chemical.pigment.Pigment; import mekanism.api.chemical.pigment.PigmentStack; import javax.annotation.Nonnull; public interface IPigmentProvider extends IChemicalProvider<Pigment> { @Nonnull @Override default PigmentStack getStack(long size) { return new PigmentStack(getChemical(), size); } }
true
e43df1995bdfcc52fb5fe68b15726074d4239cb5
Java
chaitanyakakarala/examples
/file-handler/src/test/java/com/kc/demo/util/CommonUtilTest.java
UTF-8
1,322
2.75
3
[]
no_license
package com.kc.demo.util; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Test; // TODO: Auto-generated Javadoc /** * The Class CommonUtilTest. */ public class CommonUtilTest { /** * Testrepeat split with seperator. */ @Test public void testrepeatSplitWithSeperator(){ String input = "24-Jul-2010,35,24,43,33,26,44,27,3,MERLIN"; List<String> result = new ArrayList<String>(0); result = CommonUtil.repeatSplitWithSeperator(input, result); Assert.assertFalse(result.isEmpty()); Assert.assertEquals("35", result.get(1)); } /** * Testrepeat split with seperator null chk. */ @Test public void testrepeatSplitWithSeperator_NullChk(){ List<String> result = new ArrayList<String>(0); result = CommonUtil.repeatSplitWithSeperator(null, result); Assert.assertTrue(result.isEmpty()); } /** * Test is nan. */ @Test public void testIsNan(){ Assert.assertTrue(CommonUtil.isNaN("456789")); Assert.assertFalse(CommonUtil.isNaN("123sfa0")); Assert.assertFalse(CommonUtil.isNaN(null)); } /** * Test is date. */ @Test public void testIsDate(){ Assert.assertTrue(CommonUtil.isDate("28-Jul-1990")); Assert.assertFalse(CommonUtil.isDate("30021990")); } }
true
7634db6764283db7038cc593ac6a04b45f1f1f72
Java
sergiifedotov/OOP
/alexandr_lapada/src/main/java/hw2/frequency/FreqTest.java
UTF-8
995
3
3
[]
no_license
package hw2.frequency; import java.io.*; import java.util.*; /** * Created by sanya on 22.01.2015. */ public class FreqTest { public static void main(String[] args) { Freq freq = new Freq(); try { // System.out.println(freq.setTextFromConsole()); // System.out.println(freq.setTextFromFile("freqFile.txt")); //System.out.println(freq.generateRandomText(25)); //Set<String> hashSet = freq.getWordsByFrequency(3); /* Set<String> hashSet = freq.getWordsByFrequencyMoreThan(10); Iterator<String> iter = hashSet.iterator(); //System.out.println("size = "+hashSet.size()); while(iter.hasNext()){ System.out.println(iter.next()); }*/ freq.printAcs(); System.out.println("-------------------------"); freq.printDesc(); }catch(IOException e){ System.out.println("file not found"); } } }
true
7b60a6a065151de832a89a7ff89b153a4b868ce6
Java
Canardou/ptut
/Simulator 3/src/Gui.java
UTF-8
5,063
2.53125
3
[]
no_license
import java.awt.Dimension; import java.awt.Font; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JTextField; import javax.swing.SwingWorker; import Dialogue.Dialogue; import java.awt.BorderLayout; import drawing.DessinCarte; import drawing.FontImport; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @SuppressWarnings("serial") public class Gui extends JFrame implements ActionListener { private RobotPanel [] robots; private Font comic = FontImport.getFont("ComicRelief.ttf"); private Font bcomic = FontImport.getFont("ComicRelief-Bold.ttf"); private Superviseur superviseur; private DessinCarte laby; private JButton start; private JButton stop; private JButton simuler; private JTextField seed; private JCheckBox doge; private SwingWorker<String, Object> thread; public Gui(Superviseur superviseur){ this.setTitle("Dogeberto v 1.7.0.1b Final-bis Stable ULTIMATE"); this.superviseur=superviseur; //Labyrinth sur le cote gauche this.laby = superviseur.dessinCarte(); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.getContentPane().add(this.laby, BorderLayout.WEST); //Robots sur le cote droit JPanel panel = new JPanel(); this.getContentPane().add(panel, BorderLayout.EAST); //Aligne verticalement les boites robots Box tempBox = Box.createVerticalBox(); tempBox.setEnabled(false); panel.add(tempBox); robots = new RobotPanel[3]; for(int i=0;i<3;i++){ robots[i]=new RobotPanel(laby,i); tempBox.add(robots[i]); } JPanel panel2 = new JPanel(); this.getContentPane().add(panel2, BorderLayout.SOUTH); Box tempHoriBox = Box.createHorizontalBox(); panel2.add(tempHoriBox); start = new JButton("Commencer"); start.setFont(this.bcomic.deriveFont(12f)); start.addActionListener(this); tempHoriBox.add(start); tempHoriBox.add(Box.createRigidArea(new Dimension(5,0))); stop = new JButton("Arreter"); stop.setFont(this.bcomic.deriveFont(12f)); stop.addActionListener(this); stop.setVisible(false); tempHoriBox.add(stop); simuler = new JButton("Simulation"); simuler.setFont(this.bcomic.deriveFont(12f)); simuler.addActionListener(this); tempHoriBox.add(simuler); tempHoriBox.add(Box.createRigidArea(new Dimension(5,0))); seed = new JTextField(); seed.setText("100"); seed.setFont(this.comic.deriveFont(12f)); tempHoriBox.add(seed); seed.setColumns(5); tempHoriBox.add(Box.createRigidArea(new Dimension(5,0))); doge = new JCheckBox("Doge"); doge.addActionListener(this); tempHoriBox.add(doge); this.pack(); this.setVisible(true); } public void updatePanel(){ for(int i=0;i<3;i++){ robots[i].setPanel(laby.getRobot(i).getX(), laby.getRobot(i).getY(), laby.getRobot(i).getDir()); } } public void putLog(int i, String s){ robots[i].putLog(s); } public void reset(){ for(int i=0;i<3;i++){ robots[i].resetLog(); } } public void arreter(){ //this.superviseur.end(); this.thread.cancel(true); for(int i=0;i<3;i++){ robots[i].unfreeze(); } this.start.setVisible(true); this.stop.setVisible(false); this.simuler.setVisible(true); this.seed.setVisible(true); this.seed.setEnabled(true); } @Override public void actionPerformed(ActionEvent e) { if(e.getActionCommand().compareTo("Simulation")==0){ this.start.setVisible(false); this.stop.setVisible(true); this.simuler.setVisible(false); this.seed.setEnabled(false); for(int i=0;i<3;i++){ robots[i].freeze(); } class YOLO extends SwingWorker<String, Object> {//I HAVE NO IDEA WHAT IM DOING RIGHT NOW @Override public String doInBackground() { try{ Gui.this.superviseur.simulation(Integer.parseInt(seed.getText())); }catch(InterruptedException ie){ Dialogue.Warning("Arret de la simulation"); }catch(Exception e){ e.printStackTrace(); } return null; } @Override protected void done() { Gui.this.arreter(); } } (thread=new YOLO()).execute(); //this.superviseur.simulate(); } if(e.getActionCommand().compareTo("Arreter")==0){ this.arreter(); } if(e.getActionCommand().compareTo("Commencer")==0){ this.start.setVisible(false); this.stop.setVisible(true); this.simuler.setVisible(false); this.seed.setVisible(false); for(int i=0;i<3;i++){ robots[i].freeze(); } class YOLO extends SwingWorker<String, Object> {//I HAVE NO IDEA WHAT IM DOING RIGHT NOW @Override public String doInBackground() { try{ Gui.this.superviseur.destin(); }catch(InterruptedException ie){ Dialogue.Warning("Arret de la supervision"); }catch(Exception e){ e.printStackTrace(); } return null; } @Override protected void done() { Gui.this.arreter(); } } (thread=new YOLO()).execute(); } if(e.getActionCommand().compareTo("Doge")==0){ this.laby.toggleDoge(); } } }
true
74baea9e7351f8de08722d724bb984fe0373ff26
Java
adi160791/all-projects
/ekart/src/main/java/com/niit/ekart/dao/CartDao.java
UTF-8
210
1.578125
2
[]
no_license
package com.niit.ekart.dao; import java.util.List; import com.niit.ekart.model.Cart; import com.niit.ekart.model.CartItems; public interface CartDao { public void addCart(Cart c); }
true
5d59ecbebf4a7d869cb0b7f46bd2eb8f847f8449
Java
chaseDeveloper/hsco
/hsco/src/main/java/hsco/pms/sls/hou/ctr/SLS020102/SLS020102ServiceImpl.java
UTF-8
29,188
1.726563
2
[]
no_license
package hsco.pms.sls.hou.ctr.SLS020102; import java.text.ParseException; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.nexacro.xapi.data.DataSet; import egovframework.rte.fdl.property.impl.EgovPropertyServiceImpl; import hsco.cmm.exception.NexaServiceException; import hsco.cmm.ria.nexacro.NexacroConstant; import hsco.cmm.ria.nexacro.map.DataSetMap; import hsco.cmm.service.BaseService; import hsco.cmm.util.DateUtil; import hsco.cmm.util.ObjectUtil; /** * <pre> * @Project Name : 화성도시공사 차세대정보시스템 * @Class Name : SLS020102ServiceImpl.java * @Description : 주택계약 해약처리(분양) 관리 ServiceImpl * @author : 정윤원 * @since : 2015. 10.26. * @version : 1.0 * @see : * @COPYRIGHT (c) 2015 나눔아이씨티, Inc. All Right Reserved. * * <pre> * ------------------------------------------------------------------ * Modification Information * ------------------------------------------------------------------ * 작성일 작성자 내용 * ------------------------------------------------------------------ * * </pre> */ @Service("SLS020102Service") public class SLS020102ServiceImpl extends BaseService implements SLS020102Service { protected Logger log = LoggerFactory.getLogger(this.getClass()); /** Properties Service */ @Resource(name = "propertiesService") protected EgovPropertyServiceImpl propertiesService; /** * 주택계약자 해약 리스트 조회(공통) * @param (DataSetMap, inVar, inDataset, outVar, outDataset) * @return void * @throws NexaServiceException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void selectHouseCancelList(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { DataSetMap inDsMap = (DataSetMap) inDataset.get("input1"); Map inMap = null; if (inDsMap != null) inMap = inDsMap.get(0); List<Map> records; records = (List<Map>)baseDao.list("SLS020102DAO.selectHouseCancelList", inMap); DataSetMap outDsMap = new DataSetMap(); outDsMap.setRowMaps(records); outDataset.put("output1", outDsMap); } /** * 주택분양 해약 리스트 조회 * @param (DataSetMap, inVar, inDataset, outVar, outDataset) * @return void * @throws NexaServiceException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void selectHouseLttotCancelList(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { DataSetMap inDsMap = (DataSetMap) inDataset.get("input1"); Map inMap = null; if (inDsMap != null) inMap = inDsMap.get(0); List<Map> records; records = (List<Map>)baseDao.list("SLS020102DAO.selectHouseLttotCancelList", inMap); DataSetMap outDsMap = new DataSetMap(); outDsMap.setRowMaps(records); outDataset.put("output1", outDsMap); } /** * 주택계약 해약 리스트 조회(임대) * @param (DataSetMap, inVar, inDataset, outVar, outDataset) * @return void * @throws NexaServiceException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void selectHouseRentCancelList(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { DataSetMap inDsMap = (DataSetMap) inDataset.get("input1"); Map inMap = null; if (inDsMap != null) inMap = inDsMap.get(0); List<Map> records; records = (List<Map>)baseDao.list("SLS020102DAO.selectHouseRentCancelList", inMap); DataSetMap outDsMap = new DataSetMap(); outDsMap.setRowMaps(records); outDataset.put("output1", outDsMap); } /** * 주택계약자 압류정보 조회 * @param (DataSetMap, inVar, inDataset, outVar, outDataset) * @return void * @throws NexaServiceException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void selectHcntrctrSeizrInfo(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { DataSetMap inDsMap = (DataSetMap) inDataset.get("input1"); Map inMap = null; if (inDsMap != null) inMap = inDsMap.get(0); List<Map> records; records = (List<Map>)baseDao.list("SLS020102DAO.selectHcntrctrSeizrInfo", inMap); DataSetMap outDsMap = new DataSetMap(); outDsMap.setRowMaps(records); outDataset.put("output1", outDsMap); } /** * 주택분양 이율정보조회 * @param (DataSetMap, inVar, inDataset, outVar, outDataset) * @return void * @throws NexaServiceException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void selectLttotRatioInfo(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { DataSetMap inDsMap = (DataSetMap) inDataset.get("input1"); Map inMap = null; if (inDsMap != null) inMap = inDsMap.get(0); List<Map> records; records = (List<Map>)baseDao.list("SLS020102DAO.selectLttotRatioInfo", inMap); DataSetMap outDsMap = new DataSetMap(); outDsMap.setRowMaps(records); outDataset.put("output1", outDsMap); } /** * 주택임대 이율정보조회 * @param (DataSetMap, inVar, inDataset, outVar, outDataset) * @return void * @throws NexaServiceException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void selectRentRatioInfo(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { DataSetMap inDsMap = (DataSetMap) inDataset.get("input1"); Map inMap = null; if (inDsMap != null) inMap = inDsMap.get(0); List<Map> records; records = (List<Map>)baseDao.list("SLS020102DAO.selectRentRatioInfo", inMap); DataSetMap outDsMap = new DataSetMap(); outDsMap.setRowMaps(records); outDataset.put("output1", outDsMap); } /** * 주택계약 해약(분양) 반환금 조회 * @param (DataSetMap, inVar, inDataset, outVar, outDataset) * @return void * @throws NexaServiceException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void selectHouseLttotCancelReturnAmtList(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { DataSetMap inDsMap = (DataSetMap) inDataset.get("input1"); Map inMap = null; if (inDsMap != null) inMap = inDsMap.get(0); List<Map> records; records = (List<Map>)baseDao.list("SLS020102DAO.selectHouseLttotCancelReturnAmtList", inMap); DataSetMap outDsMap = new DataSetMap(); outDsMap.setRowMaps(records); outDataset.put("output1", outDsMap); } /** * 주택 계약자 해약정보(분양) 저장 * @param (DataSetMap, inVar, inDataset, outVar, outDataset) * @return int * @throws NexaServiceException */ @SuppressWarnings({ "rawtypes" }) public int saveHouseCancelInfo(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { int iRow = 0; DataSetMap list = (DataSetMap) inDataset.get("input1"); //주택계약자해약 DataSetMap list2 = (DataSetMap) inDataset.get("input2"); //주택분양해약 int listSize = (list==null) ? 0 : list.size(); log.debug("++++++++++++++++++++++++++++++++listSize:"+listSize); for (int x = 0; x < listSize; x++) { Map map = list.get(x); //주택계약 해약정보 Map map2 = list2.get(x); //주택 분양 해약정보 int rowType = ((Integer) map.get(NexacroConstant.DATASET_ROW_TYPE)).intValue(); switch(rowType) { case DataSet.ROW_TYPE_INSERTED : //(1)해약정보 등록 baseDao.insert("SLS020102DAO.insertHouseCancelInfo" , map); //입력 //(1-1) 주택 분양 해약정보 등록 baseDao.insert("SLS020102DAO.insertHouseLttotCancelInfo" , map2); //입력 //(2)납부정보 해약 수정- 해지가 발생하며 입금되지 않은 납부정보에 대해서는 조회되지 않게 처리한다 iRow += baseDao.update("SLS020102DAO.updateCancelLttotPayList", map); //수정 //(3)주택계약정보 해약처리 iRow += baseDao.update("SLS020102DAO.updateCancelHcntrctrInfo", map); //수정 //(4-1)주택결제정보 해지등록(임대인경우,임대료 결제 정보수정)--삭제 //baseDao.insert("SLS020102DAO.insertHouseCancelSetleInfo" , map); //입력 //(4-2)주택결제정보 해지처리(임대인경우,임대료 결제 정보수정) iRow += baseDao.update("SLS020102DAO.updateCancelSetleInfo" , map); //수정 //(5) 기타수입납부 등록 : 위약금 2016.03.29 baseDao.insert("SLS020102DAO.insertEtcIncmePay" , map); //입력 break; case DataSet.ROW_TYPE_UPDATED : //업데이트는 임대해약시 유보금, 시설점검 내역만 업데이트 가능 iRow += baseDao.update("SLS020102DAO.updateHouseCancelInfo", map); //수정 break; case DataSet.ROW_TYPE_DELETED : //(1)주택계약정보 해약취소 iRow += baseDao.update("SLS020102DAO.updateHcntrctrInfo" , map); //수정 //(2)납부정보 해약 취소 iRow += baseDao.update("SLS020102DAO.updateLttotPayList" , map); //수정 //(3)주택 분양 해약정보 삭제 iRow += baseDao.delete("SLS020102DAO.deleteHouseLttotCancelInfo" , map2); //삭제 //(5)주택 해약정보삭제 iRow += baseDao.delete("SLS020102DAO.deleteHcntrctrCancelInfo" , map); //삭제 //(6)기타수입납부 삭제 2016.03.30 iRow += baseDao.delete("SLS020102DAO.deleteEtcIncmePay" , map); //삭제 break; } } return iRow; } /** * 주택계약 해약(임대) 반환금 조회 * @param (DataSetMap, inVar, inDataset, outVar, outDataset) * @return void * @throws NexaServiceException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void selectHouseCancelRentReturnAmtList(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { DataSetMap inDsMap = (DataSetMap) inDataset.get("input1"); Map inMap = null; if (inDsMap != null) inMap = inDsMap.get(0); List<Map> records; records = (List<Map>)baseDao.list("SLS020102DAO.selectHouseCancelRentReturnAmtList", inMap); DataSetMap outDsMap = new DataSetMap(); outDsMap.setRowMaps(records); outDataset.put("output1", outDsMap); } /** * 주택계약 해약(임대) 임대 납부 보증금 조회 * @param (DataSetMap, inVar, inDataset, outVar, outDataset) * @return void * @throws NexaServiceException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void selectRenLttotPayList(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { DataSetMap inDsMap = (DataSetMap) inDataset.get("input1"); Map inMap = null; if (inDsMap != null) inMap = inDsMap.get(0); List<Map> records; records = (List<Map>)baseDao.list("SLS020102DAO.selectRenLttotPayList", inMap); DataSetMap outDsMap = new DataSetMap(); outDsMap.setRowMaps(records); outDataset.put("output1", outDsMap); } /** * 주택 계약자 해약정보(임대) 저장 * @param (DataSetMap, inVar, inDataset, outVar, outDataset) * @return * @throws NexaServiceException * @throws ParseException */ @SuppressWarnings({ "rawtypes", "unchecked" }) public int saveHouseRentCancelInfo(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException, ParseException { int iRow = 0; DataSetMap list = (DataSetMap) inDataset.get("input1"); //주택계약자해약 DataSetMap list2 = (DataSetMap) inDataset.get("input2"); //주택분양해약 int listSize = (list==null) ? 0 : list.size(); log.debug("++++++++++++++++++++++++++++++++listSize:"+listSize); for (int x = 0; x < listSize; x++) { Map map = list.get(x); //주택계약 해약정보 Map map2 = list2.get(x); //주택 분양 해약정보 int rowType = ((Integer) map.get(NexacroConstant.DATASET_ROW_TYPE)).intValue(); System.out.println("rowType : " + rowType); switch(rowType) { case DataSet.ROW_TYPE_INSERTED : //(1)해약정보 등록 baseDao.insert("SLS020102DAO.insertHouseCancelInfo" , map); //입력 //(1-1) 주택 임대 해약정보 등록 baseDao.insert("SLS020102DAO.insertHouseRentCancelInfo" , map2); //입력 //(1-2) 주택 임대 시설물/시설물보수 부담액 등록 //baseDao.insert("SLS020102DAO.insertRentCancelChckDspthInfo" , map); //입력 //(2)납부정보 해약 수정- 해지가 발생하며 입금되지 않은 납부정보에 대해서는 조회되지 않게 처리한다 iRow += baseDao.update("SLS020102DAO.updateCancelLttotPayList", map); //수정 //(3)주택계약정보 해약처리 iRow += baseDao.update("SLS020102DAO.updateCancelHcntrctrInfo", map); //수정 //(4-1)주택결제정보 해지등록(임대인경우,임대료 결제 정보수정)--삭제 //baseDao.insert("SLS020102DAO.insertHouseCancelSetleInfo" , map); //입력 //(4-2)주택결제정보 해지처리(임대인경우,임대료 결제 정보수정) iRow += baseDao.update("SLS020102DAO.updateCancelSetleInfo" , map); //수정 //(5) 기타수입납부 등록 : 위약금 2016.03.29 if ("1".equals(map.get("PENLTY_APPLC_AT").toString())) { baseDao.insert("SLS020102DAO.insertEtcIncmePay" , map); //입력 } //(6)해약처리/해약취소 시 월 임대료 조정 2016.03.31 Map map4 = list.get(x); map4.put("IN_FLAG", "C"); map4.put("IN_FLAG1", ""); map4.put("IN_CNTRCTR_NO", map.get("CNTRCTR_NO").toString());//계약번호 map4.put("IN_APPLY_DATE", map.get("CANCL_DE").toString());//해약일자 map4.put("IN_MDAT_DE", map.get("CANCL_DE").toString());//해약일자 map4.put("IN_REGISTER_ID", String.valueOf(ObjectUtil.getSessionObj("S_USER_ID")));//등록자ID map4.put("IN_HOUSE_CODE", map.get("HOUSE_CODE").toString());//주택코드 map4.put("IN_CAL_DATE", map.get("RCEPT_DE").toString());//접수일자 map4.put("OUT_RESULT_CD", "0"); map4.put("OUT_RESULT_MSG", ""); baseDao.update("SLS020102DAO.SPSLS_HOUSE_RENT_PAY_CANCEL_UI", map4); if (!"0".equals(map4.get("OUT_RESULT_CD").toString())) { throw new NexaServiceException("info.메시지", map4.get("OUT_RESULT_MSG").toString()); } break; case DataSet.ROW_TYPE_UPDATED : //업데이트는 임대해약시 유보금, 시설점검 내역만 업데이트 가능 //iRow += baseDao.update("SLS020102DAO.updateHouseCancelInfo", map); //수정 break; case DataSet.ROW_TYPE_DELETED : //(1)주택계약정보 해약취소 iRow += baseDao.update("SLS020102DAO.updateHcntrctrInfo" , map); //수정 //(2)납부정보 해약 취소 iRow += baseDao.update("SLS020102DAO.updateLttotPayList" , map); //수정 //(3-A)주택 임대 점검의뢰 내용삭제 iRow += baseDao.delete("SLS020102DAO.deleteHouseCheckReqest" , map); //삭제 //(3-B)주택 임대 점검통보 내용삭제 iRow += baseDao.delete("SLS020102DAO.deleteHouseCheckDspth" , map); //삭제 //(3-C)주택 임대 해약 정보 삭제 iRow += baseDao.delete("SLS020102DAO.deleteHouseRentCancelInfo" , map2); //삭제 //(4)주택 해약정보삭제 iRow += baseDao.delete("SLS020102DAO.deleteHcntrctrCancelInfo" , map); //삭제 //(6)기타수입납부 삭제 2016.03.30 iRow += baseDao.delete("SLS020102DAO.deleteEtcIncmePay" , map); //삭제 //(7)차액금액 가져오기 2016.04.01 String dfnntAmount = selectDfnntAmount(map); //System.out.println("dfnntAmount============================> " + dfnntAmount); //감액조정이 된 경우 감액금액 및 감액결의서를 삭제한다. if(!"0".equals(dfnntAmount)){ baseDao.update("SLS020102DAO.updateDfnntAmount" , map); //차액금액 수정 map.put("DECSN_SE", "4"); baseDao.delete("SLS020102DAO.deleteHouseDecsn" , map); //주택결의 삭제 } else{ String canclDe = map.get("CANCL_DE").toString();//해약일자 String lastDay = DateUtil.lastDayOfMonth(canclDe, "yyyyMMdd"); //System.out.println("canclDe============================> " + canclDe); //System.out.println("lastDay============================> " + lastDay); //해약일자가 당월 말일인 경우 해당월의 임대료는 재조정되지않으므로 삭제하지않음. if(!canclDe.equals(lastDay)){ baseDao.delete("SLS020102DAO.deleteHouseRentPay" , map); //당월임대료 삭제 map.put("DECSN_SE", "1"); baseDao.delete("SLS020102DAO.deleteHouseDecsn" , map); //주택결의 삭제 } } break; } } return iRow; } /** * 주택 계약자 해약정보(임대) 삭제 * @param (DataSetMap, inVar, inDataset, outVar, outDataset) * @return * @throws NexaServiceException * @throws ParseException */ @SuppressWarnings({ "rawtypes", "unchecked" }) public int deleteHouseRentCancelInfo(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException, ParseException { int iRow = 0; DataSetMap list = (DataSetMap) inDataset.get("input1"); //주택계약자해약 //DataSetMap list2 = (DataSetMap) inDataset.get("input2"); //주택분양해약 int listSize = (list==null) ? 0 : list.size(); log.debug("++++++++++++++++++++++++++++++++listSize:"+listSize); Map map = list.get(0); //주택계약 해약정보 //Map map2 = list2.get(0); //주택 분양 해약정보 //(1)주택계약정보 해약취소 iRow += baseDao.update("SLS020102DAO.updateHcntrctrInfo" , map); //수정 //(2)납부정보 해약 취소 iRow += baseDao.update("SLS020102DAO.updateLttotPayList" , map); //수정 //(3-A)주택 임대 점검의뢰 내용삭제 iRow += baseDao.delete("SLS020102DAO.deleteHouseCheckReqest" , map); //삭제 //(3-B)주택 임대 점검통보 내용삭제 iRow += baseDao.delete("SLS020102DAO.deleteHouseCheckDspth" , map); //삭제 //(3-C)주택 임대 해약 정보 삭제 iRow += baseDao.delete("SLS020102DAO.deleteHouseRentCancelInfo" , map); //삭제 //(4)주택 해약정보삭제 iRow += baseDao.delete("SLS020102DAO.deleteHcntrctrCancelInfo" , map); //삭제 //(6)기타수입납부 삭제 2016.03.30 iRow += baseDao.delete("SLS020102DAO.deleteEtcIncmePay" , map); //삭제 //(7)차액금액 가져오기 2016.04.01 String dfnntAmount = selectDfnntAmount(map); //System.out.println("dfnntAmount============================> " + dfnntAmount); //감액조정이 된 경우 감액금액 및 감액결의서를 삭제한다. if(!"0".equals(dfnntAmount)){ baseDao.update("SLS020102DAO.updateDfnntAmount" , map); //차액금액 수정 map.put("DECSN_SE", "4"); baseDao.delete("SLS020102DAO.deleteHouseDecsn" , map); //주택결의 삭제 } else{ String canclDe = map.get("CANCL_DE").toString();//해약일자 String lastDay = DateUtil.lastDayOfMonth(canclDe, "yyyyMMdd"); //System.out.println("canclDe============================> " + canclDe); //System.out.println("lastDay============================> " + lastDay); //해약일자가 당월 말일인 경우 해당월의 임대료는 재조정되지않으므로 삭제하지않음. if(!canclDe.equals(lastDay)){ baseDao.delete("SLS020102DAO.deleteHouseRentPay" , map); //당월임대료 삭제 map.put("DECSN_SE", "1"); baseDao.delete("SLS020102DAO.deleteHouseDecsn" , map); //주택결의 삭제 } } return iRow; } //차액금액 @SuppressWarnings("rawtypes") public String selectDfnntAmount(Map map) { String dfnntAmount = (String)baseDao.select("SLS020102DAO.selectDfnntAmount", map); if(dfnntAmount == null){ dfnntAmount = "0"; } return dfnntAmount; } /** * 주택계약 해약정보(임대) -시설점검의뢰 조회 * @param (DataSetMap, inVar, inDataset, outVar, outDataset) * @return void * @throws NexaServiceException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void selectRentCancelChckReqestInfo(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { DataSetMap inDsMap = (DataSetMap) inDataset.get("input1"); Map inMap = null; if (inDsMap != null) inMap = inDsMap.get(0); List<Map> records; records = (List<Map>)baseDao.list("SLS020102DAO.selectRentCancelChckReqestInfo", inMap); DataSetMap outDsMap = new DataSetMap(); outDsMap.setRowMaps(records); outDataset.put("output1", outDsMap); } /** * 주택계약 해약정보(임대) -시설점검의뢰 저장 * @param (DataSetMap, inVar, inDataset, outVar, outDataset) * @return * @throws NexaServiceException */ @SuppressWarnings({ "rawtypes" }) public int saveRentCancelChckReqestInfo(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { int iRow = 0; DataSetMap list = (DataSetMap) inDataset.get("input1"); //주택계약자해약 int listSize = (list==null) ? 0 : list.size(); log.debug("++++++++++++++++++++++++++++++++listSize:"+listSize); for (int x = 0; x < listSize; x++) { Map map = list.get(x); //주택계약 해약정보 int rowType = ((Integer) map.get(NexacroConstant.DATASET_ROW_TYPE)).intValue(); System.out.println("rowType :" + rowType); //해약정보 등록 baseDao.insert("SLS020102DAO.insertRentCancelReqestInfo" , map); //입력 } return iRow; } /** * 주택계약 해약정보(임대) -시설점검의뢰 수정 * @param (DataSetMap, inVar, inDataset, outVar, outDataset) * @return * @throws NexaServiceException */ @SuppressWarnings({ "rawtypes" }) public int updateRentCancelChckReqestInfo(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { int iRow = 0; DataSetMap list = (DataSetMap) inDataset.get("input1"); //주택계약자해약 int listSize = (list==null) ? 0 : list.size(); log.debug("++++++++++++++++++++++++++++++++listSize:"+listSize); Map map = list.get(0); int rowType = ((Integer) map.get(NexacroConstant.DATASET_ROW_TYPE)).intValue(); System.out.println("rowType :" + rowType); //업데이트는 임대해약시 유보금, 시설점검 내역만 업데이트 가능 iRow += baseDao.update("SLS020102DAO.updateRentCancelReqestInfo", map); //수정 return iRow; } /** * 주택계약 해약정보(임대) -시설점검 통보 조회 * @param (DataSetMap, inVar, inDataset, outVar, outDataset) * @return void * @throws NexaServiceException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void selectRentCancelChckDspthInfo(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { DataSetMap inDsMap = (DataSetMap) inDataset.get("input1"); Map inMap = null; if (inDsMap != null) inMap = inDsMap.get(0); List<Map> records; records = (List<Map>)baseDao.list("SLS020102DAO.selectRentCancelChckDspthInfo", inMap); DataSetMap outDsMap = new DataSetMap(); outDsMap.setRowMaps(records); outDataset.put("output1", outDsMap); } /** * 주택계약 해약정보(임대) -시설점검 통보 첨부파일 조회 * @param (DataSetMap, inVar, inDataset, outVar, outDataset) * @return void * @throws NexaServiceException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void selectDspthFileList(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { DataSetMap inDsMap = (DataSetMap) inDataset.get("input1"); Map inMap = null; if (inDsMap != null) inMap = inDsMap.get(0); List<Map> records; records = (List<Map>)baseDao.list("SLS020102DAO.selectDspthFileList", inMap); DataSetMap outDsMap = new DataSetMap(); outDsMap.setRowMaps(records); outDataset.put("output1", outDsMap); } /** * 전자결제번호 입력 * @param (DataSetMap, inVar, inDataset, outVar, outDataset) * @return int * @throws NexaServiceException */ @SuppressWarnings({ "rawtypes" }) public void approveU(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { DataSetMap list = (DataSetMap) inDataset.get("input1"); //List <Map> records; Map map = list.get(0); baseDao.update("SLS020102DAO.approveU", map); DataSetMap outDsMap = new DataSetMap(); outDsMap.add(map); outDataset.put("output1", outDsMap); } //시설점검의뢰 @SuppressWarnings({ "rawtypes" }) public void approveU2(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { DataSetMap list = (DataSetMap) inDataset.get("input1"); //List <Map> records; Map map = list.get(0); baseDao.update("SLS020102DAO.approveU2", map); DataSetMap outDsMap = new DataSetMap(); outDsMap.add(map); outDataset.put("output1", outDsMap); } //시설물전자결재 @SuppressWarnings({ "rawtypes" }) public void approveFclts(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { DataSetMap list = (DataSetMap) inDataset.get("input1"); //List <Map> records; Map map = list.get(0); baseDao.update("SLS020102DAO.approveFclts", map); DataSetMap outDsMap = new DataSetMap(); outDsMap.add(map); outDataset.put("output1", outDsMap); } //시설보수부담액 납부정보 업데이트 @SuppressWarnings({ "rawtypes" }) public void updateHouseRentCancelInfo(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { DataSetMap list = (DataSetMap) inDataset.get("input1"); //List <Map> records; Map map = list.get(0); baseDao.update("SLS020102DAO.updateHouseRentCancelInfo", map); DataSetMap outDsMap = new DataSetMap(); outDsMap.add(map); outDataset.put("output1", outDsMap); } }
true
4b9466cec2b6b7341838be50f59e002d0aa63d8b
Java
snbaby/rebot
/src/main/java/com/seadun/rebot/rest/AuthController.java
UTF-8
6,243
2.09375
2
[]
no_license
/** * */ package com.seadun.rebot.rest; import java.util.Date; import java.util.List; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.seadun.rebot.constant.RebotExceptionConstants; import com.seadun.rebot.entity.Log; import com.seadun.rebot.entity.RebotException; import com.seadun.rebot.entity.User; import com.seadun.rebot.mapper.DepartmentMapper; import com.seadun.rebot.mapper.LogMapper; import com.seadun.rebot.mapper.RoleMapper; import com.seadun.rebot.mapper.UserMapper; import com.seadun.rebot.response.ResponseSuccessResult; import lombok.extern.slf4j.Slf4j; /** * @author Paul * */ @RestController @RequestMapping("api/auth") @Slf4j public class AuthController { @Autowired private UserMapper userMapper; @Autowired private RoleMapper roleMapper; @Autowired private DepartmentMapper departmentMapper; @Autowired private LogMapper logMapper; @RequestMapping(value = "login", method = RequestMethod.POST) @ResponseBody public ResponseEntity<ResponseSuccessResult> postAuthToken(HttpServletRequest request, @RequestBody User user) throws Exception { log.debug(">>>>>user login:{}", JSON.toJSONString(user)); if (StringUtils.isBlank(user.getUserName()) || StringUtils.isBlank(user.getUserPassword())) { throw new RebotException(RebotExceptionConstants.USER_VALID_FAILD_CODE, RebotExceptionConstants.USER_VALID_FAILD_MESSAGE, RebotExceptionConstants.USER_VALID_FAILD_HTTP_STATUS); } List<User> userList = userMapper.select(user); if (userList.size() == 0) { throw new RebotException(RebotExceptionConstants.USER_VALID_FAILD_CODE, RebotExceptionConstants.USER_VALID_FAILD_MESSAGE, RebotExceptionConstants.USER_VALID_FAILD_HTTP_STATUS); } else if (userList.size() > 1) { throw new RebotException(RebotExceptionConstants.INTERNAL_SERVER_ERROR_CODE, RebotExceptionConstants.INTERNAL_SERVER_ERROR_MESSAGE, RebotExceptionConstants.INTERNAL_SERVER_ERROR_HTTP_STATUS); } else { request.getSession().setAttribute("isLogin", "yes");// 登录成功 request.getSession().setAttribute("username", user.getUserName());// 登录成功 request.getSession().setAttribute("userId", userList.get(0).getId());// 登录成功 request.getSession().setMaxInactiveInterval(4 * 60 * 60); } Log log = new Log(); log.setId(UUID.randomUUID().toString()); log.setUserId(request.getSession().getAttribute("userId").toString()); log.setUserName(request.getSession().getAttribute("username").toString()); log.setMessage("用户" + request.getSession().getAttribute("username").toString() + "登录系统"); log.setCrtTime(new Date()); logMapper.insert(log); JSONObject jsb = new JSONObject(); jsb.put("username", user.getUserName()); jsb.put("roleId", userList.get(0).getRoleId()); jsb.put("userId", userList.get(0).getId()); jsb.put("departmentId", userList.get(0).getDepartmentId()); jsb.put("roleList", roleMapper.list()); jsb.put("departmentList", departmentMapper.list()); ResponseSuccessResult responseResult = new ResponseSuccessResult(HttpStatus.OK.value(), "success", jsb); return new ResponseEntity<>(responseResult, HttpStatus.OK); } @GetMapping(value = "logout") @ResponseBody public ResponseEntity<ResponseSuccessResult> postAuthToken(HttpServletRequest request) throws Exception { log.debug(">>>>>user:{} ,logout", request.getSession().getAttribute("username")); Log log = new Log(); log.setId(UUID.randomUUID().toString()); log.setUserId(request.getSession().getAttribute("userId").toString()); log.setUserName(request.getSession().getAttribute("username").toString()); log.setMessage("用户" + request.getSession().getAttribute("username").toString() + "退出系统"); log.setCrtTime(new Date()); logMapper.insert(log); request.getSession().invalidate(); ResponseSuccessResult responseResult = new ResponseSuccessResult(HttpStatus.OK.value(), "success"); return new ResponseEntity<>(responseResult, HttpStatus.OK); } @PostMapping(value = "change") @ResponseBody public ResponseEntity<ResponseSuccessResult> passwordChange(HttpServletRequest request, @RequestBody JSONObject jsb) throws Exception { log.debug(">>>>>user:{} ,logout", request.getSession().getAttribute("username")); String oldPassword = jsb.getString("oldPassword"); String newPassword = jsb.getString("newPassword"); User user = userMapper.selectByPrimaryKey(request.getSession().getAttribute("userId").toString()); if (!user.getUserPassword().equals(oldPassword)) { throw new RebotException(RebotExceptionConstants.USER_VALID_PASSWORD_FAILD_CODE, RebotExceptionConstants.USER_VALID_PASSWORD_FAILD_MESSAGE, RebotExceptionConstants.USER_VALID_PASSWORD_FAILD_HTTP_STATUS); } user.setUserPassword(newPassword); user.setUptUser(request.getSession().getAttribute("username").toString()); user.setUptTime(new Date()); userMapper.updateByPrimaryKeySelective(user); Log log = new Log(); log.setId(UUID.randomUUID().toString()); log.setUserId(request.getSession().getAttribute("userId").toString()); log.setUserName(request.getSession().getAttribute("username").toString()); log.setMessage("用户" + request.getSession().getAttribute("username").toString() + "修改密码"); log.setCrtTime(new Date()); logMapper.insert(log); request.getSession().invalidate(); ResponseSuccessResult responseResult = new ResponseSuccessResult(HttpStatus.OK.value(), "success"); return new ResponseEntity<>(responseResult, HttpStatus.OK); } }
true
cc92e2ae30639d23e0b5d4d2d886e0bbbc18aa05
Java
jchen78/SOEN6441
/GameEngine/src/game/action/sequence/visitee/PlaceMinionVisitee.java
UTF-8
3,522
2.6875
3
[]
no_license
package game.action.sequence.visitee; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import game.action.sequence.interfaces.IVisitee; import game.action.sequence.interfaces.IVisitor; import game.core.enums.CityAreaData; import game.core.interfaces.ICityArea; import game.core.interfaces.IGameInstance; import game.core.interfaces.IPlayer; import game.engine.*; import game.error.EntityNotSetException; import game.error.InvalidOperationException; public class PlaceMinionVisitee implements IVisitee { private ICityArea _selectedArea; private ActionType _sourceOfAction; public PlaceMinionVisitee(ActionType sourceOfAction) { _sourceOfAction = sourceOfAction; } @Override public void accept(IVisitor visitor) throws GameOverException, EntityNotSetException, InvalidOperationException { IPlayer currentPlayer = visitor.getCurrentPlayer(); ICityArea[] originalPopulatedAreas = currentPlayer.getPopulatedAreas(visitor); List<ICityArea> currentlyPopulatedAreas = Arrays.asList(originalPopulatedAreas); List<ICityArea> possibleChoices; List<IVisitee> translatedChoices = new LinkedList<IVisitee>(); if (currentPlayer.getNumberOfMinionsInHand() == 0) { List<IVisitee> areasForRemoval = new LinkedList<IVisitee>(); for (ICityArea populatedArea : currentlyPopulatedAreas) areasForRemoval.add(new SelectionVisitee(populatedArea.getCityAreaName().getDescriptiveName())); SingleActionSelector removalSelector = new SingleActionSelector(originalPopulatedAreas, "map areas"); removalSelector.accept(visitor); SelectionVisitee selection = (SelectionVisitee)removalSelector.getSelection(); ICityArea removedArea = currentlyPopulatedAreas.get(selection.getSelectedIndex()); try { removedArea.removeMinions(currentPlayer, 1); } catch (InvalidOperationException e) { e.printStackTrace(); } currentPlayer.returnMinionsToHand(1); if (removedArea.getMinions()[currentPlayer.getIndex()] == 0) currentlyPopulatedAreas.remove(removedArea); } if (currentlyPopulatedAreas.size() == 0) { possibleChoices = Arrays.asList(visitor.getAllCityAreas()); for (ICityArea mapArea : possibleChoices) translatedChoices.add(new SelectionVisitee(mapArea.getCityAreaName().getDescriptiveName())); } else { possibleChoices = new LinkedList<ICityArea>(); for (CityAreaData mapAreaName : CityAreaData.values()) { for (ICityArea populatedArea : currentlyPopulatedAreas) { if (populatedArea.isAdjacent(mapAreaName)) { possibleChoices.add(visitor.getCityArea(mapAreaName)); translatedChoices.add(new SelectionVisitee(mapAreaName.getDescriptiveName())); break; } } } } IVisitee[] areasForPlacement = translatedChoices.toArray(new IVisitee[translatedChoices.size()]); SingleActionSelector selector = new SingleActionSelector(areasForPlacement, "map areas"); selector.accept(visitor); SelectionVisitee selection = (SelectionVisitee)selector.getSelection(); for (ICityArea mapArea : possibleChoices) { if (mapArea.getCityAreaName().getDescriptiveName() == selection.getDescription()) { _selectedArea = mapArea; try { _selectedArea.addMinions(currentPlayer, 1); } catch (InvalidOperationException e) { // TODO Re-select an area e.printStackTrace(); } break; } } } @Override public String getDescription() { return "Place a minion on the board."; } public ICityArea getNewlyPopulatedArea() { return _selectedArea; } }
true
792301344f760c03c5a93025c92975d0637290b7
Java
PenghaiZhang/openEQUELLA
/Platform/Plugins/com.tle.platform.common/src/com/tle/core/plugins/AbstractPluginService.java
UTF-8
10,153
1.601563
2
[ "Apache-2.0", "LGPL-3.0-only", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause", "EPL-1.0", "LGPL-2.0-or-later", "Classpath-exception-2.0", "LicenseRef-scancode-jdom", "ICU", "Apache-1.1", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "GPL-1.0-or-later", "CPL-1.0", "CDDL-1.0", "MIT", "LicenseRef-scancode-freemarker", "GPL-2.0-only", "NetCDF", "CDDL-1.1" ]
permissive
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * The Apereo Foundation licenses this file to you 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.tle.core.plugins; import com.tle.client.PluginClassResolver; import com.tle.common.filters.Filter; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.java.plugin.Plugin; import org.java.plugin.PluginLifecycleException; import org.java.plugin.PluginManager; import org.java.plugin.registry.Extension; import org.java.plugin.registry.ExtensionPoint; import org.java.plugin.registry.Library; import org.java.plugin.registry.ManifestInfo; import org.java.plugin.registry.PluginDescriptor; import org.java.plugin.registry.PluginPrerequisite; import org.java.plugin.registry.PluginRegistry; import org.java.plugin.registry.PluginRegistry.RegistryChangeData; import org.java.plugin.registry.PluginRegistry.RegistryChangeListener; public abstract class AbstractPluginService extends PluginClassResolver implements PluginService { protected PluginManager pluginManager; protected static PluginService thisService; protected Map<String, TLEPluginLocation> pluginIdToLocation = new HashMap<String, TLEPluginLocation>(); protected Map<String, List<RegistryChangeListener>> changeListeners = new HashMap<String, List<RegistryChangeListener>>(); public void setPluginManager(PluginManager pluginManager) { this.pluginManager = pluginManager; } public AbstractPluginService() { thisService = this; // NOSONAR } @Override public Map<String, TLEPluginLocation> getPluginIdToLocation() { return pluginIdToLocation; } public static PluginService get() { return thisService; } public static String getMyPluginId(Class<?> callerClass) { return thisService.getPluginIdForObject(callerClass); } @Override public ClassLoader getLoaderForPluginId(String pluginId) { try { PluginDescriptor descriptor = getPluginDescriptor(pluginId); ensureActivated(descriptor); return getClassLoader(descriptor); } catch (IllegalArgumentException iae) { return getClass().getClassLoader(); } } public static class TLEPluginLocation implements org.java.plugin.PluginManager.PluginLocation { private final ManifestInfo manifestInfo; private final String jar; private final URL context; private final URL manifest; private final int version; @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof TLEPluginLocation)) { return false; } return manifestInfo.getId().equals(((TLEPluginLocation) obj).manifestInfo.getId()); } @Override public int hashCode() { return manifestInfo.getId().hashCode(); } public TLEPluginLocation(ManifestInfo info, String jar, URL context, URL manifest) { this(info, jar, -1, context, manifest); } public TLEPluginLocation( ManifestInfo info, String jar, int version, URL context, URL manifest) { this.manifestInfo = info; this.jar = jar; this.context = context; this.manifest = manifest; this.version = version; } public int getVersion() { return version; } public String getJar() { return jar; } @Override public URL getContextLocation() { return context; } @Override public URL getManifestLocation() { return manifest; } public ManifestInfo getManifestInfo() { return manifestInfo; } } protected Object instantiatePluginClass(PluginDescriptor plugin, String clazz) { try { if (!pluginManager.isPluginActivated(plugin)) { pluginManager.activatePlugin(plugin.getId()); } return pluginManager.getPluginClassLoader(plugin).loadClass(clazz).newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } @Override public ClassLoader getClassLoader(PluginDescriptor plugin) { return pluginManager.getPluginClassLoader(plugin); } @Override public Iterable<URL> getLocalClassPath(String pluginId) { PluginDescriptor descriptor = pluginManager.getRegistry().getPluginDescriptor(pluginId); Collection<Library> libraries = descriptor.getLibraries(); ArrayList<URL> urls = new ArrayList<URL>(); for (Library lib : libraries) { if (lib.isCodeLibrary() && !lib.getPath().endsWith(".jar")) // $NON-NLS-1$ { urls.add(pluginManager.getPathResolver().resolvePath(lib, lib.getPath())); } } return urls; } @Override public ClassLoader getClassLoader(String pluginId) { PluginDescriptor desc = pluginManager.getRegistry().getPluginDescriptor(pluginId); return getClassLoader(desc); } @Override public void ensureActivated(PluginDescriptor plugin) { try { pluginManager.activatePlugin(plugin.getId()); } catch (PluginLifecycleException e) { throw new RuntimeException(e); } } @SuppressWarnings("nls") @Override public ExtensionPoint getExtensionPoint(String pluginId, String pointId) { PluginDescriptor descId = pluginManager.getRegistry().getPluginDescriptor(pluginId); ExtensionPoint extPoint = descId.getExtensionPoint(pointId); if (extPoint == null) { throw new Error("ExtensionPoint " + pointId + " not found for plugin " + pluginId); } return extPoint; } @Override public Collection<Extension> getConnectedExtensions(String pluginId, String pointId) { return getExtensionPoint(pluginId, pointId).getConnectedExtensions(); } @Override public Object getBean(String id, String clazzName) { return getBean(pluginManager.getRegistry().getPluginDescriptor(id), clazzName); } @Override public void registerExtensionListener( String pluginId, String extensionId, RegistryChangeListener listener) { String uniqueId = pluginManager.getRegistry().makeUniqueId(pluginId, extensionId); List<RegistryChangeListener> listenerList = changeListeners.get(uniqueId); if (listenerList == null) { listenerList = new ArrayList<RegistryChangeListener>(); } listenerList.add(listener); changeListeners.put(uniqueId, listenerList); } @Override public String getPluginIdForObject(Object object) { Plugin plugin = pluginManager.getPluginFor(object); if (plugin != null) { return plugin.getDescriptor().getId(); } return null; } @Override public Plugin getPluginForObject(Object object) { return pluginManager.getPluginFor(object); } public void registryChanged(RegistryChangeData changed) { for (String extpointId : changeListeners.keySet()) { if (!changed.modifiedExtensions(extpointId).isEmpty() || !changed.removedExtensions(extpointId).isEmpty() || !changed.addedExtensions(extpointId).isEmpty()) { List<RegistryChangeListener> listenerList = changeListeners.get(extpointId); if (listenerList != null) { for (RegistryChangeListener listener : listenerList) { listener.registryChanged(changed); } } } } } @Override public Set<PluginDescriptor> getAllPluginsAndDependencies( Filter<PluginDescriptor> filter, Set<String> disallowed, boolean includeOptional) { PluginRegistry registry = pluginManager.getRegistry(); Set<PluginDescriptor> rv = new HashSet<PluginDescriptor>(); for (PluginDescriptor d : registry.getPluginDescriptors()) { if (!rv.contains(d) && (filter == null || filter.include(d))) { rv.add(d); recursivelyIncludePrerequisites( registry, rv, d, new LinkedList<String>(), disallowed, includeOptional); } } return rv; } @SuppressWarnings("nls") private void recursivelyIncludePrerequisites( PluginRegistry registry, Set<PluginDescriptor> plugins, PluginDescriptor desc, Deque<String> trail, Set<String> disallowed, boolean includeOptional) { trail.push(desc.getId()); for (PluginPrerequisite ppr : desc.getPrerequisites()) { PluginDescriptor pprDesc = registry.getPluginDescriptor(ppr.getPluginId()); if ((includeOptional || !ppr.isOptional()) && !plugins.contains(pprDesc)) { if (disallowed.contains(pprDesc.getId())) { throw new RuntimeException( "Plugin " + desc.getId() + " requires banned plugin " + pprDesc.getId() + ", trail is:" + trail); } plugins.add(pprDesc); recursivelyIncludePrerequisites( registry, plugins, pprDesc, trail, disallowed, includeOptional); } } trail.pop(); } public PluginManager getPluginManager() { return pluginManager; } @Override public PluginDescriptor getPluginDescriptor(String id) { return pluginManager.getRegistry().getPluginDescriptor(id); } @Override public PluginBeanLocator getBeanLocator(String pluginId) { throw new UnsupportedOperationException(); } @Override public void initLocatorsFor(List<Extension> extensions) { // do nothing } @Override public String getPluginIdForClass(Class<?> clazz) { return getPluginIdForObject(clazz); } }
true
448004c7f4d1ba69fa8826f4c930ba04478ebf81
Java
Fstall/DTCC_JavaAcademy
/RSTechSearchService/src/main/java/com/rstech/search/transform/YahooUkTransformer.java
UTF-8
484
2.15625
2
[]
no_license
package com.rstech.search.transform; import com.rstech.search.SearchSite; public class YahooUkTransformer extends YahooTransformer { private static YahooUkTransformer instance = new YahooUkTransformer(); public static YahooUkTransformer getInstance(){ return instance; } private YahooUkTransformer(){ } @Override public String getBaseUrl() { return "http://uk.search.yahoo.com"; } @Override public SearchSite getSearchSite() { return SearchSite.YAHOO_UK; } }
true
69e0ea68aefb6bef1fe77981db851ffa1ed9d0a3
Java
SucreLighT/StudentManagement
/src/student/QueryStudent.java
UTF-8
8,418
2.859375
3
[]
no_license
package student; // 查询学生类 import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class QueryStudent extends JPanel implements ActionListener { JTextField Sno, Sname, Ssex, SageMin, SageMax, Sdept; JButton findButton, cancelButton; // 实现查询学生界面 public QueryStudent() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.err.println("Exception:" + e); } Sno = new JTextField(12); Sname = new JTextField(12); Ssex = new JTextField(12); SageMin = new JTextField(12); SageMax = new JTextField(12); Sdept = new JTextField(12); findButton = new JButton("查询"); findButton.addActionListener(this); cancelButton = new JButton("取消"); cancelButton.addActionListener(this); Box box0 = Box.createHorizontalBox(); Box box1 = Box.createHorizontalBox(); Box box2 = Box.createHorizontalBox(); Box box3 = Box.createHorizontalBox(); Box box4 = Box.createHorizontalBox(); Box box5 = Box.createHorizontalBox(); Box box6 = Box.createHorizontalBox(); Box box7 = Box.createHorizontalBox(); JLabel title = new JLabel("查询学生信息"); title.setFont(new Font("宋体", Font.BOLD, 12)); box0.add(title); box1.add(new JLabel("学 号:")); box1.add(Sno); box2.add(new JLabel("姓 名:")); box2.add(Sname); box3.add(new JLabel("性 别:")); box3.add(Ssex); box4.add(new JLabel("年龄下限:")); box4.add(SageMin); box5.add(new JLabel("年龄上限:")); box5.add(SageMax); box6.add(new JLabel("系 别:")); box6.add(Sdept); box7.add(findButton); box7.add(cancelButton); Box boxH = Box.createVerticalBox(); boxH.add(box1); boxH.add(box2); boxH.add(box3); boxH.add(box4); boxH.add(box5); boxH.add(box6); boxH.add(box7); boxH.add(Box.createVerticalGlue()); JPanel messPanel1 = new JPanel(); JPanel messPanel2 = new JPanel(); messPanel1.add(box0); messPanel2.add(boxH); setLayout(new BorderLayout()); JSplitPane splitV = new JSplitPane(JSplitPane.VERTICAL_SPLIT, messPanel1, messPanel2); splitV.setEnabled(false); add(splitV, BorderLayout.CENTER); validate(); } // 实现查询学生功能 // 预计可实现:查询所有记录,根据学号查询唯一学生,根据姓名查询唯一学生,根据性别查询所有学生,根据系别查询所有,根据系别、年龄范围范围所有 public void actionPerformed(ActionEvent c) { Object obj = c.getSource(); String sql = null; if (obj == findButton) { // 查询所有记录 if (Sno.getText().equals("") && Sname.getText().equals("") && Ssex.getText().equals("") && SageMin.getText().equals("") && SageMax.getText().equals("") && Sdept.getText().equals("")) { sql = "select * from student "; System.out.print("查询所有记录:" + sql + "\n"); } else { // 根据学号查询唯一学生 if (!Sno.getText().equals("")) { // 学号不为空,查询指定该学号的学生 if (Sname.getText().equals("") && Ssex.getText().equals("") && SageMin.getText().equals("") && SageMax.getText().equals("") && Sdept.getText().equals("")) { // 其他字段没有值 sql = "select * from student where Sno='" + Sno.getText() + "'"; } else { Sno.setText(""); Sname.setText(""); Ssex.setText(""); SageMin.setText(""); SageMax.setText(""); Sdept.setText(""); JOptionPane.showMessageDialog(this, "不支持此类查询!"); } System.out.print("根据学号查询学生信息:" + sql + "\n"); } else { if (!Sname.getText().equals("")) { // 姓名不为空,查询指定该姓名的学生 if (Ssex.getText().equals("") && SageMin.getText().equals("") && SageMax.getText().equals("") && Sdept.getText().equals("")) { // 其他字段没有值 sql = "select * from student where Sname='" + Sname.getText() + "'"; } else { Sno.setText(""); Sname.setText(""); Ssex.setText(""); SageMin.setText(""); SageMax.setText(""); Sdept.setText(""); JOptionPane.showMessageDialog(this, "不支持此类查询!"); } System.out.print("根据姓名查询学生信息:" + sql + "\n"); } else { if (!Ssex.getText().equals("")) { // 性别字段有值 if (SageMin.getText().equals("") && SageMax.getText().equals("") && Sdept.getText().equals("")) { // 其他字段没有值 // 根据性别查询所有学生 sql = "select * from student where Ssex='" + Ssex.getText() + "'"; } else { Sno.setText(""); Sname.setText(""); Ssex.setText(""); SageMin.setText(""); SageMax.setText(""); Sdept.setText(""); JOptionPane.showMessageDialog(this, "不支持此类查询!"); } System.out.print("根据性别查询学生信息:" + sql + "\n"); } else { if (!Sdept.getText().equals("")) { // 系别字段有值 if (SageMin.getText().equals("") && SageMax.getText().equals("")) { // 年龄上下限字段没有值 // 根据系别查询所在系所有学生 sql = "select * from student where Sdept='" + Sdept.getText() + "'"; System.out.print("根据系别查询所在系所有学生:" + sql + "\n"); } else { if (SageMin.getText().equals("")) { // 年龄上限有值 sql = "select * from student where Sdept='" + Sdept.getText() + "' and Sage<'" + Integer.parseInt(SageMax.getText()) + "'"; } else if (SageMax.getText().equals("")) { // 年龄下限有值 sql = "select * from student where Sdept='" + Sdept.getText() + "' and Sage>'" + Integer.parseInt(SageMin.getText()) + "'"; } else { // 年龄上下限都有值 sql = "select * from student where Sdept='" + Sdept.getText() + "' and Sage between " + Integer.parseInt(SageMin.getText()) + " and " + Integer.parseInt(SageMax.getText()) + ""; } System.out.print("根据系别、年龄查询学生:" + sql + "\n"); } } } } } } ShowStudent ShowStudent = new ShowStudent(sql); }else{ if(obj == cancelButton) { Sno.setText(""); Sname.setText(""); Ssex.setText(""); SageMin.setText(""); SageMax.setText(""); Sdept.setText(""); } } } }
true
862958d4f9a08bf5557b80b9574371c701f91de3
Java
pawanbole/Algorithm-and-Data-Structures
/Project1/Solution/Question2/src/MaxSubArray.java
UTF-8
4,820
3.40625
3
[]
no_license
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class MaxSubArray { public static void main(String[] args) throws IOException { int[] arr = getInput(); int x = getParameter(); int res = maxSubArray(arr, x); if(res > -1) System.out.println("Max subarray length is : " + res); else{ System.out.println("No max subarray for the given input"); } try { writeToFile(res); } catch (Exception e) { e.printStackTrace(); } } private static int getParameter() { Scanner kbd = new Scanner(System.in); System.out.println("Enter median value"); return kbd.nextInt(); } private static int maxSubArray(int[] arr, int x) { sortArray(arr, 0, arr.length - 1); return findSubArrayLength(arr, x); } private static int findSubArrayLength(int[] arr, int x) { int res = 0, left = 0, right = 0; int index = findIndex(arr, x); left = index - 0; right = (arr.length - 1) - index; if(index > 0) { if (arr[index] == x) { if (left <= right) { return arr.length; } else { return ((right * 2) + 1); } } else { if (index > 0) { if (((arr[index - 1] + arr[index]) / 2) < x) { if (left <= right) { return arr.length; } else { return ((right * 2) + 1); } } else { if (left <= right) { return arr.length; } else { return ((right * 2) + 2); } } } else { return arr.length; } } } return -1; } public static int findIndex(int arr[], int x) { //returns the first occurance of the data or the first highest element for (int i = 0; i < arr.length; i++) { if (arr[i] == x) { return i; } else if (arr[i] > x) { return i; } } return -1; } public static void sortArray(int[] arr, int left, int right) { // I have used dual pivot quick sort as it is more efficient than single pivot quick sort. // We can use insertion sort in case the number of elements are less than 48. // This approach is similar to the implementaion of Array sort function for primitives in Java if (right > left) { // Choose outermost elements as pivots if (arr[left] > arr[right]) swap(arr, left, right); int p = arr[left], q = arr[right]; // Partition A according to invariant below int l = left + 1, g = right - 1, k = l; while (k <= g) { if (arr[k] < p) { swap(arr, k, l); ++l; } else if (arr[k] >= q) { while (arr[g] > q && k < g) --g; swap(arr, k, g); --g; if (arr[k] < p) { swap(arr, k, l); ++l; } } ++k; } --l; ++g; // Swap pivots to final place swap(arr, left, l); swap(arr, right, g); // Recursively sort partitions sortArray(arr, left, l - 1); sortArray(arr, l + 1, g - 1); sortArray(arr, g + 1, right); } } static void swap(int[] A, int i, int j) { final int tmp = A[i]; A[i] = A[j]; A[j] = tmp; } public static int[] getInput() { Scanner kbd = new Scanner(System.in); System.out.println("Enter array separated with ',' "); String s1 = kbd.next(); String[] a = s1.split(","); int[] arr = new int[a.length]; for (int i = 0; i < a.length; i++) { arr[i] = Integer.parseInt(a[i]); } return arr; } private static void writeToFile(int res) throws IOException { File outputFile = new File("Output2.txt"); FileWriter fw = null; String output = ("Max subarray length is : " + res); try { fw = new FileWriter(outputFile); fw.write(output); } catch (Exception e) { System.out.println("Exception occurred"); } finally { fw.close(); } } }
true
3333687857085605c6480bac6536c8c0c3d821c3
Java
KleberQueiroz/contas
/src/apps/appConta.java
WINDOWS-1252
1,080
3.21875
3
[]
no_license
package apps; import bancos.Pessoa; import contas.Conta; public class appConta { public static void main(String[] args) { Pessoa p1 = new classes.Pessoa("Fulano", "fulano@gmail.com"); Pessoa p2 = new Pessoa("Ciclano", "ciclano@gmail.com"); Conta c1 = new Conta(); c1.setCorrentista(p1); c1.setNumero(129845); c1.setSaldo(150.00f); Conta c2=new Conta (324124,p2, 41234.00f); System.out.println("O nome do correntista :" +c1.getCorrentista().getNome()); System.out.println("O numero da conta :" +c1.getNumero()); System.out.println("O valor inicial da conta :" +c1.getSaldo()); System.out.println("O nome do correntista :" +c2.getCorrentista().getNome()); System.out.println("O numero da conta :" +c2.getNumero()); System.out.println("O valor inicial da conta :" +c2.getSaldo()); if(c2.sacar(4.00f)) System.out.println("Saque efetuado com sucesso"); else System.out.println("Saque No resalizado - Saldo Insuficiete"); c2.depositar(1000909978.00f); System.out.println("Novo Saldo : "+ c2.getSaldo()); } }
true
a58281c6bf27551afe37541b0b519c3f2a59eeea
Java
Capsar/Rapture
/minecraft/pq/rapture/module/Fullbright.java
UTF-8
1,186
1.96875
2
[]
no_license
package pq.rapture.module; import net.minecraft.client.multiplayer.WorldClient; import pq.rapture.module.base.Module; import pq.rapture.module.base.Type; import pq.rapture.protection.Protection; import pq.rapture.util.TimeHelper; /** * Created by Haze on 6/17/2015. Project Rapture. */ public class Fullbright extends Module { private TimeHelper helper; private float curLight = 0; private Thread enableThread, disableThread; public Fullbright() { super(Protection.decrypt("B98E7262FD2580D7177145EB7BBADD7E"), new String[] {}, Protection.decrypt("C7142FD4C1DB69F65089E330130AB3D96A41F60204A39794908B7329FC609ECD"), Type.RENDER, "B", 0xFF21ffcb); helper = new TimeHelper(); curLight = 0; } public void editTable(WorldClient world, float value) { if (world == null) return; float[] table = world.provider.lightBrightnessTable; for (int index = 0; index < table.length; index++) table[index] = table[index] > value ? table[index] : value; world.provider.lightBrightnessTable = table; } @Override public boolean onEnable() { getGameSettings().gammaSetting = 31; return super.onEnable(); } @Override public boolean onDisable() { getGameSettings().gammaSetting = 0; return super.onDisable(); } }
true
42186702565c43f84ba8ea3feef0c629daa8e275
Java
POO-UNALMED/taller-6-JuanPabloGutierrezTamayo
/src/main/java/vehiculos/Camion.java
UTF-8
495
2.640625
3
[]
no_license
package vehiculos; public class Camion extends Vehiculo { private int ejes; private static int cantidadCamiones; public Camion(String placa, String nombre, int precio, int peso, Fabricante fabricante, int eje) { super(placa, 2,80,nombre,precio,peso,"4X2",fabricante); this.ejes=eje; cantidadCamiones++; } public int getEjes() { return ejes; } public void setEjes(int ejes) { this.ejes = ejes; } public static int getCantidadCamiones() { return cantidadCamiones; } }
true
9e0f4b6afe534aab93ebab1a36084c0fa5c84fee
Java
fjw0312/TXNews
/src/TXNews/Main/NewsWebActivity.java
GB18030
2,969
2.03125
2
[]
no_license
package TXNews.Main; import mybroadcast.MyBroadcastReceiver; import TXNews.bean.HistoryModel; import TXNews.bean.RecordModel; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ImageView; import android.widget.TextView; @SuppressLint("SetJavaScriptEnabled") public class NewsWebActivity extends Activity{ ImageView img_back; TextView Tx_title; TextView Tx_share; //δʹ TextView Tx_collect; WebView webView; String str_html = ""; String str_title = ""; private OnClickListener l = new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub if(arg0==img_back){ NewsWebActivity.this.finish(); }else if(arg0==Tx_share){ // ĿǰЧ Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain") ;// intent.putExtra(Intent.EXTRA_TITLE, "NB XXXX"); //ñ intent.putExtra(Intent.EXTRA_SUBJECT, "fangjiongwen-TEST");// intent.putExtra(Intent.EXTRA_TEXT, str_html); // startActivity(Intent.createChooser(intent,"")); //Ӧѡ }else if(arg0==Tx_collect){ //ղ RecordModel recordModel = new RecordModel(str_html,str_title); HistoryModel.collectRecord_Map_lst.add(recordModel); MyBroadcastReceiver.sendBroad_MSG_HAL("ղسɹ"); } } }; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); // ActionBar actionBar = getActionBar(); actionBar.hide(); setContentView(R.layout.activity_newshtml); Intent intent = getIntent(); str_html = intent.getStringExtra("str_html"); str_title = intent.getStringExtra("str_title"); RecordModel recordModel = new RecordModel(str_html,str_title); HistoryModel.historyRecord_Map_lst.add(recordModel); img_back = (ImageView)findViewById(R.id.img_back); Tx_title = (TextView)findViewById(R.id.Tx_title); Tx_collect = (TextView)findViewById(R.id.Tx_collect); webView = (WebView)findViewById(R.id.web_id); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); // TODO Auto-generated method stub //return super.shouldOverrideUrlLoading(view, url); return true; } }); img_back.setOnClickListener(l); Tx_collect.setOnClickListener(l); //web webView.loadUrl(str_html); } }
true
b56ba76a3cbbdbcda5335b0cb0cf96f3e3b428ac
Java
yornel13/roles_web
/src/servlets/EmpresaServlet.java
UTF-8
1,174
2.21875
2
[]
no_license
package servlets; import utilidad.Const; import utilidad.Fecha; import utilidad.SessionUtility; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/empresa") public class EmpresaServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (SessionUtility.isExpiry(req, resp)) return; req.getRequestDispatcher("empresa.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (SessionUtility.isExpiry(req, resp)) return; if (req.getParameter("goEmpleados") != null) { req.getSession().setAttribute(Const.FECHA, Fecha.getFechaActualInit()); resp.sendRedirect("rol/empleados"); } if (req.getParameter("goClientes") != null) { resp.sendRedirect("clientes"); } } }
true
ffd7d8b5d80d5d672e8a721b6098a5397b36612b
Java
ashudhage/27062020Automation
/BasicCoreJava/src/collection/Students.java
UTF-8
404
2.53125
3
[]
no_license
package collection; import oops.inheritance.Mobile; import oops.inheritance.SmartPhone; import oops.inheritance.Telephone; public class Students { public static void main(String[] args) { String [] std=new String [18]; Object Telephone=new SmartPhone(); Object a=10; Object name="ashu"; Object b=true; Object []arr=new Object[3]; arr[0]=10; arr[1]="ashu"; arr[2]=true; } }
true
135eb811a8135afe12939e8e577262c978a18741
Java
rfscholte/sonar-update-center
/sonar-update-center-common/src/main/java/org/sonar/updatecenter/common/PluginReferential.java
UTF-8
7,314
1.804688
2
[]
no_license
/* * SonarSource :: Update Center :: Common * Copyright (C) 2010 SonarSource * dev@sonar.codehaus.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.updatecenter.common; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import org.sonar.updatecenter.common.exception.DependencyCycleException; import org.sonar.updatecenter.common.exception.IncompatiblePluginVersionException; import org.sonar.updatecenter.common.exception.PluginNotFoundException; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Sets.newTreeSet; public class PluginReferential { private Set<Plugin> plugins; private PluginReferential() { this.plugins = newTreeSet(); } public static PluginReferential create(List<Plugin> pluginList) { PluginReferential pluginReferential = new PluginReferential(); for (Plugin plugin : pluginList) { pluginReferential.add(plugin); } return pluginReferential; } public static PluginReferential createEmpty() { return PluginReferential.create(Lists.<Plugin>newArrayList()); } /** * @return the list of plugins where last releases is master releases */ public List<Plugin> getLastMasterReleasePlugins() { return newArrayList(Iterables.filter(plugins, new Predicate<Plugin>() { public boolean apply(Plugin input) { return input.getLastRelease().isMaster(); } })); } public List<Plugin> getPlugins() { return newArrayList(plugins); } /** * @throws NoSuchElementException if plugin could not be found */ public Plugin findPlugin(final String key) { try { return Iterables.find(plugins, new Predicate<Plugin>() { public boolean apply(Plugin input) { return input.getKey().equals(key); } }); } catch (NoSuchElementException e) { throw new NoSuchElementException("Unable to find plugin with key " + key); } } public boolean doesContainPlugin(final String key) { return Iterables.any(plugins, new Predicate<Plugin>() { public boolean apply(Plugin input) { return input.getKey().equals(key); } }); } public boolean doesContainRelease(final String key, Version version) { for (Plugin plugin : plugins) { if (plugin.getKey().equals(key) && plugin.doesContainVersion(version)) { return true; } } return false; } public List<String> findLastReleasesWithDependencies(String pluginKey) { List<String> removablePlugins = newArrayList(); Plugin plugin = findPlugin(pluginKey); if (plugin != null) { Release pluginRelease = plugin.getLastRelease(); removablePlugins.add(plugin.getKey()); for (Release child : pluginRelease.getChildren()) { removablePlugins.add(child.getKey()); } for (Release incomingDependencies : pluginRelease.getIncomingDependencies()) { removablePlugins.addAll(findLastReleasesWithDependencies(incomingDependencies.getArtifact().getKey())); } } return removablePlugins; } public PluginReferential setParent(Release release, String parentKey) { try { Plugin pluginParent = findPlugin(parentKey); Release parent = getParentRelease(release, pluginParent); release.setParent(parent); parent.addChild(release); return this; } catch (NoSuchElementException e) { throw new PluginNotFoundException(String.format("The plugin '%s' required by the plugin '%s' is missing.", parentKey, release.getKey()), e); } } private Release getParentRelease(Release release, Plugin pluginParent) { try { return pluginParent.getRelease(release.getVersion()); } catch (NoSuchElementException e) { throw new IncompatiblePluginVersionException(String.format("The plugins '%s' and '%s' must have exactly the same version as they belong to the same group.", release.getKey(), pluginParent.key), e); } } public void addOutgoingDependency(Release release, String requiredPluginReleaseKey, String requiredMinimumReleaseVersion) { try { Plugin requiredPlugin = findPlugin(requiredPluginReleaseKey); Release minimalRequiredRelease = requiredPlugin.getMinimalRelease(Version.create(requiredMinimumReleaseVersion)); if (minimalRequiredRelease != null) { release.addOutgoingDependency(minimalRequiredRelease); minimalRequiredRelease.addIncomingDependency(release); checkDependencyCycle(release); } else { Release latest = requiredPlugin.getLastRelease(); if (latest != null) { throw new IncompatiblePluginVersionException(String.format("The plugin '%s' is in version %s whereas the plugin '%s' requires a least a version %s.", requiredPlugin.getKey(), latest.getVersion().getName(), release.getArtifact().getKey(), requiredMinimumReleaseVersion)); } } } catch (NoSuchElementException e) { throw new PluginNotFoundException(String.format("The plugin '%s' required by '%s' is missing.", requiredPluginReleaseKey, release.getArtifact().getKey()), e); } } private void checkDependencyCycle(Release release) { List<Release> releases = newArrayList(); try { checkDependencyCycle(release, releases); } catch (DependencyCycleException e) { List<String> releaseKeys = newArrayList(Iterables.transform(releases, new Function<Release, String>() { public String apply(Release input) { return input.getArtifact().getKey(); } })); throw new DependencyCycleException("There is a dependency cycle between plugins '" + Joiner.on("', '").join(releaseKeys) + "' that must be cut.", e); } } private void checkDependencyCycle(Release release, List<Release> releases) { for (Release outgoingDependency : release.getOutgoingDependencies()) { if (releases.contains(outgoingDependency)) { throw new DependencyCycleException(); } releases.add(outgoingDependency); checkDependencyCycle(outgoingDependency, releases); } } List<Release> getLastMasterReleases() { List<Release> releases = newArrayList(); for (Plugin plugin : getLastMasterReleasePlugins()) { releases.add(plugin.getLastRelease()); } return releases; } private PluginReferential add(Plugin plugin) { this.plugins.add(plugin); return this; } }
true
0381fe5089a8f074a4469184813de77ddf1b3747
Java
edcamero/filtro
/src/control/UsuarioController.java
UTF-8
1,125
2.25
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 control; import View.Principal; import View.Usuario.UsuarioGui2; import View.Usuario.UsuarioLista; /** * * @author blade */ public class UsuarioController { private static UsuarioController usuarioController; Principal principal; UsuarioGui2 usuarioGui; UsuarioLista usuarioListaGui; private UsuarioController(){ principal = Principal.getInstance(); } public static UsuarioController getInstancia(){ if ( usuarioController==null) { usuarioController=new UsuarioController(); } return usuarioController; } public void agregarGui(){ usuarioGui=UsuarioGui2.getIntancia(); principal.mostrarInternal(usuarioGui); } public void listarGui() { usuarioListaGui = UsuarioLista.getEstancia(); //this.getListar(); principal.mostrarInternal(usuarioListaGui); } }
true
dcdb6d94b0524de8ae749fdce5b189970965c59e
Java
alanparley/musicexchange_hw
/src/test/java/GuitarTest.java
UTF-8
1,522
2.953125
3
[]
no_license
import Instruments.Guitar; import Instruments.InstrumentType; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class GuitarTest { Guitar guitar; @Before public void before(){ guitar = new Guitar("Fender", "Stratocaster", "Black", InstrumentType.STRINGS, 6); } @Test public void canGetMake(){ assertEquals("Fender", guitar.getMake()); } @Test public void canGetModel(){ assertEquals("Stratocaster", guitar.getModel()); } @Test public void canGetColour(){ assertEquals("Black", guitar.getColour()); } @Test public void canGetNumberOfStrings(){ assertEquals(6, guitar.getNumberOfStrings()); } @Test public void canGetInstrumentType(){ assertEquals(InstrumentType.STRINGS, guitar.getInstrumentType()); } @Test public void canGetBuyingPrice(){ assertEquals(0.00, guitar.getBuyingPrice(), 0.01); } @Test public void canSetBuyingPrice(){ guitar.setBuyingPrice(500.00); assertEquals(500.00, guitar.getBuyingPrice(), 0.00); } @Test public void canPlayInstrument(){ assertEquals("Guitar goes: KERRANNG!", guitar.play("KERRANNG!")); } @Test public void canCalculateMarkup(){ guitar.setBuyingPrice(500.00); guitar.setSalePrice(625.00); assertEquals(125.00, guitar.calculateMarkup(guitar.getBuyingPrice(), guitar.getSalePrice()), 0.01); } }
true
21d2a19c5656084c7eb51e80732e3c81d3874538
Java
yangfan0725/sd
/src/com/kingdee/eas/fdc/invite/supplier/TenderInfoCollection.java
UTF-8
1,160
2.328125
2
[]
no_license
package com.kingdee.eas.fdc.invite.supplier; import com.kingdee.bos.dao.AbstractObjectCollection; import com.kingdee.bos.dao.IObjectPK; public class TenderInfoCollection extends AbstractObjectCollection { public TenderInfoCollection() { super(TenderInfoInfo.class); } public boolean add(TenderInfoInfo item) { return addObject(item); } public boolean addCollection(TenderInfoCollection item) { return addObjectCollection(item); } public boolean remove(TenderInfoInfo item) { return removeObject(item); } public TenderInfoInfo get(int index) { return(TenderInfoInfo)getObject(index); } public TenderInfoInfo get(Object key) { return(TenderInfoInfo)getObject(key); } public void set(int index, TenderInfoInfo item) { setObject(index, item); } public boolean contains(TenderInfoInfo item) { return containsObject(item); } public boolean contains(Object key) { return containsKey(key); } public int indexOf(TenderInfoInfo item) { return super.indexOf(item); } }
true
27908403e750d67335c3b9806d87cc9b09687d19
Java
SandeepBethi/Sandeep-Bethi-National-Vaccination-Distribution-System
/src/Business/DistributionCentreEnterprise.java
UTF-8
512
2.328125
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Business; /** * * @author Bethi */ public class DistributionCentreEnterprise extends Enterprise{ ShippingOrganization sho; public DistributionCentreEnterprise(String enterpriseName) { super(enterpriseName); sho=(ShippingOrganization)getOrgDirectory().newOrg(Organization.SHIPPING); } public ShippingOrganization getSho() { return sho; } }
true
1eacdac5e5285db7230d8ee5211abb0bf8325e3c
Java
namo-ratna-trayaya/Grail
/java/src/Translator.java
UTF-8
23,846
2.421875
2
[ "Apache-2.0" ]
permissive
/** * This file copyright (c) 2015-2016, Jing Fan, Adalbert Gerald Soosai Raj, and Jignesh M. Patel * * See the file CREDITS.txt in the root directory for details. **/ import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; import Block.BeginWhileBlock; import Block.Block; import Block.CreateTableBlock; import Block.DropIndexBlock; import Block.DropTableBlock; import Block.EndWhileBlock; import Block.InsertBlock; import Block.SelectIntoBlock; import Block.UpdateVertexBlock; /** * @brief This is the translation module of Grail. * It will convert the user input into basic (not-optimized) T-SQL. */ public class Translator { // The options that we fetch from the config file. private HashMap<String, String> options = null; // Convert options to easy-to-use way. Such as <isIteration, y> private HashMap<String, String> convertedOptions = new HashMap<String, String>(); // Generated Sql blocks. private ArrayList<Block> blocks = new ArrayList<Block>(); // Current tables in process. private ArrayList<String> tableNameList = new ArrayList<String>(); // Current indent level. private int indentLevel; // The tables that contains the information about the message senders. private HashSet<String> senders = new HashSet<String>(); private enum StatementType { BEGIN_IF, ASSIGNMENT, MUTATE_VALUE, SEND_MSG, END_IF } /** * @brief Constructor. * @param options The options generated by the parser. */ public Translator(HashMap<String, String> options) { this.options = options; this.indentLevel = 0; } /** * @brief Return SQL code blocks. * @return SQL code blocks. */ public ArrayList<Block> getBlocks() { return this.blocks; } /** * @brief Return senders. * @return Senders. */ public HashSet<String> getSenders() { return senders; } /** * @brief Return converted options. * @return Converted Options. */ public HashMap<String, String> getConvertedOptions() { return this.convertedOptions; } /** * @brief Generate begin of while. */ private void beginWhile() { blocks.add(new BeginWhileBlock("beginWhile", this.indentLevel, this.options.get("End"))); ++this.indentLevel; } /** * @brief Generate end of while. */ private void endWhile() { Iterator<String> iter = this.tableNameList.iterator(); // Drop all the tables that should only be used within iterations. while (iter.hasNext()) { String val = iter.next(); // These tables should be kept as they will be used in the next // iteration. if (val.equals("message") || val.equals("next") || val.equals("in_cnts") || val.equals("out_cnts")) { continue; } this.blocks.add(new DropTableBlock("drop" + val, this.indentLevel, val)); iter.remove(); } blocks.add(new EndWhileBlock("endWhile", this.indentLevel, this.options.get("End"), "message")); --this.indentLevel; } /** * @brief Generate link counts table. * @param isIn Is the table for in-coming edges. */ private void generateCnts(boolean isIn) { String[] tableNames = { "in_cnts", "out_cnts"}; String[] attrs = {"src", "dest"}; ArrayList<String> fromList = new ArrayList<String>(); fromList.add("edge"); ArrayList<String> attrList = new ArrayList<String>(); // Decide the attributes according to whether the table is for // in-coming edges or out-going edges. attrList.add(attrs[isIn ? 1 : 0] + " AS id"); attrList.add("COUNT(" + attrs[isIn ? 0 : 1] + ") AS cnt"); this.blocks.add(new SelectIntoBlock("genCnt", // Stage string. this.indentLevel, // Indent level. attrList, // Attributes. // Target table. tableNames[isIn ? 0 : 1], fromList, // From tables. null, // No extra predicates. false,// Don't join tables with id. // Group by attribute. attrs[isIn ? 1 : 0])); this.tableNameList.add(tableNames[isIn ? 0 : 1]); } /** * @brief Combine messages, that is do aggregation on the messages. */ private void combineMsg() { String aggregationVal = options.get("CombineMessage") .replace("message", "message.val"); ArrayList<String> attrList = new ArrayList<String>(); attrList.add("message.id AS id"); attrList.add(aggregationVal + " AS val"); ArrayList<String> fromList = new ArrayList<String>(); fromList.add("message"); this.blocks.add(new SelectIntoBlock("combineMsg", // The stage string. this.indentLevel, // The indent level. attrList, // The attribute list. "cur", // The new table name. fromList, // The from tables. null, // No predicates. false, // Don't join on id. "id")); // Group by attributes. this.tableNameList.add("cur"); this.convertedOptions.put("aggFunc", aggregationVal); } /** * @brief Generate a table for a variable. * @param context The context table, which stores the current visible * vertices and their values. * @param stat The statement that expresses the value of the variable. * @return An ArrayList, the first one should be the var name, the second * should be the SQL block. */ private void genTbForVar(String context, String stat) { int l = stat.indexOf('='); String varName = stat.substring(0, l).trim(); String exp = stat.substring(l+1).trim(); if (context.equals("cur")) { exp = exp.replace("getAggregationVal()", "cur.val"); } else { exp = exp.replace("getAggregationVal()", context+".val"); } exp = exp.replace("getVal()", "next.val"); // Calculate the number of tables that have appeared. String atomics[] = exp.split(" |\\+|-|\\*|/|<|>|(==)|(AND)|(OR)"); Pattern p = Pattern.compile("\\.(val)|(id)"); HashSet<String> usedTbs = new HashSet<String>(); for (String item : atomics) { item = item.trim(); if (item.equals("")) continue; Matcher m = p.matcher(item); // System.out.println(item); while (m.find()) { // Mark relevant tables. usedTbs.add(item.substring(0, m.start())); } } // @Note: currently scalar operation on variable is not support. // For example, tmp = cur.val - 3, because this // one can be directly integrated into other operations by using UDF. ArrayList<String> attrList = new ArrayList<String>(); ArrayList<String> fromList = new ArrayList<String>(); String tbName = context; if (usedTbs.size() <= 1) { if (context.equals("cur")) { tbName = usedTbs.iterator().next(); } } attrList.add(tbName + ".id AS id"); attrList.add(tbName + ".val AS val"); fromList.addAll(usedTbs); this.blocks.add(new SelectIntoBlock(// The stage string. "genVar", // The indent level. this.indentLevel, // The attribute list. attrList, // The variable name, // used as table name. varName, // The from tables. fromList, // The predicates. exp, // Join thest tables on (vertex)id. true, // No group by. null)); this.tableNameList.add(varName); } /** * @brief Join several tables with id as common attributes. * @param targetTb The table to store result. * @param tbList The table involved, joined by the common id attributes. * @param exp The predicates. * @param valFrom The table where value is from. */ private void join(String targetTb, ArrayList<String> tbList, String exp, String valFrom) { ArrayList<String> attrList = new ArrayList<String>(); attrList.add(tbList.get(0) + ".id AS id"); attrList.add(valFrom + ".val AS val"); this.blocks.add(new SelectIntoBlock("join", this.indentLevel, attrList, targetTb, tbList, exp, true, null)); this.tableNameList.add(targetTb); } /** * @brief Send messages. The way of join will depend on the send direction. * For example, if send to out-going neighbours, should join on edge.src; if * send to all neighbours, a union should be used. * @param dir The direction. * @param content The content. * @param context The context of the send statement. */ private void sendMsg(String dir, String content, String context) { String[] attrs = {"src", "dest"}; String joinStr = ""; // The way of join. 0 means no in_cnts and out_cnts are used. 1 means only // in_cnts is used. 2 means only out_cnts is used. 3 means both are used. int joinFlag = 0; ArrayList<String> attrList = new ArrayList<String>(); ArrayList<String> fromList = new ArrayList<String>(); String atomics[] = content.split(" |\\+|-|\\*|/|<|>|(==)|(AND)|(OR)"); Pattern p = Pattern.compile("\\.(val)|(id)"); HashSet<String> usedTbs = new HashSet<String>(); for (String item : atomics) { item = item.trim(); if (item.equals("")) continue; Matcher m = p.matcher(item); // System.out.println(item); while (m.find()) { // Mark relevant tables. String tbName = item.substring(0, m.start()); usedTbs.add(item.substring(0, m.start())); fromList.add(tbName); this.senders.add(tbName); } } fromList.add("edge"); if (content.contains("out_cnts")) { fromList.add("out_cnts"); joinFlag |= 0x2; } if (content.contains("in_cnts")) { fromList.add("in_cnts"); joinFlag |= 0x1; } String pred = null; if ((joinFlag >> 1) == 1) { joinStr += " AND out_cnts.id = " + context + ".id"; } if ((joinFlag & 1) == 1) { joinStr += " AND in_cnts.id = " + context + ".id"; } switch (dir) { // Only send to in neighbours and out neighbours. case "in": case "out": { int flag = dir.equals("in") ? 0 : 1; attrList.add(attrs[flag] + " AS id"); attrList.add(content + " AS val"); pred = "edge." + attrs[1-flag] + " = " + context + ".id" + joinStr; String groupBy = dir.equals("in") ? "src" : "dest"; this.blocks.add(new SelectIntoBlock("sendMsg", this.indentLevel, attrList, "message", fromList, pred, true, groupBy)); break; } // Send to all neighbours. case "all": { int flag = 0; attrList.add(attrs[flag] + " AS id"); attrList.add(content + " AS val"); SelectIntoBlock lhs = new SelectIntoBlock("genMsg0", this.indentLevel + 1, attrList, null, fromList, "edge." + attrs[1-flag] + " = "+context+".id " + joinStr, false, "src"); flag = 1 - flag; attrList.clear(); attrList.add(attrs[flag] + " AS id"); attrList.add(content + " AS val"); SelectIntoBlock rhs = new SelectIntoBlock("genMsg1", this.indentLevel + 1, attrList, null, fromList, "edge." + attrs[1-flag] + " = "+context+".id " + joinStr, false, "dest"); ArrayList<String> newAttrList = new ArrayList<String>(); newAttrList.add("*"); this.blocks.add(new SelectIntoBlock("sendMsg", // The stage string. this.indentLevel, // The indent level. newAttrList, // The attribute list. "message", // The new table name. lhs, // Left table SQL. rhs, // Right table SQL. "union all")); // Union operation. } // Don't send any messages. case "no": break; } this.tableNameList.add("message"); this.convertedOptions.put("contentStr", content); } /** * @brief Get the type of the statement. * @param stat The SQL statement string. * @return The type. */ private StatementType getStatementType(String stat) { if (stat.startsWith("if")) return StatementType.BEGIN_IF; if (stat.startsWith("setVal")) return StatementType.MUTATE_VALUE; if (stat.startsWith("send")) return StatementType.SEND_MSG; if (stat.startsWith("}")) return StatementType.END_IF; return StatementType.ASSIGNMENT; } /** * @brief Update values and send messages. */ private void updateAndSend() { String[] statements = options.get("UpdateAndSend").split("\n"); // Contexts record the current level of table value is used. The "cur" is // the default value. If you are wrapped in a if statment, for example, // if (update) {}, "update" should be the context. Stack<String> contexts = new Stack<String>(); // New tables generated. String context = "cur"; // setValue() will change newVal. String newVal = null; for (int i = 0; i < statements.length; ++i) { String stat = statements[i]; switch (this.getStatementType(stat)) { case BEGIN_IF: { // TODO(Jing): Currently the if just support single flow control. But it's // easy to support things like // if (isBig AND isSmall), if (isBig Or isSmall) contexts.push(context); String flowControl = stat.substring(stat.indexOf('(')+1, stat.lastIndexOf(')')).trim(); if (context.equals("cur")) { context = flowControl; } else { // join context table and flow control table String targetTb = TbNameGen.getNextTbName(); ArrayList<String> tbList = new ArrayList<String>(); tbList.add(context); tbList.add(flowControl); this.join(targetTb, tbList, null, flowControl); context = targetTb; } break; } case MUTATE_VALUE: { newVal = stat.substring(stat.indexOf('(')+1, stat.lastIndexOf(')')) .trim(); newVal = newVal.replace("getAggregationVal()", context + ".val"); newVal = newVal.replace("getVal()", "next.val"); blocks.add(new UpdateVertexBlock("setVal", this.indentLevel, context, newVal)); this.convertedOptions.put("setValContext", context); this.convertedOptions.put("setValNewVal", newVal); if (context.equals("cur")) { this.convertedOptions.put("isSender", "all"); } else { this.convertedOptions.put("isSender", "notAll"); } break; } case SEND_MSG: { String[] params = stat.substring(stat.indexOf('(') + 1, stat.lastIndexOf(')')).split(","); // record send direction. for (int j = 0; j < params.length; ++j) { params[j] = params[j].trim(); } this.convertedOptions.put("msgDir", params[0]); // params[0] should be either all, in, out or no, which indicates the // message sending direction. params[1] should be the message value. params[1] = params[1].replace("getVal()", "next.val"); params[1] = params[1].replace("getAggregationVal()", context + ".val"); sendMsg(params[0], params[1], context); this.convertedOptions.put("SendMsgDir", params[0]); break; } case END_IF: { context = contexts.pop(); break; } case ASSIGNMENT: { this.genTbForVar(context, stat); break; } } } } /** @brief Drop table. * @param s The name of the table. */ private void dropTable(String s) { this.blocks.add(new DropTableBlock("drop" + s, this.indentLevel, s)); } /** * @brief Work in every iteration. */ private void superstep() { this.combineMsg(); this.dropTable("message"); this.tableNameList.remove("message"); this.updateAndSend(); } /** * @brief Copy data from vertex table. * @return The SQL statement. */ private void copyVertex() { String initVal = options.get("InitiateVal"); switch (initVal) { case "INT_MAX": { initVal = Common.INT_MAX; break; } case "INT_MIN": { initVal = Common.INT_MIN; break; } case "DBL_MAX": { initVal = Common.DBL_MAX; break; } case "DBL_MIN": { initVal = Common.DBL_MIN; break; } } ArrayList<String> attrList = new ArrayList<String>(); attrList.add("id AS id"); attrList.add("CAST(" + initVal + " AS "+ this.options.get("VertexValType") + ")" + " AS val"); ArrayList<String> fromList = new ArrayList<String>(); fromList.add("vertex"); this.blocks.add(new SelectIntoBlock("copyVertex", // The stage string. this.indentLevel, // The indent level. attrList, // The attribute list. "next", // The table name. fromList, // The from tables. null, // No predicates. false, // Don't join table on id. null)); // No group by. this.tableNameList.add("next"); } /** * @brief Init message table. * @param attrs The attrs of message table. */ private void initMsg(String[] attrs) { ArrayList<String> attrList = new ArrayList<String>(); ArrayList<String> fromList = new ArrayList<String>(); if (attrs[0].equals("ALL")) { attrList.add("*"); attrList.add(attrs[1]); fromList.add("vertex"); this.blocks.add(new InsertBlock("initMsg", // The stage string. this.indentLevel, // The indent level. "*, " + "CAST(" + attrs[1] + " as " + this.options.get("MessageValType") + ")", // The attribute string. "message", // The new table. "vertex")); // The from table. } else { this.blocks.add(new Block("initMsg", // The stage string. this.indentLevel, // The indent level. // The SQL. "INSERT INTO message VALUES(" + attrs[0] + ", " + "CAST(" + attrs[1] + " as " + this.options.get("MessageValType") + ")" + ");")); } } /** * @brief Create table. * @param stage The stage string. * @param tbName The new table name. * @param attrs The attribute list. */ private void createTable(String stage, String tbName, String[] attrs) { this.blocks.add(new CreateTableBlock(stage, // The staget string. this.indentLevel, // The indent level. tbName, // The new table name. attrs)); // The attributes. this.tableNameList.add(tbName); } /** * @brief Init. */ private void init() { this.blocks.add( new DropTableBlock("initdropcur", this.indentLevel, "cur")); this.blocks.add( new DropTableBlock("initdropmsg", this.indentLevel, "message")); this.blocks.add( new DropTableBlock("initdropnext", this.indentLevel, "next")); this.blocks.add( new DropTableBlock("initdropoutcnts", this.indentLevel, "out_cnts")); this.blocks.add( new DropTableBlock("initdroptoupdate", this.indentLevel, "toupdate")); this.blocks.add( new DropIndexBlock("initdropsrcindex", this.indentLevel, "idx_src", "edge")); this.blocks.add( new DropIndexBlock("initdropdestindex", this.indentLevel, "idx_dest", "edge")); // Copy Vertex table. this.copyVertex(); String initMsg = options.get("InitialMessage"); initMsg = initMsg.substring(initMsg.indexOf('(') + 1, initMsg.lastIndexOf(')')).trim(); String initMsgStrs[] = initMsg.split(","); for (int i = 0; i < initMsgStrs.length; ++i) { initMsgStrs[i] = initMsgStrs[i].trim(); } String[] attrs = {"id int" , "val " + options.get("MessageValType")}; this.createTable("createMsg", "message", attrs); this.initMsg(initMsgStrs); // Generate in_cnts table or out_cnts table. if (options.get("UpdateAndSend").contains("in_cnts")) { this.generateCnts(true); } if (options.get("UpdateAndSend").contains("out_cnts")) { this.generateCnts(false); } } /** * @brief Generate SQL. */ public void translate() { init(); beginWhile(); superstep(); endWhile(); } }
true
361994e37cfc0a33ddc57e4b03940288cc15a87f
Java
eirunye/Eirunye_SpringBoot_Notes
/Spring_Boot_JPA/src/main/java/com/eirunye/spring_boot_jpa/repository/UserRepository.java
UTF-8
1,620
2.359375
2
[]
no_license
package com.eirunye.spring_boot_jpa.repository; import com.eirunye.spring_boot_jpa.bean.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.List; /** * Author Eirunye * Created by on 2018/9/29. * Describe * 提示:这里需要注意的是命名规则 查找find,删除delete等等 */ public interface UserRepository extends JpaRepository<User, Integer> { /** * @param id 根据id获取当前user数据 * @return user */ User findAllById(Integer id); /** * 通过用户名和密码来获取用户 * @param username 参数用户名 * @param password 参数密码 * @return 返回user */ User findAllByUsernameAndPassword(String username, String password); /** * 模糊查询 自定义查询语句 * @param username * @return */ @Query(value = "select * from user u where u.username like %:username%",nativeQuery=true) List<User> findAllByUsername(@Param("username") String username); @Modifying @Transactional @Query(value = "insert into user(username,password,create_time,update_time) values(?1,?2,?3,?4)",nativeQuery = true) int findAllByUsernameAndPasswordAndCreateTimeAndUpdateTime(String username, String password, Date create_time,Date update_time); }
true
0b2b93f1f752fc3e4270ac74525f95dc096a2142
Java
dnuttle/algorithms
/src/test/java/net/nuttle/algorithms/search/TwoSumTest.java
UTF-8
316
2.171875
2
[]
no_license
package net.nuttle.algorithms.search; import org.junit.Test; import edu.princeton.cs.algs4.StdOut; public class TwoSumTest { @Test public void test1() { int[] vals = {-2, -1, -1, 0, 0, 0, 0, 1, 1, 2, 2}; StdOut.println(TwoSum.faster(vals)); //Assert.assertEquals(6, TwoSum.faster(vals)); } }
true
d25301d19213a29fbe593d29d8d238f3f4b3e491
Java
FirstTestOrganizationForLearning/hotel
/b2b_common/src/main/java/com/fntx/common/domain/dto/HotelStatusEntityBean.java
UTF-8
3,514
2.234375
2
[]
no_license
package com.fntx.common.domain.dto; import com.alibaba.fastjson.annotation.JSONField; import java.io.Serializable; import java.util.Objects; /** * @Copyright (C), 2019, 琥珀丶时光 * @ClassName: HotelStatusEntityBean * @Author: 王俊文 * @Date: 19-7-18 下午4:58 * @Description: TODO */ public class HotelStatusEntityBean implements Serializable { private static final long serialVersionUID = 1L; /** * Hotel : 4732165 * MinPrice : 55 * MinPrice_MyCurrency : 55 * Currency_minPrice : RMB * MinPriceRoom : 146532285 * MinPriceInfoEntity : {"MinPrice_AfterTax":{"MinPrice_CashBack":{"MinPrice":55,"MinPrice_OriginalCurrency":55,"OriginalCurrency":"RMB","MinPrice_RoomID":146532285}}} */ @JSONField(name="Hotel") private Long Hotel; @JSONField(name="MinPrice") private Double MinPrice; @JSONField(name="MinPrice_MyCurrency") private Double MinPrice_MyCurrency; @JSONField(name="Currency_minPrice") private String Currency_minPrice; @JSONField(name="MinPriceRoom") private Long MinPriceRoom; @JSONField(name="MinPriceInfoEntity") private MinPriceInfoEntityBean MinPriceInfoEntity; public Long getHotel() { return Hotel; } public void setHotel(Long Hotel) { this.Hotel = Hotel; } public Double getMinPrice() { return MinPrice; } public void setMinPrice(Double MinPrice) { this.MinPrice = MinPrice; } public Double getMinPrice_MyCurrency() { return MinPrice_MyCurrency; } public void setMinPrice_MyCurrency(Double MinPrice_MyCurrency) { this.MinPrice_MyCurrency = MinPrice_MyCurrency; } public String getCurrency_minPrice() { return Currency_minPrice; } public void setCurrency_minPrice(String Currency_minPrice) { this.Currency_minPrice = Currency_minPrice; } public Long getMinPriceRoom() { return MinPriceRoom; } public void setMinPriceRoom(Long MinPriceRoom) { this.MinPriceRoom = MinPriceRoom; } public MinPriceInfoEntityBean getMinPriceInfoEntity() { return MinPriceInfoEntity; } public void setMinPriceInfoEntity(MinPriceInfoEntityBean MinPriceInfoEntity) { this.MinPriceInfoEntity = MinPriceInfoEntity; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof HotelStatusEntityBean)) return false; HotelStatusEntityBean that = (HotelStatusEntityBean) o; return Hotel.equals(that.Hotel) && MinPrice.equals(that.MinPrice) && MinPrice_MyCurrency.equals(that.MinPrice_MyCurrency) && Currency_minPrice.equals(that.Currency_minPrice) && MinPriceRoom.equals(that.MinPriceRoom) && MinPriceInfoEntity.equals(that.MinPriceInfoEntity); } @Override public int hashCode() { return Objects.hash(Hotel, MinPrice, MinPrice_MyCurrency, Currency_minPrice, MinPriceRoom, MinPriceInfoEntity); } @Override public String toString() { return "HotelStatusEntityBean{" + "Hotel=" + Hotel + ", MinPrice=" + MinPrice + ", MinPrice_MyCurrency=" + MinPrice_MyCurrency + ", Currency_minPrice='" + Currency_minPrice + '\'' + ", MinPriceRoom=" + MinPriceRoom + ", MinPriceInfoEntity=" + MinPriceInfoEntity + '}'; } }
true
e94192da1e4e84c4add78ff9795a73321b36edba
Java
zcq18962285918/hp-ssm-
/src/main/java/cn/pzhu/mapper/ItemMapper.java
UTF-8
273
1.625
2
[ "Apache-2.0" ]
permissive
package cn.pzhu.mapper; import cn.pzhu.base.BaseDao; import cn.pzhu.po.Item; import org.apache.ibatis.annotations.Param; import java.util.List; public interface ItemMapper extends BaseDao<Item> { List<Item> listtj(@Param("list") List<Integer> types); }
true
2edeb0151ae88a09e8b66d29420c0e97e95b0adc
Java
precipices/SPM
/文件操作test/FileTest/src/test/ListFileServlet.java
GB18030
5,310
2.796875
3
[]
no_license
package test; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class ListFileServlet */ @WebServlet("/ListFileServlet") public class ListFileServlet extends HttpServlet { private static final long serialVersionUID = 1L; public ListFileServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * Ҫе޸ * 1.Ҫsessionõû ٽuserTypeΪ"teacher","student""manager" * 2.ûΪʦ,Ҫsessionõ½ʦ ٽteacherNameΪ½ʦ */ String userType = "manager";// û String teacherName = ""; // õuploadĿ¼ File rootPath = new File(this.getServletContext().getRealPath("/WEB-INF/upload")); // uploadĿ¼,򴴽 if (!rootPath.exists()) { System.out.println("Ŀ¼" + rootPath + ",..."); rootPath.mkdirs(); } // key=teacherName,value=isCheckedDirectoryListMap Map teacherMap = new HashMap(); //rootPathȡļ뵽teacherMap if(listFile(rootPath,teacherMap)==false) { String message = "ӦóֵĴ:[ͨ][]ļ!!"; request.setAttribute("message", message); request.getRequestDispatcher("jspForUpload/message.jsp").forward(request, response); return; } request.setAttribute("teacherMap", teacherMap); if ("teacher".equals(userType)) { // ûΪʦ,õʦ,תteacherShowFile.jspʾʦļ request.setAttribute("teacherName", teacherName); request.getRequestDispatcher("jspForUpload/teacherShowFile.jsp").forward(request, response); return; } else if ("student".equals(userType)) { // ûΪѧ,תstudentShowFile.jspʾпصļ request.getRequestDispatcher("jspForUpload/studentShowFile.jsp").forward(request, response); return; } else if ("manager".equals(userType)) { // ûΪԱ,תuploadAgree.jspļĴ request.getRequestDispatcher("jspForUpload/managerShowFile.jsp").forward(request, response); return; } else { String message = "ӦóֵĴ:teacher,student,managerû!!"; request.setAttribute("message", message); request.getRequestDispatcher("jspForUpload/message.jsp").forward(request, response); return; } } //rootPathȡļ뵽teacherMap public boolean listFile(File rootPath, Map teacherMap) { /* * ļṹ: * 1.ϴļWEB-INF/upload * 2.ÿʦһʦļ * 3.ʦļĿ¼:[ͨ][] * 4.[ͨ][]ļ´ʦļ,ļϴʱԭļ */ // õʦļб File[] teacherDirectoryList = rootPath.listFiles(); // ÿʦļ for (File teacherDirectory : teacherDirectoryList) { // teacherMapkey,valueֵ String teacherName = teacherDirectory.getName();// õʦ List isCheckedDirectoryList = new ArrayList();// [ͨ][]list teacherMap.put(teacherName, isCheckedDirectoryList); List checkedFileList = new ArrayList();// ͨļlist List unCheckedFileList = new ArrayList();// дļlist isCheckedDirectoryList.add(checkedFileList); isCheckedDirectoryList.add(unCheckedFileList); // õʦļµ[ͨ][]ļ File[] isCheckedDirectory = teacherDirectory.listFiles(); // [ͨ][]ļ for (File isChecked : isCheckedDirectory) { if (isChecked.getName().equals("ͨ")) { // õͨļ File[] checkedFiles = isChecked.listFiles(); // ͨļ for (File checkedFile : checkedFiles) { // ļcheckedFileList checkedFileList.add(checkedFile.getName()); System.out.println(checkedFile.getName()); } } else if (isChecked.getName().equals("")) { // õд˵ļ File[] unCheckedFiles = isChecked.listFiles(); // д˵ļ for (File unCheckedFile : unCheckedFiles) { // ļunCheckedFileList unCheckedFileList.add(unCheckedFile.getName()); System.out.println(unCheckedFile.getName()); } } else { return false; } } } return true; } }
true
f834800ec116c0508ed04403613b2ba0f5a13d01
Java
multi-os-engine/moe-natj
/src/main/java/org/moe/natj/general/ptr/impl/IntPtrImpl.java
UTF-8
16,387
2.390625
2
[ "Apache-2.0" ]
permissive
/* Copyright 2014-2016 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.moe.natj.general.ptr.impl; import org.moe.natj.c.CRuntime; import org.moe.natj.general.Pointer; import org.moe.natj.general.ptr.IGuardedPtr; import org.moe.natj.general.ptr.IntPtr; class IntPtrImpl extends VoidPtrImpl implements IntPtr { protected static final int ELEM_SIZE = CRuntime.INT_SIZE; // Reserved for NatJ runtime protected IntPtrImpl(Pointer peer) { super(peer); } // For ofs and java.nio.Buffer creation protected IntPtrImpl(long peer, Object bufferOwner) { super(peer, false, bufferOwner); } // For public creation IntPtrImpl(int capacity, boolean owned) { super(CRuntime.allocInt(capacity), owned, null); } @Override public boolean isConstPtr() { return false; } @Override public final Integer get() { return getValue(0); } @Override public final Integer get(int idx) { return getValue(idx); } @Override public final int getValue() { return getValue(0); } @Override public int getValue(int idx) { return CRuntime.loadInt(getRoot(), idx); } @Override public final Integer[] toArray(int length) { return toArray(0, length); } @Override public Integer[] toArray(int fromIndex, int toIndex) { if (toIndex < fromIndex) { throw new IllegalArgumentException(); } int length = toIndex - fromIndex; Integer[] array = new Integer[length]; copyTo(fromIndex, array, 0, length); return array; } @Override public final int[] toIntArray(int length) { return toIntArray(0, length); } @Override public int[] toIntArray(int fromIndex, int toIndex) { if (toIndex < fromIndex) { throw new IllegalArgumentException(); } return CRuntime.createIntArray(getRoot() + fromIndex * ELEM_SIZE, toIndex - fromIndex); } @Override public final void copyTo(Integer[] dest) { if (dest == null) { throw new IllegalArgumentException(); } copyTo(0, dest, 0, dest.length); } @Override public final void copyTo(Integer[] dest, int length) { if (dest == null) { throw new IllegalArgumentException(); } copyTo(0, dest, 0, length); } @Override public void copyTo(int srcOffset, Integer[] dest, int destOffset, int length) { if (dest == null || destOffset < 0 || length < 0 || destOffset + length > dest.length) { throw new IllegalArgumentException(); } final long root = getRoot(); for (int idx = 0; idx < length; ++idx, ++srcOffset, ++destOffset) { dest[destOffset] = CRuntime.loadInt(root, srcOffset); } } @Override public final void copyTo(int[] dest) { if (dest == null) { throw new IllegalArgumentException(); } copyTo(0, dest, 0, dest.length); } @Override public final void copyTo(int[] dest, int length) { if (dest == null) { throw new IllegalArgumentException(); } copyTo(0, dest, 0, length); } @Override public void copyTo(int srcOffset, int[] dest, int destOffset, int length) { if (dest == null || destOffset < 0 || length < 0 || destOffset + length > dest.length) { throw new IllegalArgumentException(); } CRuntime.copyFromNativeIntArray(dest, destOffset, getRoot(), srcOffset, length); } @Override public void set(Integer obj) { setValue(obj); } @Override public void set(int idx, Integer obj) { setValue(idx, obj); } @Override public void setValue(int value) { setValue(0, value); } @Override public void setValue(int idx, int value) { CRuntime.storeInt(getRoot(), idx, value); } @Override public void copyFrom(Integer[] src) { if (src == null) { throw new IllegalArgumentException(); } copyFrom(src, 0, 0, src.length); } @Override public void copyFrom(Integer[] src, int destOffset) { if (src == null) { throw new IllegalArgumentException(); } copyFrom(src, 0, destOffset, src.length); } @Override public void copyFrom(Integer[] src, int destOffset, int length) { if (src == null) { throw new IllegalArgumentException(); } copyFrom(src, 0, destOffset, length); } @Override public void copyFrom(Integer[] src, int srcOffset, int destOffset, int length) { if (src == null || srcOffset < 0 || length < 0 || srcOffset + length > src.length) { throw new IllegalArgumentException(); } final long root = getRoot(); for (int i = 0; i < length; ++i, ++srcOffset, ++destOffset) { CRuntime.storeInt(root, destOffset, src[srcOffset]); } } @Override public void copyFrom(int[] src) { if (src == null) { throw new IllegalArgumentException(); } copyFrom(src, 0, 0, src.length); } @Override public void copyFrom(int[] src, int destOffset) { if (src == null) { throw new IllegalArgumentException(); } copyFrom(src, 0, destOffset, src.length); } @Override public void copyFrom(int[] src, int destOffset, int length) { if (src == null) { throw new IllegalArgumentException(); } copyFrom(src, 0, destOffset, length); } @Override public void copyFrom(int[] src, int srcOffset, int destOffset, int length) { if (src == null || srcOffset < 0 || length < 0 || srcOffset + length > src.length) { throw new IllegalArgumentException(); } CRuntime.copyIntArray(getRoot(), destOffset, src, srcOffset, length); } @Override public IntPtr ofs(int elemOffset) { return new IntPtrImpl(getRoot() + elemOffset * ELEM_SIZE, this); } @Override public boolean isGuarded() { return false; } @Override public final IntPtr getGuarded(int length) { return getGuarded(0, length); } @Override public IntPtr getGuarded(int fromIndex, int toIndex) { if (toIndex < fromIndex) { throw new IllegalArgumentException(); } return new GuardedIntPtrImpl(getRoot(), this, fromIndex, toIndex); } @Override public int getGuardLow() { throw new UnsupportedOperationException(); } @Override public int getGuardHigh() { throw new UnsupportedOperationException(); } static class ConstIntPtrImpl extends IntPtrImpl { // Reserved for NatJ runtime protected ConstIntPtrImpl(Pointer peer) { super(peer); } // For ofs creation only protected ConstIntPtrImpl(long peer, Object bufferOwner) { super(peer, bufferOwner); } // For public creation ConstIntPtrImpl(int capacity, boolean owned) { super(capacity, owned); } @Override public boolean isConstPtr() { return true; } @Override public void set(Integer obj) { throw new UnsupportedOperationException(); } @Override public void set(int idx, Integer obj) { throw new UnsupportedOperationException(); } @Override public final void setValue(int value) { throw new UnsupportedOperationException(); } @Override public final void setValue(int idx, int value) { throw new UnsupportedOperationException(); } @Override public final void copyFrom(Integer[] src) { throw new UnsupportedOperationException(); } @Override public final void copyFrom(Integer[] src, int destOffset) { throw new UnsupportedOperationException(); } @Override public void copyFrom(Integer[] src, int destOffset, int length) { throw new UnsupportedOperationException(); } @Override public final void copyFrom(Integer[] src, int srcOffset, int destOffset, int length) { throw new UnsupportedOperationException(); } @Override public final void copyFrom(int[] src) { throw new UnsupportedOperationException(); } @Override public final void copyFrom(int[] src, int destOffset) { throw new UnsupportedOperationException(); } @Override public void copyFrom(int[] src, int destOffset, int length) { throw new UnsupportedOperationException(); } @Override public final void copyFrom(int[] src, int srcOffset, int destOffset, int length) { throw new UnsupportedOperationException(); } @Override public final IntPtr ofs(int elemOffset) { return new ConstIntPtrImpl(getRoot() + elemOffset * ELEM_SIZE, this); } @Override public IntPtr getGuarded(int fromIndex, int toIndex) { if (toIndex < fromIndex) { throw new IllegalArgumentException(); } return new GuardedConstIntPtrImpl(getRoot(), this, fromIndex, toIndex); } } private static class GuardedIntPtrImpl extends IntPtrImpl implements IGuardedPtr { protected final int low; protected final int hi; // For ofs and guarded creation only public GuardedIntPtrImpl(long peer, Object bufferOwner, int low, int hi) { super(peer, bufferOwner); if (low > hi) { throw new IllegalArgumentException(); } this.low = low; this.hi = hi; } @Override public boolean checkIndex(int index) { return index >= low && index < hi; } @Override public boolean isGuarded() { return true; } @Override public int getValue(int idx) { if (!checkIndex(idx)) { throw new IndexOutOfBoundsException(); } return super.get(idx); } @Override public Integer[] toArray(int fromIndex, int toIndex) { if (!checkIndex(fromIndex) || !checkIndex(toIndex)) { throw new IndexOutOfBoundsException(); } return super.toArray(fromIndex, toIndex); } @Override public int[] toIntArray(int fromIndex, int toIndex) { if (!checkIndex(fromIndex) || !checkIndex(toIndex)) { throw new IndexOutOfBoundsException(); } return super.toIntArray(fromIndex, toIndex); } @Override public void copyTo(int srcOffset, Integer[] dest, int destOffset, int length) { if (!checkIndex(srcOffset) || !checkIndex(srcOffset + length - 1)) { throw new IndexOutOfBoundsException(); } super.copyTo(srcOffset, dest, destOffset, length); } @Override public void copyTo(int srcOffset, int[] dest, int destOffset, int length) { if (!checkIndex(srcOffset) || !checkIndex(srcOffset + length - 1)) { throw new IndexOutOfBoundsException(); } super.copyTo(srcOffset, dest, destOffset, length); } @Override public void setValue(int idx, int value) { if (!checkIndex(idx)) { throw new IndexOutOfBoundsException(); } super.set(idx, value); } @Override public void copyFrom(Integer[] src, int srcOffset, int destOffset, int length) { if (!checkIndex(destOffset) || !checkIndex(destOffset + length - 1)) { throw new IndexOutOfBoundsException(); } super.copyFrom(src, srcOffset, destOffset, length); } @Override public void copyFrom(int[] src, int srcOffset, int destOffset, int length) { if (!checkIndex(destOffset) || !checkIndex(destOffset + length - 1)) { throw new IndexOutOfBoundsException(); } super.copyFrom(src, srcOffset, destOffset, length); } @Override public IntPtr ofs(int elemOffset) { return new GuardedIntPtrImpl(getRoot() + elemOffset * ELEM_SIZE, this, low + elemOffset, hi + elemOffset); } @Override public IntPtr getGuarded(int fromIndex, int toIndex) { if (toIndex < fromIndex) { throw new IllegalArgumentException(); } return new GuardedIntPtrImpl(getRoot(), this, fromIndex, toIndex); } @Override public int getGuardLow() { return low; } @Override public int getGuardHigh() { return hi; } } private static class GuardedConstIntPtrImpl extends GuardedIntPtrImpl { // For ofs and guarded creation only public GuardedConstIntPtrImpl(long peer, Object bufferOwner, int low, int hi) { super(peer, bufferOwner, low, hi); } @Override public boolean isConstPtr() { return true; } @Override public void set(Integer obj) { throw new UnsupportedOperationException(); } @Override public void set(int idx, Integer obj) { throw new UnsupportedOperationException(); } @Override public final void setValue(int value) { throw new UnsupportedOperationException(); } @Override public final void setValue(int idx, int value) { throw new UnsupportedOperationException(); } @Override public final void copyFrom(Integer[] src) { throw new UnsupportedOperationException(); } @Override public final void copyFrom(Integer[] src, int destOffset) { throw new UnsupportedOperationException(); } @Override public void copyFrom(Integer[] src, int destOffset, int length) { throw new UnsupportedOperationException(); } @Override public final void copyFrom(Integer[] src, int srcOffset, int destOffset, int length) { throw new UnsupportedOperationException(); } @Override public final void copyFrom(int[] src) { throw new UnsupportedOperationException(); } @Override public final void copyFrom(int[] src, int destOffset) { throw new UnsupportedOperationException(); } @Override public final void copyFrom(int[] src, int srcOffset, int destOffset) { throw new UnsupportedOperationException(); } @Override public final void copyFrom(int[] src, int srcOffset, int destOffset, int length) { throw new UnsupportedOperationException(); } @Override public final IntPtr ofs(int elemOffset) { return new GuardedConstIntPtrImpl(getRoot() + elemOffset * ELEM_SIZE, this, low + elemOffset, hi + elemOffset); } @Override public IntPtr getGuarded(int fromIndex, int toIndex) { if (toIndex < fromIndex) { throw new IllegalArgumentException(); } return new GuardedConstIntPtrImpl(getRoot(), this, fromIndex, toIndex); } } }
true
dd1ffef02c21be895257694da77dfdb6a9f8379d
Java
t0903/attendance
/app/src/main/java/com/lyzyxy/attendance/ScanActivity.java
UTF-8
6,031
1.960938
2
[]
no_license
package com.lyzyxy.attendance; import android.content.Intent; import android.os.Vibrator; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.lyzyxy.attendance.model.User; import com.lyzyxy.attendance.network.RetrofitRequest; import com.lyzyxy.attendance.network.result.RequestResult; import com.lyzyxy.attendance.util.AuthUtil; import com.lyzyxy.attendance.util.Constant; import com.lyzyxy.attendance.util.MsgUtil; import java.util.HashMap; import java.util.Map; import cn.bingoogolapple.qrcode.core.QRCodeView; import cn.bingoogolapple.qrcode.zxing.ZXingView; public class ScanActivity extends BaseActivity implements QRCodeView.Delegate, View.OnClickListener{ private static final String TAG = "ScanActivity"; private static final int REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY = 666; private ZXingView mZXingView; private TextView open_close_flashlight; private boolean flashligthopend = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scan); Toolbar toolbar = findViewById(R.id.toolbar); toolbar.setTitle(""); toolbar.setNavigationIcon(R.drawable.icon_back); setSupportActionBar(toolbar); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ScanActivity.this.finish(); } }); mZXingView = findViewById(R.id.zbarview); mZXingView.setDelegate(this); open_close_flashlight = findViewById(R.id.open_close_flashlight); open_close_flashlight.setOnClickListener(this); } @Override protected void onStart() { super.onStart(); mZXingView.startCamera(); // 打开后置摄像头开始预览,但是并未开始识别 // mZBarView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览,但是并未开始识别 mZXingView.startSpotAndShowRect(); // 显示扫描框,并开始识别 } @Override protected void onStop() { mZXingView.stopCamera(); // 关闭摄像头预览,并且隐藏扫描框 super.onStop(); } @Override protected void onDestroy() { mZXingView.onDestroy(); // 销毁二维码扫描控件 super.onDestroy(); } private void vibrate() { Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); vibrator.vibrate(200); } @Override public void onScanQRCodeSuccess(String result) { Log.i(TAG, "result:" + result); //Toast.makeText(ScanActivity.this,"扫描结果为:" + result,Toast.LENGTH_SHORT).show(); if(result.startsWith("content:id:")){ int id = Integer.parseInt(result.substring(11)); joinCourse(id); }else{ Toast.makeText(ScanActivity.this,"二维码不正确!",Toast.LENGTH_SHORT).show(); vibrate(); mZXingView.startSpot(); // 重新开始识别 } } private void joinCourse(int id){ String url = Constant.URL_BASE + "user/join"; Map<String,Object> params = new HashMap<String, Object>(); params.put("userId",AuthUtil.user.getId()); params.put("classId",id); RetrofitRequest.sendPostRequest(url, params,null, false, new RetrofitRequest.ResultHandler(ScanActivity.this) { @Override public void onBeforeResult() { // 这里可以放关闭loading } @Override public void onResult(RequestResult r) { if(r.getCode() == Constant.SUCCESS){ vibrate(); Intent intent=new Intent(); setResult(RESULT_OK, intent); finish(); }else if(!r.getMsg().equals("")){ MsgUtil.msg(ScanActivity.this,r.getMsg()); }else{ MsgUtil.msg(ScanActivity.this,R.string.net_server_error); } } @Override public void onAfterFailure() { // 这里可以放关闭loading } }); } @Override public void onCameraAmbientBrightnessChanged(boolean isDark) { // 这里是通过修改提示文案来展示环境是否过暗的状态,接入方也可以根据 isDark 的值来实现其他交互效果 String tipText = mZXingView.getScanBoxView().getTipText(); String ambientBrightnessTip = "\n环境过暗,请打开闪光灯"; if (isDark) { if (!tipText.contains(ambientBrightnessTip)) { mZXingView.getScanBoxView().setTipText(tipText + ambientBrightnessTip); } } else { if (tipText.contains(ambientBrightnessTip)) { tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip)); mZXingView.getScanBoxView().setTipText(tipText); } } } @Override public void onScanQRCodeOpenCameraError() { Log.e(TAG, "打开相机出错"); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.open_close_flashlight: if(flashligthopend){ mZXingView.closeFlashlight(); flashligthopend = false; }else{ mZXingView.openFlashlight(); flashligthopend = true; } break; default: } } }
true
69cede0e6d96d54485442642808cdfdc721978c3
Java
pixeldev/fullpvp
/src/main/java/me/pixeldev/fullpvp/commands/FullPVPCommand.java
UTF-8
2,682
2.390625
2
[]
no_license
package me.pixeldev.fullpvp.commands; import me.fixeddev.ebcm.parametric.CommandClass; import me.fixeddev.ebcm.parametric.annotation.ACommand; import me.fixeddev.ebcm.parametric.annotation.Injected; import me.fixeddev.ebcm.parametric.annotation.Usage; import me.pixeldev.fullpvp.Delegates; import me.pixeldev.fullpvp.files.FileCreator; import me.pixeldev.fullpvp.message.Message; import me.pixeldev.fullpvp.utils.StringDecorator; import org.bukkit.command.CommandSender; import team.unnamed.inject.InjectAll; import team.unnamed.inject.name.Named; import java.util.Arrays; import java.util.List; @ACommand(names = "fullpvp") @InjectAll public class FullPVPCommand implements CommandClass { private StringDecorator stringDecorator; @Named("config") private FileCreator config; @Named("language") private FileCreator language; @Named("menu") private FileCreator menu; @Delegates private Message fileMessage; @ACommand(names = {"", "help"}) public boolean runMainCommand(@Injected(true) CommandSender sender) { List<String> messages = getHelpMessages(); messages.replaceAll(line -> stringDecorator.getCenteredMessage(line)); messages.forEach(sender::sendMessage); return true; } @ACommand(names = "reload") @Usage(usage = "§8- §9[config, language, menu]") public boolean runReloadCommand(@Injected(true) CommandSender sender, String file) { if (!sender.hasPermission("fullpvp.admin")) { sender.sendMessage(fileMessage.getMessage(null, "i18n.no-permission")); return true; } String successfully = fileMessage.getMessage(null, "reload.successfully").replace("%file%", file); switch (file) { case "config": config.reload(); sender.sendMessage(successfully); break; case "menu": menu.reload(); sender.sendMessage(successfully); break; case "language": language.reload(); sender.sendMessage(successfully); break; default: sender.sendMessage(fileMessage.getMessage(null, "reload.invalid")); break; } return true; } private List<String> getHelpMessages() { return Arrays.asList( "§9-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-", "§7FullPVP §9v0.0.1 §8- §7Desarrollado por §9PixelDev", "§9-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-" ); } }
true
c6bc86c5bf4deafb54c7c5f625d278d15724c2ec
Java
raduAndrada/SD-assignment1_2
/assignment1_2-data-access/src/ro/utcn/sd/assign/one/entities/Flgt.java
UTF-8
2,036
1.976563
2
[]
no_license
package ro.utcn.sd.assign.one.entities; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import com.google.common.base.MoreObjects; @Entity @Table(name = "FLGT") public class Flgt { @Id @GeneratedValue @Column(name = "id") private Long id; @Column(name = "flgt_nb") private String flgtNb; @Column(name = "apln_tp") private String aplnTp; @Column(name = "dprt_ct") private String dprtCt; @Column(name = "arr_tm") private String arrTm; @Column(name = "nb_st") private Integer nbSt; @OneToMany(mappedBy = "flgt", fetch = FetchType.LAZY) private Set<UsrFlgt> usrFlgts; @OneToMany(mappedBy = "flgt", fetch = FetchType.LAZY) private Set<Ct> cts; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getAplnTp() { return aplnTp; } public void setAplnTp(String aplnTp) { this.aplnTp = aplnTp; } public String getDprtCt() { return dprtCt; } public void setDprtCt(String dprtCt) { this.dprtCt = dprtCt; } public String getArrTm() { return arrTm; } public void setArrTm(String arrTm) { this.arrTm = arrTm; } public Integer getNbSt() { return nbSt; } public void setNbSt(Integer nbSt) { this.nbSt = nbSt; } public String getFlgtNb() { return flgtNb; } public void setFlgtNb(String flgtNb) { this.flgtNb = flgtNb; } public Set<UsrFlgt> getUsrFlgts() { return usrFlgts; } public void setUsrFlgts(Set<UsrFlgt> usrFlgts) { this.usrFlgts = usrFlgts; } public Set<Ct> getCts() { return cts; } public void setCts(Set<Ct> cts) { this.cts = cts; } @Override public String toString() { return MoreObjects.toStringHelper("").add("flgtNb", flgtNb).add("id", id).add("nbSt", nbSt) .add("cts", cts.toString()).add("arpnTp", aplnTp).add("arrTm", arrTm).add("arrTm", arrTm).toString(); } }
true
fc6c1693e7851ef5b964c652572b415fe2f468e7
Java
aaronfedyan/r4intellij
/src/com/r4intellij/typing/PipeInfo.java
UTF-8
2,001
2.25
2
[ "BSD-2-Clause", "MIT" ]
permissive
package com.r4intellij.typing; import com.intellij.psi.PsiElement; import com.r4intellij.psi.api.RCallExpression; import com.r4intellij.psi.api.ROperator; import com.r4intellij.psi.api.ROperatorExpression; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.List; import java.util.Objects; /** * @author Holger Brandl */ public class PipeInfo { public static final PipeInfo NONE = new PipeInfo(false, false); public final boolean firstArgInjected; public final boolean isPipeTarget; public PipeInfo(boolean isPipeTarget, boolean firstArgInjected) { this.firstArgInjected = firstArgInjected; this.isPipeTarget = isPipeTarget; } public static PipeInfo fromCallExpression(RCallExpression callExpression) { boolean isPipeTarget = isPipeTarget(callExpression); boolean firstArgInjected = isPipeTarget && !hasDotArgs(callExpression); return new PipeInfo(isPipeTarget, firstArgInjected); } private static boolean hasDotArgs(@NotNull RCallExpression callExpression) { return callExpression .getArgumentList().getExpressionList() .stream() .anyMatch(ex -> Objects.equals(ex.getText(), ".")); } private static boolean isPipeTarget(@NotNull RCallExpression callExpression) { // TODO convert to settings item List<String> pipeOps = Arrays.asList("%>%", "%<>%", "%T>"); PsiElement callExParent = callExpression.getParent(); if (callExParent != null && callExParent instanceof ROperatorExpression) { ROperatorExpression opExpression = (ROperatorExpression) callExParent; if (opExpression.getLeftExpr() == callExpression) return false; ROperator operator = opExpression.getOperator(); if (operator == null) return false; String opText = operator.getText(); return pipeOps.contains(opText); } return false; } }
true
f21f0ae90f144a38340a6ad5baf6133ec63095ce
Java
emretanriverdi/city-guide-app
/app/src/main/java/com/example/android/batumitravelguide/FoodActivity.java
UTF-8
1,860
2.015625
2
[ "Apache-2.0" ]
permissive
package com.example.android.batumitravelguide; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ListView; import java.util.Objects; public class FoodActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); setTitle(getString(R.string.local_dishes)); Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true); ItemList foodList = new ItemList(); foodList.add(getString(R.string.chvishtari), getString(R.string.chvishtari_text), R.drawable.food_chvishtari); foodList.add(getString(R.string.pkhali), getString(R.string.pkhali_text), R.drawable.georgian_walnut_salad); foodList.add(getString(R.string.georgian_kebab), getString(R.string.georgian_kebab_text), R.drawable.food_georgian_kebab_with_sour_plum_sauce); foodList.add(getString(R.string.khachapuri), getString(R.string.khachapuri_text), R.drawable.food_khachapuri); foodList.add(getString(R.string.trout), getString(R.string.trout_text), R.drawable.food_trout); foodList.add(getString(R.string.eggplant_walnut_rolls), getString(R.string.eggplant_walnut_rolls_text), R.drawable.food_eggplant_walnut_rolls); foodList.add(getString(R.string.kharcho), getString(R.string.kharcho_text), R.drawable.food_kharcho); foodList.add(getString(R.string.borjomi), getString(R.string.borjomi_text), R.drawable.food_borjomi); ItemAdapter foodAdapter = new ItemAdapter(this, foodList.get()); ListView listView = findViewById(R.id.custom_full_list); listView.setAdapter(foodAdapter); } @Override public boolean onSupportNavigateUp() { finish(); return true; } }
true
7f256eef99b399381357b67dc7d6307485a34720
Java
Parmerlee/SomethingImprotant
/HBMClient/src/main/java/com/bonc/mobile/hbmclient/state/view_switcher/State.java
UTF-8
135
1.617188
2
[]
no_license
package com.bonc.mobile.hbmclient.state.view_switcher; public interface State { public void entry(int index); public void out(); }
true
b2051385370841fe57cc8c56a38a8ab1b6f39146
Java
newohybat/civ-game-abandoned
/src/test/java/cz/muni/fi/civ/newohybat/bpmn/CitySurplusRulesJUnitTest.java
UTF-8
14,325
1.820313
2
[]
no_license
package cz.muni.fi.civ.newohybat.bpmn; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.drools.KnowledgeBase; import org.drools.base.RuleNameMatchesAgendaFilter; import org.drools.builder.KnowledgeBuilder; import org.drools.builder.KnowledgeBuilderConfiguration; import org.drools.builder.KnowledgeBuilderFactory; import org.drools.builder.ResourceType; import org.drools.builder.conf.PropertySpecificOption; import org.drools.event.rule.AfterActivationFiredEvent; import org.drools.event.rule.AgendaEventListener; import org.drools.impl.StatefulKnowledgeSessionImpl; import org.drools.io.ResourceFactory; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.ArgumentCaptor; import cz.muni.fi.civ.newohybat.drools.events.TurnEvent; import cz.muni.fi.civ.newohybat.persistence.facade.dto.CityDTO; import cz.muni.fi.civ.newohybat.persistence.facade.dto.CityImprovementDTO; import cz.muni.fi.civ.newohybat.persistence.facade.dto.PlayerDTO; import cz.muni.fi.civ.newohybat.persistence.facade.dto.TileDTO; import cz.muni.fi.civ.newohybat.persistence.facade.dto.UnitDTO; import cz.muni.fi.civ.newohybat.persistence.facade.dto.UnitTypeDTO; public class CitySurplusRulesJUnitTest extends BaseJUnitTest { private static KnowledgeBase kbase; public CitySurplusRulesJUnitTest() throws Exception{ } @BeforeClass public static void setKnowledgeBase() throws Exception { System.out.println("Loading knowledge base."); KnowledgeBuilderConfiguration config = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(); config.setOption(PropertySpecificOption.ALWAYS); KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(config); kbuilder.add(ResourceFactory.newClassPathResource("rules/common.drl"), ResourceType.DRL); kbuilder.add(ResourceFactory.newClassPathResource("rules/turn-city.drl"), ResourceType.DRL); kbuilder.add(ResourceFactory.newClassPathResource("rules/governmentRules.drl"), ResourceType.DRL); kbuilder.add(ResourceFactory.newClassPathResource("rules/cityImprovementRules.drl"), ResourceType.DRL); //kbuilder.add(ResourceFactory.newClassPathResource("cityTurnProcess.bpmn"), ResourceType.BPMN2); kbase = kbuilder.newKnowledgeBase(); kbase.addKnowledgePackages(kbuilder.getKnowledgePackages()); } @Before public void before(){ setSessions(kbase); } @After public void after(){ ksession.dispose(); } private static CityDTO getCity(Long id, String name){ CityDTO city = new CityDTO(); city.setId(id); city.setName(name); city.setResourcesConsumption(0); city.setResourcesProduction(0); city.setUnitsSupport(0); city.setFoodConsumption(0); city.setFoodProduction(0); city.setFoodStock(0); city.setSize(0); city.setTradeProduction(0); city.setPeopleEntertainers(0); city.setPeopleScientists(0); city.setPeopleTaxmen(0); city.setWeLoveDay(false); city.setDisorder(false); city.setSize(1); city.setPeopleHappy(0); city.setPeopleContent(0); city.setPeopleUnhappy(0); city.setImprovements(new HashSet<String>()); return city; } private static CityDTO getCity(Long id, String name, Set<Long> managedTiles){ CityDTO city = getCity(id,name); city.setManagedTiles(managedTiles); return city; } private static TileDTO getTile(Long id, Integer foodProduction, Integer resourcesProduction, Integer tradeProduction){ TileDTO tile = new TileDTO(); tile.setId(id); tile.setFoodProduction(foodProduction); tile.setResourcesProduction(resourcesProduction); tile.setTradeProduction(tradeProduction); return tile; } private static PlayerDTO getPlayer(Long id, String name, String government){ PlayerDTO player = new PlayerDTO(); player.setId(id); player.setName(name); player.setGovernment(government); player.setLuxuriesRatio(0); player.setTaxesRatio(0); player.setResearchRatio(0); player.setResearch(0); return player; } private static CityImprovementDTO getImprovement(String ident, Integer upkeepCost){ CityImprovementDTO imp = new CityImprovementDTO(); imp.setUpkeepCost(upkeepCost); imp.setIdent(ident); return imp; } private static UnitDTO getUnit(Long id,String type, Long owner){ UnitDTO unit = new UnitDTO(); unit.setId(id); unit.setType(type); unit.setAttackStrength(0); unit.setDefenseStrength(0); unit.setOwner(owner); return unit; } private static UnitTypeDTO getUnitType(String ident){ UnitTypeDTO type = new UnitTypeDTO(); type.setIdent(ident); Set<String> actions = new HashSet<String>(); type.setActions(actions); return type; } @Test public void testCityImprovementsUpkeep(){ AgendaEventListener ael = mock( AgendaEventListener.class ); ksession.addEventListener( ael ); // prepare test data PlayerDTO player = getPlayer(1L, "honza", "despotism"); player.setLuxuriesRatio(30); player.setTaxesRatio(30); player.setResearchRatio(40); CityDTO city = getCity(5L,"marefy"); city.setTradeProduction(10); city.setOwner(player.getId()); // insert facts ksession.insert(city); ksession.insert(player); ((StatefulKnowledgeSessionImpl)ksession).session.getAgenda().activateRuleFlowGroup("manageSurpluses"); ksession.fireAllRules(new RuleNameMatchesAgendaFilter("Trade To Luxuries/Taxes/Research Resolution")); ArgumentCaptor<AfterActivationFiredEvent> aafe = ArgumentCaptor.forClass( AfterActivationFiredEvent.class ); verify( ael ,atLeastOnce()).afterActivationFired( aafe.capture() ); List<String> firedRules = getFiredRules(aafe.getAllValues()); Assert.assertTrue("Trade To Luxuries/Taxes/Research Resolution Fired",firedRules.contains("Trade To Luxuries/Taxes/Research Resolution")); Assert.assertTrue("City Luxuries According to Luxuries Ratio",city.getLuxuriesAmount()==3); Assert.assertTrue("City Taxes According to Taxes Ratio",city.getTaxesAmount()==3); Assert.assertTrue("City Research According to Research Ratio",city.getResearchAmount()==4); } @Test public void testCityTaxesToTreasury(){ AgendaEventListener ael = mock( AgendaEventListener.class ); ksession.addEventListener( ael ); // prepare test data PlayerDTO player = getPlayer(1L, "honza", "despotism"); player.setTreasury(0); CityDTO city = getCity(5L,"marefy"); city.setTaxesAmount(150); city.setImprovementsUpkeep(0); city.setOwner(player.getId()); CityDTO city2 = getCity(6L,"brno"); city2.setTaxesAmount(100); city2.setImprovementsUpkeep(0); city2.setOwner(player.getId()); // insert facts ksession.insert(city); ksession.insert(city2); ksession.insert(player); ksession.getWorkingMemoryEntryPoint("GameControlStream").insert(new TurnEvent()); ((StatefulKnowledgeSessionImpl)ksession).session.getAgenda().activateRuleFlowGroup("manageSurpluses"); ksession.fireAllRules(new RuleNameMatchesAgendaFilter("Taxes Surplus To Treasury")); ArgumentCaptor<AfterActivationFiredEvent> aafe = ArgumentCaptor.forClass( AfterActivationFiredEvent.class ); verify( ael ,atLeastOnce()).afterActivationFired( aafe.capture() ); List<String> firedRules = getFiredRules(aafe.getAllValues()); Assert.assertTrue("Taxes Surplus To Treasury Fired",firedRules.contains("Taxes Surplus To Treasury")); Assert.assertTrue("City Taxes Go To Treasury",player.getTreasury()==250); } @Test public void testCityTaxesShortageFromTreasury(){ AgendaEventListener ael = mock( AgendaEventListener.class ); ksession.addEventListener( ael ); // prepare test data PlayerDTO player = getPlayer(1L, "honza", "despotism"); player.setTreasury(60); CityDTO city = getCity(5L,"marefy"); city.setTaxesAmount(0); city.setImprovementsUpkeep(50); city.setOwner(player.getId()); // insert facts ksession.insert(city); ksession.insert(player); ksession.getWorkingMemoryEntryPoint("GameControlStream").insert(new TurnEvent()); ((StatefulKnowledgeSessionImpl)ksession).session.getAgenda().activateRuleFlowGroup("manageSurpluses"); ksession.fireAllRules(new RuleNameMatchesAgendaFilter("Taxes Shortage Covered From Treasury")); ArgumentCaptor<AfterActivationFiredEvent> aafe = ArgumentCaptor.forClass( AfterActivationFiredEvent.class ); verify( ael ,atLeastOnce()).afterActivationFired( aafe.capture() ); List<String> firedRules = getFiredRules(aafe.getAllValues()); Assert.assertTrue("Taxes Shortage Covered From Treasury Fired",firedRules.contains("Taxes Shortage Covered From Treasury")); Assert.assertTrue("City Taxes Shortage Get From Treasury",player.getTreasury()==10); } @Test public void testCityTaxesShortageNotCoveredFromTreasury(){ AgendaEventListener ael = mock( AgendaEventListener.class ); ksession.addEventListener( ael ); // prepare test data Set<String> improvements = new HashSet<String>(); improvements.add("bank"); improvements.add("factory"); PlayerDTO player = getPlayer(1L, "honza", "despotism"); player.setTreasury(40); CityDTO city = getCity(5L,"marefy"); city.setTaxesAmount(0); city.setImprovementsUpkeep(50); city.setOwner(player.getId()); city.setImprovements(improvements); // insert facts ksession.insert(city); ksession.insert(player); ksession.getWorkingMemoryEntryPoint("GameControlStream").insert(new TurnEvent()); ((StatefulKnowledgeSessionImpl)ksession).session.getAgenda().activateRuleFlowGroup("manageSurpluses"); ksession.fireAllRules(new RuleNameMatchesAgendaFilter("Taxes Shortage Not Covered From Treasury")); ArgumentCaptor<AfterActivationFiredEvent> aafe = ArgumentCaptor.forClass( AfterActivationFiredEvent.class ); verify( ael ,atLeastOnce()).afterActivationFired( aafe.capture() ); List<String> firedRules = getFiredRules(aafe.getAllValues()); Assert.assertTrue("Taxes Shortage Not Covered From Treasury Fired",firedRules.contains("Taxes Shortage Not Covered From Treasury")); Assert.assertTrue("City Taxes Shortage Zero Treasury",player.getTreasury()==0); Assert.assertTrue("City Improvement Sold.",city.getImprovements().size()<2); } @Test public void testCityResearchContribute(){ AgendaEventListener ael = mock( AgendaEventListener.class ); ksession.addEventListener( ael ); // prepare test data PlayerDTO player = getPlayer(1L, "honza", "despotism"); player.setResearch(60); CityDTO city = getCity(5L,"marefy"); city.setResearchAmount(10); city.setOwner(player.getId()); // insert facts ksession.insert(city); ksession.insert(player); ksession.getWorkingMemoryEntryPoint("GameControlStream").insert(new TurnEvent()); ((StatefulKnowledgeSessionImpl)ksession).session.getAgenda().activateRuleFlowGroup("manageSurpluses"); ksession.fireAllRules(new RuleNameMatchesAgendaFilter("Research Of City To Global")); ArgumentCaptor<AfterActivationFiredEvent> aafe = ArgumentCaptor.forClass( AfterActivationFiredEvent.class ); verify( ael ,atLeastOnce()).afterActivationFired( aafe.capture() ); List<String> firedRules = getFiredRules(aafe.getAllValues()); Assert.assertTrue("Research Of City To Global Fired",firedRules.contains("Research Of City To Global")); Assert.assertTrue("Research Of City To Global",player.getResearch()==70); } @Test public void testCityFoodSurplusToStock(){ AgendaEventListener ael = mock( AgendaEventListener.class ); ksession.addEventListener( ael ); // prepare test data PlayerDTO player = getPlayer(1L, "honza", "despotism"); player.setResearch(60); CityDTO city = getCity(5L,"marefy"); city.setResearchAmount(10); city.setOwner(player.getId()); city.setFoodProduction(250); city.setFoodConsumption(120); city.setFoodStock(10); // insert facts ksession.insert(city); ksession.insert(player); ksession.getWorkingMemoryEntryPoint("GameControlStream").insert(new TurnEvent()); ((StatefulKnowledgeSessionImpl)ksession).session.getAgenda().activateRuleFlowGroup("manageSurpluses"); ksession.fireAllRules(new RuleNameMatchesAgendaFilter("Food Surplus To Stock")); ArgumentCaptor<AfterActivationFiredEvent> aafe = ArgumentCaptor.forClass( AfterActivationFiredEvent.class ); verify( ael ,atLeastOnce()).afterActivationFired( aafe.capture() ); List<String> firedRules = getFiredRules(aafe.getAllValues()); Assert.assertTrue("Food Surplus To Stock Fired",firedRules.contains("Food Surplus To Stock")); Assert.assertTrue("Food Surplus To Stock Check",city.getFoodStock()==140); } @Test public void testCityFoodShortageNotFromStock(){ AgendaEventListener ael = mock( AgendaEventListener.class ); ksession.addEventListener( ael ); // prepare test data PlayerDTO player = getPlayer(1L, "honza", "despotism"); CityDTO city = getCity(5L,"marefy"); city.setOwner(player.getId()); city.setFoodProduction(250); city.setFoodConsumption(300); city.setSize(3); city.setFoodStock(10); // insert facts ksession.insert(city); ksession.insert(player); ksession.getWorkingMemoryEntryPoint("GameControlStream").insert(new TurnEvent()); ((StatefulKnowledgeSessionImpl)ksession).session.getAgenda().activateRuleFlowGroup("affectPopulation"); ksession.fireAllRules(new RuleNameMatchesAgendaFilter("Food Shortage Not Covered From Stock")); ArgumentCaptor<AfterActivationFiredEvent> aafe = ArgumentCaptor.forClass( AfterActivationFiredEvent.class ); verify( ael ,atLeastOnce()).afterActivationFired( aafe.capture() ); List<String> firedRules = getFiredRules(aafe.getAllValues()); Assert.assertTrue("Food Shortage Not Covered From Stock Fired",firedRules.contains("Food Shortage Not Covered From Stock")); Assert.assertTrue("Food Stock Empty",city.getFoodStock()==0); Assert.assertTrue("City Size Decreased",city.getSize()==2); } }
true
98e99329aeb6440e770be5ba6f275e5ca3b5e547
Java
3dsound/arcore-android-sdk
/samples/cloud_anchor_java/app/src/main/java/com/google/ar/core/examples/java/cloudanchor/ResolveDialogFragment.java
UTF-8
2,579
2.21875
2
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.ar.core.examples.java.cloudanchor; import android.app.AlertDialog; import android.app.Dialog; import android.os.Bundle; import android.text.Editable; import android.view.View; import android.widget.EditText; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.FragmentActivity; import com.google.common.base.Preconditions; /** A DialogFragment for the Resolve Dialog Box. */ public class ResolveDialogFragment extends DialogFragment { interface OkListener { /** * This method is called by the dialog box when its OK button is pressed. * * @param dialogValue the long value from the dialog box */ void onOkPressed(Long dialogValue); } private EditText roomCodeField; private OkListener okListener; public void setOkListener(OkListener okListener) { this.okListener = okListener; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { FragmentActivity activity = Preconditions.checkNotNull(getActivity(), "The activity cannot be null."); AlertDialog.Builder builder = new AlertDialog.Builder(activity); // Passing null as the root is fine, because the view is for a dialog. View dialogView = activity.getLayoutInflater().inflate(R.layout.resolve_dialog, null); roomCodeField = dialogView.findViewById(R.id.room_code_input); builder .setView(dialogView) .setTitle(R.string.resolve_dialog_title) .setPositiveButton( R.string.resolve_dialog_ok, (dialog, which) -> { Editable roomCodeText = roomCodeField.getText(); if (okListener != null && roomCodeText != null && roomCodeText.length() > 0) { Long longVal = Long.valueOf(roomCodeText.toString()); okListener.onOkPressed(longVal); } }) .setNegativeButton(R.string.cancel, (dialog, which) -> {}); return builder.create(); } }
true
95723cf2be37a6a41cd290a8a7ecec1f4544a1c2
Java
Pratt-Eric/ClearfieldRequestor
/requestor/src/java/com/prt/models/Calendar.java
UTF-8
1,738
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 com.prt.models; import java.io.Serializable; import java.util.ArrayList; /** * * @author P-ratt */ public class Calendar implements Serializable { private String guid; private String name; private String desc; private ArrayList<User> users = new ArrayList<>(); private ArrayList<Group> groups = new ArrayList<>(); private ArrayList<Event> events = new ArrayList<>(); private boolean editable; private int index; private String xrefGuid; public ArrayList<Event> getEvents() { return events; } public void setEvents(ArrayList<Event> events) { this.events = events; } public String getXrefGuid() { return xrefGuid; } public void setXrefGuid(String xrefGuid) { this.xrefGuid = xrefGuid; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public ArrayList<User> getUsers() { return users; } public void setUsers(ArrayList<User> users) { this.users = users; } public ArrayList<Group> getGroups() { return groups; } public void setGroups(ArrayList<Group> groups) { this.groups = groups; } public boolean isEditable() { return editable; } public void setEditable(boolean editable) { this.editable = editable; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } }
true
f29a8ec89182af59346355c0731f17102ecebf10
Java
JackMutobu/LeagueGenerator
/LeagueTable/LeagueTable/src/main/java/com/mycompany/leaguetable/MainAplication.java
UTF-8
8,640
2.984375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.leaguetable; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; /** * * @author jmuto */ public class MainAplication { private static Scanner in = new Scanner(System.in); private static final String fileName = "teams.csv"; public static void main(String args[]) throws IOException { int selectedMenu = selectMenu(); switch(selectedMenu) { case 1: getTeamsFromUser(); displayTeams(); break; case 2: generateFixtures(); break; case 3: displayTeams(); case 4: System.exit(0); break; default: System.out.println("Not supported menu"); } } public static int selectMenu() { System.out.println("Select menu\n1. Input teams(10)\n2. Generate fixtures\n3. Display teams\n4. Exit"); return Integer.parseInt(in.next()); } public static void getTeamsFromUser() throws IOException { System.out.println("Input teams"); List<Team> teams = new ArrayList<Team>(); int teamsCounter = 1; String pass = in.nextLine();//prompt console to start accepting input while(teamsCounter <= 10) { Team teamToAdd = new Team(); System.out.println("Team " + teamsCounter); System.out.println("Name"); teamToAdd.setName(in.nextLine()); System.out.println("Town"); teamToAdd.setTown(in.nextLine()); System.out.println("Stadium"); teamToAdd.setStadium(in.nextLine()); teams.add(teamToAdd); teamsCounter++; } CSVHelper.saveCsvFile(teams, fileName); } public static void displayTeams() throws IOException { List<Team> teams = CSVHelper.readTeamsFromCsvFile(fileName); System.out.println("Teams name ----------- Local Town ---------- Team Stadium"); for(Team team : teams) { System.out.println( team.getName() + "--------" +team.getTown()+ "-------"+team.getStadium()); } } public static void generateFixtures() throws IOException { List<Fixture> fixtures = generateCombination(); List<Fixture> homeTownfixtures = new ArrayList<>(); int week = 1; boolean isSameWeekend = false; int counter = 0; while(counter<fixtures.size()) { if(fixtures.get(counter).getTeam1().getTown().equals(fixtures.get(counter).getTeam2().getTown())) { homeTownfixtures.add(fixtures.get(counter)); fixtures.remove(counter); continue; } else { if(!isSameWeekend) { fixtures.get(counter).setWeekend("Weekend" +week); isSameWeekend = true; } else { fixtures.get(counter).setWeekend("Weekend" +week); isSameWeekend = false; week++; } } counter++; } for(Fixture fixture: homeTownfixtures) { if(!isSameWeekend) { fixture.setWeekend("Weekend" +week); isSameWeekend = true; } else { fixture.setWeekend("Weekend" +week); isSameWeekend = false; week++; } } fixtures.addAll(homeTownfixtures); fixtures.addAll(setSecondLeg(fixtures, week)); displayFixtures(fixtures); } public static void displayFixtures(List<Fixture> fixtures) { System.out.println("Id-----Team1------- Team2----- Town --- Stadium ---- Weekend ---- IsFirstLeg"); int id = 1; for(Fixture fixture : fixtures) { System.out.println(id+"----"+ fixture.getTeam1().getName()+ "-----" +fixture.getTeam2().getName()+"----"+fixture.getTown()+"----"+fixture.getStadium()+ "-------"+fixture.getWeekend()+ "-------"+fixture.getIsFirstLeg()); id++; } } public static List<Fixture> combineTeams(List<Team> teams) { List<Fixture> fixtures = new ArrayList<Fixture>(); for(int i = 0; i<teams.size();i++) { for(int j = i + 1;j<teams.size();j++) { fixtures.add(new Fixture(teams.get(i),teams.get(j))); } } return fixtures; } public static List<Fixture> setSecondLeg(List<Fixture> fixtures,int actualWeek) { List<Fixture> newFixtures = new ArrayList<>(); int week = actualWeek +1; for(Fixture fixture:fixtures) { Fixture fixtureToAdd = new Fixture(fixture.getTeam1(),fixture.getTeam2(),false); fixtureToAdd.setWeekend("Weekend"+week); newFixtures.add(fixtureToAdd); week++; } return newFixtures; } public static List<String> getTowns() throws IOException { List<Team> teams = CSVHelper.readTeamsFromCsvFile(fileName); List<String> towns = new ArrayList<>(); for(Team team: teams) { if(!towns.contains(team.getTown())) towns.add(team.getTown()); } return towns; } public static List<Fixture> generateCombination() throws IOException { List<Team> teamList = CSVHelper.readTeamsFromCsvFile(fileName); List<Fixture> fixtures = new ArrayList<>(); int teams = teamList.size(); // If odd number of teams add a "ghost". boolean ghost = false; if (teams % 2 == 1) { teams++; ghost = true; } // Generate the fixtures using the cyclic algorithm. int totalRounds = teams - 1; int matchesPerRound = teams / 2; String[][] rounds = new String[totalRounds][matchesPerRound]; for (int round = 0; round < totalRounds; round++) { for (int match = 0; match < matchesPerRound; match++) { int home = (round + match) % (teams - 1); int away = (teams - 1 - match + round) % (teams - 1); // Last team stays in the same place while the others // rotate around it. if (match == 0) { away = teams - 1; } // Add one so teams are number 1 to teams not 0 to teams - 1 // upon display. rounds[round][match] = (home + 1) + " v " + (away + 1); } } // Interleave so that home and away games are fairly evenly dispersed. String[][] interleaved = new String[totalRounds][matchesPerRound]; int evn = 0; int odd = (teams / 2); for (int i = 0; i < rounds.length; i++) { if (i % 2 == 0) { interleaved[i] = rounds[evn++]; } else { interleaved[i] = rounds[odd++]; } } rounds = interleaved; // Last team can't be away for every game so flip them // to home on odd rounds. for (int round = 0; round < rounds.length; round++) { if (round % 2 == 1) { rounds[round][0] = flip(rounds[round][0]); } } // Populate fixtures for (int i = 0; i < rounds.length; i++) { String[] roundsString = rounds[i]; for(String s : roundsString) { String[] comp = s.split("v"); fixtures.add(new Fixture(teamList.get((Integer.parseInt(comp[0].trim()) - 1)),teamList.get((Integer.parseInt(comp[1].trim())) - 1))); } } return fixtures; } private static String flip(String match) { String[] components = match.split(" v "); return components[1] + " v " + components[0]; } }
true
bcaea0070e52a31c0b5e130f9063823d0dae7d5d
Java
kgw3577/GraduationProject
/Web/Closet/src/main/java/com/my/closet/user/dao/UserDAO.java
UTF-8
1,051
2.15625
2
[]
no_license
package com.my.closet.user.dao; import java.util.List; import java.util.Map; import org.springframework.dao.DataAccessException; import com.my.closet.user.vo.UserVO; public interface UserDAO { public List<UserVO> selectAllUsers() throws DataAccessException; //모든 사용자 public UserVO selectThisUser(String userID) throws DataAccessException; //id로 사용자 하나 선택 public List<UserVO> selectUser(UserVO userFilter) throws DataAccessException; //조건으로 사용자 선택 public String addUser(UserVO userInfo) throws DataAccessException; //사용자 추가 //아이디 찾기 //비밀번호 찾기 public String updateUser(UserVO userInfo) throws DataAccessException; //사용자 정보 수정 public String deleteUser(String userID) throws DataAccessException; //사용자 삭제 public String checkExistUser(UserVO userInfo) throws DataAccessException; //해당 유저 존재여부 확인 public String verifyIdPwd(String userID, String pwd) throws DataAccessException; //ID, 패스워드 유효성 확인 }
true
dca467b9b5c0dbfa84fd922489afffabcd2e682b
Java
cache117/cs478-perceptron
/src/edu/byu/cstaheli/cs478/toolkit/strategy/StaticStrategy.java
UTF-8
1,359
2.734375
3
[]
no_license
package edu.byu.cstaheli.cs478.toolkit.strategy; import edu.byu.cstaheli.cs478.toolkit.LearnerData; import edu.byu.cstaheli.cs478.toolkit.Matrix; /** * Created by cstaheli on 1/20/2017. */ public class StaticStrategy extends LearningStrategy { private Matrix testData; public StaticStrategy(LearnerData learnerData) throws Exception { super(learnerData); Matrix testData = new Matrix(); testData.loadArff(learnerData.getEvalParameter()); if (learnerData.isNormalized()) testData.normalize(); // BUG! This may normalize differently from the training data. It should use the same ranges for normalization! } public Matrix getTestData() { return testData; } @Override public Matrix getTrainingFeatures() { return new Matrix(getArffData(), 0, 0, getArffData().rows(), getArffData().cols() - 1); } @Override public Matrix getTrainingLabels() { return new Matrix(getArffData(), 0, getArffData().cols() - 1, getArffData().rows(), 1); } @Override public Matrix getTestingFeatures() { return new Matrix(testData, 0, 0, testData.rows(), testData.cols() - 1); } @Override public Matrix getTestingLabels() { return new Matrix(testData, 0, testData.cols() - 1, testData.rows(), 1); } }
true
9859f738704af6bbabc5aa93956721b130907e2a
Java
helenarth/ssq
/sshwork/PcbMis/src/com/yaxing/Dao/UserDao.java
UTF-8
168
1.835938
2
[]
no_license
package com.yaxing.Dao; import com.yaxing.base.BaseDao; import com.yaxing.model.User; public interface UserDao extends BaseDao<User>{ User getByNameAndPassword(); }
true
32add950e9e3d99bb00cf28049313290ab938f47
Java
abdallahSQaradeh/Search-for-Jobs
/SFJob/src/RedisJava.java
UTF-8
2,660
2.953125
3
[]
no_license
import java.util.ArrayList; import java.util.HashMap; import redis.clients.jedis.Jedis; public class RedisJava { private HashMap<String,ArrayList<JobNode>> Jobs; private String[] list_names = {"it","healthcare","social","marketing","communication","media","other","operation","hotel", "graphicdesign","languages","account","engineering","education","art","business","law"}; public RedisJava() { System.out.println("Connection to server sucessfully"); //Connecting to Redis server on localhost Jobs = new HashMap(); Jedis jedis = new Jedis("localhost"); for(String str:list_names){ ArrayList<JobNode> list = new ArrayList(500); String JobNamestr = "JobName" + str; String JobCompanystr = "JobCompany" + str; String JobLocationstr = "JobLocation" + str; String JobDatestr = "JobDate" + str; String JobLinkstr = "JobLink" + str; while( jedis.llen(JobNamestr) !=0){ String job_name = jedis.rpop(JobNamestr); String job_company = jedis.rpop(JobCompanystr); String job_location = jedis.rpop(JobLocationstr); String job_publish_date = jedis.rpop(JobDatestr); String job_link = jedis.rpop(JobLinkstr); JobNode node = new JobNode(job_name,job_company,job_location,job_publish_date,job_link); list.add(node); System.out.println("hey "); } Jobs.put(str, list); System.out.println(str + " size : " + list.size()); } //print(); System.out.println("Connection to server sucessfully"); //check whether server is running or not System.out.println("Server is running: "+jedis.ping()); } // public void print(){ // for(JobNode job:Jobs){ // System.out.println("Job : " + job.job_name); // System.out.println("Company : " + job.job_company); // System.out.println("Job Location : " + job.job_location); // System.out.println("Job date : " + job.job_publish_date); // System.out.println("Job link : " + job.job_link); // } public HashMap<String,ArrayList<JobNode>> getJobs(){ return Jobs; } } class JobNode{ String job_name; String job_company; String job_location; String job_publish_date; String job_link; public JobNode(String job_name,String job_company,String job_location,String job_publish_date ,String job_link){ this.job_name = job_name; this.job_company = job_company; this.job_location = job_location; this.job_publish_date = job_publish_date; this.job_link = job_link; } }
true
0d6c564d9a273d59bd719532372786aa915a4801
Java
alterloki/solution
/codejam/src/y2013/contest/qualify/ProblemA.java
UTF-8
4,214
3.171875
3
[]
no_license
/** * Created by IntelliJ IDEA. * User: ashevenkov * Date: 05.04.15 * Time: 22:56 */ package y2013.contest.qualify; import java.io.*; import java.util.Scanner; /** * //TESTED * @author ashevenkov */ public class ProblemA { public static final String TITLE = "A-large-practice"; private static BufferedReader in = prodIn(); private static BufferedWriter out = prodOut(); private static BufferedWriter prodOut() { try { return new BufferedWriter(new FileWriter("codejam/output/" + TITLE + ".out")); } catch (IOException e) { e.printStackTrace(); } return null; } private static BufferedReader prodIn() { try { return new BufferedReader(new FileReader("codejam/input/" + TITLE + ".in")); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } private static BufferedWriter testOut() { return new BufferedWriter(new OutputStreamWriter(System.out)); } private static BufferedReader testIn() { return new BufferedReader(new InputStreamReader(System.in)); } public static void main(String[] args) throws Exception { new ProblemA().solve(in, out); out.flush(); out.close(); } //implement private void solve(BufferedReader in, BufferedWriter out) throws Exception { Scanner scanner = new Scanner(in); int t = Integer.parseInt(scanner.nextLine()); for (int i = 0; i < t; i++) { char[][] board = new char[4][]; for (int j = 0; j < 4; j++) { String next = scanner.nextLine(); board[j] = next.toCharArray(); } if(i < t - 1) { scanner.nextLine(); } out.write("Case #" + (i + 1) + ": " + solveBoard(board)); out.newLine(); } } private String solveBoard(char[][] board) { boolean owon = isCharWon(board, 'O'); boolean xwon = isCharWon(board, 'X'); boolean haveEmpty = isHaveEmpty(board); if(owon) { return "O won"; } if(xwon) { return "X won"; } if(haveEmpty) { return "Game has not completed"; } else { return "Draw"; } } private boolean isHaveEmpty(char[][] board) { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i].length; j++) { if(board[i][j] == '.') { return true; } } } return false; } private boolean isCharWon(char[][] board, char c) { boolean cwon = false; for (int i = 0; i < 4; i++) { if (isFullRow(board, i, c)) { cwon = true; break; } } if (!cwon) { for (int i = 0; i < 4; i++) { if (isFullColumn(board, i, c)) { cwon = true; break; } } } if (!cwon) { int ocount = 0; for (int i = 0; i < 4; i++) { if (board[i][i] == c || board[i][i] == 'T') { ocount++; } } cwon = ocount == 4; } if (!cwon) { int ocount = 0; for (int i = 0; i < 4; i++) { if (board[i][3 - i] == c || board[i][3 - i] == 'T') { ocount++; } } cwon = ocount == 4; } return cwon; } private boolean isFullColumn(char[][] board, int col, char c) { int count = 0; for (int i = 0; i < 4; i++) { if (board[i][col] == c || board[i][col] == 'T') { count++; } } return count == 4; } private boolean isFullRow(char[][] board, int row, char c) { int count = 0; for (int i = 0; i < 4; i++) { if (board[row][i] == c || board[row][i] == 'T') { count++; } } return count == 4; } }
true
448be2e0615be06bcfbc5ad78d5cddf366b5f09d
Java
lkaymakanov/RegisterService
/RegisterService/src/net/is_bg/ltf/update/register/services/InitProcessorContainer.java
UTF-8
2,240
2.09375
2
[]
no_license
package net.is_bg.ltf.update.register.services; import net.is_bg.ltf.update.register.common.results.delduplicateaddress.ClientDelDuplicateResult; import net.is_bg.ltf.update.register.common.sql.registertourist.v1.RegisterTouristInsertV1; import net.is_bg.ltf.update.register.tourist.GenerateScriptsUtils; import net.is_bg.web.base.processors.IProcessObject; import net.is_bg.web.base.processors.ProcessorContainer; public class InitProcessorContainer { private static InitProcessorContainer ref = null; private InitProcessorContainer(){} public static final String SCRIPT_PROLOG = "do \n $$declare \n begin \n"; public static final String SCRIPT_EPILOG = " end$$; \n"; public static final String EMPTY_SQL = SCRIPT_PROLOG + SCRIPT_EPILOG; public void initContainer(ProcessorContainer processor) { ProcessorContainer container = (ProcessorContainer)processor; container.addProcessor(RegisterTouristInsertV1.class, new IProcessObject<RegisterTouristInsertV1>() { @Override public RegisterTouristInsertV1 processObject(RegisterTouristInsertV1 object) { return GenerateScriptsUtils.processObject(object); } }); container.addProcessor(ClientDelDuplicateResult.class, new IProcessObject<ClientDelDuplicateResult>() { @Override public ClientDelDuplicateResult processObject( ClientDelDuplicateResult arg0) { // TODO Auto-generated method stub if(arg0 != null) { if (arg0.getClientInfo() != null && arg0.getClientInfo().getClientAddress() != null){ System.out.println("Client Address is:" + arg0.getClientInfo().getClientAddress().toString()); } if(arg0.getFields().get(0) != null){ System.out.println(arg0.getFields().get(0)); } if(arg0.getMsg() != null ){ System.out.println(arg0.getMsg()); } } return arg0; } }); System.out.println("===============================InitProcessorContainer========================================"); } public static void initProcessContainer(){ if(ref == null) { ref = new InitProcessorContainer(); ref.initContainer(ProcessorContainer.getProcessContainer()); } } }
true
e4232ecb6673af3fac58360766b9bd009879d3df
Java
msmtmsmt123/jadx-1
/f737922a0ddc9335bb0fc2f3ae5ffe93_source_from_JADX/java_files/ex.java
UTF-8
1,148
1.640625
2
[]
no_license
import java.io.Reader; import java.util.ArrayList; import java.util.List; import java.util.Map; public class ex implements bh { public ex(cc ccVar) { } public String j6() { return "AIDL"; } public void DW() { } public boolean FH() { return true; } public String[] Hw() { return new String[]{"*.aidl"}; } public String[] v5() { return new String[0]; } public List<bj> Zo() { return new ArrayList(); } public void j6(bv bvVar, bj bjVar) { } public void j6(bv bvVar, Reader reader, Map<bj, cm> map) { } public void j6(bv bvVar, Reader reader, Map<bj, cj> map, boolean z) { } public boolean VH() { return false; } public long j6(String str) { return 0; } public String[] DW(String str) { return null; } public Reader j6(String str, String str2, String str3) { return null; } public void gn() { } public bf u7() { return null; } public bg tp() { return null; } public bi EQ() { return null; } }
true
5895d45e212a50fed5bb2160794091cab880572f
Java
Gaetitan/Goldfish
/Goldfish/src/com/polytech/goldfish/businesslogic/manager/ActivityManager.java
UTF-8
1,659
2.765625
3
[]
no_license
package com.polytech.goldfish.businesslogic.manager; import java.util.Collection; import com.polytech.goldfish.businesslogic.business.Activity; import com.polytech.goldfish.businesslogic.factory.ActivityFactory; import com.polytech.goldfish.persistence.factoryjdbc.ActivityFactoryJDBC; import com.polytech.goldfish.util.GoldfishException; /** * This class allows a user to create a new activity * * @author Pierre Laborde * */ public class ActivityManager { private static final Integer Integer = null; private final ActivityFactory factory; public ActivityManager(){ this.factory = new ActivityFactoryJDBC(); } public Integer createActivity(String name, String description, Integer id) throws GoldfishException { if(name.isEmpty() || description.isEmpty()) { throw new GoldfishException("Please fill all the fields."); } else { return this.factory.createActivity(name, description, id); } } public Integer updateActivity(Integer id, String name, String description) throws GoldfishException { if(name.isEmpty() || description.isEmpty()) { throw new GoldfishException("Please fill all the fields."); } else { return this.factory.updateActivity(id, name, description); } } public Integer deleteActivity(Integer id) throws GoldfishException { return this.factory.deleteActivity(id); } public Activity findActivityById(Integer id){ return this.factory.getActivityById(id); } public Collection<Activity> findAllActivities(){ return this.factory.getAllActivities(); } public Collection<Activity> findAllActivitiesOfAnUser(Integer id){ return this.factory.getAllActivitiesOfAnUser(id); } }
true
0777108c83877752bb1e541fc7f44807c8fc9127
Java
jitheshchandra/fms
/src/main/java/com/ssrv/fms/controller/IncidentRegisterController.java
UTF-8
7,419
1.929688
2
[]
no_license
package com.ssrv.fms.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.ssrv.fms.model.incident.IncidentStatus; import com.ssrv.fms.service.branch.intf.BranchService; import com.ssrv.fms.service.incident.IIncidentService; import com.ssrv.fms.service.organization.intf.OrganizationService; import com.ssrv.fms.vo.incidents.EscalationLevelInfo; import com.ssrv.fms.vo.incidents.EscalationMatrixInfo; import com.ssrv.fms.vo.incidents.IncidentCategoryInfo; import com.ssrv.fms.vo.incidents.IncidentInfo; import com.ssrv.fms.vo.incidents.UpdateIncidentStatusForms; import com.ssrv.fms.vo.incidents.impl.EscalationMatrixInfoForm; import com.ssrv.fms.vo.incidents.impl.IncidentCategoryInfoForm; import com.ssrv.fms.vo.incidents.impl.IncidentInfoFormImpl; @Controller public class IncidentRegisterController { @Autowired IIncidentService incidentService; @Autowired private BranchService branchServive; @Autowired private OrganizationService organizationIntf; @Autowired private BranchService branchService; @RequestMapping(value = "/EscalationLevel", method = RequestMethod.GET) public String escalationLevel(Model incidentRegisterModel) { List<EscalationLevelInfo> escalationLevels = incidentService .getEscalationLevelList(); incidentRegisterModel .addAttribute("escalationLevels", escalationLevels); return "EscalationLevel"; } @RequestMapping(value = "/saveEscalationLevel", method = RequestMethod.GET) public String saveEscalationLevel(String name) { incidentService.saveEscalationLevel(name); return "redirect:EscalationLevel"; } @RequestMapping(value = "/deleteEscalationLevel", method = RequestMethod.POST) public @ResponseBody Map<String, Object> deleteEscalationLevel(@RequestParam String escalationId) { Boolean result = incidentService.deleteEscalationLevel(Long .parseLong(escalationId)); Map<String, Object> returnResult = new HashMap<String, Object>(); returnResult.put("result", result); return returnResult; } @RequestMapping(value = "/deleteEscalationMatrix", method = RequestMethod.POST) public @ResponseBody Map<String, Object> deleteEscalationMatrix( @RequestParam String escalationMatrixId) { Boolean result = incidentService.deleteEscalationMatrix(Long .parseLong(escalationMatrixId)); Map<String, Object> returnResult = new HashMap<String, Object>(); returnResult.put("result", result); return returnResult; } @RequestMapping(value = "/IncidentCategoryEntity", method = RequestMethod.GET) public String addIncidentCategory(Model incidentRegisterModel) { List<IncidentCategoryInfo> categoryList = incidentService .getIncidentCategoryList(); incidentRegisterModel.addAttribute("categories", categoryList); return "IncidentCategoryEntity"; } @RequestMapping(value = "/saveIncidentCategoryEntity", method = RequestMethod.GET) public String saveIncidentCategoryEntity( IncidentCategoryInfoForm incidentCategoryInfoForm, BindingResult result) { if (result.hasErrors()) { return "IncidentCategoryEntity"; } if (!StringUtils .isEmpty(incidentCategoryInfoForm.getParentCategoryId())) { incidentCategoryInfoForm.setParentCategory(incidentService .getIncidentCategoryById(Long .parseLong(incidentCategoryInfoForm .getParentCategoryId()))); } /** * throw exception if not successful. */ incidentService.saveIncidentCategory(incidentCategoryInfoForm); return "redirect:IncidentCategoryEntity"; } @RequestMapping(value = "/EscalationMatrixEntity", method = RequestMethod.GET) public String EscalationMatrixEntity(HttpServletRequest request, HttpServletResponse response, ModelMap model) { List<IncidentCategoryInfo> categoryList = incidentService .getIncidentCategoryList(); model.addAttribute("categories", categoryList); return "EscalationMatrixEntity"; } @RequestMapping(value = "/getIncidentCategories", method = RequestMethod.POST) public @ResponseBody List<IncidentCategoryInfo> getIncidentCategories() { List<IncidentCategoryInfo> categoryList = incidentService .getIncidentCategoryList(); return categoryList; } @RequestMapping(value = "/getIncidentCategoriesHavingEscalationMatrix", method = RequestMethod.POST) public @ResponseBody List<IncidentCategoryInfo> getIncidentCategoriesHavingEscalationMatrix( @RequestParam String branchId) { List<IncidentCategoryInfo> categoryList = incidentService .getIncidentCategoriesHavingEscalationMatrix(Long .parseLong(branchId)); return categoryList; } @RequestMapping(value = "/getEscalationMatrix", method = RequestMethod.POST) public @ResponseBody Map<String, Object> getEscalationMatrix(@RequestParam String branchId, @RequestParam String categoryTypeId) { Map<String, Object> returnMap = new HashMap<String, Object>(); List<EscalationMatrixInfo> escList = incidentService .getEscalationMatrix(Long.parseLong(branchId), Long.parseLong(categoryTypeId)); returnMap.put("escList", escList); List<EscalationLevelInfo> escalationLevels = incidentService .getEscalationLevelList(); returnMap.put("escalationLevels", escalationLevels); return returnMap; } @RequestMapping(value = "/saveEscalationMatrix", method = RequestMethod.POST) public String saveEscalationMatrix( EscalationMatrixInfoForm escalationMatrixInfoForm, ModelMap model) { incidentService.saveEscalationMatrix(escalationMatrixInfoForm); return "redirect:/EscalationMatrixEntity"; } @RequestMapping(value = "/IncidentRegisterEntity", method = RequestMethod.GET) public String addIncidentRegister(Model incidentRegisterModel) { return "IncidentRegisterEntity"; } @RequestMapping(value = "/saveIncident", method = RequestMethod.POST) public String saveIncident(IncidentInfoFormImpl incidentInfoForm, ModelMap model) { incidentService.saveIncident(incidentInfoForm); return "redirect:/IncidentRegisterEntity"; } @RequestMapping(value = "/IncidentRegisterUpdateEntity", method = RequestMethod.GET) public String addIncidentRegisterUpdate(Model incidentRegisterModel) { return "IncidentRegisterUpdateEntity"; } @RequestMapping(value = "/getOpenIncidents", method = RequestMethod.POST) public @ResponseBody List<IncidentInfo> getOpenIncidents() { List<IncidentInfo> incidentList = incidentService .getIncidentsByStatus(IncidentStatus.O); return incidentList; } @RequestMapping(value = "/updateIncidents", method = RequestMethod.POST) public String updateIncidentForm( UpdateIncidentStatusForms updateIncidentStatusForm, BindingResult result) { if (result.hasErrors()) { return "IncidentRegisterUpdateEntity"; } incidentService.updateIncidentStatus(updateIncidentStatusForm); return "redirect:/IncidentRegisterUpdateEntity"; } }
true
29a9e99b31a578b76ff08353b7de0fbd8a66f9b4
Java
jamesho-tw/demo
/src/main/java/com/example/demo/controller/rest/UserRestController.java
UTF-8
2,426
2.390625
2
[]
no_license
package com.example.demo.controller.rest; import com.example.data.user.model.entity.User; import com.example.data.user.service.UserService; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.Collection; @RestController @RequestMapping("/user") public class UserRestController { protected static final Logger logger = LoggerFactory.getLogger(UserRestController.class); @Autowired private UserService userService; @RequestMapping(value = "/", method = RequestMethod.GET) public ResponseEntity<?> readAll() { Collection<User> users = userService.readAll(); if (users == null) { // TODO: return error message } logger.debug(String.format("USER SIZE: %d", users.size())); return new ResponseEntity<Collection<User>>(users, HttpStatus.OK); } @RequestMapping(value = "/{name}", method = RequestMethod.GET) public ResponseEntity<?> readByName(@PathVariable("name") String name) { if (StringUtils.isEmpty(StringUtils.trimToNull(name))) { return new ResponseEntity<String>("Invalid argument", HttpStatus.BAD_REQUEST); } User user = userService.read(name); if (user == null) { return new ResponseEntity<String>("User not found", HttpStatus.BAD_REQUEST); } logger.debug(String.format("USER: %s", user.toString())); return new ResponseEntity<User>(user, HttpStatus.OK); } /* for example: $ curl -v -X POST http://localhost:8080/user/add -H "Content-Type: application/json" \ -d '{"name": "james", "password": "123456", "salt": "XXX", "mustChangePassword": true, "status": 1}' */ @RequestMapping(value = "/add", method = RequestMethod.POST) public ResponseEntity<?> create(@RequestBody User user) { // TODO: validation return new ResponseEntity<User>(userService.create(user), HttpStatus.OK); } }
true
2cbf37746b13bb9448ed2eeec113d2346f557e73
Java
Easante2/RestaurantFinderApp
/app/src/main/java/uk/ac/aston/restaurantfinderapp/SelectEateryTypeActivity.java
UTF-8
391
1.742188
2
[]
no_license
package uk.ac.aston.restaurantfinderapp; import android.support.v4.app.Fragment; import uk.ac.aston.restaurantfinderapp.Fragments.SelectEateryTypeFragment; /** * Created by Emmanuel on 09/04/2016. */ public class SelectEateryTypeActivity extends SingleFragmentActivity { @Override protected Fragment createFragment() { return new SelectEateryTypeFragment(); } }
true
95a289520e1f056d4c1ed3c86c3631c84d95650f
Java
derzhylo/githubtestproject
/src/main/java/SignUpPage.java
UTF-8
3,217
2.40625
2
[]
no_license
import io.qameta.allure.Step; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class SignUpPage { WebDriver driver; private WebDriverWait explicitlyWait; public SignUpPage(WebDriver driver) { PageFactory.initElements(driver, this); this.driver = driver; } @FindBy(xpath = "//h1[text() = 'Join GitHub']") private WebElement heading; @FindBy(xpath = "//input[@id='user_login']") private WebElement userNameField; @FindBy(xpath = "//input[@id='user_email']") private WebElement emailField; @FindBy(xpath = "//input[@id='user_password']") private WebElement passwordField; @FindBy(xpath = "//*[@id='signup_button']") private WebElement createAccountButton; @FindBy(xpath = "//div[@class='flash flash-error my-3']") private WebElement mainError; @FindBy(xpath = "//*[text() = \"Username can't be blank\"]") private WebElement userEmptyNameError; @FindBy(xpath = "//*[text() = \"Email can't be blank\"]") private WebElement emailEmptyError; @FindBy(xpath = "//*[text() = \"Password can't be blank\"]") private WebElement passwordEmptyError; @FindBy(xpath = "//div[@class='mb-1']") private WebElement userNameError; @FindBy(xpath = "//p[text()='Email is invalid or already taken']") private WebElement emailError; @FindBy(xpath = "//p[@class='note mb-3']") private WebElement passwordError; @Step("Verify username value {username}") public SignUpPage typeUserName(String username){ userNameField.sendKeys(username); return this; } @Step("Verify password value {password}") public SignUpPage typePassword(String password){ passwordField.sendKeys(password); return this; } @Step("Verify email value {email}") public SignUpPage typeEmail(String email){ emailField.sendKeys(email); return this; } public Boolean isEnabled(){ return createAccountButton.isEnabled(); } public String getHeadingText(){ return heading.getText(); } public String getMainErrorText(){ return mainError.getText(); } public String getUsernameErrorText(){ explicitlyWait = new WebDriverWait(driver, 10); explicitlyWait.until(ExpectedConditions.visibilityOf(userNameError)); return userNameError.getText(); } public String getPasswordErrorText(){ return passwordError.getText(); } public String getEmailErrorText(){ explicitlyWait = new WebDriverWait(driver, 10); explicitlyWait.until(ExpectedConditions.visibilityOf(emailError)); return emailError.getText(); } public String getEmptyUsernameErrorText(){ return userEmptyNameError.getText(); } public String getEmptyPasswordErrorText(){ return passwordEmptyError.getText(); } public String getEmptyEmailErrorText(){ return emailEmptyError.getText(); } }
true
3ee2152280aded8168a6d86ddd54c912971071eb
Java
Hau-Bold/BikeContract
/src/main/java/statistics/ShowSalesStatistics.java
UTF-8
8,951
2.609375
3
[]
no_license
package statistics; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.SQLException; import java.util.Calendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import constants.Constants; import constants.IntersportColors; import contract.Contract; import contractDigitalizer.BikeContract; import database.DatabaseLogic; import utils.Utils; /** the class ShowSalesStatistics */ public class ShowSalesStatistics extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; private JPanel panelSouth; private JComboBox<String> monthBox; List<Contract> lstContract = null; /** the inner class SumsOfContracts */ private class SumsOfContracts { private Double uvp = .0; private Double houseprice = .0; public void addUvp(Double uvp) { this.uvp += uvp; } public void addHouseprice(Double houseprice) { this.houseprice += houseprice; } // get & set will follow below here public Double getUvp() { return uvp; } public Double getHouseprice() { return houseprice; } } private JPanel chartPanel; /** * Constructor. * * @param countOfMonth * - the count of Month */ public ShowSalesStatistics(String countOfMonth) { initComponent(countOfMonth); } /** * initializes this component for time period now - countOfMonth * * @param countOfMonths * - describes the time period: start=now- countOfMonth;end=now */ private void initComponent(String countOfMonth) { int month = Utils.getMonth(countOfMonth); try { lstContract = DatabaseLogic.getContractsOfLastMonth(month); } catch (SQLException e) { e.printStackTrace(); } lstContract.forEach(contract -> { try { contract.setSellPositions(DatabaseLogic.getSellPositions(contract.getIdOfContract())); } catch (SQLException e) { e.printStackTrace(); } }); chartPanel = createChartPanel(lstContract, month); this.add(chartPanel, BorderLayout.NORTH); this.setSize(1000, 800); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.setLocationRelativeTo(null); /** Instantiating the panel for customer's actions */ panelSouth = new JPanel(new GridLayout(1, 7)); panelSouth.setBackground(IntersportColors.INTERSPORT_CORAL); panelSouth.setOpaque(Boolean.TRUE); panelSouth.setBorder(BorderFactory.createRaisedBevelBorder()); monthBox = new JComboBox<String>( new String[] { Constants.ONE_MONTH, Constants.TWO_MONTHS, Constants.THREE_MONTHS, Constants.SIX_MONTHS, Constants.NINE_MONTHS, Constants.TWELVE_MONTHS, Constants.FIFTEEN_MONTHS, Constants.EIGHTEEN_MONTHS, Constants.TWENTY_ONE_MONTHS, Constants.TWENTY_FOUR_MONTHS }); monthBox.setBackground(Color.GREEN); monthBox.setBounds(60, 20, 50, 25); monthBox.setBorder(BorderFactory.createRaisedBevelBorder()); monthBox.setSelectedItem(Constants.SIX_MONTHS); monthBox.addActionListener(this); panelSouth.add(Utils.getEmptyPanel()); panelSouth.add(Utils.getEmptyPanel()); panelSouth.add(Utils.getEmptyPanel()); panelSouth.add(Utils.getEmptyPanel()); panelSouth.add(Utils.getEmptyPanel()); panelSouth.add(Utils.getEmptyPanel()); panelSouth.add(monthBox); this.add(panelSouth, BorderLayout.SOUTH); } /** * creates the chartpanel for the contracts that should be analysed * * @param lstContract * the contracts that should be analysed * @param countOfMonths * - describes the time period: start=now- countOfMonth;end=now * @return */ private JPanel createChartPanel(List<Contract> lstContract, int countOfMonths) { String chartTitle = Constants.SALES_STATISTCS + Constants.COLON + Constants.EMPTY_SPACE + Constants.HOUSE_PRICE + Constants.PIPE + Constants.UVP; String xAxisLabel = Constants.MONTHS; String yAxisLabel = Constants.SUMS_OF_CONTRACTS; Map<Integer, ShowSalesStatistics.SumsOfContracts> monthMappedToSumsOfContractedContracts = getOrderedSumsOfContracts( lstContract, countOfMonths); CategoryDataset dataset = createDataset(monthMappedToSumsOfContractedContracts, countOfMonths); boolean showLegend = Boolean.TRUE; boolean createURL = Boolean.TRUE; boolean createTooltip = Boolean.FALSE; JFreeChart chart = ChartFactory.createBarChart(chartTitle, xAxisLabel, yAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, createTooltip, createURL); // Assign it to the chart CategoryPlot plot = chart.getCategoryPlot(); final NumberAxis xAxis = (NumberAxis) plot.getRangeAxis(); xAxis.setStandardTickUnits(NumberAxis.createStandardTickUnits()); return new ChartPanel(chart) { private static final long serialVersionUID = 1L; private int width = 1000; private int height = 735; @Override public Dimension getPreferredSize() { return new Dimension(width, height); } }; } /** * creates the dataset: month to corresponding houseprice and uvp * * @param monthMappedToSumsOfContractedContracts * - months to corresponding houseprices and uvps * @param months * - the count of months * @return */ private DefaultCategoryDataset createDataset( Map<Integer, ShowSalesStatistics.SumsOfContracts> monthMappedToSumsOfContractedContracts, int months) { final DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for (int month = 0; month <= months; month++) { SumsOfContracts sumsOfContracts = monthMappedToSumsOfContractedContracts.get(month); dataset.addValue(sumsOfContracts.getHouseprice(), Constants.HOUSE_PRICE, String.valueOf(-months + month)); dataset.addValue(sumsOfContracts.getUvp(), Constants.UVP, String.valueOf(-months + month)); } return dataset; } /** * yields the contracted contracts mapped to the month of the contracted date * * @param lstContract * - the contracts * @param month * - the month * @return - the ordered contracts */ private Map<Integer, ShowSalesStatistics.SumsOfContracts> getOrderedSumsOfContracts(List<Contract> lstContract, int month) { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, -month); Map<Integer, ShowSalesStatistics.SumsOfContracts> response = new HashMap<Integer, ShowSalesStatistics.SumsOfContracts>(); for (int i = 0; i <= month; i++) { if (i > 0) { calendar.add(Calendar.MONTH, 1); } String contractedDate = BikeContract.SIMPLE_DATE_FORMAT.format(calendar.getTime()); String contractedMonth = contractedDate.split("\\.")[1].trim(); String contractedYear = contractedDate.split("\\.")[2].trim(); Iterator<Contract> iterator = lstContract.iterator(); ShowSalesStatistics.SumsOfContracts sumsOfContracts = new ShowSalesStatistics.SumsOfContracts(); while (iterator.hasNext()) { Contract contract = iterator.next(); String tmpCreatedAt = contract.getCreatedAt(); String contractedAtDateTmp = tmpCreatedAt.split(Constants.EMPTY_SPACE)[0].trim(); String contractedAtDateMonth = contractedAtDateTmp.split("\\.")[1].trim(); String contractedAtDateYear = contractedAtDateTmp.split("\\.")[2].trim(); if ((contractedAtDateMonth.equals(contractedMonth)) && (contractedAtDateYear.equals(contractedYear))) { Double uvp = Utils.getTotalUvpOfContract(contract); Double housePrice = Utils.getTotalHousepriceOfContract(contract); sumsOfContracts.addUvp(uvp); sumsOfContracts.addHouseprice(housePrice); iterator.remove(); } } response.put(i, sumsOfContracts); } return response; } @Override public void actionPerformed(ActionEvent event) { Object o = event.getSource(); if (o.equals(monthBox)) { String value = (String) monthBox.getSelectedItem(); processContracts(value); } } private void processContracts(String value) { int month = Utils.getMonth(value); try { lstContract = DatabaseLogic.getContractsOfLastMonth(month); } catch (SQLException e) { e.printStackTrace(); } lstContract.forEach(contract -> { try { contract.setSellPositions(DatabaseLogic.getSellPositions(contract.getIdOfContract())); } catch (SQLException e) { e.printStackTrace(); } }); this.remove(chartPanel); chartPanel = createChartPanel(lstContract, month); this.add(chartPanel, BorderLayout.NORTH); this.validate(); } }
true
33390648d9a5d93d1d721ec12decb502540d5e98
Java
BugsEverywhere/learning
/leetcode/src/main/java/indi/simon/learning/leetcode/动态规划/Quiz264_reviewed.java
UTF-8
3,532
3.765625
4
[]
no_license
package indi.simon.learning.leetcode.动态规划; import java.util.Arrays; /** * @author chenzhuo(zhiyue) */ //todo: 感觉有点数论的意思,我的算法(nthUglyNumber)在1548这个神奇的数字上就不work了,因为计算出来的结果还有质因数31。。。他之前都work。但假使对所有数都work,我的复杂度也高了。 // 官方的题解更加合理,定义三个指针p2, p3, p5,分别表示算到当前所使用的2的个数,3的个数,5的个数。每次迭代计算得到合理的dp[i]时,相应的指针往前移动一步。 public class Quiz264_reviewed { public static void main(String[] args) { Quiz264_reviewed quiz264Notfinish = new Quiz264_reviewed(); int res = quiz264Notfinish.nthUglyNumberOfficial(1548); System.out.println(res); } //我的成功的dp public int nthUglyNumberMyDp(int n) { //dp[i]表示第i个丑数 long[] dp = new long[n + 1]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; dp[1] = 1; for (int i = 2; i <= n; i++) { for (int j = i - 1; j >= 0; j--) { long times2 = dp[j] * 2; long times3 = dp[j] * 3; long times5 = dp[j] * 5; if (times5 <= dp[i - 1]) { //够不着了,后面不用看了 break; } if (times2 > dp[i - 1]) { dp[i] = Math.min(dp[i], times2); } else if (times3 > dp[i - 1]) { dp[i] = Math.min(dp[i], times3); } else if (times5 > dp[i - 1]) { dp[i] = Math.min(dp[i], times5); } } } return (int) dp[n]; } //我的失败的解答 public int nthUglyNumber(int n) { int[] dp = new int[n + 1]; dp[0] = 1; dp[1] = 1; int lastPointer = 0; int x = 0; for (int i = 2; i <= n; i++) { int minThisRound = Integer.MAX_VALUE; for (int j = i - 1; j >= 0; j--) { if ((long) dp[j] * 5 <= (long) dp[i - 1]) { break; } if (dp[j] * 2 > dp[i - 1] && dp[j] * 2 < minThisRound) { lastPointer = j; x = 2; minThisRound = dp[j] * 2; } if (dp[j] * 3 > dp[i - 1] && dp[j] * 3 < minThisRound) { lastPointer = j; x = 3; minThisRound = dp[j] * 3; } if (dp[j] * 5 > dp[i - 1] && dp[j] * 5 < minThisRound) { lastPointer = j; x = 5; minThisRound = dp[j] * 5; } } dp[i] = minThisRound; } System.out.println(lastPointer); System.out.println(x); return dp[n]; } public int nthUglyNumberOfficial(int n) { int[] dp = new int[n + 1]; dp[1] = 1; int p2 = 1, p3 = 1, p5 = 1; for (int i = 2; i <= n; i++) { int num2 = dp[p2] * 2, num3 = dp[p3] * 3, num5 = dp[p5] * 5; dp[i] = Math.min(Math.min(num2, num3), num5); if (dp[i] == num2) { p2++; } if (dp[i] == num3) { p3++; } if (dp[i] == num5) { p5++; } } return dp[n]; } }
true
263629038a7286501b6f271546666396a41ee3c6
Java
palaksareen/projectt
/onlinehelp/src/main/java/uk/co/o2/onlinehelp/soapclient/helper/SoaConfig.java
UTF-8
2,857
1.851563
2
[]
no_license
package uk.co.o2.onlinehelp.soapclient.helper; import org.springframework.stereotype.Component; import uk.co.o2.onlinehelp.util.DynamicProperties; @Component public class SoaConfig { private String httpsProtocols = DynamicProperties.getProperty("https.protocols"); private Integer soaSoapReadTimeout = DynamicProperties.getIntegerProperty("soa.read.timeoutMS"); private Integer soaSoapConnectionTimeout = DynamicProperties.getIntegerProperty("soa.connection.timeoutMS"); private Integer soaRestReadTimeout = DynamicProperties.getIntegerProperty("kana.read.timeoutMS"); private Integer soaRestConnectionTimeout = DynamicProperties.getIntegerProperty("kana.connection.timeoutMS"); private String subscriberServiceUrl = DynamicProperties.getProperty("subscriber.service.url"); private String userAcctsServiceUrl = DynamicProperties.getProperty("useraccts.service.url"); private String kanaServiceUrl = DynamicProperties.getProperty("kana.service.url"); // key store private String keyStorePassword = DynamicProperties.getProperty("soa.keystore.password"); private String username = DynamicProperties.getProperty("soa.username"); private String password = DynamicProperties.getProperty("soa.password"); // Trust store private String soaTrustedStoreCertificateLocation = DynamicProperties.getProperty("soa.trustedstore.certificate.location"); private String soaTrustedStorePassword = DynamicProperties.getProperty("soa.trustedstore.password"); private String soaCertificateLocation = DynamicProperties.getProperty("soa.certificate.location"); public SoaConfig() { } public String getHttpsProtocols() { return httpsProtocols; } public Integer getSoaSoapReadTimeout() { return soaSoapReadTimeout; } public String getSubscriberServiceUrl() { return subscriberServiceUrl; } public String getUserAcctsServiceUrl() { return userAcctsServiceUrl; } public Integer getSoaSoapConnectionTimeout() { return soaSoapConnectionTimeout; } public String getKeyStorePassword() { return keyStorePassword; } public String getUsername() { return username; } public String getPassword() { return password; } public String getSoaTrustedStoreCertificateLocation() { return soaTrustedStoreCertificateLocation; } public String getSoaTrustedStorePassword() { return soaTrustedStorePassword; } public String getSoaCertificateLocation() { return soaCertificateLocation; } public String getKanaServiceUrl() { return kanaServiceUrl; } public Integer getSoaRestReadTimeout() { return soaRestReadTimeout; } public Integer getSoaRestConnectionTimeout() { return soaRestConnectionTimeout; } }
true
1bcd27125f30698ef8670ea83faf098ebdadfad5
Java
hopeyone/car-tech
/src/main/java/com/mrhopeyone/domain/Group.java
UTF-8
2,692
2.46875
2
[]
no_license
package com.mrhopeyone.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.*; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; /** * A Group. */ @Entity @Table(name = "jhi_group") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @SuppressWarnings("common-java:DuplicatedBlocks") public class Group implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @Column(name = "name") private String name; @OneToMany(mappedBy = "group") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @JsonIgnoreProperties(value = { "group" }, allowSetters = true) private Set<ToDont> toDonts = new HashSet<>(); // jhipster-needle-entity-add-field - JHipster will add fields here public Long getId() { return this.id; } public Group id(Long id) { this.setId(id); return this; } public void setId(Long id) { this.id = id; } public String getName() { return this.name; } public Group name(String name) { this.setName(name); return this; } public void setName(String name) { this.name = name; } public Set<ToDont> getToDonts() { return this.toDonts; } public void setToDonts(Set<ToDont> toDonts) { if (this.toDonts != null) { this.toDonts.forEach(i -> i.setGroup(null)); } if (toDonts != null) { toDonts.forEach(i -> i.setGroup(this)); } this.toDonts = toDonts; } public Group toDonts(Set<ToDont> toDonts) { this.setToDonts(toDonts); return this; } public Group addToDont(ToDont toDont) { this.toDonts.add(toDont); toDont.setGroup(this); return this; } public Group removeToDont(ToDont toDont) { this.toDonts.remove(toDont); toDont.setGroup(null); return this; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Group)) { return false; } return id != null && id.equals(((Group) o).id); } @Override public int hashCode() { // see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/ return getClass().hashCode(); } // prettier-ignore @Override public String toString() { return "Group{" + "id=" + getId() + ", name='" + getName() + "'" + "}"; } }
true
f1caf9f1b94397e0e00544f961084c7c4e7c2141
Java
marcobarrios/xocolatav2
/Xocolata_v2/src/Clases/Productos.java
UTF-8
10,244
2.359375
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 Clases; /** * * @author Marco */ public class Productos { private String codigo = ""; private int marca = 0; private int tipoProducto = 0; private int talla = 0; private int genero = 0; private String color = ""; private String descripcion = ""; private double precioDolar = 0.0; private double impuestoProducto = 0.0; private double envioProducto = 0.0; private double precioCostoDolar = 0.0; private double tipoCambio = 0.0; private double precioCostoQuetzal = 0.0; private double envioGt = 0.0; private double porcentajeGanancia = 0.0; private double gananciaEstimada = 0.0; private double precioVenta = 0.0; private double porcentajeGananciaSugerida = 0.0; private double gananciaSugerida = 0.0; private double precioSugeridoVendedor = 0.0; private int estadoProducto = 1; private int idPedido = 0; private double porcentajeOferta = 0.0; private double descuentoOferta = 0.0; private double precioOfertado = 0.0; private double precioOfertadoSugerido = 0.0; private double porcentajeOfertaVenta = 0.0; private double descuentoVenta = 0.0; private double precioVentaFinal = 0.0; /** * @return the codigo */ public String getCodigo() { return codigo; } /** * @param codigo the codigo to set */ public void setCodigo(String codigo) { this.codigo = codigo; } /** * @return the marca */ public int getMarca() { return marca; } /** * @param marca the marca to set */ public void setMarca(int marca) { this.marca = marca; } /** * @return the tipoProducto */ public int getTipoProducto() { return tipoProducto; } /** * @param tipoProducto the tipoProducto to set */ public void setTipoProducto(int tipoProducto) { this.tipoProducto = tipoProducto; } /** * @return the talla */ public int getTalla() { return talla; } /** * @param talla the talla to set */ public void setTalla(int talla) { this.talla = talla; } /** * @return the genero */ public int getGenero() { return genero; } /** * @param genero the genero to set */ public void setGenero(int genero) { this.genero = genero; } /** * @return the color */ public String getColor() { return color; } /** * @param color the color to set */ public void setColor(String color) { this.color = color; } /** * @return the descripcion */ public String getDescripcion() { return descripcion; } /** * @param descripcion the descripcion to set */ public void setDescripcion(String descripcion) { this.descripcion = descripcion; } /** * @return the precioDolar */ public double getPrecioDolar() { return precioDolar; } /** * @param precioDolar the precioDolar to set */ public void setPrecioDolar(double precioDolar) { this.precioDolar = precioDolar; } /** * @return the impuestoProducto */ public double getImpuestoProducto() { return impuestoProducto; } /** * @param impuestoProducto the impuestoProducto to set */ public void setImpuestoProducto(double impuestoProducto) { this.impuestoProducto = impuestoProducto; } /** * @return the envioProducto */ public double getEnvioProducto() { return envioProducto; } /** * @param envioProducto the envioProducto to set */ public void setEnvioProducto(double envioProducto) { this.envioProducto = envioProducto; } /** * @return the precioCostoDolar */ public double getPrecioCostoDolar() { return precioCostoDolar; } /** * @param precioCostoDolar the precioCostoDolar to set */ public void setPrecioCostoDolar(double precioCostoDolar) { this.precioCostoDolar = precioCostoDolar; } /** * @return the tipoCambio */ public double getTipoCambio() { return tipoCambio; } /** * @param tipoCambio the tipoCambio to set */ public void setTipoCambio(double tipoCambio) { this.tipoCambio = tipoCambio; } /** * @return the precioCostoQuetzal */ public double getPrecioCostoQuetzal() { return precioCostoQuetzal; } /** * @param precioCostoQuetzal the precioCostoQuetzal to set */ public void setPrecioCostoQuetzal(double precioCostoQuetzal) { this.precioCostoQuetzal = precioCostoQuetzal; } /** * @return the envioGt */ public double getEnvioGt() { return envioGt; } /** * @param envioGt the envioGt to set */ public void setEnvioGt(double envioGt) { this.envioGt = envioGt; } /** * @return the porcentajeGanancia */ public double getPorcentajeGanancia() { return porcentajeGanancia; } /** * @param porcentajeGanancia the porcentajeGanancia to set */ public void setPorcentajeGanancia(double porcentajeGanancia) { this.porcentajeGanancia = porcentajeGanancia; } /** * @return the gananciaEstimada */ public double getGananciaEstimada() { return gananciaEstimada; } /** * @param gananciaEstimada the gananciaEstimada to set */ public void setGananciaEstimada(double gananciaEstimada) { this.gananciaEstimada = gananciaEstimada; } /** * @return the precioVenta */ public double getPrecioVenta() { return precioVenta; } /** * @param precioVenta the precioVenta to set */ public void setPrecioVenta(double precioVenta) { this.precioVenta = precioVenta; } /** * @return the porcentajeGananciaSugerida */ public double getPorcentajeGananciaSugerida() { return porcentajeGananciaSugerida; } /** * @param porcentajeGananciaSugerida the porcentajeGananciaSugerida to set */ public void setPorcentajeGananciaSugerida(double porcentajeGananciaSugerida) { this.porcentajeGananciaSugerida = porcentajeGananciaSugerida; } /** * @return the gananciaSugerida */ public double getGananciaSugerida() { return gananciaSugerida; } /** * @param gananciaSugerida the gananciaSugerida to set */ public void setGananciaSugerida(double gananciaSugerida) { this.gananciaSugerida = gananciaSugerida; } /** * @return the precioSugeridoVendedor */ public double getPrecioSugeridoVendedor() { return precioSugeridoVendedor; } /** * @param precioSugeridoVendedor the precioSugeridoVendedor to set */ public void setPrecioSugeridoVendedor(double precioSugeridoVendedor) { this.precioSugeridoVendedor = precioSugeridoVendedor; } /** * @return the estadoProducto */ public int getEstadoProducto() { return estadoProducto; } /** * @param estadoProducto the estadoProducto to set */ public void setEstadoProducto(int estadoProducto) { this.estadoProducto = estadoProducto; } /** * @return the idPedido */ public int getIdPedido() { return idPedido; } /** * @param idPedido the idPedido to set */ public void setIdPedido(int idPedido) { this.idPedido = idPedido; } /** * @return the porcentajeOferta */ public double getPorcentajeOferta() { return porcentajeOferta; } /** * @param porcentajeOferta the porcentajeOferta to set */ public void setPorcentajeOferta(double porcentajeOferta) { this.porcentajeOferta = porcentajeOferta; } /** * @return the descuentoOferta */ public double getDescuentoOferta() { return descuentoOferta; } /** * @param descuentoOferta the descuentoOferta to set */ public void setDescuentoOferta(double descuentoOferta) { this.descuentoOferta = descuentoOferta; } /** * @return the precioOfertado */ public double getPrecioOfertado() { return precioOfertado; } /** * @param precioOfertado the precioOfertado to set */ public void setPrecioOfertado(double precioOfertado) { this.precioOfertado = precioOfertado; } /** * @return the porcentajeOfertaVenta */ public double getPorcentajeOfertaVenta() { return porcentajeOfertaVenta; } /** * @param porcentajeOfertaVenta the porcentajeOfertaVenta to set */ public void setPorcentajeOfertaVenta(double porcentajeOfertaVenta) { this.porcentajeOfertaVenta = porcentajeOfertaVenta; } /** * @return the descuentoVenta */ public double getDescuentoVenta() { return descuentoVenta; } /** * @param descuentoVenta the descuentoVenta to set */ public void setDescuentoVenta(double descuentoVenta) { this.descuentoVenta = descuentoVenta; } /** * @return the precioVentaFinal */ public double getPrecioVentaFinal() { return precioVentaFinal; } /** * @param precioVentaFinal the precioVentaFinal to set */ public void setPrecioVentaFinal(double precioVentaFinal) { this.precioVentaFinal = precioVentaFinal; } /** * @return the precioOfertadoSugerido */ public double getPrecioOfertadoSugerido() { return precioOfertadoSugerido; } /** * @param precioOfertadoSugerido the precioOfertadoSugerido to set */ public void setPrecioOfertadoSugerido(double precioOfertadoSugerido) { this.precioOfertadoSugerido = precioOfertadoSugerido; } }
true
ec8bc5e0caf475abfc58d2b5867ce676e6110a93
Java
zafrul-ust/tcmISDev
/src/main/java/radian/web/servlets/cmm/CMMSearchMsdsNew.java
UTF-8
446
1.554688
2
[]
no_license
package radian.web.servlets.cmm; import radian.tcmis.server7.share.helpers.ServerResourceBundle; public class CMMSearchMsdsNew extends radian.web.servlets.share.SearchMsdsNew { public String getClient() { //System.out.println("\n\n============ CMMsearchmsds check it is here...."); return "CMM"; } protected ServerResourceBundle getBundle() { return (ServerResourceBundle) new CMMServerResourceBundle(); } }
true
703c15c9fc1fcf910f104c916367725a34752824
Java
Ameg-yag/TLS-Attacker
/TLS-Core/src/main/java/de/rub/nds/tlsattacker/core/protocol/message/PskDheServerKeyExchangeMessage.java
UTF-8
3,292
1.976563
2
[ "Apache-2.0" ]
permissive
/** * TLS-Attacker - A Modular Penetration Testing Framework for TLS * * Copyright 2014-2017 Ruhr University Bochum / Hackmanit GmbH * * Licensed under Apache License 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package de.rub.nds.tlsattacker.core.protocol.message; import de.rub.nds.modifiablevariable.ModifiableVariableFactory; import de.rub.nds.modifiablevariable.ModifiableVariableProperty; import de.rub.nds.modifiablevariable.bytearray.ModifiableByteArray; import de.rub.nds.modifiablevariable.integer.ModifiableInteger; import de.rub.nds.modifiablevariable.util.ArrayConverter; import de.rub.nds.tlsattacker.core.config.Config; import de.rub.nds.tlsattacker.core.protocol.handler.ProtocolMessageHandler; import de.rub.nds.tlsattacker.core.protocol.handler.PskDheServerKeyExchangeHandler; import de.rub.nds.tlsattacker.core.state.TlsContext; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class PskDheServerKeyExchangeMessage extends DHEServerKeyExchangeMessage { private ModifiableByteArray identityHint; @ModifiableVariableProperty(type = ModifiableVariableProperty.Type.LENGTH) private ModifiableInteger identityHintLength; public PskDheServerKeyExchangeMessage() { super(); } public PskDheServerKeyExchangeMessage(Config tlsConfig) { super(tlsConfig); } public ModifiableByteArray getIdentityHint() { return identityHint; } public void setIdentityHint(ModifiableByteArray identityHint) { this.identityHint = identityHint; } public void setIdentityHint(byte[] identity) { this.identityHint = ModifiableVariableFactory.safelySetValue(this.identityHint, identity); } public ModifiableInteger getIdentityHintLength() { return identityHintLength; } public void setIdentityHintLength(ModifiableInteger identityHintLength) { this.identityHintLength = identityHintLength; } public void setIdentityHintLength(int identityHintLength) { this.identityHintLength = ModifiableVariableFactory.safelySetValue(this.identityHintLength, identityHintLength); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("PskDheServerKeyExchangeMessage:"); sb.append("\n Modulus p: "); if (super.modulus != null && super.modulus.getValue() != null) { sb.append(ArrayConverter.bytesToHexString(modulus.getValue())); } else { sb.append("null"); } sb.append("\n Generator g: "); if (generator != null && generator.getValue() != null) { sb.append(ArrayConverter.bytesToHexString(generator.getValue())); } else { sb.append("null"); } sb.append("\n Public Key: "); if (getPublicKey() != null) { sb.append(ArrayConverter.bytesToHexString(getPublicKey().getValue(), false)); } else { sb.append("null"); } return sb.toString(); } @Override public ProtocolMessageHandler getHandler(TlsContext context) { return new PskDheServerKeyExchangeHandler(context); } @Override public String toCompactString() { return "DHE_PSK_SERVER_KEY_EXCHANGE"; } }
true
f04cc76ebc319ddc1eeaf5e2acab685ec3b824dd
Java
bharatarora12345/JAVA_PROGRAMMING
/Recursionn/WarmReception.java
UTF-8
746
2.90625
3
[]
no_license
package Recursion; import java.util.Scanner; public class WarmReception { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // no. of customers int n = sc.nextInt(); // arrival timing int ar1[] = new int[n]; for (int i = 0; i < n; i++) { ar1[i] = sc.nextInt(); } //Departure timining int ar2[] = new int[n]; for (int i = 0; i < n; i++) { ar2[i] = sc.nextInt(); } //chair counts = c int c = 1; int a = ar1[0]; int b = ar2[0]; for (int i = 0; i < n; i++) { if (a > ar1[0] && b < ar2[i]){ } } } }
true
665b5a601fa6879a95b32b7dc49092fdc3e04d93
Java
TatsianaKlasevich/Logistic_Base
/main/java/com/klasevich/lb/creator/DeliveryTruckFactory.java
UTF-8
1,267
2.46875
2
[]
no_license
package com.klasevich.lb.creator; import com.klasevich.lb.entity.DeliveryTruck; import com.klasevich.lb.entity.ProductType; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.List; public class DeliveryTruckFactory { private static final Logger logger = LogManager.getLogger(); public DeliveryTruck createTruck(List<String> list) { DeliveryTruck truck; int truckId; boolean isLoaded; int capacity; ProductType productType; truckId = Integer.parseInt(list.get(0)); String loaded = list.get(1); if (loaded.equals("loaded")) { isLoaded = true; } else { isLoaded = false; } logger.debug(loaded); capacity = Integer.parseInt(list.get(2)); logger.debug(capacity); String type = list.get(3); if (type.equals("perishable")) { productType = ProductType.PERISHABLE; } else { productType = ProductType.NONPERISHABLE; } logger.debug(productType); truck = new DeliveryTruck(truckId, isLoaded, capacity, productType); logger.debug(truck); return truck; } }
true
a92ec22175555528e3df0b253c55269ef56dd317
Java
niksan870/Proyecto_Mingeso
/Back/Spring/src/main/java/com/grupo3/backfcyp/services/UserService.java
UTF-8
8,516
2.671875
3
[]
no_license
package com.grupo3.backfcyp.services; import com.grupo3.backfcyp.models.*; import com.grupo3.backfcyp.models.Class; import com.grupo3.backfcyp.repositories.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController @RequestMapping(value = "/users") public class UserService { @Autowired public UserRepository userRepository; @Autowired public RoleRepository roleRepository; @Autowired public CoordinationRepository coordinationRepository; @Autowired private ClassRepository classRepository; @Autowired private CareerRepository careerRepository; @CrossOrigin @RequestMapping(method = RequestMethod.GET) @ResponseBody public List<User> getUsers(){ return this.userRepository.findAll(); } @CrossOrigin @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public User getUserById(@PathVariable Long id){ return this.userRepository.findUserById(id); } @CrossOrigin @RequestMapping(value = "/update",method = RequestMethod.PUT) @ResponseBody public User updateUser(@Valid @RequestBody User user){ return this.userRepository.save(user); } @CrossOrigin @RequestMapping(value = "/getByRoles", method = RequestMethod.POST) @ResponseBody public List<User> getUsersByRole(@RequestBody @Valid Role role){ return this.roleRepository.findRoleByRole(role.getRole()).getUsers(); } //Creacion de un usuario de cualquier tipo a partir de roles ya creados. @CrossOrigin @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public Map<String,Object> createUser(@Valid @RequestBody User user){ List<Role> roleList; Map<String,Object> response = new HashMap<>(); if(this.userRepository.findUserByEmail(user.getEmail()) != null){ response.put("status",101); //el mail del usuario ya existe response.put("user",null); return response; } if(this.userRepository.findUserByName(user.getName())!=null){ response.put("status",102); //el nombre del usuario ya existe response.put("user",null); return response; } /* desde el front debe elegir si o si un rol*/ if((roleList = user.getRoles()).isEmpty()) { response.put("status","El usuario no tiene roles seleccionados, vuelva a registrar uno valido"); response.put("user",null); return response; } boolean roles[] = new boolean[4];roles[0]=false;roles[1]=false;roles[2]=false;roles[3]=false; int i = 0; for(Role role: roleList){ if(role.getRole().compareTo("su") ==0) roles[0] = true; else if(role.getRole().compareTo("coordination") ==0) roles[1] = true; else if(role.getRole().compareTo("teacher") ==0) roles[2] = true; else if(role.getRole().compareTo("student") ==0) roles[3] = true; i++; this.roleRepository.findRoleByRole(role.getRole()).getUsers().add(user); } //Si es coordinador if(roles[1]) { System.out.println("Soy coordinador"); List<Coordination> coordinations = user.getCoordCoordinations(); if(coordinations != null){ for(Coordination coordination: coordinations){ //Se establece el usuario que lidera esta coordinación. this.coordinationRepository.findCoordinationById(coordination.getId()).setCoordinator(user); } } } //Si es profesor if(roles[2]){ System.out.println("Soy profesor"); List<Class> classes = user.getClasses_teachers(); if(classes != null){ for(Class teacherClass: classes){ this.classRepository.findClassById(teacherClass.getId()).getTeachers().add(user); } //this.classRepository.saveAll(classes); } } //Si es estudiante if(roles[3]){ System.out.println("Soy alumno"); if(user.getCareers() != null){ List<Career> careers = user.getCareers(); for(Career career: careers){ this.careerRepository.findCareerById(career.getId()).getUsers().add(user); } } //this.careerRepository.saveAll(careers); if(user.getClasses_students() != null){ List<Class> classes = user.getClasses_students(); for(Class studentClass: classes){ this.classRepository.findClassById(studentClass.getId()).getStudents().add(user); } } //this.classRepository.saveAll(classes); } this.userRepository.save(user); response.put("status","Usuario agregado correctamente a la base de datos"); response.put("user",user); return response; // if(!(roleList = user.getRoles()).isEmpty()){ // for(Role role: roleList){ // Role role_exist = roleRepository.findRoleByRole(role.getRole()); // if(role_exist != null){//Si el rol existe // role_exist.getUsers().add(user); // } // } // } // List<Coordination> coordinationList; // if((coordinationList = user.getCoordinations() ) != null){ // for(Coordination coordination : coordinationList){ // Coordination coordination_exist = this.sectionRepository.findSectionByCode(coordination.getCode()); // if(coordination_exist != null){ // coordination_exist.getUsers().add(user); // } // } // } // return this.userRepository.save(user); } @CrossOrigin @RequestMapping(value = "/login",method = RequestMethod.POST) @ResponseBody public Map<String,Object> login(@RequestBody User user){ Map<String,String> user_data = new HashMap<String,String>(); System.out.println("Usuario: " + user.getEmail() + " " + user.getPassword()); Map<String,Object> response = new HashMap<String,Object>(); User userFronRepo = this.userRepository.findUserByEmailAndPasswordIgnoreCase(user.getEmail(),user.getPassword().toString()); if(userFronRepo != null){ user_data.put("logged","in"); user_data.put("id",userFronRepo.getId().toString()); user_data.put("name",userFronRepo.getName()); user_data.put("email",userFronRepo.getEmail()); response.put("user",user_data); response.put("roles",userFronRepo.getRoles()); }else{ user_data.put("logged","out"); user_data.put("id",""); user_data.put("name",""); user_data.put("email",""); response.put("user",user_data); response.put("roles",null); } return response; } @CrossOrigin @RequestMapping(value = "/student/{id}/getAllProblems",method = RequestMethod.GET) @ResponseBody public List<Problem> getSolutionsByStudent(@PathVariable Long id){ List<Problem> problems = new ArrayList<>(); User student = this.userRepository.findUserById(id); List<Solution> solutions = student.getSolutions(); for(Solution solution: solutions){ problems.add(solution.getProblem()); } return problems; } @CrossOrigin @RequestMapping(value = "/student/{id}/getSolvedProblems",method = RequestMethod.GET) @ResponseBody public List<Problem> getUnsolvedSolutions (@PathVariable Long id){ User student = this.userRepository.findUserById(id); List<Problem> problems = new ArrayList<>(); for(Solution sol: student.getSolutions()){ if(sol.isSuccess()){ problems.add(sol.getProblem()); } } return problems; } }
true
5b8e807807292ad17827f33f502e83b244573e5e
Java
adi-sk/Assignments
/assignments/test/src/com/assignment/FullTimeEmployee.java
UTF-8
1,043
3
3
[]
no_license
package com.assignment; public class FullTimeEmployee extends Employee { private int salary,pf; public FullTimeEmployee(String firstName, String lastName, int age, int empId, String designation,int salary,int pf) { super(firstName, lastName, age, empId, designation); // TODO Auto-generated constructor stub this.salary= salary; this.pf = pf; } @Override public String toString() { return super.toString()+"FullTimeEmployee [salary=" + salary + ", pf=" + pf + "]"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + pf; result = prime * result + salary; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; FullTimeEmployee other = (FullTimeEmployee) obj; if (pf != other.pf) return false; if (salary != other.salary) return false; return true; } }
true
746fe50d058a8ed68e312fc94114cc8ded6a2763
Java
Hunter-Bobeck/Flash_Mob
/banners/Fake_Loading_Bar.java
UTF-8
1,722
2.703125
3
[]
no_license
package banners; import utilities.*; public class Fake_Loading_Bar { public Fake_Loading_Bar() { // 0% // System.out.print("▯▯▯▯▯▯▯▯▯▯ 0% "); Wait.milliseconds(Random.integer_to(700)); // 10% // System.out.print("\r"); System.out.print("▮▯▯▯▯▯▯▯▯▯ 10% "); Wait.milliseconds(Random.integer_to(500)); // 20% // System.out.print("\r"); System.out.print("▮▮▯▯▯▯▯▯▯▯ 20% "); Wait.milliseconds(Random.integer_to(400)); // 30% // System.out.print("\r"); System.out.print("▮▮▮▯▯▯▯▯▯▯ 30% "); Wait.milliseconds(Random.integer_to(300)); // 40% // System.out.print("\r"); System.out.print("▮▮▮▮▯▯▯▯▯▯ 40% "); Wait.milliseconds(Random.integer_to(300)); // 50% // System.out.print("\r"); System.out.print("▮▮▮▮▮▯▯▯▯▯ 50% "); Wait.milliseconds(Random.integer_to(600)); // 60% // System.out.print("\r"); System.out.print("▮▮▮▮▮▮▯▯▯▯ 60% "); Wait.milliseconds(Random.integer_to(250)); // 70% // System.out.print("\r"); System.out.print("▮▮▮▮▮▮▮▯▯▯ 70% "); Wait.milliseconds(Random.integer_to(350)); // 80% // System.out.print("\r"); System.out.print("▮▮▮▮▮▮▮▮▯▯ 80% "); Wait.milliseconds(Random.integer_to(250)); System.out.print("\r"); System.out.print("▮▮▮▮▮▮▮▮▮▯ 90% "); Wait.milliseconds(Random.integer_to(800)); System.out.print("\r"); System.out.print("▮▮▮▮▮▮▮▮▮▮ 100% "); Wait.milliseconds(300); System.out.print("\r"); System.out.print(" "); System.out.println(); } }
true
055eb881938a8d86c5cf0b9cb530d5178e0b20c7
Java
ihe-brasil/gazelle
/gazelle-tm/gazelle-tm-ejb/src/main/java/net/ihe/gazelle/tm/gazelletest/bean/RoleInTestSystemInSession.java
UTF-8
2,794
2.171875
2
[]
no_license
package net.ihe.gazelle.tm.gazelletest.bean; import net.ihe.gazelle.tm.gazelletest.model.definition.RoleInTest; import net.ihe.gazelle.tm.systems.model.SystemInSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; public class RoleInTestSystemInSession implements Serializable { private static final Logger LOG = LoggerFactory.getLogger(RoleInTestSystemInSession.class); private static final long serialVersionUID = -3968712038630847330L; private RoleInTest roleInTest; private SystemInSession systemInSession; public RoleInTestSystemInSession(RoleInTest roleInTest, SystemInSession systemInSession) { this.roleInTest = roleInTest; this.systemInSession = systemInSession; } public RoleInTest getRoleInTest() { if (LOG.isDebugEnabled()) { LOG.debug("getRoleInTest"); } return roleInTest; } public void setRoleInTest(RoleInTest roleInTest) { if (LOG.isDebugEnabled()) { LOG.debug("setRoleInTest"); } this.roleInTest = roleInTest; } public SystemInSession getSystemInSession() { if (LOG.isDebugEnabled()) { LOG.debug("getSystemInSession"); } return systemInSession; } public void setSystemInSession(SystemInSession systemInSession) { if (LOG.isDebugEnabled()) { LOG.debug("setSystemInSession"); } this.systemInSession = systemInSession; } @Override public int hashCode() { if (LOG.isDebugEnabled()) { LOG.debug("hashCode"); } final int prime = 31; int result = 1; result = (prime * result) + ((roleInTest == null) ? 0 : roleInTest.hashCode()); result = (prime * result) + ((systemInSession == null) ? 0 : systemInSession.hashCode()); return result; } @Override public boolean equals(Object obj) { if (LOG.isDebugEnabled()) { LOG.debug("equals"); } if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } RoleInTestSystemInSession other = (RoleInTestSystemInSession) obj; if (roleInTest == null) { if (other.roleInTest != null) { return false; } } else if (!roleInTest.equals(other.roleInTest)) { return false; } if (systemInSession == null) { if (other.systemInSession != null) { return false; } } else if (!systemInSession.equals(other.systemInSession)) { return false; } return true; } }
true
1d6fcf2179ff84215238f3b8466b9c548c82f025
Java
patrickpycheung/credit-limit
/src/main/java/com/somecompany/service/CreditLimitService.java
UTF-8
6,041
2.828125
3
[ "MIT" ]
permissive
package com.somecompany.service; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.somecompany.model.Entity; /** * Services related to credit limit. * * @author patrick */ @Service public class CreditLimitService { @Value("${reportPath}") String reportPath; /** * Generate credit limit report. * * @param dataList * @throws IOException */ public void generateCreditLimitReport(List<List<String>> dataList) throws IOException { // Key is entity name, value is the entity itself HashMap<String, Entity> entityInfoMap = new HashMap<>(); // Stores the names of all root entities List<String> rootEntityList = new ArrayList<>(); // Create Entity objects for (int i = 0; i < dataList.size(); i++) { if (i == 0) { // Is header row continue; } Entity entity = new Entity(); entity.setName(dataList.get(i).get(0)); String parent = dataList.get(i).get(1); if (parent.equals("")) { // Is a root entity rootEntityList.add(entity.getName()); } entity.setParent(parent); entity.setLimit(Integer.valueOf(dataList.get(i).get(2))); entity.setUtilization(Integer.valueOf(dataList.get(i).get(3))); // Initialize listOfSubEntities List<String> entityList = new ArrayList<>(); entity.setListOfSubEntities(entityList); // Initialize totalUtilization as current entity's utilization first entity.setTotalUtilization(Integer.valueOf(dataList.get(i).get(3))); entity.setTotalLimitOfSubEntities(0); entityInfoMap.put(entity.getName(), entity); } // Establish the group relationship for (Entry<String, Entity> entry : entityInfoMap.entrySet()) { String currentEntityName = entry.getKey(); Entity currentEntity = entry.getValue(); String parent = currentEntity.getParent(); while (!parent.equals("")) { // Current entity has parent Entity parentEntity = entityInfoMap.get(parent); // Add current entity to its parent's listOfSubEntities List<String> currentParentSubEntities = parentEntity.getListOfSubEntities(); if (!currentParentSubEntities.contains(currentEntityName)) { currentParentSubEntities.add(currentEntityName); } // Set parent's totalUtilization to include current entity's totalUtilization parentEntity .setTotalUtilization(parentEntity.getTotalUtilization() + currentEntity.getTotalUtilization()); // Set parent's totalLimitOfSubEntities to include current entity's limit parentEntity.setTotalLimitOfSubEntities( parentEntity.getTotalLimitOfSubEntities() + currentEntity.getLimit()); // Prepare for next loop parent = parentEntity.getParent(); } } // Print report for (String currentRootEntityName : rootEntityList) { Entity currentRootEntity = entityInfoMap.get(currentRootEntityName); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(reportPath, true)); /* Label */ System.out.print("Entities: "); bufferedWriter.write("Entities: "); List<String> list = currentRootEntity.getListOfSubEntities(); list.add(0, currentRootEntityName); for (int i = 0; i < list.size(); i++) { // Print the current subEntity System.out.print(list.get(i)); bufferedWriter.write(list.get(i)); if (i == list.size() - 1) { // Last subEntity System.out.print(":"); bufferedWriter.write(":"); } else { // Not last subEntity System.out.print("/"); bufferedWriter.write("/"); } } System.out.println(); System.out.println(); bufferedWriter.write("\n\n"); /* Content */ int totalUtilization = currentRootEntity.getTotalUtilization(); int limit = currentRootEntity.getLimit(); int utilization = currentRootEntity.getUtilization(); int totalLimitOfSubEntities = currentRootEntity.getTotalLimitOfSubEntities(); // Report on limit breach if (totalUtilization > limit) { // Limit breach System.out.print("Limit breach at " + currentRootEntityName); System.out.print(" ("); System.out.print("limit = " + limit); System.out.print(", "); System.out.print("direct utilisation = " + utilization); System.out.print(", "); System.out.print("combined utilisation = " + totalUtilization); System.out.print(")."); bufferedWriter.write("Limit breach at " + currentRootEntityName); bufferedWriter.write(" ("); bufferedWriter.write("limit = " + limit); bufferedWriter.write(", "); bufferedWriter.write("direct utilisation = " + utilization); bufferedWriter.write(", "); bufferedWriter.write("combined utilisation = " + totalUtilization); bufferedWriter.write(")."); } else { // No limit breach System.out.print("No limit breaches"); bufferedWriter.write("No limit breaches"); } System.out.println(); System.out.println(); bufferedWriter.write("\n\n"); // Report on where the combined sub-entity limits are higher than the limits at the parent group(s) // (i.e. // limit warning) if (totalLimitOfSubEntities > limit) { // Limit warning System.out.print("Combined sub-entity limit is higher than the parent limit"); System.out.print(" ("); System.out.print("limit = " + limit); System.out.print(", "); System.out.print("Combined sub-entity limit = " + totalLimitOfSubEntities); System.out.print(")."); bufferedWriter.write("Combined sub-entity limit is higher than the parent limit"); bufferedWriter.write(" ("); bufferedWriter.write("limit = " + limit); bufferedWriter.write(", "); bufferedWriter.write("Combined sub-entity limit = " + totalLimitOfSubEntities); bufferedWriter.write(")."); } System.out.println(); System.out.println(); bufferedWriter.write("\n\n"); bufferedWriter.close(); } } }
true
ed52f87ccbd5285754d8b8166eeb5cf35a9b3c25
Java
06022015/forealert
/forealert-intf/src/main/java/com/forealert/intf/entity/GroupMemberEntity.java
UTF-8
2,195
2.03125
2
[]
no_license
package com.forealert.intf.entity; import com.couchbase.client.java.repository.annotation.Field; import com.fasterxml.jackson.annotation.JsonIgnore; import com.forealert.intf.entity.type.PrivilegeType; import org.springframework.data.couchbase.core.mapping.Document; import javax.xml.bind.annotation.XmlRootElement; import java.util.HashSet; import java.util.Set; /** * Created by IntelliJ IDEA. * User: ashqures * Date: 7/26/17 * Time: 8:48 PM * To change this template use File | Settings | File Templates. */ @XmlRootElement(name = "group_member") @Document(expiry = 0) public class GroupMemberEntity extends Base{ public static String TYPE = "GroupMember"; @Field private String groupId; @Field private String userId; @Field private Set<PrivilegeType> privilege; @Field private boolean admin; private UserEntity user; public GroupMemberEntity() { setTypeKey(TYPE); } @JsonIgnore public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } @JsonIgnore public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public Set<PrivilegeType> getPrivilege() { return privilege; } public void setPrivilege(Set<PrivilegeType> privilege) { this.privilege = privilege; } public void addPrivilege(PrivilegeType privilegeType){ if(null == getPrivilege()) setPrivilege(new HashSet<PrivilegeType>()); getPrivilege().add(privilegeType); } public boolean hasPrivilege(PrivilegeType privilegeType){ if(null == getPrivilege()){ return getPrivilege().contains(privilegeType); } return false; } public boolean isAdmin() { return admin; } public void setAdmin(boolean admin) { this.admin = admin; } public UserEntity getUser() { return user; } public void setUser(UserEntity user) { this.user = user; } @Override public String getTypeKey() { return TYPE; } }
true
1b64b97afdd44e53b31c6cba91106b72488a52d5
Java
nickmage/Battleship
/src/main/java/com/app/exception/WinnerException.java
UTF-8
114
1.84375
2
[]
no_license
package com.app.exception; public class WinnerException extends Exception{ public WinnerException(){ } }
true