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
caa7398c86bbaa85a86fe712edf98a9a1e633ee4
Java
tianchao62375540/spring-boot-all
/redis/redis-01/src/main/java/com/tc/Hack.java
UTF-8
739
2.734375
3
[]
no_license
package com.tc; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.*; /** * @Auther: tianchao * @Date: 2020/3/24 21:37 * @Description: */ public class Hack { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(6379); while (true){ Socket socket = serverSocket.accept(); byte[] bytes = new byte[1024]; InputStream inputStream = socket.getInputStream(); inputStream.read(bytes); System.out.println(new String(bytes)); OutputStream outputStream = socket.getOutputStream(); outputStream.write("OK".getBytes()); } } }
true
75be3a2cf4ee0d402e3facc943852d68d29940a7
Java
LZ9/AgileDev
/app/src/main/java/com/lodz/android/agiledev/ui/mvp/refresh/activity/MvpTestRefreshActivity.java
UTF-8
3,346
2.0625
2
[ "Apache-2.0" ]
permissive
package com.lodz.android.agiledev.ui.mvp.refresh.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.lodz.android.agiledev.R; import com.lodz.android.agiledev.ui.mvp.refresh.MvpTestRefreshPresenter; import com.lodz.android.agiledev.ui.mvp.refresh.MvpTestRefreshViewContract; import com.lodz.android.component.mvp.base.activity.MvpBaseRefreshActivity; import com.lodz.android.component.widget.base.TitleBarLayout; import com.lodz.android.core.utils.ToastUtils; import java.util.Random; import butterknife.BindView; import butterknife.ButterKnife; /** * 刷新测试类 * Created by zhouL on 2017/7/17. */ public class MvpTestRefreshActivity extends MvpBaseRefreshActivity<MvpTestRefreshPresenter, MvpTestRefreshViewContract> implements MvpTestRefreshViewContract{ public static void start(Context context) { Intent starter = new Intent(context, MvpTestRefreshActivity.class); context.startActivity(starter); } /** 结果 */ @BindView(R.id.result) TextView mResult; /** 获取成功数据按钮 */ @BindView(R.id.get_success_reuslt_btn) Button mGetSuccessResultBtn; /** 获取失败数据按钮 */ @BindView(R.id.get_fail_reuslt_btn) Button mGetFailResultBtn; @Override protected MvpTestRefreshPresenter createMainPresenter() { return new MvpTestRefreshPresenter(); } @Override protected int getLayoutId() { return R.layout.activity_mvp_test_layout; } @Override protected void findViews(Bundle savedInstanceState) { ButterKnife.bind(this); initTitleBarLayout(getTitleBarLayout()); } private void initTitleBarLayout(TitleBarLayout titleBarLayout) { titleBarLayout.setTitleName(R.string.mvp_demo_refresh_title); } @Override protected void onDataRefresh() { getPresenterContract().getRefreshData(new Random().nextInt(9) % 2 == 0); } @Override protected void clickReload() { super.clickReload(); showStatusLoading(); getPresenterContract().getResult(true); } @Override protected void clickBackBtn() { super.clickBackBtn(); finish(); } @Override protected void setListeners() { super.setListeners(); mGetSuccessResultBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showStatusLoading(); getPresenterContract().getResult(true); } }); mGetFailResultBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showStatusLoading(); getPresenterContract().getResult(false); } }); } @Override protected void initData() { super.initData(); showStatusNoData(); } @Override public void setResult(String result) { mResult.setText(result); } @Override public void refreshFail(String tips) { ToastUtils.showShort(getContext(), tips); } @Override public void showResult() { mResult.setVisibility(View.VISIBLE); } }
true
0692ba3debac4726f05f43765d078cfa8f767bd0
Java
firelion0725/MVP-Architecture
/app/src/main/java/com/leo/test/business/task/TaskContract.java
UTF-8
367
1.890625
2
[]
no_license
package com.leo.test.business.task; import com.leo.test.base.BaseActivityView; import com.leo.test.base.BaseView; /** * @author leo, ZhangWei * @date 2018/4/19 * @function */ public interface TaskContract { interface TaskView extends BaseActivityView{ void showData(String str); } interface TaskPresenter { void getData(); } }
true
4be88e09425b7e25ead6e200faccb49024a1d5b2
Java
xbb0911/bos2.0
/bos_management/src/main/java/com/xbb/bos/dao/base/SubAreaRepository.java
UTF-8
377
1.523438
2
[]
no_license
package com.xbb.bos.dao.base; import com.xbb.bos.domain.base.SubArea; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; /** * 分区管理dao * Created by xbb on 2017/12/28. */ public interface SubAreaRepository extends JpaRepository<SubArea,String>,JpaSpecificationExecutor<SubArea>{ }
true
1734f52d4ffdf7fce2ffa215308999b7709610ad
Java
mmolasy/PortalOcenyZdjec
/src/main/java/pl/molasym/photoGrade/sql/PhotoFilesSQL.java
UTF-8
517
1.859375
2
[]
no_license
package pl.molasym.photoGrade.sql; /** * Created by moliq on 19.11.16. */ public class PhotoFilesSQL { public static final String PhotoFromUser = "Select p from Photo p where p.user = :user and visibility = :visibility"; public static final String PhotoById = "Select p from Photo p where p.photoId = :photoId"; public static final String AllPhotoFromUser = "Select p from Photo p where p.user = :user"; public static final String GET_PHOTO_OWNER = "Select p.user from Photo p where p = :photo"; }
true
17a22ce9563267b88ae92a006744d6e39a4c12af
Java
RussellSpr0uts/dungeonbuilder-auth-be
/src/main/java/com/drees/cognito/dtos/cognito/RefreshDTO.java
UTF-8
715
2.265625
2
[]
no_license
package com.drees.cognito.dtos.cognito; import com.fasterxml.jackson.annotation.JsonProperty; public class RefreshDTO { private String email = ""; private String refreshToken = ""; /** * @return the email */ public String getEmail() { return email; } /** * @param email * the email to set */ public void setEmail(final String email) { this.email = email; } /** * @return the refreshToken */ @JsonProperty("refresh-token") public String getRefreshToken() { return refreshToken; } /** * @param refreshToken the refreshToken to set */ public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; } }
true
1975b8960da78d7fdb74c875ad9ec41ab9e2143c
Java
blodemaster/CS61B
/autograder/submission/proj1a/ArrayDequeTest.java
UTF-8
1,457
3.34375
3
[]
no_license
public class ArrayDeqeueTest { public static boolean checkSize(int expect, int real) { if (expect != real) { System.out.println("size() return " + real + ", but expected value is " + expect); return false; } return true; } public static boolean checkEmpty(int expect, int real) { if (expect != real) { System.out.println("isEmpty() return " + real + ", but expected value is " + expect); return false; } return true; } public static boolean checkIntElement(int expect, int real) { if (expect != real) { System.out.println("expect element's value is " + expect + ", but receiving " + real); return false; } return true; } public static void main(String[] args) { int[] truthArray = new int[] {}; ArrayDeqeue<Integer> evalArray = new ArrayDeqeue(); evalArray.addFirst(3); evalArray.addFirst(2); evalArray.addFirst(1); evalArray.addLast(4); evalArray.addLast(5); evalArray.removeFirst(); evalArray.removeFirst(); evalArray.removeLast(); evalArray.removeLast(); evalArray.removeLast(); evalArray.removeLast(); for (int i = 0; i < truthArray.length; i++) { checkIntElement(truthArray[i], evalArray.get(i)); } evalArray.printDeqeue(); } }
true
015a746eb695148dcd6481e7d1044774e34c2c82
Java
voroninMark/vocacook
/app/src/main/java/univ/ducoroy/test/HTTP/VolleyUtils.java
UTF-8
2,725
2.1875
2
[]
no_license
package univ.ducoroy.test.HTTP; import android.content.Context; import com.android.volley.AuthFailureError; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.JsonRequest; import com.android.volley.toolbox.StringRequest; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import static android.provider.ContactsContract.CommonDataKinds.Website.URL; public class VolleyUtils { public static void GET_METHOD(Context context, String url, final VolleyResponseListener listener) { // Initialize a new StringRequest StringRequest stringRequest = new StringRequest( Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { listener.onResponse(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { listener.onError(error.toString()); } }) { }; // Access the RequestQueue through singleton class. RequestSingleton.getInstance(context).addToRequestQueue(stringRequest); } public static void POST_METHOD(Context context, String url, final Map<String, String> getParams, final VolleyResponseListener listener) { // Initialize a new StringRequest StringRequest stringRequest = new StringRequest( Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { listener.onResponse(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { listener.onError(error.toString()); } }) { @Override protected Map<String, String> getParams() { return getParams; } }; // Access the RequestQueue through singleton class. RequestSingleton.getInstance(context).addToRequestQueue(stringRequest); } }
true
9edc03c2d8895832dc5cca27160d4e8ff181b194
Java
jakkritpotter/DatabaseExample
/app/src/main/java/com/android/mobile/databaseexample/HolderListAdapter.java
UTF-8
256
1.632813
2
[]
no_license
package com.android.mobile.databaseexample; /** * Created by 5N1P3R on 22/2/2560. */ import android.widget.Button; import android.widget.TextView; public class HolderListAdapter { TextView txtName,txtSurname,txtAge; Button btnEdit,btnDelete; }
true
776246d71bcbba7a9158b79dd0f7e903172bf6c5
Java
thandekasibiya/Segrada
/segradaclient/RowColumn.java
UTF-8
614
2.734375
3
[]
no_license
package com.example.segradaclient; import android.widget.ImageButton; //this class represent the grids rows and column public class RowColumn { ImageButton button; Cell cell; public RowColumn(ImageButton button, Cell cell) { this.button = button; this.cell = cell; } public ImageButton getButton() { return button; } public void setButton(ImageButton button) { this.button = button; } public Cell getCell() { return cell; } public void setCell(Cell cell) { this.cell = cell; } }
true
25e9b22432e36c8e8845f706d1b0a7fd8fa7c5a7
Java
phd-jaybie/ifip-revamped
/src/org/tensorflow/demo/phd/abstraction/MrObjectManager.java
UTF-8
7,514
2.5
2
[]
no_license
package org.tensorflow.demo.phd.abstraction; import android.util.Xml; import org.tensorflow.demo.Classifier; import org.tensorflow.demo.network.NetworkFragment; import org.tensorflow.demo.network.XmlOperator; import org.tensorflow.demo.phd.detector.cv.CvDetector; import org.tensorflow.demo.simulator.App; import org.xmlpull.v1.XmlSerializer; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by deg032 on 6/2/18. * * Note: To maintain the privacy of object/s and user/s, please have these objects only created by * by the system-level functions and not by external or third-party applications and/or services. */ public class MrObjectManager { // List of live objects that are detected. protected static List<MrObject> MrObjects = new ArrayList<>(); static String[] sensitiveObjects = new String[] //high sensitivity objects {"person", "bed", "toilet", "laptop", "mouse","keyboard", "cell phone"}; public class MrObject { private String name; //private String description; private String[] permissions; private String privacyLabel; public String getName() { return name; } public String[] getPermissions() { return permissions; } public String getPrivacyLabel() { return privacyLabel; } public MrObject(final String name, final String[] permissions, final String privacyLabel) { this.name = name; this.permissions = permissions; this.privacyLabel = privacyLabel; } public MrObject(final MrObject object) { this.name = object.getName(); this.permissions = object.getPermissions(); this.privacyLabel = object.getPrivacyLabel(); } } private boolean userPermitted(String appName, String object){ //if permitted: return false; // if not: return true; } private String getPrivacylabel(String object){ // Below is a simplistic object sensitivity labelling. if (Arrays.asList(sensitiveObjects).contains(object)) { return "PRIVATE"; } else { return "PUBLIC"; } } public void generateList(){ // This generates an initial list of MrObjects that is associated to this user. // Ideally, it also generates a list with objects associated with certain apps and other // users. List<MrObject> fromStorage = new ArrayList<>(); // Get list from storage and add it to the live list. MrObjects.addAll(fromStorage); // We can also create a new list of sensitive objects from the pre-saved list of private // objects of the user. } private void addMrObject(final MrObject object) { if (MrObjects.isEmpty()) MrObjects.add(object); else { List<MrObject> fromNetworkList = new ArrayList<>(); // Check if object is already present on live list. for (MrObject mrObject : MrObjects){ if (mrObject.getName() == object.getName()) break; fromNetworkList.add(object); } MrObjects.addAll(fromNetworkList); } } public void refreshList(){ // This refreshes the list of live MrObjects. // We can practically remove objects that have been added but has not been accessed for a // while or those that are past their time to live. } public void refreshListFromNetwork(NetworkFragment networkFragment, boolean receiveFlag) { // Check for received objects over the network. if (receiveFlag) { List<MrObject> fromNetwork = new ArrayList<>(); fromNetwork = networkFragment.getObjects(); // Get list from network and add it to the live list. if (fromNetwork!= null) { for (MrObject nObject : fromNetwork) { for (MrObject mrObject : MrObjects) { if (mrObject.getName() != nObject.getName()) MrObjects.add(nObject); } } } // Then refresh list. refreshList(); } // Then share some public objects. List<MrObject> publicObjects = new ArrayList<>(); for (MrObject object: MrObjects) { if (object.getPrivacyLabel() == "PUBLIC") publicObjects.add(object); } networkFragment.shareObjects(writeXml(publicObjects)); } private String writeXml(List<MrObjectManager.MrObject> mrObjects){ XmlSerializer serializer = Xml.newSerializer(); StringWriter writer = new StringWriter(); try { serializer.setOutput(writer); serializer.startDocument("UTF-8", true); serializer.startTag("", "MR-objects"); serializer.attribute("", "number", String.valueOf(mrObjects.size())); for (MrObjectManager.MrObject object: mrObjects){ serializer.startTag("", "object"); serializer.startTag("", "name"); serializer.text(object.getName()); serializer.endTag("", "name"); serializer.endTag("", "object"); } serializer.endTag("", "MR-objects"); serializer.endDocument(); return writer.toString(); } catch (Exception e) { throw new RuntimeException(e); } } public void processObject(App app, Classifier.Recognition object) { // check user preferences of what is the supposed sensitivity of this object // if app is not allowed to see this object type, return //if (!userPermitted(app.getName(),object.getTitle())) return; // check object if in 'live' list // if not, add to live list String[] permissions = {app.getName()}; String privacyLabel = getPrivacylabel(object.getTitle()); addMrObject(new MrObject(object.getTitle(),permissions,privacyLabel)); } public void processObject(App app, CvDetector.Recognition object) { // check user preferences of what is the supposed sensitivity of this object // if app is not allowed to see this object type, return //if (!userPermitted(app.getName(),object.getTitle())) return; // check object if in 'live' list // if not, add to live list String[] permissions = {app.getName()}; String privacyLabel = getPrivacylabel(object.getTitle()); addMrObject(new MrObject(object.getTitle(),permissions,privacyLabel)); } public void processObject(XmlOperator.XmlObject object) { // this adds the received objects from the Network to the live objects // It is, however, preferrable, if there is an additional separate handling of the objects // received from the network and the live objects. // Also, we may configure the necessary privacy labels of these objects String[] permissions = {object.getDescription()}; String privacyLabel = getPrivacylabel(object.getName()); addMrObject(new MrObject(object.getName(),permissions,privacyLabel)); } public void storeList() { // when the app is closed, store the list before it is destroyed. } public int numberOfObjects(){ return MrObjects.size(); } }
true
8bb6e751f69ac4911153025c0889e02dd162fffd
Java
saoov/sblib
/sblib/src/main/java/org/sb/event/domain/ReplyVO.java
UTF-8
257
1.6875
2
[]
no_license
package org.sb.event.domain; import java.util.Date; import lombok.Data; @Data public class ReplyVO { private Long reply_no; private Long event_no; private String reply; private String replyer; private Date replyDate; private Date updateDate; }
true
ba11d3308a6820759c41693e747fd4c2856fd84f
Java
addonin/patternsGoF
/structural/composite/CompositeClient.java
UTF-8
667
2.75
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 structural.composite; /** * * @author dimon */ public class CompositeClient { public static void main(String[] args) { Composite root = new Composite("root"); root.add(new Leaf("1, 1 level")); root.add(new Leaf("2, 1 level")); Composite composite1 = new Composite("1, 1 level"); composite1.add(new Leaf("1, 2 level")); root.add(composite1); root.print(); } }
true
689de68a1f33eabb880d6d6ca592f29087c00130
Java
Himanshu-Kandwal/MEMESENA-WITH-ADMIN
/app/src/main/java/msm/MemeSena/AppStickerActivity/PrivacyPolicyActivity.java
UTF-8
2,602
2.171875
2
[ "MIT" ]
permissive
package msm.MemeSena.AppStickerActivity; import android.os.Bundle; import android.view.View; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import msm.MemeSena.Base.BaseActivity; import msm.MemeSena.R; public class PrivacyPolicyActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.privacypolicyactivity); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(R.string.labal_privacy_policy); } ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar); WebView htmlWebView = (WebView) findViewById(R.id.webView); WebSettings webSetting = htmlWebView.getSettings(); webSetting.setJavaScriptEnabled(true); webSetting.setDisplayZoomControls(true); htmlWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); progressBar.setVisibility(View.GONE); } }); htmlWebView.loadUrl(getString(R.string.txt_privacy_policy_url)); /*String htmlFilename = "WAStickers_Packs_Privacy_Policy.htm"; AssetManager mgr = getBaseContext().getAssets(); try { InputStream in = mgr.open(htmlFilename, AssetManager.ACCESS_BUFFER); String htmlContentInStringFormat = StreamToString(in); in.close(); htmlWebView.loadDataWithBaseURL(null, htmlContentInStringFormat, "text/html", "utf-8", null); } catch (IOException e) { e.printStackTrace(); }*/ } public static String StreamToString(InputStream in) throws IOException { if (in == null) { return ""; } Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { } return writer.toString(); } }
true
989b36bc58f4ac61d5ff401ba148adf94077e8ec
Java
shafali731/APCS1-hw
/APCS1/HW21/Commafier.java
UTF-8
978
3.09375
3
[]
no_license
public class Commafier{ public static String commafyR(int a){ String strInt= Integer.toString(a); int L= strInt.length(); String newNum= ""; if (L<=3){ return strInt + newNum; } newNum = commafyR(Integer.parseInt(strInt.substring(0, L-3)))+ "," + (strInt.substring(L-3))+ newNum; strInt= strInt.substring(0, L-3); return newNum; } public static String commafyF(int a){ String strInt= Integer.toString(a); //int L= strInt.length(); String newNum= ""; for(int L= strInt.length(); L>3 ; strInt = strInt.substring(0, L-3), L-=3){ newNum= "," + strInt.substring(L-3); } return strInt + newNum; } public static void main(String[] args){ // System.out.println(commafyR(1)); // System.out.println(commafyR(1000)); // System.out.println(commafyR(1000000)); //System.out.println(commafyF(1)); //System.out.println(commafyF(1000)); //System.out.println(commafyF(1000000)); for (String s: args){ sop(commafyR (s));} }}
true
18e8d64d761a56eb22b88874dd7105a459ab6aa7
Java
ttiyemba/Spring-MicroService-Api
/account/src/main/java/com/qa/tapiwa/spring/data/repo/AccountRepo.java
UTF-8
283
1.625
2
[]
no_license
package com.qa.tapiwa.spring.data.repo; import com.qa.tapiwa.spring.data.domain.Account; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface AccountRepo extends JpaRepository<Account,Long>{ }
true
9518d7efca923a5b6e1f5419dbe60f93bcbc60ed
Java
sheppe/pharis-cosc319-project
/test/particlesim/CharacteristicTest.java
UTF-8
5,272
2.703125
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package particlesim; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Sheppe */ public class CharacteristicTest { public CharacteristicTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getCharacteristicType method, of class Characteristic. */ @Test public void testGetCharacteristicType() { System.out.println("getCharacteristicType"); Characteristic instance = new Characteristic(); CharacteristicType expResult = new CharacteristicType(); CharacteristicType result = instance.getCharacteristicType(); assertEquals(expResult.getClass(), result.getClass()); } /** * Test of setCharacteristicType method, of class Characteristic. */ @Test public void testSetCharacteristicType() { System.out.println("setCharacteristicType"); CharacteristicType newValue = null; Characteristic instance = new Characteristic(); instance.setCharacteristicType(newValue); } /** * Test of getBehaviourModifier method, of class Characteristic. */ @Test public void testGetBehaviourModifier() { System.out.println("getBehaviourModifier"); Characteristic instance = new Characteristic(); float expResult = 0.0F; float result = instance.getBehaviourModifier(); assertEquals(expResult, result); } /** * Test of setBehaviourModifier method, of class Characteristic. */ @Test public void testSetBehaviourModifier() { System.out.println("setBehaviourModifier"); float newValue = 0.0F; Characteristic instance = new Characteristic(); instance.setBehaviourModifier(newValue); } /** * Test of getCharacteristicType method, of class Characteristic. */ @Test public void testGetCharacteristicType1() { System.out.println("getCharacteristicType"); Characteristic instance = new Characteristic(); CharacteristicType expResult = new CharacteristicType(); CharacteristicType result = instance.getCharacteristicType(); assertEquals(expResult.getClass(), result.getClass()); } /** * Test of setCharacteristicType method, of class Characteristic. */ @Test public void testSetCharacteristicType_CharacteristicType() { System.out.println("setCharacteristicType"); CharacteristicType newValue = null; Characteristic instance = new Characteristic(); instance.setCharacteristicType(newValue); } /** * Test of getBehaviourModifier method, of class Characteristic. */ @Test public void testGetBehaviourModifier1() { System.out.println("getBehaviourModifier"); Characteristic instance = new Characteristic(); float expResult = 0.0F; float result = instance.getBehaviourModifier(); assertEquals(expResult, result); } /** * Test of setBehaviourModifier method, of class Characteristic. */ @Test public void testSetBehaviourModifier_float() { System.out.println("setBehaviourModifier"); float newValue = 0.0F; Characteristic instance = new Characteristic(); instance.setBehaviourModifier(newValue); } /** * Test of getCharacteristicType method, of class Characteristic. */ @Test public void testGetCharacteristicType2() { System.out.println("getCharacteristicType"); Characteristic instance = new Characteristic(); CharacteristicType expResult = new CharacteristicType(); CharacteristicType result = instance.getCharacteristicType(); assertEquals(expResult, result); } /** * Test of setCharacteristicType method, of class Characteristic. */ @Test public void testSetCharacteristicType_CharacteristicType_1args() { System.out.println("setCharacteristicType"); CharacteristicType newValue = null; Characteristic instance = new Characteristic(); instance.setCharacteristicType(newValue); } /** * Test of getBehaviourModifier method, of class Characteristic. */ @Test public void testGetBehaviourModifier2() { System.out.println("getBehaviourModifier"); Characteristic instance = new Characteristic(); float expResult = 0.0F; float result = instance.getBehaviourModifier(); assertEquals(expResult, result); } /** * Test of setBehaviourModifier method, of class Characteristic. */ @Test public void testSetBehaviourModifier_float_1args() { System.out.println("setBehaviourModifier"); float newValue = 0.0F; Characteristic instance = new Characteristic(); instance.setBehaviourModifier(newValue); } }
true
6af10d303ba5922a5e195362ebb9e0de18ce5fa4
Java
fekdas/CSvorob_JHomeWork
/src/HomeWork12/HomeWork12task1task2.java
WINDOWS-1251
2,212
4.21875
4
[]
no_license
package HomeWork12; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; /* * 1) String, . . , . . ( ). "". . 2) . */ public class HomeWork12task1task2 { public static void main(String[] args) { ArrayList<String> strings = new ArrayList<>(); Scanner sc = new Scanner(System.in); String exit = null; String s = null; do // { System.out.println(" "); if(sc.hasNext()) { s = sc.next(); } strings.add(s); System.out.println("? (anykey - YES / X - exit)"); if(sc.hasNext()) { exit = sc.next(); } } while (!exit.equalsIgnoreCase("x")); System.out.println(" : " + strings.toString()); for (int i = 0; i< strings.size(); i++) { String s2 = strings.get(i); s2 = s2.replaceAll("a", ""); // "" strings.set(i, s2); } System.out.println(" --: " + strings.toString()); // HashSet<String> hs = new HashSet<>(strings); strings.clear(); strings.addAll(hs); System.out.println(" : " + strings.toString()); } }
true
76dfbbe4ec2c782e80f5cf252fe9e012f6cdeab7
Java
wesleycode/Projeto-Integrador-III
/Kartodromo/src/View/AvaliacoesDeKartodromo.java
UTF-8
7,463
2.5625
3
[]
no_license
package View; import Bo.AvaliacaoBO; import Model.Avaliacao; import Model.Kartodromo; import Model.Piloto; import Utilities.Colors; import Utilities.Fonts; import Utilities.Info; import Utilities.InformacoesPiloto; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.security.Key; import java.util.*; import javax.swing.table.DefaultTableModel; public class AvaliacoesDeKartodromo extends JFrame implements ActionListener { private JPanel fundo; private JPanel drawer; private JButton btnVoltar; private JLabel logo; private JLabel avaliacoesLabel; private JLabel MediaLabel; private JScrollPane jScrollPanekartodromo; private JTable tableKartodromo; private DefaultTableModel tabelamento; private Piloto piloto; private Kartodromo kartodromo; private InformacoesPiloto informacoesPiloto; public AvaliacoesDeKartodromo(Piloto piloto, Kartodromo kartodromo) throws Exception { this.piloto = piloto; this.kartodromo = kartodromo; // Instancia de itens // initializate(); // Coloca o tema na tela setTheme(); // Adiciona o item na tela // add(); // Configura o item da tela (btn,label...) // configs(); // Configura esse frame // configurateThis(); } private void configurateThis() { setUndecorated(true); setSize(Info.MINSCREENSIZE); setLayout(null); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setTitle(Info.APP_NAME); setResizable(false); } private void initializate() { fundo = new JPanel(); drawer = new JPanel(); btnVoltar = new JButton(); logo = new JLabel(); avaliacoesLabel = new JLabel(); MediaLabel = new JLabel(); informacoesPiloto = new InformacoesPiloto(); jScrollPanekartodromo = new JScrollPane(); tableKartodromo = new JTable(); } private void add() { add(btnVoltar); add(avaliacoesLabel); add(MediaLabel); add(informacoesPiloto); add(logo); add(jScrollPanekartodromo); add(drawer); add(fundo); } private void setTheme() { if (SplashScreen.getConfiguracao().isTema()) { // Se o tema for escuro, os itens ficam assim // fundo.setBackground(Colors.CINZAMEDB); drawer.setBackground(Colors.VERDEDARK); logo.setForeground(Colors.CINZAMEDB); tableKartodromo.setBackground(Colors.VERDELIGHT); tableKartodromo.setForeground(Colors.CINZADARKB); MediaLabel.setForeground(Colors.CINZAMEDA); informacoesPiloto.setForeground(Colors.CINZALIGHTB); avaliacoesLabel.setForeground(Colors.CINZAMEDA); btnVoltar.setForeground(Colors.CINZADARKB); btnVoltar.setBackground(Colors.VERDEDARK); } else { fundo.setBackground(Colors.CINZAMEDA); drawer.setBackground(Colors.VERDEDARK); logo.setForeground(Colors.CINZAMEDB); tableKartodromo.setForeground(Colors.CINZADARKB); tableKartodromo.setBackground(Colors.VERDEDARK); MediaLabel.setForeground(Colors.CINZALIGHTB); informacoesPiloto.setForeground(Colors.BRANCO); avaliacoesLabel.setForeground(Colors.CINZALIGHTB); btnVoltar.setForeground(Colors.CINZADARKB); btnVoltar.setBackground(Colors.VERDEDARK); } } private void configs() throws Exception { fundo.setSize(Info.MINSCREENSIZE); drawer.setBounds(0, 0, 800, 100); informacoesPiloto.setBounds(600, 3, 200, 100); informacoesPiloto.setPiloto(piloto); tableKartodromo.setModel(new DefaultTableModel( new Object[][]{ }, new String[]{ "NOME DO PILOTO", "COMENTÁRIOS", "AVALIAÇÃO" } ) { boolean[] canEdit = new boolean[]{ false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit[columnIndex]; } }); tabelamento = (DefaultTableModel) tableKartodromo.getModel(); HashMap<String, Integer> mapa = new HashMap<>(); int muitoRuim = 0; int ruim = 0; int media = 0; int boa = 0; int muitoBoa = 0; String aval = null; try { for (Avaliacao avaliacao : new AvaliacaoBO().listarPorKartodromo(kartodromo)) { switch (avaliacao.getNumeroEstrelas()) { case 1: muitoRuim++; aval = "Muito Ruim"; break; case 2: ruim++; aval = "Ruim"; break; case 3: media++; aval = "Médio"; break; case 4: boa++; aval = "Bom"; break; case 5: muitoBoa++; aval = "Muito Bom"; break; } tabelamento.addRow(new Object[]{ avaliacao.getPiloto().getNome(), avaliacao.getComentario(), aval }); } } catch (Exception error) { JOptionPane.showMessageDialog(null, "Erro ao visualizar avaliações " + error.getMessage(), "Error:", JOptionPane.ERROR_MESSAGE); } mapa.put("Muito Ruim", muitoRuim); mapa.put("Ruim", ruim); mapa.put("Media", media); mapa.put("Boa", boa); mapa.put("Muito Boa", muitoBoa); // Caso o mapa esteja vazio // if (mapa.values().stream().distinct().count() == 0) { mapa.put("Media", 1); } jScrollPanekartodromo.setViewportView(tableKartodromo); jScrollPanekartodromo.setBounds(60, 150, 680, 300); logo.setFont(Fonts.SANSSERIFMIN); logo.setBounds(20, 30, 500, 35); logo.setText("PERFIL DO KARTÓDROMO"); avaliacoesLabel.setBounds(300, 120, 300, 35); avaliacoesLabel.setText("Avaliações do Kartódromo: " + kartodromo.getNome()); // AQUI COLOCA O NOME DA CORRIDA // MediaLabel.setBounds(320, 480, 300, 35); // Pega do mapa a chave que contém o maior valor // MediaLabel.setText("MÉDIA DE AVALIAÇÃO: " + Collections.max(mapa.entrySet(), Map.Entry.comparingByValue()) .getKey() .toUpperCase()); // AQUI COLOCA O NOME DO PRIMEIRO COLOCADO DA CORRIDA // btnVoltar.setBorderPainted(false); btnVoltar.setFocusPainted(false); btnVoltar.addActionListener(this); btnVoltar.setBounds(320, 540, 200, 35); btnVoltar.setText("VOLTAR"); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnVoltar) { dispose(); new AvaliarKartodromo(piloto); } } }
true
798db1c0ed265a3dce5f5167b994cb141e33cca3
Java
landy8530/example
/src/main/java/com/java8/constructor/LambdaConstructorTest.java
UTF-8
801
3.4375
3
[ "MIT" ]
permissive
package com.java8.constructor; /** * @author landyl * @create 10:58 AM 03/01/2018 */ public class LambdaConstructorTest { public static void main(String[] args) { // Method and Constructor References ××××××××××××××××××××××××××××××××××××××× // We create a reference to the Person constructor via Person::new. // The Java compiler automatically chooses the right constructor by matching the signature of PersonFactory.create. PersonFactory<Person> personFactory = Person::new; Person person = personFactory.create("Peter", "Parker"); System.out.println(person.firstName); // Method and Constructor References ××××××××××××××××××××××××××××××××××××××× } }
true
6bd80b3c4d0de28b3546f5690e8b0acab98e5130
Java
Yurlov/messaging-hub
/src/main/java/сom/viktor/yurlov/domain/rest/ResetPasswordConfirmRequest.java
UTF-8
1,024
2.109375
2
[]
no_license
package сom.viktor.yurlov.domain.rest; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonRawValue; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import lombok.experimental.FieldDefaults; import javax.validation.Valid; import javax.validation.constraints.NotNull; @Setter @Getter @FieldDefaults(level = AccessLevel.PRIVATE) @Accessors(chain = true) public class ResetPasswordConfirmRequest { @Getter @Setter @FieldDefaults(level = AccessLevel.PRIVATE) @Accessors(chain = true) public static class Secure { @JsonProperty("new_password") @NotNull String newPassword; } @Getter @Setter @FieldDefaults(level = AccessLevel.PRIVATE) @Accessors(chain = true) public static class Body { @JsonProperty("receiver") String receiver; // email or mobile @JsonProperty("code") String code; } @JsonRawValue String extra; @NotNull @Valid Secure secure; @Valid Body body; }
true
f5c3a05d2333c6b6294e5c485c7bc9d8fcd2528e
Java
ChaoPang/dictionary-api
/src/main/java/org/dictionary/controller/DictionaryController.java
UTF-8
2,227
2.28125
2
[]
no_license
package org.dictionary.controller; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import java.util.Objects; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.StringUtils; import org.dictionary.concept.WordConcept; import org.dictionary.crawl.definition.impl.DictionaryWordCrawlingServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; @Controller @RequestMapping("/") public class DictionaryController { private final static String TEMPLATE_VIEW = "view-dictionary"; private final DictionaryWordCrawlingServiceImpl dictionaryWordCrawlingService; private final LoadingCache<String, WordConcept> cachedWordConcepts = CacheBuilder.newBuilder().maximumSize(1000) .expireAfterWrite(1, TimeUnit.DAYS).build(new CacheLoader<String, WordConcept>() { public WordConcept load(String word) { return dictionaryWordCrawlingService.getWordSenses(word); } }); @Autowired public DictionaryController(DictionaryWordCrawlingServiceImpl dictionaryWordCrawlingService) { this.dictionaryWordCrawlingService = Objects.requireNonNull(dictionaryWordCrawlingService); } @RequestMapping(method = RequestMethod.GET) public String defaultView(Model model) { return TEMPLATE_VIEW; } @CrossOrigin @RequestMapping(value = "/dictionary/{word}", method = RequestMethod.GET, produces = APPLICATION_JSON_VALUE) @ResponseBody public WordConcept getWordConcept(@PathVariable("word") String wordToLookup) throws ExecutionException { if (StringUtils.isNotBlank(wordToLookup)) { return cachedWordConcepts.get(wordToLookup); } return WordConcept.create(); } }
true
f1e090b4f89d5a1a19e0c59c2e56a858441f7b86
Java
xiangzhihong/aidl
/app/src/main/java/com/xzh/aidldemo/base/App.java
UTF-8
306
1.671875
2
[]
no_license
package com.xzh.aidldemo.base; import android.app.Application; import com.xzh.aidldemo.PushClient; /** * Created by zhihong on 2016/8/3. */ public class App extends Application { @Override public void onCreate() { super.onCreate(); PushClient.getInstance().init(this); } }
true
2899341ba4d1a00e7f81345933794094053e312c
Java
FrigoCoder/Frigo
/src/test/java/frigo/math/crack/FactorialNumberSystemTest.java
UTF-8
1,327
2.890625
3
[]
no_license
package frigo.math.crack; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import org.junit.Test; public class FactorialNumberSystemTest { @Test public void test_place_values () { assertPlaceValues(0, 1); assertPlaceValues(1, 1); assertPlaceValues(2, 1, 2); assertPlaceValues(5, 1, 2); assertPlaceValues(6, 1, 2, 6); assertPlaceValues(24, 1, 2, 6, 24); } private void assertPlaceValues (int highest, long... placeValues) { FactorialNumberSystem system = new FactorialNumberSystem(highest); for( int i = 0; i < placeValues.length; i++ ){ assertThat(system.placeValue(i), is(placeValues[i])); } } @Test public void test_highest_digits () { assertHighestDigits(0, 1); assertHighestDigits(1, 1); assertHighestDigits(2, 1, 2); assertHighestDigits(5, 1, 2); assertHighestDigits(6, 1, 2, 3); assertHighestDigits(24, 1, 2, 3, 4); } private void assertHighestDigits (int highest, long... highestDigits) { FactorialNumberSystem system = new FactorialNumberSystem(highest); for( int i = 0; i < highestDigits.length; i++ ){ assertThat(system.highestDigit(i), is(highestDigits[i])); } } }
true
f1df8fa7eeaa7ef501983841fccdf8cbf2f44238
Java
zhiji6/yxw
/yxw-stats-task/src/main/java/com/yxw/stats/service/platform/DepositOrderCountServiceImpl.java
UTF-8
1,154
1.929688
2
[]
no_license
package com.yxw.stats.service.platform; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.yxw.framework.mvc.dao.BaseDao; import com.yxw.framework.mvc.service.impl.BaseServiceImpl; import com.yxw.stats.dao.platform.DepositOrderCountDao; import com.yxw.stats.entity.platform.DepositOrderCount; @Service(value = "depositOrderCountService") public class DepositOrderCountServiceImpl extends BaseServiceImpl<DepositOrderCount, String> implements DepositOrderCountService { public static Logger logger = LoggerFactory.getLogger(DepositOrderCountServiceImpl.class); @Autowired private DepositOrderCountDao depositOrderCountDao; @Override protected BaseDao<DepositOrderCount, String> getDao() { // TODO Auto-generated method stub return depositOrderCountDao; } /** * 当天门诊订单统计 * * @param map * @return */ public List<DepositOrderCount> findDepositOrderCountByDate(Map map) { return depositOrderCountDao.findDepositOrderCountByDate(map); } }
true
b16f6349212d17d1730040dfc45827fcd272eec1
Java
ElectronicWorld/FondamentiProgrammazione
/GruppoAZ/src/polveri_sottili/Settimana.java
UTF-8
860
2.546875
3
[]
no_license
package polveri_sottili; import IOUtils.IOUtils;; public class Settimana { IOUtils io= new IOUtils(); private int anno; private int nr_settimana; private float [] polveri_sottili= new float[7]; private float val_max=0; private float soglia_giornaliera=75; private float soglia_media=50; public void add_value(float polveri, int n) { this.polveri_sottili[n]=polveri; } public float media_polveri() { return io.media(polveri_sottili, 7); } //controlla che la media sia sotto la soglia public float verifica_media() { if(media_polveri()<=soglia_media) return 0; return media_polveri()-soglia_media; } //controlla i dati di un giorno siano sotto la soglia public float verifica_soglia_giornaliera(int n) { if(polveri_sottili[n]<=soglia_giornaliera) return 0; return polveri_sottili[n]-soglia_giornaliera; } }
true
0a42f203cf51fbcf45ca5421a911217e4be10271
Java
muhammedargin/GameStoreDemo
/GameStoreDemo/src/GameStore/entities/Abstract/Member.java
UTF-8
144
1.929688
2
[]
no_license
package GameStore.entities.Abstract; public abstract class Member { private int id; private String nickName; private String country; }
true
c9f60de43a4db84ddebb225afc73d5aa328c50a9
Java
meizitt/A_Q_online
/src/main/java/com/perc/qanda/mappers/CommQuestionMapper.java
UTF-8
1,137
2.078125
2
[]
no_license
package com.perc.qanda.mappers; import com.perc.qanda.bean.CommQ; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface CommQuestionMapper { @Insert("insert into comm_q(q_id,text,time,answer) " + "values(#{q_id},#{text},#{time},#{answer})") int addCommQ(CommQ commQ); @Delete("delete from comm_q where q_id=#{id}") int delCommQById(Integer id); @Select("select * from comm_q where q_id=#{id}") CommQ findCommQById(Integer id); @Select("select * from comm_q where text like '%${text}%'") List<CommQ> findCommQText(String text); @Select("select * from comm_q") List<CommQ> findAllCommQ(); @Update("update comm_q set text=#{text},answer=#{answer},time=#{time} " + "where q_id=#{q_id}") int updateCommQ(CommQ commQ); @Update("update comm_q set num=#{num} where q_id=#{id}") int updateCommQNum(Integer id,Integer num); }
true
947b5c609524fa86bffd9d2c7bdb7445d2cfba43
Java
ByVladiko/SmartWater
/app/src/main/java/com/example/smartwater/ui/cart/ShoppingCartHelper.java
UTF-8
964
2.609375
3
[]
no_license
package com.example.smartwater.ui.cart; import com.example.smartwater.model.Product; import java.util.ArrayList; import java.util.List; import java.util.Map; public class ShoppingCartHelper { private static ShoppingCart cartEntity = new ShoppingCart(); public static ShoppingCart getCart() { if (cartEntity == null) { cartEntity = new ShoppingCart(); } return cartEntity; } public static List<ShoppingCartItemsModel> getCartItems() { List<ShoppingCartItemsModel> cartItems = new ArrayList<>(); Map<Product, Integer> itemMap = getCart().getItemWithQuantity(); for (Map.Entry<Product, Integer> entry : itemMap.entrySet()) { ShoppingCartItemsModel cartItem = new ShoppingCartItemsModel(); cartItem.setProduct(entry.getKey()); cartItem.setQuantity(entry.getValue()); cartItems.add(cartItem); } return cartItems; } }
true
f5a7153d96f16ed705fb0be37f1aa9516275c529
Java
MaorRocky/Akka_whatsApp
/src/main/java/InviteGroup.java
UTF-8
2,572
2.203125
2
[]
no_license
import akka.actor.ActorRef; import java.io.Serializable; public class InviteGroup extends CreateGroupCommand implements Serializable { private User sourceUser; private User targetUser; private String target; private String groupName; private ActorRef targetActorRef = null; private ActorRef groupActorRef = null; private String answer; boolean gaveAnswer = false; public InviteGroup(String[] str, From from, Type type, String userName) { super(str, from, type, userName); this.groupName = str[0]; this.target = str[1]; } public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } public User getSourceUser() { return sourceUser; } public String getTarget() { return target; } public String getGroupName() { return groupName; } public void setSourceUser(User sourceUser) { this.sourceUser = sourceUser; } public void actorRefToInvite(ActorRef actorRefToInvite) { actorRefToInvite = actorRefToInvite; } public ActorRef getTargetActorRef() { return targetActorRef; } public void setTargetActorRef(ActorRef targetActorRef) { this.targetActorRef = targetActorRef; } public ActorRef getGroupActorRef() { return groupActorRef; } public void setGroupActorRef(ActorRef groupActorRef) { this.groupActorRef = groupActorRef; } public boolean GaveAnswer() { return gaveAnswer; } public void setGaveAnswer(boolean gaveAnswer) { this.gaveAnswer = gaveAnswer; } public User getTargetUser() { return targetUser; } public void setTargetUser(User targetUser) { this.targetUser = targetUser; } @Override public String toString() { return "InviteGroup{" + "sourceUser=" + sourceUser + ", targerUser=" + targetUser + ", target='" + target + '\'' + ", groupName='" + groupName + '\'' + ", targetActorRef=" + targetActorRef + ", answer='" + answer + '\'' + ", userAdmin=" + userAdmin + ", groupName='" + groupName + '\'' + ", type=" + type + ", from=" + from + ", isSucceeded=" + isSucceeded + ", resultString='" + resultString + '\'' + ", userResult=" + userResult + '}'; } }
true
2f60063fb1cf154cb19c86ff73c1f321b1e75b1c
Java
frankowskipawel/Metal_Machines_Android_PUB
/app/src/main/java/com/paweldev/maszynypolskie/ui/devices/service/DevicesServiceListFragment.java
UTF-8
9,149
2.015625
2
[]
no_license
package com.paweldev.maszynypolskie.ui.devices.service; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SimpleAdapter; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import com.paweldev.maszynypolskie.R; import com.paweldev.maszynypolskie.model.Device; import com.paweldev.maszynypolskie.model.Service; import com.paweldev.maszynypolskie.repository.ServiceRepository; import com.paweldev.maszynypolskie.ui.info.MessageFragment; import com.paweldev.maszynypolskie.utils.ConnectionUtils; import com.paweldev.maszynypolskie.utils.FragmentUtils; import com.paweldev.maszynypolskie.utils.StringUtils; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class DevicesServiceListFragment extends Fragment { private View v; private Device currentDevice; private Fragment previousFragment; private ListView listView; private List<Map<String, String>> services; private DevicesServiceListFragment devicesServiceListFragment; private ProgressBar progressBar; public View onCreateView(@NonNull LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) { v = inflater.inflate(R.layout.fragment_device_service_list, container, false); devicesServiceListFragment = this; progressBar = v.findViewById(R.id.progressBar_serviceList_fragment); if (!ConnectionUtils.isInternetAvailable(getContext())) { MessageFragment messageFragment = new MessageFragment(); FragmentUtils.replaceFragment(messageFragment, getFragmentManager()); messageFragment.setMessage("Brak połączenia z internetem"); } else { // ADD NAME TO TOOLBAR // ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Lista zdarzeń serwisowych"); ((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(""); // listView = v.findViewById(R.id.service_listView); // loadDataToListView(DevicesServiceListFragment.this, listView); startAsyncTask(v); // PREVIOUS BUTTON // Button prevButton = (Button) v.findViewById(R.id.previous_button_service_fragment); prevButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getFragmentManager().popBackStack(); } }); // ADD BUTTON // Button addButton = (Button) v.findViewById(R.id.devices_add_new_service_button); addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DeviceAddNewServiceFragment deviceAddNewServiceFragment = new DeviceAddNewServiceFragment(); deviceAddNewServiceFragment.setCurrentDevice(currentDevice); deviceAddNewServiceFragment.setEdit(true); FragmentUtils.replaceFragment(deviceAddNewServiceFragment, getFragmentManager()); } }); // CLICK ITEM FROM LISTVIEW // listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int index, long id) { try { Object clickItemObj = adapterView.getAdapter().getItem(index); HashMap clickItemMap = (HashMap) clickItemObj; String header = (String) clickItemMap.get("First Line"); String content = (String) clickItemMap.get("Second Line"); Service service = ServiceRepository.findServiceAfterId(StringUtils.getIdFromString(header)); DeviceAddNewServiceFragment deviceAddNewServiceFragment = new DeviceAddNewServiceFragment(); deviceAddNewServiceFragment.setCurrentService(service); deviceAddNewServiceFragment.setCurrentDevice(currentDevice); deviceAddNewServiceFragment.setEdit(false); FragmentUtils.replaceFragment(deviceAddNewServiceFragment, getFragmentManager()); } catch (Exception e) { MessageFragment messageFragment = new MessageFragment(); messageFragment.setMessage(e.getMessage()); FragmentUtils.replaceFragment(messageFragment, getFragmentManager()); e.printStackTrace(); } } }); } return v; } @RequiresApi(api = Build.VERSION_CODES.N) private void loadDataToListView(DevicesServiceListFragment devicesServiceListFragment, ListView listView) { try { List<Map<String, String>> data = new ArrayList<Map<String, String>>(); data = ServiceRepository.findAlldeviceServicesForListView(currentDevice.getId()); List<Map<String, String>> filteredData = new ArrayList<Map<String, String>>(); for (Map<String, String> datum : data) { filteredData.add(datum); } SimpleAdapter adapter = new SimpleAdapter(devicesServiceListFragment.getContext(), filteredData, android.R.layout.simple_list_item_2, new String[]{"First Line", "Second Line"}, new int[]{android.R.id.text1, android.R.id.text2}); listView.setAdapter(adapter); } catch (Exception e) { MessageFragment messageFragment = new MessageFragment(); messageFragment.setMessage(e.getMessage()); FragmentUtils.replaceFragment(messageFragment, getFragmentManager()); e.printStackTrace(); } } public void setCurrentDevice(Device currentDevice) { this.currentDevice = currentDevice; } public Fragment getPreviousFragment() { return previousFragment; } public void setPreviousFragment(Fragment previousFragment) { this.previousFragment = previousFragment; } public void startAsyncTask(View v) { DevicesServiceListFragment.GetDataFromApiAsyncTask task = new DevicesServiceListFragment.GetDataFromApiAsyncTask(this); task.execute(); } private class GetDataFromApiAsyncTask extends AsyncTask<Integer, Integer, String> { private WeakReference<DevicesServiceListFragment> activityWeakReference; private SimpleAdapter adapter; GetDataFromApiAsyncTask(DevicesServiceListFragment activity) { activityWeakReference = new WeakReference<DevicesServiceListFragment>(activity); } @Override protected void onPreExecute() { super.onPreExecute(); } @RequiresApi(api = Build.VERSION_CODES.N) @Override protected String doInBackground(Integer... integers) { progressBar.setVisibility(View.VISIBLE); progressBar.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT; try { services = ServiceRepository.findAlldeviceServicesForListView(currentDevice.getId()); } catch (Exception e) { MessageFragment messageFragment = new MessageFragment(); messageFragment.setMessage(e.getMessage()); FragmentUtils.replaceFragment(messageFragment, getFragmentManager()); e.printStackTrace(); } return "OK"; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); return; } @RequiresApi(api = Build.VERSION_CODES.Q) @Override protected void onPostExecute(String s) { super.onPostExecute(s); progressBar.setVisibility(View.GONE); progressBar.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT; List<Map<String, String>> filteredData = new ArrayList<Map<String, String>>(); for (Map<String, String> datum : services) { filteredData.add(datum); } if (devicesServiceListFragment.getContext() != null) { SimpleAdapter adapter = new SimpleAdapter(devicesServiceListFragment.getContext(), filteredData, android.R.layout.simple_list_item_2, new String[]{"First Line", "Second Line"}, new int[]{android.R.id.text1, android.R.id.text2}); listView.setAdapter(adapter); } } } }
true
14e77c46339786cf6845bd4e26470df5948a1cea
Java
rodrigoieh/JUnit-Foundation
/src/main/java/com/nordstrom/automation/junit/RunAnnouncer.java
UTF-8
7,123
2.3125
2
[ "Apache-2.0" ]
permissive
package com.nordstrom.automation.junit; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.junit.internal.AssumptionViolatedException; import org.junit.runner.Description; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class implements a notification-enhancing extension of the standard {@link RunListener} class. This run * announcer is the source of notifications sent to attached implementations of the {@link RunWatcher} interface. * Note that <b>RunAnnouncer</b> is attached * <a href="https://github.com/Nordstrom/JUnit-Foundation#support-for-standard-junit-runlistener-providers"> * automatically</a> by <b>JUnit Foundation</b>; attaching this run listener through conventional methods (Maven * or Gradle project configuration, {@code JUnitCore.addListener()}) is not only unnecessary, but will likely * suppress <b>RunWatcher</b> notifications. */ public class RunAnnouncer extends RunListener implements JUnitWatcher { private static final Map<Object, AtomicTest<?>> RUNNER_TO_ATOMICTEST = new ConcurrentHashMap<>(); private static final Logger LOGGER = LoggerFactory.getLogger(RunAnnouncer.class); /** * {@inheritDoc} */ @Override @SuppressWarnings({"rawtypes", "unchecked"}) public void testStarted(Description description) throws Exception { LOGGER.debug("testStarted: {}", description); AtomicTest<?> atomicTest = newAtomicTest(description); for (RunWatcher watcher : LifecycleHooks.getRunWatchers()) { if (isSupported(watcher, atomicTest)) { watcher.testStarted(atomicTest); } } } /** * {@inheritDoc} */ @Override @SuppressWarnings({"rawtypes", "unchecked"}) public void testFinished(Description description) throws Exception { LOGGER.debug("testFinished: {}", description); AtomicTest<?> atomicTest = getAtomicTestOf(description); for (RunWatcher watcher : LifecycleHooks.getRunWatchers()) { if (isSupported(watcher, atomicTest)) { watcher.testFinished(atomicTest); } } } /** * {@inheritDoc} */ @Override @SuppressWarnings({"rawtypes", "unchecked"}) public void testFailure(Failure failure) throws Exception { LOGGER.debug("testFailure: {}", failure); AtomicTest<?> atomicTest = setTestFailure(failure); for (RunWatcher watcher : LifecycleHooks.getRunWatchers()) { if (isSupported(watcher, atomicTest)) { watcher.testFailure(atomicTest, failure.getException()); } } } /** * {@inheritDoc} */ @Override @SuppressWarnings({"rawtypes", "unchecked"}) public void testAssumptionFailure(Failure failure) { LOGGER.debug("testAssumptionFailure: {}", failure); AtomicTest<?> atomicTest = setTestFailure(failure); for (RunWatcher watcher : LifecycleHooks.getRunWatchers()) { if (isSupported(watcher, atomicTest)) { watcher.testAssumptionFailure(atomicTest, (AssumptionViolatedException) failure.getException()); } } } /** * {@inheritDoc} */ @Override @SuppressWarnings({"rawtypes", "unchecked"}) public void testIgnored(Description description) throws Exception { LOGGER.debug("testIgnored: {}", description); // determine if retrying a failed invocation AtomicTest<?> atomicTest = getAtomicTestOf(description); // if actually ignored if (atomicTest == null) { // create new atomic test object atomicTest = newAtomicTest(description); } for (RunWatcher watcher : LifecycleHooks.getRunWatchers()) { if (isSupported(watcher, atomicTest)) { watcher.testIgnored(atomicTest); } } } /** * Create new atomic test object for the specified runner/child pair. * * @param <T> type of children associated with the specified runner * @param runner parent runner * @param identity identity for this atomic test * @return {@link AtomicTest} object */ static <T> AtomicTest<T> newAtomicTest(Object runner, T identity) { AtomicTest<T> atomicTest = new AtomicTest<>(runner, identity); RUNNER_TO_ATOMICTEST.put(runner, atomicTest); return atomicTest; } /** * Create new atomic test object for the specified description. * * @param <T> type of children associated with the specified runner * @param description description of the test that is about to be run * @return {@link AtomicTest} object (may be {@code null}) */ static <T> AtomicTest<T> newAtomicTest(Description description) { AtomicTest<T> atomicTest = null; AtomicTest<T> original = getAtomicTestOf(LifecycleHooks.getThreadRunner()); if (original != null) { atomicTest = new AtomicTest<>(original, description); RUNNER_TO_ATOMICTEST.put(description, atomicTest); } return atomicTest; } /** * Get the atomic test object for the specified class runner or method description. * * @param <T> atomic test child object type * @param testKey JUnit class runner or method description * @return {@link AtomicTest} object (may be {@code null}) */ @SuppressWarnings("unchecked") static <T> AtomicTest<T> getAtomicTestOf(Object testKey) { return (testKey == null) ? null : (AtomicTest<T>) RUNNER_TO_ATOMICTEST.get(testKey); } /** * Store the specified failure in the active atomic test. * * @param <T> atomic test child object type * @param failure {@link Failure} object * @return {@link AtomicTest} object */ private static <T> AtomicTest<T> setTestFailure(Failure failure) { AtomicTest<T> atomicTest = getAtomicTestOf(Run.getThreadRunner()); if (atomicTest == null) { atomicTest = getAtomicTestOf(failure.getDescription()); } if (atomicTest != null) { atomicTest.setThrowable(failure.getException()); } return atomicTest; } /** * Determine if the run watcher in question supports the data type of specified atomic test. * * @param watcher {@link RunWatcher} object * @param atomicTest {@link AtomicTest} object * @return {@code true} if the specified run watcher supports the indicated data type; otherwise {@code false} */ private static boolean isSupported(RunWatcher<?> watcher, AtomicTest<?> atomicTest) { return (atomicTest == null) ? false : watcher.supportedType().isInstance(atomicTest.getIdentity()); } }
true
eec9b3bf663d4c8d34780e9a1eab101d490671e2
Java
nglazyrin/chordest
/chordest/src/main/java/chordest/wave/WaveFileInfo.java
UTF-8
1,099
2.703125
3
[]
no_license
package chordest.wave; import java.io.File; import java.io.IOException; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.UnsupportedAudioFileException; public class WaveFileInfo { public final int samplingRate; public final int channels; public final double seconds; public final Exception exception; public WaveFileInfo(String fileName) { this(new File(fileName)); } public WaveFileInfo(File file) { int srTemp = -1; int cTemp = -1; double sTemp = -1; Exception ex = null; try (AudioInputStream stream = AudioSystem.getAudioInputStream(file)) { AudioFormat format = stream.getFormat(); int frames = (int) stream.getFrameLength(); cTemp = format.getChannels(); srTemp = (int) format.getSampleRate(); sTemp = frames * 1.0 / srTemp; } catch (UnsupportedAudioFileException | IOException e) { ex = e; } this.samplingRate = srTemp; this.channels = cTemp; this.seconds = sTemp; this.exception = ex; } }
true
b5178a39a7fe0c25cedd9a9823d2203c3a611423
Java
tingzhou85/HHComicViewer
/app/src/main/java/org/huxizhijian/hhcomicviewer/adapter/GalleryViewPagerAdapter.java
UTF-8
6,162
2.078125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2017 huxizhijian * * 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.huxizhijian.hhcomicviewer.adapter; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import org.huxizhijian.hhcomicviewer.model.ComicChapter; import org.huxizhijian.hhcomicviewer.ui.entry.GalleryActivity; import org.huxizhijian.hhcomicviewer.utils.CommonUtils; import org.huxizhijian.hhcomicviewer.utils.Constants; import org.huxizhijian.hhcomicviewer.view.ZoomImageView; import org.huxizhijian.hhcomicviewer.view.listener.OnCenterTapListener; import org.huxizhijian.hhcomicviewer.view.listener.OnLeftOrRightTapListener; import org.huxizhijian.sdk.imageloader.ImageLoaderOptions; import org.huxizhijian.sdk.imageloader.listener.ImageLoaderManager; import java.io.File; import java.util.LinkedList; /** * Gallery的ViewPagerAdapter * Created by wei on 2017/1/21. */ public class GalleryViewPagerAdapter extends PagerAdapter { private GalleryActivity mContext; private ComicChapter mComicChapter; private LinkedList<ZoomImageView> mRecyclerImageViews; private boolean mLoadOnLineFullSizeImage; private OnCenterTapListener onCenterTapListener; private OnLeftOrRightTapListener onLeftOrRightTapListener; //图片加载工具类 private ImageLoaderManager mImageLoader = ImageLoaderOptions.getImageLoaderManager(); public GalleryViewPagerAdapter(GalleryActivity context, boolean loadOnLineFullSizeImage) { mContext = context; mLoadOnLineFullSizeImage = loadOnLineFullSizeImage; } public void setComicChapter(ComicChapter comicChapter) { mComicChapter = comicChapter; } public void setOnLeftOrRightTapListener(OnLeftOrRightTapListener onLeftOrRightTapListener) { this.onLeftOrRightTapListener = onLeftOrRightTapListener; } public void setOnCenterTapListener(OnCenterTapListener onCenterTapListener) { this.onCenterTapListener = onCenterTapListener; } @Override public Object instantiateItem(ViewGroup container, final int position) { ZoomImageView imageView = null; if (mRecyclerImageViews == null) { mRecyclerImageViews = new LinkedList<>(); } if (mRecyclerImageViews.size() > 0) { //复用ImageView imageView = mRecyclerImageViews.removeFirst(); } else { //获得新的ImageView imageView = getImageView(); } //为不同的imageView设置不同图片 setImageViewRecycler(imageView, position); container.addView(imageView); return imageView; } private void setImageViewRecycler(final ZoomImageView imageView, int position) { if (mComicChapter != null && mComicChapter.getDownloadStatus() == Constants.DOWNLOAD_FINISHED) { //如果是下载的章节 File file = new File(mComicChapter.getSavePath(), CommonUtils.getPageName(position)); if (file.exists()) { mImageLoader.displayGallery(mContext, file, imageView); } else { Toast.makeText(mContext, "好像下载错误了~", Toast.LENGTH_SHORT).show(); } } else { //判断用户设置 if (mLoadOnLineFullSizeImage) { //加载全尺寸 if (mComicChapter != null) { mImageLoader.displayGalleryFull(mContext, mComicChapter.getPicList().get(position), imageView); } } else { //图片尺寸匹配屏幕 if (mComicChapter != null) { mImageLoader.displayGalleryFit(mContext, mComicChapter.getPicList().get(position), imageView); } } } } @Override public void destroyItem(ViewGroup container, int position, Object object) { ZoomImageView imageView = (ZoomImageView) object; //设置缩放将图片居中缩放 // imageView.setImageInCenter(); //回收图片 imageView.setImageDrawable(null); imageView.setImageBitmap(null); releaseImageViewResource(imageView); //移除页面 container.removeView(imageView); //回收页面 mRecyclerImageViews.addLast(imageView); } private void releaseImageViewResource(ZoomImageView imageView) { if (imageView == null) return; Drawable drawable = imageView.getDrawable(); if (drawable != null && drawable instanceof BitmapDrawable) { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; Bitmap bitmap = bitmapDrawable.getBitmap(); if (bitmap != null && !bitmap.isRecycled()) { bitmap.recycle(); bitmap = null; } } System.gc(); } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } @Override public int getCount() { return mComicChapter.getPageCount(); } private ZoomImageView getImageView() { ZoomImageView imageView = new ZoomImageView(mContext); if (onCenterTapListener != null) { imageView.setOnCenterTapListener(onCenterTapListener); } if (onLeftOrRightTapListener != null) { imageView.setOnLeftOrRightTapListener(onLeftOrRightTapListener); } return imageView; } }
true
f1211358d36e5ae51bc17ec69a9ddb861a56b74e
Java
steenfuentes/TheWizard
/src/main/java/edu/sdccd/cisc191/wizardGame/gui/screen/styles/ButtonUI.java
UTF-8
280
1.539063
2
[ "CC0-1.0" ]
permissive
package edu.sdccd.cisc191.wizardGame.gui.screen.styles; /** * Custom ButtonUI * * @author Mark Lucernas * Date: 2020-07-23 */ public class ButtonUI { // TODO: // http://www.java2s.com/Tutorials/Java/Swing/JButton/Change_JButton_with_BasicButtonUI_in_Java.htm }
true
4208e33482e0df5210a168f09535c68167378b2c
Java
mokhtar-ahmed/5odnyM3k
/src/com/iti/jets/carpoolingV1/synccontactsactivity/SyncContactsActivity.java
UTF-8
4,503
2.046875
2
[]
no_license
package com.iti.jets.carpoolingV1.synccontactsactivity; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.iti.jets.carpoolingV1.R; import com.iti.jets.carpoolingV1.R.layout; import com.iti.jets.carpoolingV1.R.menu; import com.iti.jets.carpoolingV1.common.Circle; import com.iti.jets.carpoolingV1.common.User; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.app.Activity; import android.app.ListActivity; import android.content.ContentResolver; import android.content.Intent; import android.content.res.Resources; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class SyncContactsActivity extends Activity { ListView list; CheckBox checkBox; SyncContactsCustomArrayAdapter adapter; Button addFriendToCircleBtn ; private ArrayList<Integer> selectedUsersIds = new ArrayList<Integer>(); private ArrayList<User> registeredFriendsList = new ArrayList<User>(); private AddUserToCircleController addUserToCircleCont; private User tempUser; private int userId,circleId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sync_contacts_view); addFriendToCircleBtn = (Button) findViewById(R.id.addFriendBtn); ContentResolver contentResolver = getContentResolver(); SyncContactsController controller = new SyncContactsController(contentResolver,this); addUserToCircleCont = new AddUserToCircleController(this); Bundle newIntent = getIntent().getExtras(); if (newIntent != null) { circleId = newIntent.getInt("circle_Id"); } addFriendToCircleBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub for(int i=0 ; i<registeredFriendsList.size();i++) { tempUser = registeredFriendsList.get(i); if (tempUser.getIsSelected()) { Toast.makeText(getApplicationContext(), tempUser.getName()+" %%%", Toast.LENGTH_SHORT).show(); } } userId = tempUser.getUserId(); addUserToCircleCont.setArguments(userId,circleId); } }); } public void getResultFromService(String result) { // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), "TESTTESTTEST", Toast.LENGTH_LONG).show(); registeredFriendsList = new ArrayList<User>(); ArrayList<String> namesList = new ArrayList<String>(); try { Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show(); JSONArray registeredFriendsJsArray = new JSONArray(result); for(int i=0;i<registeredFriendsJsArray.length();i++) { JSONObject jsObj = registeredFriendsJsArray.getJSONObject(i); System.out.println(jsObj); User tempUser = new User(); tempUser.setName(jsObj.getString("name")); tempUser.setPhone(jsObj.getString("phone")); tempUser.setUserId(jsObj.getInt("id")); if(jsObj.getString("image") == null) { tempUser.setImageURL(jsObj.getString(null)); } else { tempUser.setImageURL(jsObj.getString("image")); } namesList.add(tempUser.getName()); registeredFriendsList.add(tempUser); Toast.makeText(getApplicationContext(),tempUser.getName(),Toast.LENGTH_LONG).show(); System.out.println("Size"+" "+registeredFriendsList.size()); } Resources res =getResources(); list = ( ListView )findViewById( R.id.list ); // List defined in XML ( See Below ) /**************** Create Custom Adapter *********/ adapter=new SyncContactsCustomArrayAdapter(this,registeredFriendsList,res ); list.setAdapter( adapter ); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void onItemClick(int mPosition) { // TODO Auto-generated method stub // User userClickedValues = (User) registeredFriendsList.get(mPosition); // Toast.makeText(getApplicationContext(), userClickedValues.getName(),Toast.LENGTH_LONG).show(); } }
true
6141fd29d4b3d98d07a65d2757b31221a3ae5893
Java
Rasskopovaa/MultiServer
/Quote/src/main/java/com/example/quotes/QuoteApplication.java
UTF-8
544
1.8125
2
[]
no_license
package com.example.quotes; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.reactive.function.client.WebClient; @SpringBootApplication public class QuoteApplication { public static void main(String[] args) { SpringApplication.run(QuoteApplication.class, args); } @Bean public WebClient.Builder webClientBuilder() { return WebClient.builder(); } }
true
568ee3bf0f3a13e0cad8c4bf3830318a558a706e
Java
pabloaav/Recolect-Ar
/app/src/main/java/com/e/recolectar/adaptadores/AdaptadorPaginas.java
UTF-8
2,132
2.859375
3
[]
no_license
package com.e.recolectar.adaptadores; import android.content.Context; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.e.recolectar.R; import com.e.recolectar.fragmentos.SelectorFragment; /** * A [FragmentPagerAdapter] that returns a fragment corresponding to * one of the sections/tabs/pages. * Esta clase permite: * - Colocar los Titulos de las Tabs * - Controlar el numero de Tabs que se muestran */ public class AdaptadorPaginas extends FragmentPagerAdapter { @StringRes private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2,R.string.tab_text_3}; private final Context mContext; /*Aqui el Context es el Activity Main (un activity es un Context, porque hereda de la clase Context). En la clase MainActivity se hace: new AdaptadorPaginas(this, getSupportFragmentManager());. Es decir, que this es MainActivity, y el segundo parametro es una funcion get que devuelve un Fragment Manager, que pertenece al un padre (FragmentActivity) de MainActivity, de la cual esta hereda ese metodo */ public AdaptadorPaginas(Context context, FragmentManager fm) { super(fm); mContext = context; } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a SelectorFragment (defined as a static inner class below). return SelectorFragment.newInstance(position + 1); } @Nullable @Override public CharSequence getPageTitle(int position) { /*Aqui se obtienen los nombres de las pestañas o tabs determinados en el array del atributo TAB_TITLES de tipo entero, que, dependiendo de la posicion, mostrara el nombre de la pestaña correspondiente. * */ return mContext.getResources().getString(TAB_TITLES[position]); } @Override public int getCount() { // Show 3 total pages. return 3; } }
true
4118f8687f0834062eac039e49df99a5dd911c97
Java
tangya3158613488/Java
/exercise11_26/Example6.java
UTF-8
684
3.4375
3
[ "Apache-2.0" ]
permissive
package exercise11_26; import java.awt.*; import java.awt.event.*; public class Example6 { public static void main(String[] args) { Frame frm=new Frame("我创建的一个窗口"); Label lbl=new Label("Hello, World! I am label!",Label.CENTER); frm.setSize(300,250); frm.setLocation(100,100); frm.setLayout(null); //把java默认的页面布局方式关掉,即设置为空布局 lbl.setBounds(20,50,200,20); frm.setBackground(Color.red); lbl.setBackground(Color.pink); frm.add(lbl); frm.setVisible(true); frm.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ System.exit(0); } }); } }
true
2e75d832549a91223473e4634817351dc77f66df
Java
bismarck-solutions-sac/club-constructor
/app/src/main/java/com/diamante/clubconstructor/model/GeneralSpinner.java
UTF-8
474
2.140625
2
[]
no_license
package com.diamante.clubconstructor.model; import java.io.Serializable; public class GeneralSpinner implements Serializable { public String id; public String descripcion; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } }
true
ea1f311ace9f29910a3bc7a4d126bad3840d00a6
Java
Elionnee/Proceso-Carga-Java--Programa-De-Prueba
/procesoCarga/src/main/java/proceso_carga/CSVFileReader.java
ISO-8859-1
19,171
2.75
3
[]
no_license
package proceso_carga; import com.opencsv.CSVReader; import com.opencsv.CSVReaderBuilder; import com.opencsv.exceptions.CsvValidationException; import java.io.*; import java.nio.file.*; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.hibernate.query.*; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.log4j.PropertyConfigurator; import org.hibernate.Session; import org.apache.commons.io.FileExistsException; import org.apache.commons.io.FileUtils; interface StringFunction { String run(String str); } /** * TODO PENDIENTE DE SUBDIVIDIR EN SERVICIOS -> LoadService, Watcher... * @author snc * */ public class CSVFileReader { // Directorio que se desea monitorizar private static String filePath; // Archivos leidos private ArrayList<File> filesRead= new ArrayList<>(); // Archivos pendientes de leer private Queue<File> filesOnQueue = new LinkedList<>(); // Estado actual del thread, cambia si es interrumpido private Boolean threadState = true; // Objeto logger que registra el estado del programa por consola private org.apache.logging.log4j.Logger logger = null; // Objeto properties que nos permite acceder a los contenidos del archivo pc.properties correspondiente private Properties prop = null; private ArrayList<String> mensajesPend = new ArrayList<>(); // Lambda que permite dar un formato especfico a la string que se le pasa como parmetro de entrada StringFunction deleteSymbols = new StringFunction() { @Override public String run(String n) { String result = ""; result = n.replaceAll("[^a-zA-Z0-9.]", ""); return result; } }; /** * Constructor de la clase que se encarga de buscar el archivo .properties y de leer que archivos * csv hay en el directorio que este archivo especifica * */ public CSVFileReader() { mensajesPend.clear(); // Genera la conexin con el archivo .properties indicado prop = this.loadPropertiesFile("pc.properties"); // Crea el logger y lo configura a partir de las indicaciones del fichero log4j2.xml correspondiente logger = LogManager.getLogger(this.getClass()); PropertyConfigurator.configure(getClass().getResource("log4j2.xml")); // Comprueba si el logger creado funciona correctamente try { logger.debug("Logger funciona"); } catch(Exception e) { logger.error("Error con el log", e); e.printStackTrace(); } // Limpia las colas de archivos leidos y pendientes de leer filesRead.clear(); filesOnQueue.clear(); // Setea el directorio indicado en el properties como directorio a observar setFilePath(this.prop); } /** * Crea un objeto 'properties' * Busca el archivo .properties en el directorio indicado y trata de leerlo. En caso de no poder, lo notifica * Guarda la referencia al contenido del archivo en el objeto 'properties' * Devuelve el objeto 'properties' */ /** * Mtodo que lee los contenidos del archivo .properties * * @param filePath Ruta en la que se encuentra el archivo pc.properties * * @return prop Devuelve un objeto del tipo Properties que permite extraer los parametros del archivo .properties */ public Properties loadPropertiesFile(String filePath) { // Crea el objeto .properties prop = new Properties(); // Carga el archivo .properties de su directorio de origen, mediante un path relativo a la carpeta de recursos try (InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(filePath)) { // Carga el contenido del fichero .properties en el objeto indicado prop.load(resourceAsStream); } catch (IOException e) { mensajesPend.add("No se pudo leer el archivo .properties : " + filePath); } return prop; } /** * Conectarse a la base de datos * Tratar de crear una tabla con el nombre. En caso de que ya exista, se notifica * Se crea una query con los datos del producto * Se ejecuta la query * Se cierra la conexin con la base de datos */ /** * Mtodo que se encarga de introducir los datos a la base de datos * * @param semana Nombre de la tabla a la que se deben aadir los datos * * @param prod Datos a aadir */ private synchronized void connectToDBIntroduceData(Session session, String semana, ProductoEntity prod) { // Creamos un query que nos permite insertar valores en la base de datos String query = "INSERT INTO "+ semana + " (Id, Nombre, Precio, Cantidad, Id_Producto)\r\n" + "VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE Cantidad = VALUES(Cantidad) ;"; // Inicio de la transaccin con la bas session.getTransaction().begin(); // Creamos un objeto query con la string que contiene el query de tipo insert @SuppressWarnings("rawtypes") Query query2 = session.createNativeQuery(query); // Rellenamos los parmetros necesarios para realizar el query de tipo insert query2.setParameter(1, prod.getId()); query2.setParameter(2, prod.getNombre()); query2.setParameter(3, Double.toString(prod.getPrecio())); query2.setParameter(4, Integer.toString(prod.getCantidad())); query2.setParameter(5, prod.getTransactionId()); // Intenta actualizar la base de datos ejecutando la query try { query2.executeUpdate(); session.getTransaction().commit(); } catch(Exception e) { session.getTransaction().rollback(); } } /** * Se crea una query para crear la tabla con el nombre indicado, utilizando la conexin ya establecida con la base de datos * Se ejecuta la query */ /** * Mtodo que crea una nueva tabla en la base de datos * * @param semana Nombre de la tabla que se debe crear * * @param session Conexin abierta con la base de datos */ private synchronized void connectToDBCreateTable(String semana, Session session) { // Creamos un query del tipo create que nos permitir crear una tabala con el nombre indicado String queryTable = "CREATE TABLE " + semana + " (" + " Id varchar(80) PRIMARY KEY,\n" + " Nombre text,\n" + " Precio double,\n" + " Cantidad int,\n" + " Id_Producto text\n" + ");"; // Comienza la transaccin para actualizar la base de datos y crear una tabla usando la query try { session.getTransaction().begin(); // Crea el objeto query usando el string que contiene la query del tipo create @SuppressWarnings("rawtypes") Query query = session.createNativeQuery(queryTable); query.executeUpdate(); session.getTransaction().commit(); } catch (Exception e) { mensajesPend.add("Fallo al crear la tabla. Ya existe"); session.getTransaction().rollback(); } } private synchronized void connectToDBCreateTableLogs(Session session) { // Creamos un query del tipo create que nos permitir crear una tabala con el nombre indicado String queryTable = "CREATE TABLE logs ( Id_Log varchar(80) PRIMARY KEY, Id_Transaccin text, Info text);"; // Comienza la transaccin para actualizar la base de datos y crear una tabla usando la query try { session.getTransaction().begin(); // Crea el objeto query usando el string que contiene la query del tipo create @SuppressWarnings("rawtypes") Query query = session.createNativeQuery(queryTable); query.executeUpdate(); session.getTransaction().commit(); } catch (Exception e) { mensajesPend.add("Fallo al crear la tabla de logs, ya existe."); session.getTransaction().rollback(); } } private synchronized void connectToDBIntroduceLogs(Session session, String semana, ProductoEntity prod, String info) { // Creamos un query que nos permite insertar valores en la base de datos String query = "INSERT INTO logs (Id_Log, Id_Transaccin, Info)\r\n" + "VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE Info = VALUES(Info) ;"; // Inicio de la transaccin con la bas session.getTransaction().begin(); // Creamos un objeto query con la string que contiene el query de tipo insert @SuppressWarnings("rawtypes") Query query2 = session.createNativeQuery(query); // Rellenamos los parmetros necesarios para realizar el query de tipo insert query2.setParameter(1, UUID.randomUUID().toString()); if(prod != null) { query2.setParameter(2, prod.getId() + "_" + semana); } else { query2.setParameter(2, "INFO_GENERAL_" + semana); } query2.setParameter(3, info); // Intenta actualizar la base de datos ejecutando la query try { query2.executeUpdate(); session.getTransaction().commit(); } catch(Exception e) { session.getTransaction().rollback(); } } /** * Mtodo que devuelve la ruta al directorio que se desea monitorizar * * @return filePath Ruta al directorio que se desea monitorizar */ public String getFilePath() { return filePath; } /** * Buscamos el valor de la etiqueta 'dir' en la referencia al archivo .properties * En caso de haber un error, notificamos del mismo */ /** * Mtodo que busca la direccin del directorio a monitorizar del archivo .properties * * @param prop Objeto que contiene los datos del archivo .properties */ private void setFilePath(Properties prop) { // Extraemos el filepath del directorio que se desea monitorizar del fichero .properties try { filePath = prop.getProperty("dir"); } catch (NullPointerException e) { mensajesPend.add("Error al leer el directorio objetivo en el .properties. No se ha encontrado."); } } /** * Buscar el directorio a monitorizar * Obtener una lista con todos los archivos que contiene en ese momento * Guardar en una lista solo aquellos archivos con extensin .CSV en una lista de 'pendientes por procesar' */ /** * Mtodo que se encarga de obtener una lista que contenga todos los csv disponibles * en el directorio indicado como parametro de entrada. */ private void getFiles() { // Obtiene la referencia al directorio y extrae todos los archivos presentes en el mismo File folder = new File(filePath); File[] filesPresent = folder.listFiles(); // Comprueba que en verdad cintiene archivos if(filesPresent.length==0) { mensajesPend.add(Thread.currentThread().getId() + " : No hay archivos CSV pendientes de leer."); } else { // Comprueba que los archivos presentes son .CSV y que no habian sido leidos previamente durante esta ejecucin for(File fileName : filesPresent) { if(fileName.toString().toLowerCase().endsWith(".csv") && (fileName.isFile()) && (!filesRead.contains(fileName))) { filesOnQueue.add(fileName); } else { mensajesPend.add(Thread.currentThread().getName() + " : No hay archivos CSV pendientes de leer."); } } } } /** * Comprobar que los archivos introducidos y el directorio de destino no son nulos * Tratar de mover el archivo al directorio destino * En caso de que el archivo ya exista, reemplazar el mismo con el archivo nuevo y borrar este ltimo de su localizacin anterior * Notificar de cualquier error */ /** * Mueve el archivo indicado al directorio indicado * * @param orFilePath Nombre del archivo original que se va a mover * * @param cpFilePath Nombre del archivo una vez movido o del archivo a sustituir * * @param destDir Directorio al que se va a mover */ private void moveFile(String orFilePath, String cpFilePath, String destDir) { try { if(StringUtils.isNoneBlank(orFilePath) && StringUtils.isNoneBlank(destDir) && StringUtils.isNoneBlank(destDir)) { File orFile = new File(orFilePath); File cpFile = new File(cpFilePath); replaceFile(orFile, cpFile); mensajesPend.add("Archivo trasladado correctramente a la carpeta : " + destDir); } } catch(Exception ex) { ex.printStackTrace(); } } /** * Mover el archivo indicado al directorio indicado * En caso de no poder, sobreescribir el archivo ya existente con el mismo nombre * Borrar el archivo de su directorio original */ /** * Sobreescribe el archivo indicado con el archivo introducido * * @param orFile Archivo que se desea mover * * @param cpFile Archivo que se desea sobreescribir * * @throws IOException Cuando no consigue reemplazar el archivo o cuando no existe */ private void replaceFile(File orFile, File cpFile) throws IOException { try { FileUtils.moveFile(orFile, cpFile); } catch(FileExistsException e) { FileUtils.copyFile(orFile, cpFile); FileUtils.forceDelete(orFile); } } /** * Crear un lector para archivos CSV que lea el archivo indicado como parametro de entrada * Saltar la primera lnea del archivo, ya que no contiene datos * Comenzar a leer el archivo lnea por lnea * Aadir el archivo a la base de datos lnea por lnea * Si se aade correctamente -> Mover a la carpeta OK * Si no -> Mover a la carpeta KO */ /** * Mtodo que se encarga de leer el archivo csv que se le indica como parametro de entrada y que * almacena los contenidos del mismo en varios hashmap cuyas key son los id de los productos * * @param file Archivo que se desea leer */ private void readFile(Session session, File file) { CSVReader csv = null; String semana = file.getName(); String[] next = null; ProductoEntity p = null; // Crea un reader para leer el archivo .csv que le pasan como parametro de entrada, saltandose la 1 lnea try { Reader reader = Files.newBufferedReader(Paths.get(file.getAbsolutePath())); csv = new CSVReaderBuilder(reader).withSkipLines(1).build(); } catch (IOException e) { connectToDBIntroduceLogs(session, "Error", null , "Error al leer el fichero CSV."); } if(csv != null) { semana = semana.replace(".csv", ""); connectToDBIntroduceLogs(session, semana, null, "Conectado satisfactoriamente con la base de datos"); connectToDBCreateTable(semana, session); connectToDBCreateTable("productoentity", session); try { // Mientras haya una lnea de CSV por leer, continua while((next = csv.readNext()) != null) { // Crea una entidad nueva (Un producto nuevo) p = new ProductoEntity(next[0] + "_" + semana, next[1], Double.parseDouble(deleteSymbols.run(next[2])), Integer.parseInt(deleteSymbols.run(next[3])), next[0]); // Introduce la nueva entidad en su tabla correspondiente y en la tabla general connectToDBIntroduceData(session, semana, p); connectToDBIntroduceData(session, "productoentity", p); } // En caso de salir bien, mueve el archivo a la moveFile(file.getAbsolutePath(), (prop.getProperty("ok") + "\\" + file.getName()), prop.getProperty("ok")); } catch (CsvValidationException e) { connectToDBIntroduceLogs(session, semana, p, "CSV es null"); moveFile(file.getAbsolutePath(), prop.getProperty("ko") + "\\" + file.getName(), prop.getProperty("ko")); } catch (IOException e) { connectToDBIntroduceLogs(session, semana, p, "Error al leer el CSV"); moveFile(file.getAbsolutePath(), prop.getProperty("ko") + "\\" + file.getName(), prop.getProperty("ko")); } catch (NullPointerException e) { connectToDBIntroduceLogs(session, semana, p, "CSV es nulo"); moveFile(file.getAbsolutePath(), prop.getProperty("ko") + "\\" + file.getName(), prop.getProperty("ko")); } } } /** * Obtener la lista de archivos pendientes de leer * Mientras queden archivos pendientes por leer, asignar a los threads disponibles un archivo a leer * Interrumpir el thread en caso de error y notificar del mismo */ /** * Recoge todos los archivos nuevos que se encuentran actualmente en el directorio y los lee * * @throws InterruptedException Se lanza cuando un thread sufre una interrupcin inesperada */ public void readCSV(Session session) { Boolean pendiente = false; ArrayList<String> tempPend; tempPend = mensajesPend; mensajesPend.clear(); for (String m : tempPend) { connectToDBIntroduceLogs(session, "Inicio", null, m); } tempPend.clear(); connectToDBCreateTableLogs(session); connectToDBIntroduceLogs(session, "Inicio", null, "Comienzo de transferencia de archivos .CSV a la base de datos."); getFiles(); if (!filesOnQueue.isEmpty()) { ExecutorService threadPool = Executors.newFixedThreadPool(Integer.parseInt(prop.getProperty("numThreads"))); pendiente = true; while(Boolean.TRUE.equals(pendiente)) { pendiente = threadReadCSVExecution(session, threadPool); } } tempPend = mensajesPend; mensajesPend.clear(); for (String m : tempPend) { connectToDBIntroduceLogs(session, "Fin", null, m); } tempPend.clear(); } /** * Por cada thread disponible, comenzar a ejecutar la funcipn run() : * Adquirir un semaforo * Obtener archivo de la cola de pendientes * Avisar en caso de que haya una interrupcin inesperada y detener el thread * */ /** * Mtodo que crea los threads y su funcin de ejecucin para leer los archivos CSV * * @param threadPool Conjunto de threads disponibles * */ private Boolean threadReadCSVExecution(final Session session, ExecutorService threadPool) { threadPool.execute(new Runnable() { public void run() { try { threadGetFileFromQueue(); } catch (Exception e) { notifyThreadInt(); } } private void threadGetFileFromQueue() { File file; file = getFileFromFileQueue(); if(file != null) { readFile(session, file); filesRead.add(file); setThreadState(); } else { notifyThreadInt(); Thread.currentThread().interrupt(); } } }); if(Boolean.FALSE.equals(threadState)) { setThreadState(); return false; } else { return true; } } private synchronized void notifyThreadInt() { threadState = false; } private synchronized void setThreadState() { threadState = true; } /** * Mtodo que extrae y devuelve el primer archivo de la cola de archivos pendientes por leer * * @return filesOnQueue.poll() Primer archivo pendiente por leer */ private synchronized File getFileFromFileQueue() { if(!filesOnQueue.isEmpty()) { return filesOnQueue.poll(); } return null; } }
true
1e559d5c65d5fde7ed2914e7a29a6ca58bbb106a
Java
ashokkumaravvaru/FrameWorks-1
/RAMESH_FRAMEWORK_POM/src/com/rameshsoft/businessScript/OwnClass.java
UTF-8
1,673
1.875
2
[]
no_license
package com.rameshsoft.businessScript; import java.io.IOException; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.Test; import com.ramesh.Pojo.POJO; import com.rameshsoft.base.DriverEngine; import com.rameshsoft.constants.GmailConstants; import com.rameshsoft.pageobjects.GmailHomePage; import com.rameshsoft.pageobjects.GmailPaswordPage; import com.relevantcodes.extentreports.LogStatus; public class OwnClass extends DriverEngine{ @Test public void m1() throws IOException, EncryptedDocumentException, InvalidFormatException{ getDriver().get(POJO.getPR(GmailConstants.getConfigPath()).readProperty("url")); gettest().log(LogStatus.INFO, "url is entered successfully"); getlog().info("url is entered"); GmailHomePage.tex_emailOrPhone(POJO.getER(GmailConstants.getExcelPath()).getCellValue("sheet1", 0, 0)); gettest().log(LogStatus.INFO, "username is entered successffully"); getlog().info("username is entered"); GmailHomePage.btng_next(); gettest().log(LogStatus.INFO, "next is entered successfully"); getlog().info("next is entered"); GmailPaswordPage.tex_password(POJO.getER(GmailConstants.getExcelPath()).getCellValue("sheet1", 0, 1)); gettest().log(LogStatus.INFO, "password is entered successfully"); getlog().info("password is entered"); GmailPaswordPage.btng_pwdNext(); gettest().log(LogStatus.INFO, "signin is entered successfully"); getlog().info("signed is entered"); } }
true
83c89b31c7b2076428d93dd71892e0852edd3e48
Java
duffyco/android-art-engine
/app/src/main/java/ca/duffyco/RenderEngine/RotateEffect.java
UTF-8
1,718
2.421875
2
[]
no_license
package ca.duffyco.RenderEngine; import android.opengl.GLES20; import android.util.Pair; /** * Created by jon on 10/14/2016. */ public class RotateEffect<T> extends Effect<T> { private int uAngle; private float angle = 0.0f; private float angleFactor = 1.0f; private Texture mTexture; private String key = "uAngle"; private static final float ANGLE_FACTOR = 0.005f; public RotateEffect( int programObject ) { super.programObject = programObject; reset(); } public RotateEffect( int programObject, float inAngleFactor) { super.programObject = programObject; angleFactor = inAngleFactor; reset(); } public void reset() { angle = 0.0f; } public boolean isComplete() { return angle >= 360.0f; } public boolean subDraw(float fpsRatio) { float nextAngle = getAngle( fpsRatio ); // Log.d("uAngle", String.valueOf( nextAngle ) ); mTexture.updateState( key, nextAngle, this.getClass().getName() ); return true; } public float getAngle( float fpsRatio ) { angle += angleFactor * fpsRatio * ANGLE_FACTOR; if( angle > 360.0f ) { angle = 360.0f; } return angle; } public int getTextureID() { return 0; } public void addTexture(Texture t) { mTexture = t; mTexture.addState( key, Pair.create( GLES20.glGetUniformLocation(programObject, key), 0.0f)); } public void onNext( T data ) { if( !isActive ) setActive( true ); angle = mTexture.getState( key ); } }
true
26f7e3193e859e1692c2c2c2a80605bd108105fc
Java
viniciuspc/topicos-espciais
/Imagem/src/imagem/ValorMediaMain.java
ISO-8859-2
2,069
2.5
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package imagem; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import Formulario.Formulario; import Formulario.FormularioVarianca; import processadoresImagem.Img; /** * * @author rm61828 */ public class ValorMediaMain { public static void main (String[] args) throws Exception{ BufferedImage imagem = ImageIO.read(new File("isis.jpg")); BufferedImage imagemVlMedio = ImageIO.read(new File("isis.jpg")); BufferedImage imagemVarianca = ImageIO.read(new File("isis.jpg")); Img i = new Img(); int[][] matriz = i.lerBuffer(imagem); int[][] matrizVlMedio = i.lerBuffer(imagemVlMedio); int[][] matrizVarianca = i.lerBuffer(imagemVarianca); int vlMedio = i.vlMedio(matriz); int varianca = i.variancia(matriz); int[][] matrizTextura = i.textura(matriz, 25, 25); String s = ""; for(int c = 0; c < matrizTextura.length; c++){ for(int l = 0; l < matrizTextura[0].length; l++){ s += matrizTextura[c][l]+"\t"; } s+="\n"; } System.out.println(s); int variancaSetor = i.variancia2(0,0,300,400,matriz); System.out.println("Valor Mdio: "+vlMedio); System.out.println("Variancia do Histograma: "+variancaSetor); System.out.println("Variancia do Histograma: "+varianca); FormularioVarianca f = new FormularioVarianca(); imagem = i.lerMatriz(matriz); imagemVlMedio = i.lerMatriz(matrizVlMedio); imagemVarianca = i.lerMatriz(matrizVarianca); f.setImagem(imagem); f.setImagemVlMedio(imagemVlMedio); f.setImagemVarianca(imagemVarianca); f.exibir(); f.getJFrame().setVisible(true); } }
true
577c5675b688a79c972faaf72384ec07e553a798
Java
ryangardner/excursion-decompiling
/divestory-Fernflower/org/apache/commons/net/daytime/DaytimeUDPClient.java
UTF-8
954
2.421875
2
[]
no_license
package org.apache.commons.net.daytime; import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import org.apache.commons.net.DatagramSocketClient; public final class DaytimeUDPClient extends DatagramSocketClient { public static final int DEFAULT_PORT = 13; private final byte[] __dummyData = new byte[1]; private final byte[] __timeData = new byte[256]; public String getTime(InetAddress var1) throws IOException { return this.getTime(var1, 13); } public String getTime(InetAddress var1, int var2) throws IOException { byte[] var3 = this.__dummyData; DatagramPacket var4 = new DatagramPacket(var3, var3.length, var1, var2); var3 = this.__timeData; DatagramPacket var5 = new DatagramPacket(var3, var3.length); this._socket_.send(var4); this._socket_.receive(var5); return new String(var5.getData(), 0, var5.getLength(), this.getCharsetName()); } }
true
3ba1f56c10ebfcf6dc307ce7e6cdaaeacfe9627e
Java
AElkhoumissi/Projet3
/AmineShop/src/main/java/amine/elkhoumissi/ecommerce/metier/MessageClientMetierImpl.java
ISO-8859-1
639
2.015625
2
[]
no_license
package amine.elkhoumissi.ecommerce.metier; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import amine.elkhoumissi.ecommerce.dao.MessageClientDao; import amine.elkhoumissi.ecommerce.entities.MessageClient; /* * Ralis par: AMINE EL KHOUMISSI */ @Service @Transactional public class MessageClientMetierImpl implements MessageClientMetier { @Autowired private MessageClientDao messageClientDao; public void ajouterMessage(MessageClient messageClient) { messageClientDao.ajouterMessage(messageClient); } }
true
4888a4dd5f076a7bdfaa8bfc5dbb4caf848a0fa6
Java
WicasZ/Topicos
/Topicos/Ejercicio5/Pantalla.java
UTF-8
2,107
3.15625
3
[ "MIT" ]
permissive
package Topicos.Ejercicio5; import java.awt.Frame; import java.awt.event.*; //libreria para la line 13 hasta la 18 el WindowListener import java.awt.*; import org.w3c.dom.events.MouseEvent; public class Pantalla extends Frame implements MouseListener{ /** * */ private static final long serialVersionUID = 1L; private Contenedor obj_pintable; public Pantalla(){ initComponents(); } public void initComponents(){ this.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); obj_pintable = new Contenedor(); obj_pintable.addMouseListener(this); this.add(obj_pintable); this.setSize(500,500); this.setVisible(true); this.setTitle("Lienzo"); } public static void main(String [] args){ Pantalla p = new Pantalla(); } @Override public void mouseClicked(java.awt.event.MouseEvent e) { // TODO Auto-generated method stub System.out.println("Clicked"); if(obj_pintable.isClicked()){ obj_pintable.setW(e.getX()); obj_pintable.setH(e.getY()); obj_pintable.repaint(); }else{ obj_pintable.setX(e.getX()); obj_pintable.setY(e.getY()); } obj_pintable.setClicked(); } @Override public void mousePressed(java.awt.event.MouseEvent e) { // TODO Auto-generated method stub System.out.println("Presionado"); } @Override public void mouseReleased(java.awt.event.MouseEvent e) { // TODO Auto-generated method stub System.out.println("Liberado"); } @Override public void mouseEntered(java.awt.event.MouseEvent e) { // TODO Auto-generated method stub System.out.println("Entrado"); } @Override public void mouseExited(java.awt.event.MouseEvent e) { // TODO Auto-generated method stub System.out.println("Salido"); } }
true
10dfb904b81ab49b6ec4e7007b4e1eca7ab99372
Java
pyropunk/api
/api/src/main/java/net/za/grasser/test/api/model/Token.java
UTF-8
901
2.046875
2
[]
no_license
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Token.java * Copyright 2018 Medical EDI Services (PTY) Ltd. All rights reserved. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package net.za.grasser.test.api.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; /** * */ public class Token { @JsonInclude(Include.NON_NULL) Long id; String token; public Token() { super(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } }
true
a2c8592fd124292b10aba1e6c5db0778aaf493cd
Java
danielperez9430/Third-party-Telegram-Apps-Spy
/Hotgram/com/google/android/gms/phenotype/ExperimentTokens.java
UTF-8
7,562
1.828125
2
[]
no_license
package com.google.android.gms.phenotype; import android.os.Parcel; import android.os.Parcelable$Creator; import android.util.Base64; import com.google.android.gms.common.annotation.KeepForSdk; import com.google.android.gms.common.internal.safeparcel.AbstractSafeParcelable; import com.google.android.gms.common.internal.safeparcel.SafeParcelWriter; import com.google.android.gms.common.internal.safeparcel.SafeParcelable$Class; import com.google.android.gms.common.internal.safeparcel.SafeParcelable$Constructor; import com.google.android.gms.common.internal.safeparcel.SafeParcelable$Field; import com.google.android.gms.common.internal.safeparcel.SafeParcelable$Param; import com.google.android.gms.common.internal.safeparcel.SafeParcelable$Reserved; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; @KeepForSdk @Class(creator="ExperimentTokensCreator") @Reserved(value={1}) public class ExperimentTokens extends AbstractSafeParcelable { interface zza { } @KeepForSdk public static final Parcelable$Creator CREATOR; private static final zza zzaa; private static final byte[][] zzn; private static final ExperimentTokens zzo; @Field(id=2) private final String zzp; @Field(id=3) private final byte[] zzq; @Field(id=4) private final byte[][] zzr; @Field(id=5) private final byte[][] zzs; @Field(id=6) private final byte[][] zzt; @Field(id=7) private final byte[][] zzu; @Field(id=8) private final int[] zzv; @Field(id=9) private final byte[][] zzw; private static final zza zzx; private static final zza zzy; private static final zza zzz; static { ExperimentTokens.CREATOR = new zzh(); ExperimentTokens.zzn = new byte[0][]; ExperimentTokens.zzo = new ExperimentTokens("", null, ExperimentTokens.zzn, ExperimentTokens.zzn, ExperimentTokens.zzn, ExperimentTokens.zzn, null, null); ExperimentTokens.zzx = new zzd(); ExperimentTokens.zzy = new zze(); ExperimentTokens.zzz = new zzf(); ExperimentTokens.zzaa = new zzg(); } @Constructor public ExperimentTokens(@Param(id=2) String arg1, @Param(id=3) byte[] arg2, @Param(id=4) byte[][] arg3, @Param(id=5) byte[][] arg4, @Param(id=6) byte[][] arg5, @Param(id=7) byte[][] arg6, @Param(id=8) int[] arg7, @Param(id=9) byte[][] arg8) { super(); this.zzp = arg1; this.zzq = arg2; this.zzr = arg3; this.zzs = arg4; this.zzt = arg5; this.zzu = arg6; this.zzv = arg7; this.zzw = arg8; } public boolean equals(Object arg4) { if(((arg4 instanceof ExperimentTokens)) && (zzn.equals(this.zzp, ((ExperimentTokens)arg4).zzp)) && (Arrays.equals(this.zzq, ((ExperimentTokens)arg4).zzq)) && (zzn.equals(ExperimentTokens.zza(this.zzr), ExperimentTokens.zza(((ExperimentTokens)arg4).zzr))) && (zzn.equals(ExperimentTokens.zza(this.zzs), ExperimentTokens.zza(((ExperimentTokens)arg4).zzs))) && (zzn.equals(ExperimentTokens.zza(this.zzt), ExperimentTokens.zza(((ExperimentTokens)arg4).zzt))) && (zzn.equals(ExperimentTokens.zza(this.zzu), ExperimentTokens.zza(((ExperimentTokens)arg4).zzu))) && (zzn.equals(ExperimentTokens.zza(this.zzv), ExperimentTokens.zza(((ExperimentTokens)arg4).zzv))) && (zzn.equals(ExperimentTokens.zza(this.zzw), ExperimentTokens.zza(((ExperimentTokens)arg4).zzw)))) { return 1; } return 0; } public String toString() { String v1; StringBuilder v0 = new StringBuilder("ExperimentTokens"); v0.append("("); if(this.zzp == null) { v1 = "null"; } else { v1 = this.zzp; StringBuilder v3 = new StringBuilder(String.valueOf(v1).length() + 2); v3.append("\'"); v3.append(v1); v3.append("\'"); v1 = v3.toString(); } v0.append(v1); v0.append(", "); byte[] v2 = this.zzq; v0.append("direct"); v0.append("="); if(v2 == null) { v1 = "null"; } else { v0.append("\'"); v0.append(Base64.encodeToString(v2, 3)); v1 = "\'"; } v0.append(v1); v0.append(", "); ExperimentTokens.zza(v0, "GAIA", this.zzr); v0.append(", "); ExperimentTokens.zza(v0, "PSEUDO", this.zzs); v0.append(", "); ExperimentTokens.zza(v0, "ALWAYS", this.zzt); v0.append(", "); ExperimentTokens.zza(v0, "OTHER", this.zzu); v0.append(", "); int[] v2_1 = this.zzv; v0.append("weak"); v0.append("="); if(v2_1 == null) { v1 = "null"; } else { v0.append("("); int v1_1 = v2_1.length; int v4 = 0; int v5; for(v5 = 1; v4 < v1_1; v5 = 0) { int v6 = v2_1[v4]; if(v5 == 0) { v0.append(", "); } v0.append(v6); ++v4; } v1 = ")"; } v0.append(v1); v0.append(", "); ExperimentTokens.zza(v0, "directs", this.zzw); v0.append(")"); return v0.toString(); } public void writeToParcel(Parcel arg4, int arg5) { arg5 = SafeParcelWriter.beginObjectHeader(arg4); SafeParcelWriter.writeString(arg4, 2, this.zzp, false); SafeParcelWriter.writeByteArray(arg4, 3, this.zzq, false); SafeParcelWriter.writeByteArrayArray(arg4, 4, this.zzr, false); SafeParcelWriter.writeByteArrayArray(arg4, 5, this.zzs, false); SafeParcelWriter.writeByteArrayArray(arg4, 6, this.zzt, false); SafeParcelWriter.writeByteArrayArray(arg4, 7, this.zzu, false); SafeParcelWriter.writeIntArray(arg4, 8, this.zzv, false); SafeParcelWriter.writeByteArrayArray(arg4, 9, this.zzw, false); SafeParcelWriter.finishObjectHeader(arg4, arg5); } private static List zza(int[] arg4) { if(arg4 == null) { return Collections.emptyList(); } ArrayList v0 = new ArrayList(arg4.length); int v1 = arg4.length; int v2; for(v2 = 0; v2 < v1; ++v2) { ((List)v0).add(Integer.valueOf(arg4[v2])); } Collections.sort(((List)v0)); return ((List)v0); } private static List zza(byte[][] arg5) { if(arg5 == null) { return Collections.emptyList(); } ArrayList v0 = new ArrayList(arg5.length); int v1 = arg5.length; int v2; for(v2 = 0; v2 < v1; ++v2) { ((List)v0).add(Base64.encodeToString(arg5[v2], 3)); } Collections.sort(((List)v0)); return ((List)v0); } private static void zza(StringBuilder arg4, String arg5, byte[][] arg6) { arg4.append(arg5); arg4.append("="); if(arg6 == null) { arg5 = "null"; } else { arg4.append("("); int v5 = arg6.length; int v1 = 0; int v2; for(v2 = 1; v1 < v5; v2 = 0) { byte[] v3 = arg6[v1]; if(v2 == 0) { arg4.append(", "); } arg4.append("\'"); arg4.append(Base64.encodeToString(v3, 3)); arg4.append("\'"); ++v1; } arg5 = ")"; } arg4.append(arg5); } }
true
5049a390f121e0337d5707d6e4f558f7a10f547d
Java
lyw1996/mybatisdemoV2
/src/main/java/com/htsc/domain/QueryVo.java
UTF-8
479
1.898438
2
[]
no_license
package com.htsc.domain; /** * <h3>mabatisdemo</h3> * <p></p> * * @author : liuyuwei * @date : 2020-09-02 15:26 **/ public class QueryVo { public String getName() { return name; } public void setName(String name) { this.name = name; } private String name; private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
true
4925894cc45f7b17bdf65e4352cc22891b2f966d
Java
bellmit/AlibabaPay0428
/.svn/pristine/0a/0a4353210c1a92d38510ef23f0d35877402bd95a.svn-base
UTF-8
1,811
1.570313
2
[]
no_license
package com.hcis.items.service; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.activiti.engine.runtime.ProcessInstance; import org.springframework.web.multipart.MultipartFile; import com.hcis.ipanther.core.service.IBaseService; import com.hcis.ipanther.core.web.vo.SearchParam; import com.hcis.items.entity.ItemsExpert; public interface ItemsExpertService extends IBaseService<ItemsExpert> { public ProcessInstance startWorkFlow(ItemsExpert itemsExpert,HttpServletRequest request); public String uploadFile(ItemsExpert itemsExpert,MultipartFile file); public String uploadImg(ItemsExpert itemsExpert,MultipartFile file); public String uploadAvatar(ItemsExpert itemsExpert, MultipartFile file); public void deleteWorkFlow(String procInstId); public void submitExpert(ItemsExpert itemsExpert,SearchParam searchParam); public void submitExpertToProject(ItemsExpert itemsExpert,HttpServletRequest request); public void audit(ItemsExpert itemsExpert,HttpServletRequest request,SearchParam searchParam); public List<Map<String,Object>> listExpert(SearchParam searchParam,HttpServletRequest request); public List<Map<String,Object>> listExpertView(SearchParam searchParam,HttpServletRequest request); public List<Map<String,Object>> listProjectLitems(SearchParam searchParam); public String uploadExpertFile(SearchParam searchParam,MultipartFile[] upload,HttpServletRequest request); public int deleteExpertFile(SearchParam searchParam,HttpServletRequest request); public int deleteExperts(SearchParam searchParam); /** * 课程审核通过后向报名人员的邮箱定向推送消息 * @param course * @return */ public void sendEmeilByCourse(ItemsExpert itemsExpert,HttpServletRequest request); }
true
08d8e47668684508c8ec1cb9aa02ad97146a05bb
Java
zj-cs2103/main
/src/test/java/seedu/address/logic/commands/booking/AddBookingCommandTest.java
UTF-8
4,140
2.53125
3
[ "MIT" ]
permissive
package seedu.address.logic.commands.booking; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static seedu.address.testutil.TypicalIndexes.INDEX_SECOND; import static seedu.address.testutil.TypicalMembers.getTypicalAddressBook; import java.util.Arrays; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import seedu.address.commons.core.Messages; import seedu.address.commons.core.index.Index; import seedu.address.logic.CommandHistory; import seedu.address.logic.CustomerIndexedBooking; import seedu.address.logic.commands.CommandResult; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.UserPrefs; import seedu.address.model.booking.Booking; import seedu.address.testutil.CustomerIndexedBookingBuilder; /** * Contains integration tests (interaction with the Model) * and unit tests for AddBookingCommand. */ public class AddBookingCommandTest { @Rule public ExpectedException thrown = ExpectedException.none(); private Model model = new ModelManager(getTypicalAddressBook(), new UserPrefs()); private CommandHistory commandHistory = new CommandHistory(); @Test public void constructor_nullBooking_throwsNullPointerException() { thrown.expect(NullPointerException.class); new AddBookingCommand(null); } @Test public void execute_bookingAcceptedByModel_addSuccessful() throws Exception { CustomerIndexedBooking validBooking = new CustomerIndexedBookingBuilder().build(); CommandResult commandResult = new AddBookingCommand(validBooking).execute(model, commandHistory); Booking expectedBooking = validBooking.getBooking(model).get(); assertEquals(String.format(AddBookingCommand.MESSAGE_SUCCESS, expectedBooking), commandResult.getFeedbackToUser()); assertEquals(Arrays.asList(expectedBooking), model.getFilteredBookingList()); } @Test public void execute_duplicateBooking_throwsCommandException() throws Exception { CustomerIndexedBooking validBooking = new CustomerIndexedBookingBuilder().build(); AddBookingCommand addBookingCommand = new AddBookingCommand(validBooking); addBookingCommand.execute(model, commandHistory); thrown.expect(CommandException.class); thrown.expectMessage(AddBookingCommand.MESSAGE_DUPLICATE); addBookingCommand.execute(model, commandHistory); } @Test public void execute_customerIndexOutOfBounds_throwsCommandException() throws Exception { Index outOfBoundsIndex = Index.fromZeroBased(model.getFilteredMemberList().size()); CustomerIndexedBooking invalidBooking = new CustomerIndexedBookingBuilder().withIndex(outOfBoundsIndex).build(); AddBookingCommand invalidAddBookingCommand = new AddBookingCommand(invalidBooking); thrown.expect(CommandException.class); thrown.expectMessage(Messages.MESSAGE_INVALID_MEMBER_DISPLAYED_INDEX); invalidAddBookingCommand.execute(model, commandHistory); } @Test public void equals() { AddBookingCommand defaultBookingCommand = new AddBookingCommand(new CustomerIndexedBookingBuilder().build()); AddBookingCommand duplicateDefaultBookingCommand = new AddBookingCommand(new CustomerIndexedBookingBuilder().build()); AddBookingCommand differentBookingCommand = new AddBookingCommand(new CustomerIndexedBookingBuilder().withIndex(INDEX_SECOND).build()); // same object -> equal assertEquals(defaultBookingCommand, defaultBookingCommand); // duplicate object -> equal assertEquals(defaultBookingCommand, duplicateDefaultBookingCommand); // change customer index -> not equal assertNotEquals(defaultBookingCommand, differentBookingCommand); // different type -> not equal assertNotEquals(defaultBookingCommand, 1); assertNotEquals(defaultBookingCommand, false); } }
true
7262f4e6ca2a8db402d973af874f669b16cdc845
Java
living1/swzlw
/src/com/swzlw/service/impl/LostServiceImpl.java
UTF-8
1,501
1.984375
2
[]
no_license
package com.swzlw.service.impl; import com.swzlw.service.LostService; import com.swzlw.dao.LostDao; import com.swzlw.model.Lost; import com.swzlw.model.LostGc; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; import java.util.Map; /** * Created by 哈利波特 on 2017/11/15. */ @Service("lostService") public class LostServiceImpl implements LostService{ @Resource private LostDao lostDao; @Override public List<LostGc> findLostGc() { return lostDao.findLostGc(); } @Override public List<Lost> find(Map<String, Object> map) { return lostDao.find(map); } @Override public Long getTotal(Map<String, Object> map) { return lostDao.getTotal(map); } @Override public Lost findById(Integer id) { return lostDao.findById(id); } @Override public List<Lost> findAll() { return lostDao.findAll(); } @Override public int add(Lost lost) { // TODO Auto-generated method stub return lostDao.add(lost); } @Override public int update(Lost lost) { // TODO Auto-generated method stub return lostDao.update(lost); } @Override public int delete(Integer id) { // TODO Auto-generated method stub return lostDao.delete(id); } @Override public int updateCheckState(Lost lost) { // TODO Auto-generated method stub return 0; } @Override public int updateReturnState(Lost lost) { // TODO Auto-generated method stub return 0; } }
true
3bcef8241da341fd3c8d709f290a1ed6ea4bcd52
Java
AlexandraRyzvanovich/greenhouse
/src/main/java/com/epam/entity/WildRose.java
UTF-8
2,423
2.34375
2
[]
no_license
package com.epam.entity; import com.epam.entity.enums.Color; import com.epam.entity.enums.Multiplying; import com.epam.entity.enums.Soil; import com.epam.entity.enums.WildRoseSort; import javax.xml.bind.annotation.*; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "wild_rose", namespace = "http://www.epam.com/flowers") @XmlType(name = "Wild_rose", propOrder = { "fruitForm" }) public class WildRose extends Rose { @XmlElement(name = "fruit_Form", required = true) private String fruitForm; @XmlAttribute(name = "wild_rose_sort") private WildRoseSort wildRoseSort; public WildRose(String id, WildRoseSort wildRoseSort, String name, Soil soil, Color color, String growingTips, Multiplying multiplying, String blossomTime, int petalQuantity, String budType, String fruitForm ) { super(id, name, soil, color, growingTips, multiplying, blossomTime, petalQuantity, budType); this.fruitForm = fruitForm; this.wildRoseSort = wildRoseSort; } public WildRose() { } public WildRoseSort getWildRoseSort() { if(wildRoseSort == null){ return WildRoseSort.RUGOSA; }else { return wildRoseSort; } } public void setWildRoseSort(WildRoseSort wildRoseSort) { if (wildRoseSort == null) { this.wildRoseSort = WildRoseSort.RUGOSA; } else { this.wildRoseSort = wildRoseSort; } } public String getFruitForm() { return fruitForm; } public void setFruitForm(String fruitForm) { this.fruitForm = fruitForm; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof WildRose)) { return false; } if(!super.equals(o)){ return false; } WildRose wildRose = (WildRose) o; if (wildRose.fruitForm == null || wildRose.wildRoseSort == null) { return false; } return getWildRoseSort() == wildRose.getWildRoseSort() && getFruitForm().equals(wildRose.getFruitForm()); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + fruitForm.hashCode(); result = prime * result + wildRoseSort.hashCode(); return result; } }
true
2a08a62874fdc87e8f1d8b0ffbdd15b90695a634
Java
MichaelSims/dagger2-shared-module-playground
/app/src/main/java/com/example/dagger2sharedmoduleplayground/services/StringService.java
UTF-8
543
2.53125
3
[]
no_license
package com.example.dagger2sharedmoduleplayground.services; import com.example.shared.BestStringProvider; import com.example.shared.StringServiceApi; /** Gives you the best string. */ public class StringService implements StringServiceApi { private final BestStringProvider bestStringProvider; public StringService(BestStringProvider bestStringProvider) { this.bestStringProvider = bestStringProvider; } @Override public String getTheBestString() { return bestStringProvider.getTheBestString(); } }
true
3181e7d73a25cf03d9a44db36cfc47e94db7711f
Java
yesamer/drools
/drools-metric/src/test/java/org/drools/metric/AbstractMetricTest.java
UTF-8
1,085
1.945313
2
[ "Apache-2.0" ]
permissive
package org.drools.metric; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Metrics; import io.micrometer.core.instrument.search.Search; import org.drools.metric.util.MetricLogUtils; import org.drools.metric.util.MicrometerUtils; import org.drools.mvel.CommonTestMethodBase; import org.junit.After; import org.junit.Before; abstract class AbstractMetricTest extends CommonTestMethodBase { protected MeterRegistry registry; @Before public void setup() { System.setProperty(MetricLogUtils.METRIC_LOGGER_ENABLED, "true"); System.setProperty(MetricLogUtils.METRIC_LOGGER_THRESHOLD, "-1"); this.registry = Metrics.globalRegistry; } @After public void clearMeters() { // Remove meters we inserted without affecting those that may have already been there. Search.in(registry) .name(name -> name.startsWith("org.drools.metric")) .meters() .forEach(registry::remove); MicrometerUtils.INSTANCE.clear(); registry = null; } }
true
28174bc108325a860cda95ebb37d30587a490e34
Java
ThiAmaral/ProjetoCaixaRestaurante
/src/src/Produto.java
UTF-8
950
3.203125
3
[]
no_license
package src; public class Produto { public static void main(String[] args) { String nome =getNome(); int matricula = getCodigo(); double preco = getPreco(); toStr(nome, matricula, preco); } public static String getNome(){ String nome = "Thiago"; return nome; } public static int getCodigo(){ int codigo = 2; return codigo; } public static double getPreco(){ double preco = 2.6; return preco; } public static String setNome(){ String nome = "Batata"; return nome; } public static int setCodigo(){ int codigo = 2; return codigo; } public static float setPreco(){ float preco = 2; return preco; } public static void toStr(String nome, int codigo, double preco){ System.out.println("Produto: " + nome + " : "+ preco + ", " + codigo); } }
true
7c3b85699230d4e6a4baeefe0179a1d22d67ea5c
Java
baijifeilong/baijifeilong-spring-cloud-blog
/base/blog-foundation/src/main/java/io/github/baijifeilong/blog/foundation/feign/ArticleErrorDecoder.java
UTF-8
1,470
2.21875
2
[]
no_license
package io.github.baijifeilong.blog.foundation.feign; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import feign.Response; import feign.codec.ErrorDecoder; import io.github.baijifeilong.blog.foundation.constant.ExceptionConstants; import io.github.baijifeilong.blog.foundation.exception.RpcException; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.Optional; import java.util.Scanner; /** * @author BaiJiFeiLong@gmail.com * @date 2019-04-24 18:29 */ @Component @Slf4j public class ArticleErrorDecoder implements ErrorDecoder, ExceptionConstants { private ObjectMapper objectMapper = new ObjectMapper(); @Override public Exception decode(String s, Response response) { try { String text = new Scanner(response.body().asInputStream()).useDelimiter("\\A").next(); JsonNode jsonNode = objectMapper.readValue(text, JsonNode.class); log.info("[RPC异常] {}", jsonNode); int code = jsonNode.get("code").asInt(); String message = jsonNode.get("message").asText(); return new RpcException(code, message); } catch (IOException e) { log.error("[RCP错误] {}", e.getMessage(), e); return new RpcException(RPC_EXCEPTION_DEFAULT_CODE, Optional.ofNullable(e.getMessage()).orElse(e.toString())); } } }
true
87fa6a332117c64c1af28e3b3bfa66a83dfa896d
Java
sim1ray/SortingApplication
/SelectionSort.java
UTF-8
437
3.53125
4
[]
no_license
public class SelectionSort extends Sorting { @Override public void sort(Comparable[] array) { for (int i = 0; i < array.length; i++) { int min = i; for (int j = i+1; j < array.length; j++) { // Find minimum element if (lessThan(array[j], array[min])) { min = j; } } swap(i, min, array); } } }
true
a42f82f560c92664a14d52f86f86e94fb75dc4ae
Java
khalludi/coding_practice
/hackerrank/dynamic_programming/CoinChange.java
UTF-8
3,654
3.921875
4
[]
no_license
/* Hackerrank "The Coin Change Problem" https://www.hackerrank.com/challenges/coin-change/problem */ import java.util.HashMap; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; // Dynamic Programming Bottom Up approach - way too slow for large values public class CoinChange { // Complete the getWays function below. static long getWays(long sum, long[] coins) { // Create Memoization Table for "Bottom-Up" approach HashMap<Integer, HashSet<ArrayList<Integer>>> memo = new HashMap<Integer, HashSet<ArrayList<Integer>>>(); // Creating a set to keep combinations without duplicates HashSet<ArrayList<Integer>> combinations = new HashSet<ArrayList<Integer>>(); // Initialize empty zero element in table ArrayList<Integer> zero = new ArrayList<Integer>(); combinations.add(zero); memo.put(0, combinations); // Calculate every possible combination until sum is reached for(int i = 1; i <= sum+1; i++) { combinations = new HashSet<ArrayList<Integer>>(); for (int j = 0; j < coins.length; j++) { // If the coin is equal to the sum, i if (coins[j] == i) { // Add the coin into possible combinations ArrayList<Integer> a = new ArrayList<Integer>(); a.add(i); combinations.add(a); } else if (coins[j] < i) { // Debug print statements: //System.out.println("Map Index: " + (i - coins[j]) + ", Sum: " + i); //System.out.println(memo); //System.out.println(memo.get(i - (int)coins[j])); // Get the coin combos HashSet<ArrayList<Integer>> one_coinset = memo.get(i - (int)coins[j]); Iterator iter = one_coinset.iterator(); while(iter.hasNext()) { // Create a copy of the combination to avoid changing the old one @SuppressWarnings("unchecked") ArrayList<Integer> tmp = (ArrayList<Integer>)((ArrayList<Integer>) iter.next()).clone(); // Binary Search to keep sorted combos so HashSet can remove duplicates int index = binarySearch(tmp, (int)coins[j], 0, tmp.size() - 1); tmp.add(index, (int)coins[j]); combinations.add(tmp); } } } // Add the combinations of i into the memo table memo.put(i, combinations); } // Return the total number of combinations return memo.get((int)sum).size(); } // Reimplemented binarySearch for practice static int binarySearch(ArrayList<Integer> arr, int num, int low, int high) { if (high <= low) { if (num > arr.get(low)) { return low + 1; } else { return low; } } int mid = (high + low)/2; if (num == arr.get(mid)) { return mid; } else if (num > arr.get(mid)) { return binarySearch(arr, num, mid + 1, high); } else { return binarySearch(arr, num, low, mid - 1); } } public static void main(String args[]) { long[] coins = {8,47,13,24,25,31,32,35,3,19,40,48,1,4,17,38,22,30,33,15,44,46,36,9,20,9}; long sum = 250; System.out.println("Coin Change!"); System.out.println(getWays(sum, coins)); } }
true
d4f2d5b3426d1430501cd14271d7508bc80dae54
Java
TuthikaMouni/DemoRep
/MyFirstJavaApplication/src/main/java/com/db/connect/Java2MysqlConnection.java
UTF-8
1,160
3.1875
3
[]
no_license
package com.db.connect; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Java2MysqlConnection { private static final String url = "jdbc:mysql://localhost:3306/job_portal"; private static final String user = "root"; private static final String password = "root"; private static Connection con; private static Statement stmt; private static ResultSet rs; public static void main(String[] args) throws SQLException { String query = "SELECT * FROM job_portal.login"; try { // opening database connection to MySQL server con = DriverManager.getConnection(url, user, password); // getting Statement object to execute query stmt = con.createStatement(); // executing SELECT query rs = stmt.executeQuery(query); while (rs.next()) { String username = rs.getString(1); String password = rs.getString(2); System.out.println("=username:="+username+":password:"+password); } }catch(SQLException ex) { con.close(); stmt.close(); rs.close(); } } }
true
59686310ebe662bf6fd647f99c327aeb06f25b41
Java
angel-manuel/gesture
/src/es/uam/eps/padsof/gesture/exception/SubastaNoCancelableException.java
UTF-8
641
2.34375
2
[]
no_license
package es.uam.eps.padsof.gesture.exception; import es.uam.eps.padsof.gesture.subasta.Subasta; /** * TODO: Descripcion del tipo * * @author Borja González Farías * @author Ángel Manuel Martín * */ public class SubastaNoCancelableException extends Exception { private static final long serialVersionUID = 20160330L; private final Subasta subasta; /** * Constructor de SubastaNoCancelableException * * @param subasta */ public SubastaNoCancelableException(Subasta subasta) { this.subasta = subasta; } /** * Getter de subasta * * @return el subasta de SubastaNoCancelableException */ public Subasta getSubasta() { return subasta; } }
true
b2d917da951a4387f79044d0913a455240b9e015
Java
alihassan143/android-projects
/app/src/main/java/com/example/loginchat/RegisterActivity.java
UTF-8
3,660
2.203125
2
[]
no_license
package com.example.loginchat; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.HashMap; public class RegisterActivity extends AppCompatActivity { EditText entername,enteremail,enterpassword; Button signup; DatabaseReference databaseReference; FirebaseAuth firebaseAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); enteremail = findViewById(R.id.enteremail); entername = findViewById(R.id.entername); enterpassword = findViewById(R.id.enterpassword); signup = findViewById(R.id.btnsignup); firebaseAuth=FirebaseAuth.getInstance(); signup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email=enteremail.getText().toString(); String password=enterpassword.getText().toString(); String user_name=entername.getText().toString(); if (TextUtils.isEmpty(email)||TextUtils.isEmpty(password)||TextUtils.isEmpty(user_name)){ Toast.makeText(RegisterActivity.this, "Please Fill All Required Fields", Toast.LENGTH_SHORT).show(); }else{ RegisterBase(user_name,email,password); } } }); } private void RegisterBase(final String username, String useremail, String userpasswrod){ firebaseAuth.createUserWithEmailAndPassword(useremail,userpasswrod).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()){ FirebaseUser firebaseUser=firebaseAuth.getCurrentUser(); String id=firebaseUser.getUid(); databaseReference= FirebaseDatabase.getInstance().getReference("MyUsers").child(id); HashMap<String,String>hashMap=new HashMap<>(); hashMap.put("Username",username); hashMap.put("UserId",id); hashMap.put("Image","default"); databaseReference.setValue(hashMap).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()){ Intent i=new Intent(RegisterActivity.this,MainActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i); finish(); }else{ Toast.makeText(RegisterActivity.this, "Regter Failed", Toast.LENGTH_SHORT).show(); } } }); } } }); } }
true
59a26116e3f420de0a394aca842e181263235596
Java
LuNaTeCs-316/2014-Robot
/src/org/lunatecs316/frc2014/lib/IterativePIDController.java
UTF-8
2,223
3.296875
3
[ "BSD-2-Clause" ]
permissive
package org.lunatecs316.frc2014.lib; /** * PID Controller that can run in an iterative loop * @author Domenic Rodriguez */ public final class IterativePIDController { private double kP, kI, kD; private double integral, prev_error; private IterativeTimer deltaTimer = new IterativeTimer(); /** * Construct a new PIDController * @param kP proportional constant * @param kI integral constant * @param kD derivative constant */ public IterativePIDController(double kP, double kI, double kD) { setPID(kP, kI, kD); reset(); } /** * Set new values for kP, kI, and kD * @param kP proportional constant * @param kI integral constant * @param kD derivative constant */ public void setPID(double kP, double kI, double kD) { this.kP = kP; this.kI = kI; this.kD = kD; } /** * Reset the controller */ public void reset() { integral = prev_error = 0; deltaTimer.reset(); } /** * Run one iteration of the PID controller * @param sp setpoint (target value) * @param pv process variable (current value) * @return output of the PID algorithm */ public double run(double sp, double pv) { return run(sp, pv, -1.0, 1.0); } /** * Run one iteration of the PID controller * @param sp setpoint (target value) * @param pv process variable (current value) * @param min the minimum output * @param max the maximum output * @return output of the PID algorithm */ public double run(double sp, double pv, double min, double max) { // Get the time since the last call double dt = deltaTimer.getValue(); // Calculate output double error = sp - pv; integral += error * dt; double derivative = (error - prev_error) / dt; double output = kP * error + kI * integral + kD * derivative; // Check against limits if (output > max) output = max; else if (output < min) output = min; // Reset for next run prev_error = error; deltaTimer.reset(); return output; } }
true
fa1b6865fc86bf605561800fa1ba599f0b1fb6d4
Java
MGreco2112/Black-Jack
/src/game/Dealer.java
UTF-8
740
3.28125
3
[]
no_license
package game; public class Dealer implements Actor{ protected final String NAME; protected final int BALANCE = 0; public Dealer(String name) { this.NAME = name; } @Override public String getName() { return NAME; } @Override public int getBalance() { return BALANCE; } @Override public String getBet(int Wallet) { return "The Dealer cannot bet"; } @Override public void getActon(int choice) { switch (choice) { case 1 -> takeBet(); case 2 -> hitPlayer(); default -> System.out.println("Invalid choice"); } } public void takeBet() { } public void hitPlayer() { } }
true
138d0ed01e306b8eb65bcff096cc91f3a5aec457
Java
mohbadar/pay-connector
/src/test/java/uk/gov/pay/connector/rules/EpdqMockClient.java
UTF-8
4,228
1.789063
2
[ "LicenseRef-scancode-proprietary-license", "MIT" ]
permissive
package uk.gov.pay.connector.rules; import uk.gov.pay.connector.util.TestTemplateResourceLoader; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static javax.ws.rs.core.HttpHeaders.CONTENT_TYPE; import static javax.ws.rs.core.MediaType.TEXT_XML; import static uk.gov.pay.connector.gateway.epdq.EpdqPaymentProvider.ROUTE_FOR_MAINTENANCE_ORDER; import static uk.gov.pay.connector.gateway.epdq.EpdqPaymentProvider.ROUTE_FOR_NEW_ORDER; import static uk.gov.pay.connector.gateway.epdq.EpdqPaymentProvider.ROUTE_FOR_QUERY_ORDER; import static uk.gov.pay.connector.util.TestTemplateResourceLoader.*; public class EpdqMockClient { public EpdqMockClient() { } public void mockAuthorisationSuccess() { paymentServiceResponse(ROUTE_FOR_NEW_ORDER, TestTemplateResourceLoader.load(EPDQ_AUTHORISATION_SUCCESS_RESPONSE)); } public void mockUnknown() { paymentServiceResponse(ROUTE_FOR_QUERY_ORDER, TestTemplateResourceLoader.load(EPDQ_UNKNOWN_RESPONSE)); } public void mockAuthorisationQuerySuccess() { paymentServiceResponse(ROUTE_FOR_QUERY_ORDER, TestTemplateResourceLoader.load(EPDQ_AUTHORISATION_SUCCESS_RESPONSE)); } public void mockAuthorisationQuerySuccessAuthFailed() { paymentServiceResponse(ROUTE_FOR_QUERY_ORDER, TestTemplateResourceLoader.load(EPDQ_AUTHORISATION_FAILED_RESPONSE)); } public void mockCancelQuerySuccess() { paymentServiceResponse(ROUTE_FOR_QUERY_ORDER, TestTemplateResourceLoader.load(EPDQ_CANCEL_SUCCESS_RESPONSE)); } public void mockCaptureQuerySuccess() { paymentServiceResponse(ROUTE_FOR_QUERY_ORDER, TestTemplateResourceLoader.load(EPDQ_CAPTURE_SUCCESS_RESPONSE)); } public void mockAuthorisation3dsSuccess() { paymentServiceResponse(ROUTE_FOR_NEW_ORDER, TestTemplateResourceLoader.load(EPDQ_AUTHORISATION_SUCCESS_3D_RESPONSE)); } public void mockAuthorisationFailure() { paymentServiceResponse(ROUTE_FOR_NEW_ORDER, TestTemplateResourceLoader.load(EPDQ_AUTHORISATION_FAILED_RESPONSE)); } public void mockAuthorisationError() { paymentServiceResponse(ROUTE_FOR_NEW_ORDER, TestTemplateResourceLoader.load(EPDQ_AUTHORISATION_ERROR_RESPONSE)); } public void mockAuthorisationWaitingExternal() { paymentServiceResponse(ROUTE_FOR_NEW_ORDER, TestTemplateResourceLoader.load(EPDQ_AUTHORISATION_WAITING_EXTERNAL_RESPONSE)); } public void mockAuthorisationWaiting() { paymentServiceResponse(ROUTE_FOR_NEW_ORDER, TestTemplateResourceLoader.load(EPDQ_AUTHORISATION_WAITING_RESPONSE)); } public void mockAuthorisationOther() { paymentServiceResponse(ROUTE_FOR_NEW_ORDER, TestTemplateResourceLoader.load(EPDQ_AUTHORISATION_OTHER_RESPONSE)); } public void mockCaptureSuccess() { paymentServiceResponse(ROUTE_FOR_MAINTENANCE_ORDER, TestTemplateResourceLoader.load(EPDQ_CAPTURE_SUCCESS_RESPONSE)); } public void mockCaptureError() { paymentServiceResponse(ROUTE_FOR_MAINTENANCE_ORDER, TestTemplateResourceLoader.load(EPDQ_CAPTURE_ERROR_RESPONSE)); } public void mockCancelSuccess() { paymentServiceResponse(ROUTE_FOR_MAINTENANCE_ORDER, TestTemplateResourceLoader.load(EPDQ_CANCEL_SUCCESS_RESPONSE)); } public void mockRefundSuccess() { paymentServiceResponse(ROUTE_FOR_MAINTENANCE_ORDER, TestTemplateResourceLoader.load(EPDQ_REFUND_SUCCESS_RESPONSE)); } public void mockRefundError() { paymentServiceResponse(ROUTE_FOR_MAINTENANCE_ORDER, TestTemplateResourceLoader.load(EPDQ_REFUND_ERROR_RESPONSE)); } private void paymentServiceResponse(String route, String responseBody) { //FIXME - This mocking approach is very poor. Needs to be revisited. Story PP-900 created. stubFor( post(urlPathEqualTo(String.format("/epdq/%s", route))) .willReturn( aResponse() .withHeader(CONTENT_TYPE, TEXT_XML) .withStatus(200) .withBody(responseBody) ) ); } }
true
d44d113aadf8862e35ded130e9b39449f1c467c9
Java
sadena27/snake-game
/SnakeGame/src/Coordinate.java
UTF-8
644
3.671875
4
[]
no_license
public class Coordinate { private int row, col, direction; public Coordinate(int row, int col, int direction) { this.row = row; this.col = col; this.direction = direction; } public int getRow() { return row; } public int getCol() { return col; } public int getDirection() { return direction; } // Two coordinates are equal if they have the same row and column @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof Coordinate)) { return false; } Coordinate c = (Coordinate)obj; return c.getRow() == this.row && c.getCol() == this.col; } }
true
2915c452eace23599918e47ab53aee9abf60548d
Java
designreuse/senoj-steven
/org/andengine/p005d/p058g/C0640a.java
UTF-8
1,189
2.234375
2
[]
no_license
package org.andengine.p005d.p058g; import android.util.FloatMath; import java.util.Random; /* renamed from: org.andengine.d.g.a */ public final class C0640a { public static final Random f2627a; static { f2627a = new Random(System.nanoTime()); } public static final float m5162a(float f) { return 0.017453292f * f; } public static final boolean m5163a(int i) { return i != 0 && ((i - 1) & i) == 0; } public static float[] m5164a(float[] fArr, float f, float f2, float f3) { if (f != 0.0f) { float a = C0640a.m5162a(f); float sin = FloatMath.sin(a); float cos = FloatMath.cos(a); for (int length = fArr.length - 2; length >= 0; length -= 2) { float f4 = fArr[length]; float f5 = fArr[length + 1]; fArr[length] = (((f4 - f2) * cos) - ((f5 - f3) * sin)) + f2; fArr[length + 1] = (((f4 - f2) * sin) + ((f5 - f3) * cos)) + f3; } } return fArr; } public static float[] m5165b(float[] fArr, float f, float f2, float f3) { return C0640a.m5164a(fArr, -f, f2, f3); } }
true
b863d2f78c17c6449a70f16a8e6130c958e614d1
Java
Royesta/RSwing
/src/com/royestalab/rswing/RText.java
UTF-8
334
1.601563
2
[ "MIT" ]
permissive
/* RText.java * * Copyright(c) 2016. RoyestaLab.Com. All Rights Reserved. * This software is the proprientary information of Royesta Lab. */ package com.royestalab.rswing; import javax.swing.JTextField; /** * Component Text Field * * @author Roy Royesta Pampey (royroyesta54@gmail.com) * @author ocol */ public class RText extends JTextField { }
true
0ff04c33c88921659a14e92f3ebb921e2af9ab09
Java
mcerwenetz/SOE_Hastenteufel_HS-Mannheim
/Studienleistung2/Bank.java
UTF-8
1,593
3.40625
3
[]
no_license
package Studienleistung2; import java.util.List; abstract class Bank{ protected List<Konto> kontoliste; public Bank(){ } // Returncodes: // 0 = kein fehler // 1 = konto nicht gefunden // 2 = konto gefunden aber falsche pin // 3 = konto gefunden, richtige pin aber konto nicht aktiv public int validiereKonto(String kontonummer, String pin){ Konto k = this.getKonto(kontonummer); if(k != null){ // Konto gefunden if(k.getPin().equals(pin)){ //Pin richtig if(k.getIsaktiv()){ //Konto aktiv return 0; }else{ //Konto inaktiv return 3; } }else{ //pin falsch return 2; } } else{ return 1; } } abstract double berechneGebuehr(int betrag); public List<Konto> getKontoliste() { return kontoliste; } public Konto getKonto(String kontoNummer){ for (Konto i : this.kontoliste){ if(i.getKontonummer().equals(kontoNummer)){ return(i); } } return(null); } @Override public String toString() { return "Bank [kontoliste=" + kontoliste + "]" + "\n"; } public void sperreKonto(String kontonummer) { for(Konto k : this.kontoliste){ if(k.getKontonummer().equals(kontonummer)){ k.setIsaktiv(false); } } } }
true
0b15bcab5a44a2d98a3a8a7b7b7b53217d481b17
Java
yuxiaofeng19991117/StudentStatusManagement
/src/main/java/com/example/stumanage/controller/AdminController.java
UTF-8
1,237
2
2
[]
no_license
package com.example.stumanage.controller; import com.example.stumanage.vo.TbAdminVo; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; /** * 管理员跳转 * @author: zhangzengke * @date: 2018/2/1 **/ @RequestMapping("/admin") @Controller public class AdminController { @GetMapping("/list") public String getIndex(){ return "/stumanage/admin"; } @GetMapping("/setting") public String getSetting(HttpServletRequest request){ TbAdminVo tbAdminVo= (TbAdminVo)request.getSession().getAttribute("tbAdmin"); String admin="admin"; if((tbAdminVo.getUserName().equals(admin))){ return "/stumanage/setting"; } return "/stumanage/settings"; } @GetMapping("/index") public String index(){ return "/index"; } @GetMapping("/login") public String login(){ return "/login"; } @GetMapping("/logout") public String logout(HttpServletRequest request){ request.getSession().removeAttribute("tbAdmin"); return "/login"; } }
true
6ff7776631706b80c43988d5e6d69b44382fb55a
Java
gongmi/workSpace
/Hibernate/Hibernate_many2one/src/lee/many2one.java
WINDOWS-1252
819
2.09375
2
[]
no_license
package lee; import java.util.Date; import org.hibernate.*; import org.hibernate.cfg.*; import org.hibernate.service.*; import org.hibernate.boot.registry.*; import org.crazyit.app.domain.*; public class many2one { public static void main(String[] args) { many2one m2o = new many2one(); m2o.uni_fk(); HibernateUtil.closeSession(); HibernateUtil.sessionFactory.close(); } private void uni_fk() { Session session = HibernateUtil.currentSession(); Transaction tx = session.beginTransaction(); Group g=new Group(); User u= new User(); g.setName("С"); u.setName("gongmi"); u.setGroup(g); session.save(u); Group g2=new Group(); g2.setName(""); u.setGroup(g2); tx.commit(); HibernateUtil.closeSession(); } }
true
11d833a5a66f4a053eca450a4f1e596447d68495
Java
dabinett/WhoseTurn
/src/edu/unlv/cs/whoseturn/client/views/desktop/AdminPanel.java
UTF-8
836
2.421875
2
[]
no_license
package edu.unlv.cs.whoseturn.client.views.desktop; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; import edu.unlv.cs.whoseturn.client.views.AbstractNavigationView; import edu.unlv.cs.whoseturn.client.views.NavigationView; /** * Used to display stuff related to the administration of the program. */ public class AdminPanel extends AbstractNavigationView implements NavigationView { /** * @wbp.parser.entryPoint */ @Override public final Widget bodyAsWidget() { FlowPanel panel = new FlowPanel(); panel.setSize("1000px", "500px"); Label labelPlaceHolder = new Label(); labelPlaceHolder.setText("Admin Panel"); panel.add(labelPlaceHolder); return panel; } }
true
85acd08734911f74a0fdec5b35084a769f2b0b08
Java
rasi10/librarytest
/selenidetest/src/main/java/se/nackademin/librarytest/pages/MyProfilePage.java
UTF-8
1,551
1.914063
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 se.nackademin.librarytest.pages; import com.codeborne.selenide.SelenideElement; import org.openqa.selenium.support.FindBy; /** * @author testautomatisering */ public class MyProfilePage extends MenuPage { @FindBy(css = "#gwt-uid-5") SelenideElement userNameText; @FindBy(css = "#gwt-uid-7") SelenideElement firstNameText; @FindBy(css = "#gwt-uid-9") SelenideElement lastNameText; @FindBy(css = "#gwt-uid-11") SelenideElement phoneNumberText; @FindBy(css = "#gwt-uid-13") SelenideElement emailText; @FindBy(css = "#edit-user") SelenideElement editProfileButton; public String getUserName() { return getTextValue("user name", userNameText); //return userNameText.getText(); } public String getFirstName() { return getTextValue("first name", firstNameText); } public String getlasTName() { return getTextValue("last name", lastNameText); } public String getPhoneNumber() { return getTextValue("phone number", phoneNumberText); } public String getUserEmail() { return getTextValue("email", emailText); } public void clickEditProfileButton(){ clickButton("edit profile",editProfileButton ); } }
true
eae7fa2835546eabbd0debc2dd6a5757ffc81018
Java
bhartipriyadarshini/JavaSrc
/set1/K.java
UTF-8
256
2.53125
3
[]
no_license
class K { static int test() { System.out.println("main"); return 10; } public static void main(String args[]) { int i =test(); int j=10 +test(); System.out.println(test()); System.out.println(i); System.out.println(j); System.out.println(i+j+test()); } }
true
a4e07aabd0bafa8a220d486933ffb5eb3902a9f2
Java
junichi11/netbeans-php-enhancements
/src/com/junichi11/netbeans/php/enhancements/editor/completion/Parameters.java
UTF-8
6,374
1.515625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2019 junichi11. * * 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.junichi11.netbeans.php.enhancements.editor.completion; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.junichi11.netbeans.php.enhancements.options.PHPEnhancementsOptions; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author junichi11 */ public final class Parameters { private static final Logger LOGGER = Logger.getLogger(Parameters.class.getName()); public static final Map<String, List<Parameter>> PARAMETER_MAP = new HashMap<>(); public static final List<Parameter> DATE_FORMATS = new ArrayList<>(); public static final List<Parameter> TIMEZONES = new ArrayList<>(); public static final List<Parameter> PHPINI_DIRECTIVES = new ArrayList<>(); public static final List<Parameter> HTTP_HEADER_RESPONSES = new ArrayList<>(); public static final List<Parameter> HTTP_STATUS_CODES = new ArrayList<>(); public static final List<Parameter> HTTP_CHARSETS = new ArrayList<>(); public static final List<Parameter> HTTP_METHODS = new ArrayList<>(); public static final List<Parameter> HTTP_CACHE_CONTROL_DIRECTIVES = new ArrayList<>(); public static final List<Parameter> HTTP_LANGUAGES = new ArrayList<>(); public static final List<Parameter> ENCODINGS = new ArrayList<>(); public static final List<Parameter> CHARSETS = new ArrayList<>(); public static final List<Parameter> SUBSTCHARS = new ArrayList<>(); public static final List<Parameter> MB_LANGUAGES = new ArrayList<>(); public static final List<Parameter> MB_KANA_CONVERSIONS = new ArrayList<>(); public static final List<Parameter> MB_GET_INFO_TYPES = new ArrayList<>(); public static final List<Parameter> MB_HTTP_INPUT_TYPES = new ArrayList<>(); public static final List<Parameter> SESSION_CACHE_LIMITERS = new ArrayList<>(); public static final List<Parameter> MEDIA_TYPES = new ArrayList<>(); public static final List<Parameter> ENVS = new ArrayList<>(); private Parameters() { } static { if (PHPEnhancementsOptions.getInstance().isParametersCodeCompletion()) { load(); } } private static void load() { PARAMETER_MAP.clear(); buildParameterMap(); buildParameters(); for (String lang : Locale.getISOLanguages()) { HTTP_LANGUAGES.add(new Parameter(lang, "", "")); // NOI18N } PARAMETER_MAP.clear(); } public static void reload() { clear(); load(); } public static void clear() { PARAMETER_MAP.clear(); buildParameterMap(); for (Map.Entry<String, List<Parameter>> entry : PARAMETER_MAP.entrySet()) { List<Parameter> list = entry.getValue(); list.clear(); } PARAMETER_MAP.clear(); } private static void buildParameterMap() { // function PARAMETER_MAP.put("date_formats", DATE_FORMATS); // NOI18N PARAMETER_MAP.put("timezones", TIMEZONES); // NOI18N PARAMETER_MAP.put("phpini_directives", PHPINI_DIRECTIVES); // NOI18N PARAMETER_MAP.put("http_status_codes", HTTP_STATUS_CODES); // NOI18N PARAMETER_MAP.put("http_header_responses", HTTP_HEADER_RESPONSES); // NOI18N PARAMETER_MAP.put("http_charsets", HTTP_CHARSETS); // NOI18N PARAMETER_MAP.put("http_methods", HTTP_METHODS); // NOI18N PARAMETER_MAP.put("http_cache_control_directives", HTTP_CACHE_CONTROL_DIRECTIVES); // NOI18N PARAMETER_MAP.put("encodings", ENCODINGS); // NOI18N PARAMETER_MAP.put("charsets", CHARSETS); // NOI18N PARAMETER_MAP.put("substchars", SUBSTCHARS); // NOI18N PARAMETER_MAP.put("mb_languages", MB_LANGUAGES); // NOI18N PARAMETER_MAP.put("mb_kana_conversions", MB_KANA_CONVERSIONS); // NOI18N PARAMETER_MAP.put("mb_get_info_types", MB_GET_INFO_TYPES); // NOI18N PARAMETER_MAP.put("mb_http_input_types", MB_HTTP_INPUT_TYPES); // NOI18N PARAMETER_MAP.put("session_cache_limiters", SESSION_CACHE_LIMITERS); // NOI18N PARAMETER_MAP.put("media_types", MEDIA_TYPES); // NOI18N // array PARAMETER_MAP.put("envs", ENVS); // NOI18N } private static void buildParameters() { Gson gson = new Gson(); for (Map.Entry<String, List<Parameter>> entry : PARAMETER_MAP.entrySet()) { String target = entry.getKey(); List<Parameter> list = entry.getValue(); list.clear(); String filePath = String.format("resources/%s.json", target); // NOI18N URL resource = Function.class.getResource(filePath); if (resource == null) { continue; } try { InputStream inputStream = resource.openStream(); JsonReader jsonReader = new JsonReader(new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))); // NOI18N try { Type type = new TypeToken<ArrayList<Parameter>>() { }.getType(); ArrayList<Parameter> parameters = gson.fromJson(jsonReader, type); list.addAll(parameters); } finally { inputStream.close(); jsonReader.close(); } } catch (IOException ex) { LOGGER.log(Level.WARNING, ex.getMessage()); } } } }
true
89f9643ca356a158bfd807db6e09c22290372a82
Java
edimarbmjunior/Pedido-EICON
/src/test/java/com/edimar/pedido/controllers/PedidoControllerTest.java
UTF-8
6,713
2
2
[ "Apache-2.0" ]
permissive
package com.edimar.pedido.controllers; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.Arrays; import org.junit.Assert; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.RequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.edimar.pedido.builder.PedidoBuilder; import com.edimar.pedido.model.dto.PedidoBO; import com.edimar.pedido.repositories.PedidoRepository; import com.edimar.pedido.services.PedidoService; @RunWith(SpringRunner.class) @SpringBootTest @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class PedidoControllerTest { private MockMvc mockMvc; @Autowired private WebApplicationContext context; TestRestTemplate restTemplate = new TestRestTemplate(); HttpHeaders headers = new HttpHeaders(); private static String BASE_URL = "/pedido"; @InjectMocks @Spy private PedidoService pedidoService; @Mock private PedidoRepository produtoRepository; @Before public void setup() { MockitoAnnotations.initMocks(this); this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_JSON); } @Test public void teste01_deveRetornarSucesso_BuscaPedido() throws Exception { this.mockMvc.perform(get(BASE_URL+"/1")) .andExpect(status().isOk()) .andExpect(jsonPath("id", equalTo(1))); } @Test public void teste02_deveRetornarSucesso_BuscaPedido() throws Exception { this.mockMvc.perform(get(BASE_URL+"/todos") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); } @Test public void teste03_deveRetornarSucesso_SalvarPedido() throws Exception { this.mockMvc.perform(post(BASE_URL+"/salvarPedido") .content("{ \"dataCadastro\": \"25/05/2020\",\"codCliente\": 1,\"itemPedidos\": [{\"produtoBO\": {\"id\": 1},\"qtde\": 2},{\"produtoBO\": {\"id\": 3},\"qtde\": 7}]}") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(header().string("Location", is("http://localhost/pedido/salvarPedido/6"))); //.andDo(MockMvcResultHandlers.print()); } @Test public void teste04_deveRetornarError_SalvarPedido() throws Exception { this.mockMvc.perform(post(BASE_URL+"/salvarPedido") .content("{ \"dataCadastro\": \"25/05/2020\",\"codCliente\": 0,\"itemPedidos\": [{\"produtoBO\": {\"id\": 1},\"qtde\": 2},{\"produtoBO\": {\"id\": 3},\"qtde\": 7}]}") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isInternalServerError()); //.andDo(MockMvcResultHandlers.print()); } @Test public void teste05_deveRetornarSucesso_AtualizarPedido() throws Exception { this.mockMvc.perform(put(BASE_URL) .content("{ \"id\": 6,\"dataCadastro\": \"25/05/2020\",\"codCliente\": 3,\"itemPedidos\": [{\"produtoBO\": {\"id\": 5},\"qtde\": 3}]}") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); //.andDo(MockMvcResultHandlers.print()); } @Test public void teste06_deveRetornarError_AtualizarPedido() throws Exception { this.mockMvc.perform(put(BASE_URL) .content("{ \"id\": 9,\"dataCadastro\": \"25/05/2020\",\"codCliente\": 3,\"itemPedidos\": [{\"produtoBO\": {\"id\": 5},\"qtde\": 3}]}") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); //.andDo(MockMvcResultHandlers.print()); } @Test public void teste07_deveRetornarSucesso_DeletarProdutoPorId() throws Exception { this.mockMvc.perform(delete(BASE_URL+"/3")) .andExpect(status().isNoContent()); //.andDo(MockMvcResultHandlers.print()); } @Test public void teste08_XML_deveRetornarSucesso_BuscaProduto() throws Exception { PedidoBO pedido = PedidoBuilder.montaEntityPedidoBOTipo1().retornoEntityPedidoBO(); Mockito.doReturn(pedido).when(pedidoService).buscarPedidoPorId(Mockito.anyInt()); RequestBuilder requestBuilder = MockMvcRequestBuilders.get(BASE_URL+"/1").accept(MediaType.APPLICATION_XML); MvcResult result = mockMvc.perform(requestBuilder).andReturn(); System.out.println(result.getResponse()); String expected = "<PedidoBO><id>1</id><dataCadastro>05/10/2020</dataCadastro><numPedido>1</numPedido><codCliente>1</codCliente><valorTotalProdutos>29.5</valorTotalProdutos><itemPedidos><itemPedidos><qtde>1</qtde><valorTotalItensPedido>29.5</valorTotalItensPedido><produtoBO><id>1</id><descricao>Arroz</descricao><categoria>Alimento</categoria><preco>29.5</preco></produtoBO></itemPedidos></itemPedidos></PedidoBO>"; Assert.assertEquals(expected, result.getResponse().getContentAsString()); } @Test public void teste09_XML_deveRetornarSucesso_BuscaProduto() throws Exception { PedidoBO pedido = PedidoBuilder.montaEntityPedidoBOTipo1().retornoEntityPedidoBO(); Mockito.doReturn(Arrays.asList(pedido)).when(pedidoService).litarPedidos(); RequestBuilder requestBuilder = MockMvcRequestBuilders.get(BASE_URL+"/todos").accept(MediaType.APPLICATION_XML); MvcResult result = mockMvc.perform(requestBuilder).andReturn(); System.out.println(result.getResponse()); Assert.assertTrue(result.getResponse().getContentAsString().contains("<List><item><id>1</id>")); } }
true
f9fa48201374bf2b03209c6c7a9315dd6efa9033
Java
AngelAparicioDev/Estacionamiento
/src/main/java/com/ceiba/adn/estacionamiento/application/command/CreateTicketCommandHandler.java
UTF-8
1,285
2.203125
2
[]
no_license
package com.ceiba.adn.estacionamiento.application.command; import org.springframework.stereotype.Component; import com.ceiba.adn.estacionamiento.application.common.CommandResponse; import com.ceiba.adn.estacionamiento.application.common.commandhandleresponse.CommandHandleResponse; import com.ceiba.adn.estacionamiento.application.factory.TicketFactory; import com.ceiba.adn.estacionamiento.application.mapper.TicketCommandMapper; import com.ceiba.adn.estacionamiento.domain.entity.Ticket; import com.ceiba.adn.estacionamiento.domain.services.CreateTicketService; @Component public class CreateTicketCommandHandler implements CommandHandleResponse<TicketCommand, CommandResponse<TicketCommand>> { private final TicketFactory factory; private final CreateTicketService createTicketService; private static final TicketCommandMapper mapper = TicketCommandMapper.getInstance(); public CreateTicketCommandHandler(TicketFactory factory, CreateTicketService createTicketService) { this.factory = factory; this.createTicketService = createTicketService; } public CommandResponse<TicketCommand> exec(TicketCommand command) { Ticket ticket = this.factory.create(command); return new CommandResponse<>(mapper.toCommand(this.createTicketService.registerIncome(ticket))); } }
true
3a9ae6289ba87ed3e738b0a5d3db09e69a35f442
Java
RonaldoFaustino/Curso_Impacta
/Projeto3-operadores/src/Exercicios.java
UTF-8
305
3.28125
3
[]
no_license
public class Exercicios { public static void main(String[] args) { int valor1, valor2, resultado; valor1 = 100; valor2 = 200; resultado = valor1 + valor2; String numero = ( valor2 == 200? "Par":"Impar"); System.out.println(resultado); System.out.println(numero); } }
true
4e7253925fe8529d08a76010a6930e66d82f32a3
Java
juliatataritskaya/mymmz
/src/main/java/by/julia/bankservice/comand/LoginCommand.java
UTF-8
2,579
2.578125
3
[]
no_license
package by.julia.bankservice.comand; import by.julia.bankservice.util.ConfigurationManager; import by.julia.bankservice.util.MessageManager; import org.apache.log4j.Logger; import javax.servlet.http.HttpServletRequest; public class LoginCommand implements ActionCommand { private static Logger LOG = Logger.getLogger(LoginCommand.class); private static String PARAM_NAME_LOGIN = "login"; private static String PARAM_NAME_PASSWORD = "password"; private static final String ERROR_MESSAGE = "errorMessage"; private static final String MESSAGE = "message"; private static final String USER = "user"; private static final String USER_LOGIN = "userLogin"; private static final String ACCESS_LEVEL = "accessLevel"; @Override public String execute(HttpServletRequest request) { String page = null; VerifyAuthorization va = new VerifyAuthorization(); String login = request.getParameter(PARAM_NAME_LOGIN); String password = request.getParameter(PARAM_NAME_PASSWORD); LOG.debug("login = " + login + ", password = " + password); if (login == null || password == null || login.trim().length() == 0 || password.trim().length() == 0) { request.setAttribute(ERROR_MESSAGE, MessageManager.getInstance() .getProperty(MessageManager.NULL_DATA_ERROR_MESSAGES)); LOG.debug("Login is not entered"); page = ConfigurationManager.getInstance().getProperty( ConfigurationManager.AUTHORIZATION_PAGE_PATH); } else if (!va.verifyAuthorization(login, password)) { request.setAttribute( ERROR_MESSAGE, MessageManager.getInstance().getProperty( MessageManager.AUTHORIZATION_FALSE_ERROR_MESSAGES)); LOG.debug("Login or password is uncorrect"); page = ConfigurationManager.getInstance().getProperty( ConfigurationManager.AUTHORIZATION_PAGE_PATH); } else if (va.getLevel() == 0) { request.setAttribute(ERROR_MESSAGE, MessageManager.getInstance() .getProperty(MessageManager.USER_BLOCKED_ERROR_MESSAGES)); LOG.debug("User is blocked"); page = ConfigurationManager.getInstance().getProperty( ConfigurationManager.HOME_PAGE); } else { request.setAttribute(MESSAGE, MessageManager.getInstance() .getProperty(MessageManager.AUTHORIZATION_WAS_SUCCESS)); LOG.debug("Authorization is success"); request.getSession().setAttribute(USER, va.getUser()); request.getSession().setAttribute(USER_LOGIN, login); request.getSession().setAttribute(ACCESS_LEVEL, va.getLevel()); page = ConfigurationManager.getInstance().getProperty( ConfigurationManager.HOME_PAGE); } return page; } }
true
8b00a698f432423f6a2f484162bc34eb3b56cbee
Java
MarcoLotto/TecnicasDeDisenoTP0
/src/test/java/tecnicas/tp0/queueTestCase/QueueTestCase.java
UTF-8
1,727
2.78125
3
[]
no_license
package tecnicas.tp0.queueTestCase; import tecnicas.tp0.queue.Queue; import tecnicas.tp0.queue.TpQueue; import junit.framework.TestCase; public class QueueTestCase extends TestCase{ public void testSimple(){ Queue queue = new TpQueue(); queue.add("Item1"); queue.add("Item2"); queue.add("Item3"); assertEquals(3, queue.size()); assertEquals("Item1", queue.top()); queue.remove(); assertEquals(2, queue.size()); assertEquals("Item2", queue.top()); queue.remove(); assertEquals(1, queue.size()); assertEquals("Item3", queue.top()); queue.remove(); assertEquals(0, queue.size()); try{ queue.remove(); } catch(AssertionError e){ return; } fail(); } public void testComplex(){ Queue queue = new TpQueue(); queue.add("Item1"); queue.add("Item2"); queue.add("Item3"); assertEquals(3, queue.size()); assertEquals("Item1", queue.top()); queue.remove(); assertEquals(2, queue.size()); assertEquals("Item2", queue.top()); queue.add("Item4"); assertEquals(3, queue.size()); assertEquals("Item2", queue.top()); queue.remove(); assertEquals("Item3", queue.top()); queue.remove(); assertEquals(1, queue.size()); assertEquals("Item4", queue.top()); queue.remove(); assertEquals(0, queue.size()); try{ queue.remove(); fail(); } catch(AssertionError e){ } queue.add("Item5"); queue.add("Item6"); queue.remove(); assertEquals(1, queue.size()); assertEquals("Item6", queue.top()); queue.add("Item7"); assertEquals(2, queue.size()); assertEquals("Item6", queue.top()); queue.remove(); assertEquals("Item7", queue.top()); queue.remove(); try{ queue.top(); fail(); } catch(AssertionError e){ } } }
true
f8cf07aed5b42247ba42ce265371d0c13d5a1edf
Java
xiaoxiaoll1/corona-game
/src/test/java/com/xiaozijian/protectmycommunity/ProtectmycommunityApplicationTests.java
UTF-8
2,354
2.3125
2
[]
no_license
package com.xiaozijian.protectmycommunity; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class ProtectmycommunityApplicationTests { // // @Autowired // CacheHandler cacheHandler; // // @Autowired // RedisUtil redisUtil; // // @Autowired // StringRedisTemplate stringRedisTemplate; // // @Autowired // WordlistVocabulary wordlistVocabulary; // // @Test // void contextLoads() { // } // // @Test // void redisTest(){ // redisUtil.setRedisTemplate(stringRedisTemplate); // redisUtil.set("qmk","handsome"); // System.out.println(redisUtil.get("qmk")); // redisUtil.delete("qmk"); // // } // // //test for store the words into cache // @Test // void retrieveListFromDb(){ // redisUtil.setRedisTemplate(stringRedisTemplate); // Collection<HyphenationWord> wordlist = wordlistVocabulary.getAllWords("CET4"); // for (HyphenationWord wordEntry:wordlist){ // String listName=wordEntry.getWordListName(); // String word = wordEntry.getWord().trim(); // String hword = wordEntry.getHword().trim(); // System.out.println(word+":"+hword); // redisUtil.hPut(listName,word,hword); // } // } // // //try to retrieve a key which dose not exist at redis cache // @Test // void retrieveNotExistKey(){ // redisUtil.setRedisTemplate(stringRedisTemplate); // System.out.println(redisUtil.hKeys("CET5").isEmpty()); // } // // @Test // void testRerieveFromCache(){ // HashMap<String,String> result=new HashMap<String,String>(); // redisUtil.setRedisTemplate(stringRedisTemplate); // Set keys = redisUtil.hKeys("CET4"); // for (Object obj : keys){ // String word=(String)obj; // String hword=(String)redisUtil.hGet("CET4",word); // System.out.println(word+"::"+hword); // result.put(word,hword); // } // String param= JSON.toJSONString(result); // System.out.println(param); // // } // // @Test // void testCompleteProcess(){ // System.out.println(cacheHandler.retrieveList("CET4")); // } // // @Test // void updateTest(){ // redisUtil.setRedisTemplate(stringRedisTemplate); // cacheHandler.updateCache("CET4"); // } }
true
042f57a4f276512613465993047d96f73c829fcc
Java
oharasteve/eagle
/src/com/eagle/programmar/CMD/Statements/CMD_Call_Statement.java
UTF-8
1,175
2.21875
2
[ "Apache-2.0" ]
permissive
// Copyright Eagle Legacy Modernization LLC, 2010-date // Original author: Steven A. O'Hara, Jul 31, 2011 package com.eagle.programmar.CMD.Statements; import com.eagle.programmar.CMD.Terminals.CMD_Argument; import com.eagle.programmar.CMD.Terminals.CMD_Keyword; import com.eagle.tokens.TokenChooser; import com.eagle.tokens.TokenList; import com.eagle.tokens.TokenSequence; import com.eagle.tokens.punctuation.PunctuationColon; import com.eagle.tokens.punctuation.PunctuationHyphen; import com.eagle.tokens.punctuation.PunctuationSlash; public class CMD_Call_Statement extends TokenSequence { public @DOC("call.mspx") CMD_Keyword CALL = new CMD_Keyword("call"); public @OPT PunctuationColon colon; public CMD_Argument what; public @OPT TokenList<CMD_Call_Parameter> args; public static class CMD_Call_Parameter extends TokenChooser { public @CHOICE CMD_Argument arg; public @CHOICE static class CMD_Call_Minus_Option extends TokenSequence { public PunctuationHyphen minus; public CMD_Argument option; } public @CHOICE static class CMD_Call_Slash_Option extends TokenSequence { public PunctuationSlash slash; public CMD_Argument option; } } }
true
5c1da46422596270231b5d1971ec3c90ea8d2e50
Java
Likitha11/Playground
/Decrypt the message/Main.java
UTF-8
288
2.375
2
[]
no_license
#include<iostream> using namespace std; int main() { int m,n,s=0; cin>>m; cin>>n; int f=m+n; for(int i=1;i<f;i++) { if(f%i==0) { s=s+i; } } if(s==f) cout<<"They can read the message"; else cout<<"They can't read the message"; return 0; }
true
38e57b152adfdbbcbf2e814c3872dfc7bf004ba4
Java
DongHaiShen/CodeingInterviews
/src/26_SubstructureInTree/SubstructureInTreeTest.java
UTF-8
1,384
3
3
[]
no_license
/** * @Author sdh * @Date Created in 2019/2/27 10:37 * @description */ public class SubstructureInTreeTest { public static void main(String[] args) { SubstructureInTree test = new SubstructureInTree(); TreeNode root1 = new TreeNode(); root1.val = 8; root1.right = new TreeNode(); root1.right.val = 7; root1.left = new TreeNode(); root1.left.val = 8; root1.left.left = new TreeNode(); root1.left.left.val = 9; root1.left.right = new TreeNode(); root1.left.right.val = 2; root1.left.right.left = new TreeNode(); root1.left.right.left.left = new TreeNode(); root1.left.right.left.left.val = 4; root1.left.right.left.right = new TreeNode(); root1.left.right.left.right.val = 7; TreeNode root2 = new TreeNode(); root2.val = 8; root2.left = new TreeNode(); root2.left.val = 9; root2.right = new TreeNode(); root2.right.val = 2; System.out.println(test.hasSubtree(root1, root2)); System.out.println(test.hasSubtree(root2, root1)); System.out.println(test.hasSubtree(root1, root1.left)); System.out.println(test.hasSubtree(root1, null)); System.out.println(test.hasSubtree(null, root2)); System.out.println(test.hasSubtree(null, null)); } }
true
885910aee98309057e2458f28d0b27ef6f93b9d5
Java
katsuunhi/Java-Art-Examples
/Java_Art_Examples/Ch12/ch12/EnumTest2.java
GB18030
566
3.40625
3
[]
no_license
package ch12; import static ch12.DiscountType2.*; //̬ import java.util.EnumSet; //ʹEnumSetķrange() public class EnumTest2 { public static void main( String args[] ) { for(DiscountType2 type : DiscountType2.values()) //values() System.out.println("type: " + type.getExplain() + " rate: " + type.getRate()); //EnumSetrange() for(DiscountType2 type : EnumSet.range(EXTRA_DISCOUNT, SUPER_DISCOUNT)) System.out.println("type: " + type.getExplain() + ", rate: " + type.getRate()); } }
true
17bb808babbb0dfdd2e60503b29cecdd175385c6
Java
josephrubin/gameutils
/src/main/java/box/shoe/gameutils/ai/Outcome.java
UTF-8
177
2
2
[]
no_license
package box.shoe.gameutils.ai; /* pack */ class Outcome { public final Behavior BEHAVIOR; public Outcome(Behavior behavior) { BEHAVIOR = behavior; } }
true
5f47a1e9d6a4cd1fdf9cd851b1769b1907e21daf
Java
jitendrakr93/InnerClasses
/src/com/jit/inner03/Test.java
UTF-8
194
2.296875
2
[]
no_license
package com.jit.inner03; public class Test { public static void main(String[] args) { Outer o = new Outer(); Outer.Inner i = o.new Inner(); i.m1(); new Outer().new Inner().m1(); } }
true
521ab38c5582fcac03b988a08ab07a7cb6498828
Java
sjb3/java142_repo
/HW01_BYUN/mantra.java
UTF-8
520
2.734375
3
[]
no_license
/** * CSC 142 * Sung Justin Byun No partner at this stage * HW#1 Last updated 09/27 * appx. 5 hours total * Used IDE: IntelliJIDEA(Eclipse) **/ // Mantra //////////////// public class Mantra { public static void main(String[] args) { System.out.println("7. Mantra:"); mantra_str(); System.out.println(); mantra_str(); } public static void mantra_str() { System.out.println("There\'s one thing every coder must understand:\nThe system.outprintln commnand."); } }
true
dc976b881f889feb21ee8dea42cd102b714e200a
Java
thimda/rsd_web
/ba/src/public/nc/uap/lfw/login/authfield/ComboExtAuthField.java
GB18030
818
2.03125
2
[]
no_license
package nc.uap.lfw.login.authfield; /** * ֶ֤ * @author dengjt * 2006-4-18 */ public class ComboExtAuthField extends ExtAuthField { private static final long serialVersionUID = -8079924277920349800L; private String[][] options = null; private int selectedIndex = -1; public ComboExtAuthField() { super(); } public ComboExtAuthField(String label, String name, boolean required) { super(label, name, required); } public String[][] getOptions() { return options; } public void setOptions(String[][] options) { this.options = options; } public int getSelectedIndex() { return selectedIndex; } public void setSelectedIndex(int selectedIndex) { this.selectedIndex = selectedIndex; } @Override public int getType() { return ExtAuthFiledTypeConst.TYPE_CHOOSE; } }
true
5cb2c7a108e5c253f6bd42f51d9201426e09eb0a
Java
felipergil/heranca1
/src/metodista/br/Desktop.java
UTF-8
1,294
2.984375
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package metodista.br; /** * * @author 248543 */ public class Desktop extends Computador { private String corGabinete; private int potenciaFonteEnergia; public Desktop(int velocidade, int memoria, String fabricante) { super(velocidade, memoria, fabricante); this.corGabinete = "Branco"; this.potenciaFonteEnergia = 400; } public Desktop(int velocidade, int memoria, String fabricante, String cor, int potencia) { super(velocidade, memoria, fabricante); this.corGabinete = cor; this.potenciaFonteEnergia = potencia; } public String getCorGabinete() { return this.corGabinete; } public int getPotenciaFonteEnergia(){ return this.potenciaFonteEnergia; } public String informacoesCompletas() { return "Sou um desktop. Meu processador " + super.getFabricanteProcessador() + " trabalho a uma velocidade " + super.getVelocidadeDeProcessador() + " Possuo " + super.getQuantidadeDeMemoria() + "Mb de memória. " + "Meu gabinete é de cor " + corGabinete + "."; } }
true
f345e664f4a743229b96c64ff86fa1751addee72
Java
zhouhualing/SmartElectricSystem
/smarthome/src/main/java/com/harmazing/spms/ifttt/dto/SpmsIftttDeviceDTO.java
UTF-8
377
2.09375
2
[]
no_license
package com.harmazing.spms.ifttt.dto; import java.io.Serializable; public class SpmsIftttDeviceDTO implements Serializable { private String mac; private Integer type; public String getMac() { return mac; } public void setMac(String mac) { this.mac = mac; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } }
true
f05be9efa1355e512284ef531e7cc5f3d8584534
Java
Vadzka500/extime-andriod-bug_fixes_2
/app/src/main/java/ai/extime/Receivers/OpenVoice.java
UTF-8
406
1.867188
2
[]
no_license
package ai.extime.Receivers; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import org.greenrobot.eventbus.EventBus; import ai.extime.Events.SetVoicePush; public class OpenVoice extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { EventBus.getDefault().post(new SetVoicePush()); } }
true
9b6ea055d77e4eb7f90d4379889df8b1c798e0b2
Java
ProximaHaiz/online_library
/src/main/java/online_lib/beans/BookList.java
UTF-8
2,518
2.609375
3
[]
no_license
package online_lib.beans; import online_lib.db.DbConnection; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by Proxima on 14.03.2016. */ public class BookList { private List<Book> bookList = new ArrayList<>(); public BookList() { } private List<Book> getBooks(String query) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = DbConnection.getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(query); while (rs.next()) { Book book = new Book(); book.setId(rs.getLong("id")); book.setName(rs.getString("name")); book.setGenre(rs.getString("genre")); book.setIsbn(rs.getString("isbn")); book.setAuthor(rs.getString("author")); book.setPageCount(rs.getInt("page_count")); book.setPublich_Date(rs.getInt("publish_year")); book.setPublisher(rs.getString("publisher")); book.setImage(rs.getBytes("image")); bookList.add(book); } } catch (SQLException e) { Logger.getLogger(BookList.class.getName()).log(Level.SEVERE, null, e); e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return bookList; } public List<Book> getAllBook() { if (!bookList.isEmpty()) { return bookList; } else { return getBooks("Select * from book order by name"); } } public List<Book> getBooksByGenre(long id) {; return getBooks("select b.id,b.name,b.isbn,b.page_count,b.publish_year, p.name as publisher, a.fio as author, g.name as genre, b.image from book b " + "inner join author a on b.author_id=a.id " + "inner join genre g on b.genre_id=g.id " + "inner join publisher p on b.publisher_id=p.id " + "where genre_id=" + id + " order by b.name " + "limit 0,5"); } }
true
b2b2a51c070705f28f38cae581adf4748eb11de9
Java
lvsravikanth/freequent
/src/com/scalar/core/response/MessageResponse.java
UTF-8
3,413
2.71875
3
[]
no_license
package com.scalar.core.response; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.Map; import java.io.Writer; import com.scalar.core.ScalarActionException; /** * User: Sujan Kumar Suppala * Date: Oct 1, 2013 * Time: 8:03:53 PM * * The <code>MessageResponse</code> class extends <code>AbstractResponse</code> to implement message output. * <p> * The message is provided by {@link #getMessage()}. * */ public class MessageResponse extends AbstractResponse { protected static final Log logger = LogFactory.getLog(MessageResponse.class); /** * Constant used to load and output the message from the {@link com.vignette.ui.core.action.Action} data. * * @see #load * @see #getOutputAttributes() */ protected static final String MESSAGE = "vui.message"; /** * Constant used as the tag name for this <code>Response</code>. * * @see #getTag() */ protected static final String VUI_MESSAGE = "vuiMessage"; /** * Constant used for message attribute output. */ protected static final String MESSAGE_ATTRIBUTE = "message"; /** * The message to use as output. */ protected String message = null; /** * Prepares the data with the provided message. * * @param data the data to prepare * @param message the message */ public static void prepareData(Map<String, Object> data, String message) { data.put(MESSAGE, message); } /** * Returns <code>true</code> if the data <code>Map</code> has message response data, otherwise <code>false</code>. * * @param data the data * @return <code>true</code> if the data <code>Map</code> has message response data, otherwise <code>false</code> */ public static boolean hasMessageData(Map<String, Object> data) { return ( null != data.get(MESSAGE) ); } /** * Constructs a new <code>MessageResponse</code>. This is the default constructor. */ public MessageResponse() { } /** * Constructs a new <code>MessageResponse</code> with the given message. * * @param message the message */ public MessageResponse(String message) { setMessage(message); } @Override public String getTag() { return VUI_MESSAGE; } /** * Creates no output for this <code>Response</code>. The actual output occurs in * {@link #getOutputAttributes()}. */ public void createOutput(Writer writer) throws ScalarActionException { // Nothing to do here } /** * Adds the message as an attribute to the <code>Response</code> output. The attribute name is {@link #MESSAGE}. */ @Override public Map<String, String> getOutputAttributes() { Map<String, String> attributes = super.getOutputAttributes(); attributes.put(MESSAGE_ATTRIBUTE, getMessage()); return attributes; } /** * Loads the message data for this <code>Response</code>. */ @Override public void load(Map<String, Object> loadData) { super.load(loadData); setMessage(getValue(MESSAGE)); } /** * Sets the message to use as output. * * @param message the message * @see #getMessage() */ public void setMessage(String message) { this.message = message; } /** * Returns the message to use as output. * * @return the message * @see #setMessage(String) */ public String getMessage() { return message; } }
true
350bca8797976e3568ac1c04159d97cc0c98e81a
Java
Damboooo/OOD
/Code/src/UI/HeadManager/ProjectsListWindow.java
UTF-8
2,521
2.515625
3
[]
no_license
package UI.HeadManager; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.*; import ProjectManagement.Module; import ProjectManagement.Project; import ProjectManagement.ProjectCatalogue; import ResourceManagement.Resource; import ResourceManagement.User; import UI.ProjectManager.ProjectDetailsWindow; public class ProjectsListWindow extends UI.Employee.UserWindow { private JLabel[] labels = new JLabel[6]; private ArrayList<JButton> editButtons = new ArrayList<>(); private int counter; private JLabel label; private JButton searchButton; private JTextField searchTextField; private ArrayList<Project> projects; public ProjectsListWindow (User user) { super(user); setTitle("پنل مدیریت پروژه"); // Rectangle r = new Rectangle(0, 0, 100, 100); // super.panel.add(r); projects = ProjectCatalogue.getInstance().getProjectList(); label = new JLabel("لیست پروژه ها"); label.setSize(60, 25); label.setLocation(600, 90); super.panel.add(label); searchTextField = new JTextField(); searchTextField.setSize(300, 25); searchTextField.setLocation(250, 150); super.panel.add(searchTextField); searchButton = new JButton("جستجو"); searchButton.setSize(65, 25); searchButton.setLocation(200, 150); super.panel.add(searchButton); // ==================================> خوندن از دیتابیس for (counter = 0; counter < projects.size(); counter++) { JButton editButton = new JButton(projects.get(counter).getName()); editButton.setSize(180, 25); editButton.setLocation(300, 200 + 30 * counter); editButton.addActionListener(new ActionListener() { Project p = projects.get(counter); public void actionPerformed(ActionEvent e) { editProject(p); } }); editButtons.add(editButton); super.panel.add(editButton); } } private JLabel createLabel(String s, int x, int y) { JLabel label = new JLabel(s); label.setSize(90, 25); label.setLocation(x, y); panel.add(label); return label; } @Override public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; super.paint(g2); Stroke dashed = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] { 5 }, 0); g2.setStroke(dashed); g2.drawRect(115, 150, 560, 370); } public void editProject(Project project) { new ProjectDetailsWindow(user, project); } public void search() { } }
true
0cc84575806eae621520792567a06520dc5e2f23
Java
JohnnyGuye/code-of-kutulu
/codeOfKutulu/src/main/java/codeofkutulu/mazes/TooSmallForUsTwo.java
UTF-8
565
2.328125
2
[]
no_license
package codeofkutulu.mazes; public class TooSmallForUsTwo extends Maze { final static String[] map = { "###############", "#.....#U#.....#", "#.#w###.###w#.#", "#..##.....##..#", "#.##..#.#..##.#", "#.#..##.##..#.#", "#.#.###.###.#.#", "#.............#", "#.#.###.###.#.#", "#.#S#.#.#.#S#.#", "#.###.#.#.###.#", "#.............#", "###.###.###.###", "#....##.##....#", "#.##.......##.#", "###############" }; @Override public String[] getMap(){ return map; } public TooSmallForUsTwo() { super("Too small for us two"); } }
true
50e78a381f9fb160488f8f62702f6b3007265da4
Java
LeandroMuC/curriculum-backend
/src/main/java/com/curriculum/ficha/model/CasoFicha.java
UTF-8
1,248
2.234375
2
[]
no_license
package com.curriculum.ficha.model; import java.time.LocalDateTime; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name= "caso_ficha") public class CasoFicha { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer idCasoFicha; @ManyToOne @JoinColumn(name="id_caso",nullable=false) private Caso caso; @ManyToOne @JoinColumn(name="id_ficha",nullable=false) private Ficha ficha; @Column(name="inser_time",nullable=false) private LocalDateTime insertTime; public Integer getIdCasoFicha() { return idCasoFicha; } public void setIdCasoFicha(Integer idCasoFicha) { this.idCasoFicha = idCasoFicha; } public Caso getCaso() { return caso; } public void setCaso(Caso caso) { this.caso = caso; } public Ficha getFicha() { return ficha; } public void setFicha(Ficha ficha) { this.ficha = ficha; } public LocalDateTime getInsertTime() { return insertTime; } public void setInsertTime(LocalDateTime insertTime) { this.insertTime = insertTime; } }
true
03f58f52ef2c580b9d803892093aaf701800df8a
Java
ssaykos/2015_03sulofstudy
/학원수업(설진욱샘)/src/_1주/_2일차_4PlusMinus01.java
WINDOWS-1252
1,049
3.34375
3
[]
no_license
package _1; public class _2_4PlusMinus01 { public static void main(String[] args) { // TODO Auto-generated method stub int a=10; int b=20; int c; c= ++a + b++;//c=11+20=31 System.out.println("a:"+a);//11 System.out.println("b:"+b);//21 System.out.println("c:"+c);//31 System.out.println("-----"); c= a++ + --b;//c=11+20=31 System.out.println("a:"+a);//12 System.out.println("b:"+b);//20 System.out.println("c:"+c);//31 System.out.println("-----"); a=15; b=12; c= --a + --b;//c=14+11=25 System.out.println("a:"+a);//14 System.out.println("b:"+b);//11 System.out.println("c:"+c);//25 System.out.println("-----"); int x=3, y=5,z; z= x++ + --y;//z=3+4=7 System.out.println("x:"+x);//4 System.out.println("y:"+y);//4 System.out.println("z:"+z);//7 System.out.println("-----"); z+= --x + y++;//z=7+3+4=14 System.out.println("x:"+x);//3 System.out.println("y:"+y);//5 System.out.println("z:"+z);//14 } }
true
f79b7701b624cff101c6648ee02fde462aa62ee2
Java
VladanStar/ProducerConsumerThread
/KupacProizvodjac/src/com/company/Main.java
UTF-8
354
1.890625
2
[]
no_license
package com.company; public class Main { public static void main(String[] args) { // write your code here Proizvod proizvod = new Proizvod(); Proizvodjac proizvodjac = new Proizvodjac(proizvod,1); Potrosac potrosac = new Potrosac(proizvod,1); potrosac.start(); proizvodjac.start(); } }
true