blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b31a625b8e27470f0d8b8fc866e1ae3558f3d648 | 20,469,814,187,633 | 6eab96dee264d655de26787a83fd55a486a79be4 | /app/src/main/java/com/tck/erpmanager/net/model/GetGoodsListModelImpl.java | cbbdfe521940b05b7358edee7fa00f5a11d62e06 | []
| no_license | tck8888/ERPManager | https://github.com/tck8888/ERPManager | 6a61f11cd24944f3789c177a1045cbcdaf4785c6 | 24f05a0508ebe08871732bfcd45cb68891b0e131 | refs/heads/master | 2021-01-01T17:45:51.594000 | 2017-11-11T01:36:09 | 2017-11-11T01:36:09 | 98,152,003 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tck.erpmanager.net.model;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.model.Response;
import com.tck.commonlibrary.base.MyCallBack;
import com.tck.commonlibrary.common.CommonConstant;
import com.tck.commonlibrary.common.HttpUrlList;
import com.tck.commonlibrary.utils.AppSharePreferenceMgr;
import com.tck.commonlibrary.utils.GsonUtil;
import com.tck.erpmanager.ERPApp;
import com.tck.erpmanager.bean.ProductListBean;
import com.tck.erpmanager.net.contract.ProductContract;
/**
* Created by tck on 2017/6/26.
*/
public class GetGoodsListModelImpl implements ProductContract.GetGoodsListModel {
@Override
public void getGoodsList(final MyCallBack<ProductListBean> myCallBack) {
OkGo.<ProductListBean>get(HttpUrlList.ProductModule.GET_GOODS_LIST)
.tag(this)
.params("userId", (Integer) AppSharePreferenceMgr.get(ERPApp.getContext(), CommonConstant.KEY_USER_ID, -1))
.execute(new AbsCallback<ProductListBean>() {
@Override
public void onSuccess(Response<ProductListBean> response) {
myCallBack.showSuccess(response.body());
}
@Override
public ProductListBean convertResponse(okhttp3.Response response) throws Throwable {
return GsonUtil.GsonToBean(response.body().string(), ProductListBean.class);
}
@Override
public void onError(Response<ProductListBean> response) {
super.onError(response);
if (response != null) {
myCallBack.showError(response.message());
}
}
});
}
}
| UTF-8 | Java | 1,844 | java | GetGoodsListModelImpl.java | Java | [
{
"context": "r.net.contract.ProductContract;\n\n/**\n * Created by tck on 2017/6/26.\n */\n\npublic class GetGoodsListModel",
"end": 554,
"score": 0.9995120763778687,
"start": 551,
"tag": "USERNAME",
"value": "tck"
}
]
| null | []
| package com.tck.erpmanager.net.model;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.model.Response;
import com.tck.commonlibrary.base.MyCallBack;
import com.tck.commonlibrary.common.CommonConstant;
import com.tck.commonlibrary.common.HttpUrlList;
import com.tck.commonlibrary.utils.AppSharePreferenceMgr;
import com.tck.commonlibrary.utils.GsonUtil;
import com.tck.erpmanager.ERPApp;
import com.tck.erpmanager.bean.ProductListBean;
import com.tck.erpmanager.net.contract.ProductContract;
/**
* Created by tck on 2017/6/26.
*/
public class GetGoodsListModelImpl implements ProductContract.GetGoodsListModel {
@Override
public void getGoodsList(final MyCallBack<ProductListBean> myCallBack) {
OkGo.<ProductListBean>get(HttpUrlList.ProductModule.GET_GOODS_LIST)
.tag(this)
.params("userId", (Integer) AppSharePreferenceMgr.get(ERPApp.getContext(), CommonConstant.KEY_USER_ID, -1))
.execute(new AbsCallback<ProductListBean>() {
@Override
public void onSuccess(Response<ProductListBean> response) {
myCallBack.showSuccess(response.body());
}
@Override
public ProductListBean convertResponse(okhttp3.Response response) throws Throwable {
return GsonUtil.GsonToBean(response.body().string(), ProductListBean.class);
}
@Override
public void onError(Response<ProductListBean> response) {
super.onError(response);
if (response != null) {
myCallBack.showError(response.message());
}
}
});
}
}
| 1,844 | 0.626356 | 0.621475 | 46 | 39.086956 | 30.542078 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.456522 | false | false | 3 |
363f412dd3180b75a28d3045aaff872871da9682 | 16,630,113,437,084 | 9fbd38d3477c25d9e0ec3532c2e19ff658edcbbe | /jawn/chess/src/chess/queen.java | 41db3f27675cf68043ae98a37e248dc44e9e31c7 | []
| no_license | adambombz/randochessjavashit | https://github.com/adambombz/randochessjavashit | f55cee951d2504d7b1d69e8ac6eaea4f27ffb96b | a9c79f391af4bd9a9041e5ccdf611a0e6722966b | refs/heads/master | 2020-08-03T04:28:05.474000 | 2019-09-29T08:37:41 | 2019-09-29T08:37:41 | 211,625,072 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package chess;
import info.gridworld.actor.ActorWorld;
import info.gridworld.actor.Critter;
import info.gridworld.grid.Location;
import java.util.ArrayList;
/**
*
* @author baxteac
*/
public class queen extends Critter implements Piece{
String name="Queen";
@Override
public boolean canMove(int x, int y, int num, ActorWorld world) {
boolean c=false;
Location go=new Location(x,y);
int temp=getLocation().getRow()-x;
if(getLocation().getRow()==x||getLocation().getCol()==y||getLocation().getCol()-y==temp||getLocation().getCol()-y==-temp){
c=true;
}
if(c&&world.getGrid().get(go) instanceof Piece&&world.getGrid().get(go).getColor()==getColor()){
c=false;
}
return c&&!between(new Location(x,y),world);
}
public boolean between(Location loc,ActorWorld world){
boolean c=false;
Location start = getLocation();
int dir=start.getDirectionToward(loc);
while(!start.equals(loc.getAdjacentLocation((dir+180)%360))&&world.getGrid().isValid(start.getAdjacentLocation(dir))){
start=start.getAdjacentLocation(dir);
if(world.getGrid().get(start) instanceof Piece){
c=true;
break;
}
}
return c;
}
public String getName(){
return name;
}
public ArrayList<Location> possibleMoves(int num,ActorWorld world){
ArrayList<Location> moves=new ArrayList<Location>();
for(int i=1;i<9;i++){
for(int j=1;j<9;j++){
if(canMove(i,j,num,world)){
moves.add(new Location(i,j));
}
}
}
return moves;
}
public void act(){
}
public ArrayList<Location> betweenLocations(Location loc,ActorWorld world){
ArrayList<Location> moves=new ArrayList<Location>();
Location start = getLocation();
int dir=start.getDirectionToward(loc);
while(!start.equals(loc.getAdjacentLocation((dir+180)%360))&&world.getGrid().isValid(start.getAdjacentLocation(dir))){
start=start.getAdjacentLocation(dir);
moves.add(start);
if(world.getGrid().get(start) instanceof Piece){
break;
}
}
return moves;
}
}
| UTF-8 | Java | 2,236 | java | queen.java | Java | [
{
"context": "\n\nimport java.util.ArrayList;\n\n\n\n/**\n *\n * @author baxteac\n */\npublic class queen extends Critter implements",
"end": 287,
"score": 0.9996299147605896,
"start": 280,
"tag": "USERNAME",
"value": "baxteac"
}
]
| null | []
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package chess;
import info.gridworld.actor.ActorWorld;
import info.gridworld.actor.Critter;
import info.gridworld.grid.Location;
import java.util.ArrayList;
/**
*
* @author baxteac
*/
public class queen extends Critter implements Piece{
String name="Queen";
@Override
public boolean canMove(int x, int y, int num, ActorWorld world) {
boolean c=false;
Location go=new Location(x,y);
int temp=getLocation().getRow()-x;
if(getLocation().getRow()==x||getLocation().getCol()==y||getLocation().getCol()-y==temp||getLocation().getCol()-y==-temp){
c=true;
}
if(c&&world.getGrid().get(go) instanceof Piece&&world.getGrid().get(go).getColor()==getColor()){
c=false;
}
return c&&!between(new Location(x,y),world);
}
public boolean between(Location loc,ActorWorld world){
boolean c=false;
Location start = getLocation();
int dir=start.getDirectionToward(loc);
while(!start.equals(loc.getAdjacentLocation((dir+180)%360))&&world.getGrid().isValid(start.getAdjacentLocation(dir))){
start=start.getAdjacentLocation(dir);
if(world.getGrid().get(start) instanceof Piece){
c=true;
break;
}
}
return c;
}
public String getName(){
return name;
}
public ArrayList<Location> possibleMoves(int num,ActorWorld world){
ArrayList<Location> moves=new ArrayList<Location>();
for(int i=1;i<9;i++){
for(int j=1;j<9;j++){
if(canMove(i,j,num,world)){
moves.add(new Location(i,j));
}
}
}
return moves;
}
public void act(){
}
public ArrayList<Location> betweenLocations(Location loc,ActorWorld world){
ArrayList<Location> moves=new ArrayList<Location>();
Location start = getLocation();
int dir=start.getDirectionToward(loc);
while(!start.equals(loc.getAdjacentLocation((dir+180)%360))&&world.getGrid().isValid(start.getAdjacentLocation(dir))){
start=start.getAdjacentLocation(dir);
moves.add(start);
if(world.getGrid().get(start) instanceof Piece){
break;
}
}
return moves;
}
}
| 2,236 | 0.646691 | 0.639535 | 77 | 28.038961 | 29.313107 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.636364 | false | false | 3 |
eb55b173608cd0750bf551f32d92f4829ec2544e | 8,684,423,905,307 | e026076bcd5968d5c45f03b1f631a4bff6578a61 | /hw3/q2/SimpleTextEditor.java | 50c89e3d0def8cd057c8060a482e2eff6825c7a0 | []
| no_license | ElifKeles/Java-Assignments | https://github.com/ElifKeles/Java-Assignments | cf5c7c423f6370fc234ec07aee35b774b618c217 | bc27ff46d9685a8af2ffa20dd1d45635486006a1 | refs/heads/main | 2023-03-15T20:43:52.437000 | 2021-03-09T16:06:58 | 2021-03-09T16:06:58 | 346,059,151 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;
/**
*SimpleTextEditor class which provides the some of the edit functionality of a text editor.
*/
public class SimpleTextEditor
{
//Data fields
List<Character> listOfCharacters;
//Methods
public SimpleTextEditor(List newList)
{
listOfCharacters=newList;
}
/**
* reads a text file and construct the text.
* @param fileName name of file to be read
* @return 0 if successful, -1 if the text is empty
*/
public int read(String fileName)
{
StringBuilder data= new StringBuilder("");
try
{
File fileObj = new File(fileName);
Scanner myReader = new Scanner(fileObj);
while (myReader.hasNextLine())
{
data.append(myReader.nextLine() );
}
//loop
//construct the text
for(int i=0;i<data.length();i++)
{
listOfCharacters.add(data.charAt(i));
}
if(listOfCharacters.isEmpty() )
{
System.out.println("The text is empty");
return -1;
}
System.out.println(listOfCharacters);
myReader.close();
}
catch (FileNotFoundException e)
{
System.out.println("An error occurred.");
e.printStackTrace();
}
return 0;
}
/**
* reads a text file and construct the text.
* With iterator
* @param fileName name of file to be read
* @param iter iterator object reference
* @return 0 if successful, -1 if the text is empty
*/
public int read(String fileName, ListIterator iter)
{StringBuilder data= new StringBuilder("");
try
{
File fileObj = new File(fileName);
Scanner myReader = new Scanner(fileObj);
while (myReader.hasNextLine())
{
data.append(myReader.nextLine() );
}
//initialize iterator
iter= listOfCharacters.listIterator();
//construct the text
for(int i=0;i<data.length();i++)
{
iter.add(data.charAt(i));
}
if(listOfCharacters.isEmpty() )
{
System.out.println("The text is empty");
return -1;
}
System.out.println(listOfCharacters);
myReader.close();
}
catch (FileNotFoundException e)
{
System.out.println("An error occurred.");
e.printStackTrace();
}
return 0;
}
/**
* adds one or more characters at the specified
* position in text.
* @param ch character or characters to add to text
* @param index position to add the characters
* @return 0 if adding successful, -1 if not
*/
public int add(String ch, int index)
{
if(listOfCharacters.isEmpty())
{
return -1;
}
for (int i=0; i<ch.length(); ++i)
{
listOfCharacters.add(index, ch.charAt(i));
index++;
}
System.out.println(listOfCharacters);
return 0;
}
/**
* adds one or more characters at the specified
* position in text. With iterator.
* @param ch character or characters to add to text
* @param index position to add the characters
* @param iter iterator object reference
* @return 0 if adding successful, -1 if not
*/
public int add(String ch, int index, ListIterator iter)
{
if(listOfCharacters.isEmpty())
{
return -1;
}
//initialize iterator
iter= listOfCharacters.listIterator(index);
int i=0;
while (iter.hasNext())
{
iter.add(ch.charAt(i));
i++;
if(i== ch.length())
break;
}
System.out.println(listOfCharacters);
return 0;
}
/**
* Looks for a group of characters in list
* @param ch group of characters that will be searched in the list
* @return the start index of the first occurrence of the searched group of characters.
* If the searched characters is not in the list, returns -1
*/
public int find(String ch)
{
boolean flag=false;
for (int i=0; i<listOfCharacters.size(); ++i)
{
for(int j=0; j<ch.length(); ++j)
{
if(listOfCharacters.get(i+j)== ch.charAt(j))
flag=true;
else
{
flag=false;
break;
}
}
if(flag)
{
return i;
}
}
return -1;
}
/**
* Looks for a group of characters in list. With iterator
* @param ch group of characters that will be searched din list
* @return the start index of the first occurrence of the searched group of characters.
* If the searched characters is not in the list, returns -1
* @param iter iterator object reference
*/
public int find(String ch, ListIterator iter)
{
boolean flag=false;
//initialize iterator
iter=listOfCharacters.listIterator();
while (iter.hasNext())
{
for(int i=0; i<ch.length(); ++i)
{
if (iter.next().equals( ch.charAt(i)) )
flag=true;
else
{
flag=false;
break;
}
}
if (flag)
{
int loc=iter.nextIndex()-ch.length();
return loc;
}
}
return -1;//error case
}
/**
* replaces all occurrences of a character with another character.
* @param ch1 character to be changed
* @param ch2 character to be changed with
*/
public void replace(Character ch1, Character ch2)
{
for(int i=0; i <listOfCharacters.size(); ++i)
{
if(listOfCharacters.get(i)==ch1)
listOfCharacters.set(i, ch2);
}
System.out.println(listOfCharacters);
}
/**
* replaces all occurrences of a character with another character.
* @param ch1 character to be changed
* @param ch2 character to be changed with
* @param iter iterator object reference
*/
public void replace(Character ch1, Character ch2, ListIterator iter)
{
//initialize iterator
iter=listOfCharacters.listIterator();
while (iter.hasNext())
{
if(iter.next().equals(ch1) )
iter.set(ch2);// add(ch2);
}
System.out.println(listOfCharacters);
}
}
| UTF-8 | Java | 7,249 | java | SimpleTextEditor.java | Java | []
| null | []
| import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;
/**
*SimpleTextEditor class which provides the some of the edit functionality of a text editor.
*/
public class SimpleTextEditor
{
//Data fields
List<Character> listOfCharacters;
//Methods
public SimpleTextEditor(List newList)
{
listOfCharacters=newList;
}
/**
* reads a text file and construct the text.
* @param fileName name of file to be read
* @return 0 if successful, -1 if the text is empty
*/
public int read(String fileName)
{
StringBuilder data= new StringBuilder("");
try
{
File fileObj = new File(fileName);
Scanner myReader = new Scanner(fileObj);
while (myReader.hasNextLine())
{
data.append(myReader.nextLine() );
}
//loop
//construct the text
for(int i=0;i<data.length();i++)
{
listOfCharacters.add(data.charAt(i));
}
if(listOfCharacters.isEmpty() )
{
System.out.println("The text is empty");
return -1;
}
System.out.println(listOfCharacters);
myReader.close();
}
catch (FileNotFoundException e)
{
System.out.println("An error occurred.");
e.printStackTrace();
}
return 0;
}
/**
* reads a text file and construct the text.
* With iterator
* @param fileName name of file to be read
* @param iter iterator object reference
* @return 0 if successful, -1 if the text is empty
*/
public int read(String fileName, ListIterator iter)
{StringBuilder data= new StringBuilder("");
try
{
File fileObj = new File(fileName);
Scanner myReader = new Scanner(fileObj);
while (myReader.hasNextLine())
{
data.append(myReader.nextLine() );
}
//initialize iterator
iter= listOfCharacters.listIterator();
//construct the text
for(int i=0;i<data.length();i++)
{
iter.add(data.charAt(i));
}
if(listOfCharacters.isEmpty() )
{
System.out.println("The text is empty");
return -1;
}
System.out.println(listOfCharacters);
myReader.close();
}
catch (FileNotFoundException e)
{
System.out.println("An error occurred.");
e.printStackTrace();
}
return 0;
}
/**
* adds one or more characters at the specified
* position in text.
* @param ch character or characters to add to text
* @param index position to add the characters
* @return 0 if adding successful, -1 if not
*/
public int add(String ch, int index)
{
if(listOfCharacters.isEmpty())
{
return -1;
}
for (int i=0; i<ch.length(); ++i)
{
listOfCharacters.add(index, ch.charAt(i));
index++;
}
System.out.println(listOfCharacters);
return 0;
}
/**
* adds one or more characters at the specified
* position in text. With iterator.
* @param ch character or characters to add to text
* @param index position to add the characters
* @param iter iterator object reference
* @return 0 if adding successful, -1 if not
*/
public int add(String ch, int index, ListIterator iter)
{
if(listOfCharacters.isEmpty())
{
return -1;
}
//initialize iterator
iter= listOfCharacters.listIterator(index);
int i=0;
while (iter.hasNext())
{
iter.add(ch.charAt(i));
i++;
if(i== ch.length())
break;
}
System.out.println(listOfCharacters);
return 0;
}
/**
* Looks for a group of characters in list
* @param ch group of characters that will be searched in the list
* @return the start index of the first occurrence of the searched group of characters.
* If the searched characters is not in the list, returns -1
*/
public int find(String ch)
{
boolean flag=false;
for (int i=0; i<listOfCharacters.size(); ++i)
{
for(int j=0; j<ch.length(); ++j)
{
if(listOfCharacters.get(i+j)== ch.charAt(j))
flag=true;
else
{
flag=false;
break;
}
}
if(flag)
{
return i;
}
}
return -1;
}
/**
* Looks for a group of characters in list. With iterator
* @param ch group of characters that will be searched din list
* @return the start index of the first occurrence of the searched group of characters.
* If the searched characters is not in the list, returns -1
* @param iter iterator object reference
*/
public int find(String ch, ListIterator iter)
{
boolean flag=false;
//initialize iterator
iter=listOfCharacters.listIterator();
while (iter.hasNext())
{
for(int i=0; i<ch.length(); ++i)
{
if (iter.next().equals( ch.charAt(i)) )
flag=true;
else
{
flag=false;
break;
}
}
if (flag)
{
int loc=iter.nextIndex()-ch.length();
return loc;
}
}
return -1;//error case
}
/**
* replaces all occurrences of a character with another character.
* @param ch1 character to be changed
* @param ch2 character to be changed with
*/
public void replace(Character ch1, Character ch2)
{
for(int i=0; i <listOfCharacters.size(); ++i)
{
if(listOfCharacters.get(i)==ch1)
listOfCharacters.set(i, ch2);
}
System.out.println(listOfCharacters);
}
/**
* replaces all occurrences of a character with another character.
* @param ch1 character to be changed
* @param ch2 character to be changed with
* @param iter iterator object reference
*/
public void replace(Character ch1, Character ch2, ListIterator iter)
{
//initialize iterator
iter=listOfCharacters.listIterator();
while (iter.hasNext())
{
if(iter.next().equals(ch1) )
iter.set(ch2);// add(ch2);
}
System.out.println(listOfCharacters);
}
}
| 7,249 | 0.50407 | 0.498414 | 256 | 26.316406 | 20.58532 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.371094 | false | false | 3 |
b1c71a72cace2b0a4d3fdc60cd0c0ca7b519917d | 781,684,107,895 | 0d0176aa7fafb5247c4b03377a2effd02a4a3a54 | /src/main/java/com/virjanand/springbookskata/repositories/BookRepository.java | cd31f7e7606456e79b4431f83f4f03280f0f7749 | []
| no_license | Virjanand/spring-books-kata | https://github.com/Virjanand/spring-books-kata | 766566a6eb8ed93bf9e8f556c63d4f01e3655020 | b21570046804ddcd9d171c46b15f4085e45aa39a | refs/heads/master | 2020-08-03T04:54:58.549000 | 2019-10-01T13:08:32 | 2019-10-01T13:08:32 | 211,630,261 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.virjanand.springbookskata.repositories;
import com.virjanand.springbookskata.domain.Book;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository extends JpaRepository<Book, Long> {
}
| UTF-8 | Java | 236 | java | BookRepository.java | Java | []
| null | []
| package com.virjanand.springbookskata.repositories;
import com.virjanand.springbookskata.domain.Book;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository extends JpaRepository<Book, Long> {
}
| 236 | 0.847458 | 0.847458 | 7 | 32.714287 | 28.589281 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 3 |
ff022a12293732ec8360ad39ae06e1f9c4312863 | 32,701,881,024,515 | 0bba0bac3865b2e70a0d268e9eba42c8de513a3c | /mantis-network/src/main/java/io/reactivex/mantis/network/push/LegacyTcpPushServer.java | e215f75beb360f34a3335bb2eb60beda4b69a657 | [
"Apache-2.0"
]
| permissive | Netflix/mantis | https://github.com/Netflix/mantis | f5206c1d1a127ea76c4e47f31db4dd654ed620f9 | cafbe81a6c22128cafbbb7b90b2d107501a28e44 | refs/heads/master | 2023-08-17T18:28:46.594000 | 2023-08-16T04:21:03 | 2023-08-16T04:21:03 | 190,664,284 | 1,393 | 197 | Apache-2.0 | false | 2023-09-14T21:04:02 | 2019-06-06T23:44:48 | 2023-09-12T20:27:34 | 2023-09-14T21:04:00 | 27,325 | 1,345 | 170 | 81 | Java | false | false | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.network.push;
import io.mantisrx.common.metrics.Counter;
import io.mantisrx.common.metrics.Metrics;
import io.mantisrx.common.metrics.MetricsRegistry;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.WriteBufferWaterMark;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.compression.JdkZlibDecoder;
import io.netty.handler.codec.compression.JdkZlibEncoder;
import io.netty.handler.codec.compression.ZlibWrapper;
import io.netty.handler.timeout.IdleStateHandler;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import mantis.io.reactivex.netty.RxNetty;
import mantis.io.reactivex.netty.channel.ConnectionHandler;
import mantis.io.reactivex.netty.channel.ObservableConnection;
import mantis.io.reactivex.netty.pipeline.PipelineConfigurator;
import mantis.io.reactivex.netty.pipeline.PipelineConfiguratorComposite;
import mantis.io.reactivex.netty.server.RxServer;
import rx.Observable;
import rx.functions.Func1;
public class LegacyTcpPushServer<T> extends PushServer<T, RemoteRxEvent> {
private Func1<Map<String, List<String>>, Func1<T, Boolean>> predicate;
private String name;
private MetricsRegistry metricsRegistry;
public LegacyTcpPushServer(PushTrigger<T> trigger, ServerConfig<T> config,
Observable<String> serverSignals) {
super(trigger, config, serverSignals);
this.predicate = config.getPredicate();
this.name = config.getName();
this.metricsRegistry = config.getMetricsRegistry();
}
@Override
public RxServer<?, ?> createServer() {
RxServer<RemoteRxEvent, RemoteRxEvent> server
= RxNetty.newTcpServerBuilder(port, new ConnectionHandler<RemoteRxEvent, RemoteRxEvent>() {
@Override
public Observable<Void> handle(
final ObservableConnection<RemoteRxEvent, RemoteRxEvent> newConnection) {
final InetSocketAddress socketAddress = (InetSocketAddress) newConnection.getChannel().remoteAddress();
// extract groupId, id, predicate from incoming byte[]
return
newConnection.getInput()
.flatMap(new Func1<RemoteRxEvent, Observable<Void>>() {
@Override
public Observable<Void> call(
RemoteRxEvent incomingRequest) {
if (incomingRequest.getType() == RemoteRxEvent.Type.subscribed) {
Map<String, String> params = incomingRequest.getSubscribeParameters();
// client state
String id = null;
String slotId = null;
String groupId = null;
// sample state
boolean enableSampling = false;
long samplingTimeMsec = 0;
// predicate state
Map<String, List<String>> predicateParams = null;
if (params != null && !params.isEmpty()) {
predicateParams = new HashMap<String, List<String>>();
for (Entry<String, String> entry : params.entrySet()) {
List<String> values = new LinkedList<>();
values.add(entry.getValue());
predicateParams.put(entry.getKey(), values);
}
if (params.containsKey("id")) {
id = params.get("id");
}
if (params.containsKey("slotId")) {
slotId = params.get("slotId");
}
if (params.containsKey("groupId")) {
groupId = params.get("groupId");
}
if (params.containsKey("sample")) {
samplingTimeMsec = Long.parseLong(params.get("sample")) * 1000;
if (samplingTimeMsec < 50) {
throw new IllegalArgumentException("Sampling rate too low: " + samplingTimeMsec);
}
enableSampling = true;
}
if (params.containsKey("sampleMSec")) {
samplingTimeMsec = Long.parseLong(params.get("sampleMSec"));
if (samplingTimeMsec < 50) {
throw new IllegalArgumentException("Sampling rate too low: " + samplingTimeMsec);
}
enableSampling = true;
}
}
Func1<T, Boolean> predicateFunction = null;
if (predicate != null) {
predicateFunction = predicate.call(predicateParams);
}
// support legacy metrics per connection
Metrics sseSinkMetrics = new Metrics.Builder()
.name("DropOperator_outgoing_subject_" + slotId)
.addCounter("onNext")
.addCounter("dropped")
.build();
sseSinkMetrics = metricsRegistry.registerAndGet(sseSinkMetrics);
Counter legacyMsgProcessedCounter = sseSinkMetrics.getCounter("onNext");
Counter legacyDroppedWrites = sseSinkMetrics.getCounter("dropped");
return manageConnection(newConnection, socketAddress.getHostString(), socketAddress.getPort(),
groupId, slotId, id, null,
false, null, enableSampling, samplingTimeMsec,
predicateFunction, null, legacyMsgProcessedCounter, legacyDroppedWrites,
null);
}
return null;
}
});
}
})
.pipelineConfigurator(new PipelineConfiguratorComposite<RemoteRxEvent, RemoteRxEvent>(
new PipelineConfigurator<RemoteRxEvent, RemoteRxEvent>() {
@Override
public void configureNewPipeline(ChannelPipeline pipeline) {
// pipeline.addLast(new LoggingHandler(LogLevel.ERROR)); // uncomment to enable debug logging
pipeline.addLast("idleStateHandler", new IdleStateHandler(10, 2, 0));
pipeline.addLast("heartbeat", new HeartbeatHandler());
pipeline.addLast("gzipInflater", new JdkZlibEncoder(ZlibWrapper.GZIP));
pipeline.addLast("gzipDeflater", new JdkZlibDecoder(ZlibWrapper.GZIP));
pipeline.addLast("frameEncoder", new LengthFieldPrepender(4)); // 4 bytes to encode length
pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(5242880, 0, 4, 0, 4)); // max frame = half MB
}
}, new LegacyTcpPipelineConfigurator(name)))
.channelOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(1024 * 1024, 5 * 1024 * 1024))
.build();
return server;
}
}
| UTF-8 | Java | 9,861 | java | LegacyTcpPushServer.java | Java | [
{
"context": "/*\n * Copyright 2019 Netflix, Inc.\n *\n * Licensed under the Apache License, Ve",
"end": 28,
"score": 0.9574626684188843,
"start": 21,
"tag": "NAME",
"value": "Netflix"
}
]
| null | []
| /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.mantis.network.push;
import io.mantisrx.common.metrics.Counter;
import io.mantisrx.common.metrics.Metrics;
import io.mantisrx.common.metrics.MetricsRegistry;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.WriteBufferWaterMark;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.compression.JdkZlibDecoder;
import io.netty.handler.codec.compression.JdkZlibEncoder;
import io.netty.handler.codec.compression.ZlibWrapper;
import io.netty.handler.timeout.IdleStateHandler;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import mantis.io.reactivex.netty.RxNetty;
import mantis.io.reactivex.netty.channel.ConnectionHandler;
import mantis.io.reactivex.netty.channel.ObservableConnection;
import mantis.io.reactivex.netty.pipeline.PipelineConfigurator;
import mantis.io.reactivex.netty.pipeline.PipelineConfiguratorComposite;
import mantis.io.reactivex.netty.server.RxServer;
import rx.Observable;
import rx.functions.Func1;
public class LegacyTcpPushServer<T> extends PushServer<T, RemoteRxEvent> {
private Func1<Map<String, List<String>>, Func1<T, Boolean>> predicate;
private String name;
private MetricsRegistry metricsRegistry;
public LegacyTcpPushServer(PushTrigger<T> trigger, ServerConfig<T> config,
Observable<String> serverSignals) {
super(trigger, config, serverSignals);
this.predicate = config.getPredicate();
this.name = config.getName();
this.metricsRegistry = config.getMetricsRegistry();
}
@Override
public RxServer<?, ?> createServer() {
RxServer<RemoteRxEvent, RemoteRxEvent> server
= RxNetty.newTcpServerBuilder(port, new ConnectionHandler<RemoteRxEvent, RemoteRxEvent>() {
@Override
public Observable<Void> handle(
final ObservableConnection<RemoteRxEvent, RemoteRxEvent> newConnection) {
final InetSocketAddress socketAddress = (InetSocketAddress) newConnection.getChannel().remoteAddress();
// extract groupId, id, predicate from incoming byte[]
return
newConnection.getInput()
.flatMap(new Func1<RemoteRxEvent, Observable<Void>>() {
@Override
public Observable<Void> call(
RemoteRxEvent incomingRequest) {
if (incomingRequest.getType() == RemoteRxEvent.Type.subscribed) {
Map<String, String> params = incomingRequest.getSubscribeParameters();
// client state
String id = null;
String slotId = null;
String groupId = null;
// sample state
boolean enableSampling = false;
long samplingTimeMsec = 0;
// predicate state
Map<String, List<String>> predicateParams = null;
if (params != null && !params.isEmpty()) {
predicateParams = new HashMap<String, List<String>>();
for (Entry<String, String> entry : params.entrySet()) {
List<String> values = new LinkedList<>();
values.add(entry.getValue());
predicateParams.put(entry.getKey(), values);
}
if (params.containsKey("id")) {
id = params.get("id");
}
if (params.containsKey("slotId")) {
slotId = params.get("slotId");
}
if (params.containsKey("groupId")) {
groupId = params.get("groupId");
}
if (params.containsKey("sample")) {
samplingTimeMsec = Long.parseLong(params.get("sample")) * 1000;
if (samplingTimeMsec < 50) {
throw new IllegalArgumentException("Sampling rate too low: " + samplingTimeMsec);
}
enableSampling = true;
}
if (params.containsKey("sampleMSec")) {
samplingTimeMsec = Long.parseLong(params.get("sampleMSec"));
if (samplingTimeMsec < 50) {
throw new IllegalArgumentException("Sampling rate too low: " + samplingTimeMsec);
}
enableSampling = true;
}
}
Func1<T, Boolean> predicateFunction = null;
if (predicate != null) {
predicateFunction = predicate.call(predicateParams);
}
// support legacy metrics per connection
Metrics sseSinkMetrics = new Metrics.Builder()
.name("DropOperator_outgoing_subject_" + slotId)
.addCounter("onNext")
.addCounter("dropped")
.build();
sseSinkMetrics = metricsRegistry.registerAndGet(sseSinkMetrics);
Counter legacyMsgProcessedCounter = sseSinkMetrics.getCounter("onNext");
Counter legacyDroppedWrites = sseSinkMetrics.getCounter("dropped");
return manageConnection(newConnection, socketAddress.getHostString(), socketAddress.getPort(),
groupId, slotId, id, null,
false, null, enableSampling, samplingTimeMsec,
predicateFunction, null, legacyMsgProcessedCounter, legacyDroppedWrites,
null);
}
return null;
}
});
}
})
.pipelineConfigurator(new PipelineConfiguratorComposite<RemoteRxEvent, RemoteRxEvent>(
new PipelineConfigurator<RemoteRxEvent, RemoteRxEvent>() {
@Override
public void configureNewPipeline(ChannelPipeline pipeline) {
// pipeline.addLast(new LoggingHandler(LogLevel.ERROR)); // uncomment to enable debug logging
pipeline.addLast("idleStateHandler", new IdleStateHandler(10, 2, 0));
pipeline.addLast("heartbeat", new HeartbeatHandler());
pipeline.addLast("gzipInflater", new JdkZlibEncoder(ZlibWrapper.GZIP));
pipeline.addLast("gzipDeflater", new JdkZlibDecoder(ZlibWrapper.GZIP));
pipeline.addLast("frameEncoder", new LengthFieldPrepender(4)); // 4 bytes to encode length
pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(5242880, 0, 4, 0, 4)); // max frame = half MB
}
}, new LegacyTcpPipelineConfigurator(name)))
.channelOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(1024 * 1024, 5 * 1024 * 1024))
.build();
return server;
}
}
| 9,861 | 0.477943 | 0.472264 | 174 | 55.672413 | 36.94873 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.793103 | false | false | 3 |
c59fc59da66e2a1b5609bd2ba02a0564d82a5d80 | 7,791,070,707,530 | 8de447da90ef44a5d1655d4b1b9349873f39ac1e | /src/test/java/nl/knmi/geoweb/iwxxm_2_1/converter/VASigmetToIWXXMTest.java | 2c13a5a17687a0a72b6badb05d6a527ac8c379b7 | [
"MIT"
]
| permissive | KNMI/GeoWeb-Aviation-MessageConverter | https://github.com/KNMI/GeoWeb-Aviation-MessageConverter | 6dbb48c09d5dc710f3f67b8dbcedf52fca74cced | 5d51ae995597602dc1474803929fe95bdc213dd3 | refs/heads/master | 2021-06-09T11:09:28.128000 | 2019-11-07T13:45:06 | 2019-11-07T13:45:06 | 107,537,907 | 1 | 6 | MIT | false | 2019-11-07T13:45:08 | 2017-10-19T11:33:30 | 2019-11-01T08:49:29 | 2019-11-07T13:45:08 | 1,188 | 1 | 6 | 1 | Java | false | false | package nl.knmi.geoweb.iwxxm_2_1.converter;
import java.util.Arrays;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.test.context.junit4.SpringRunner;
import nl.knmi.geoweb.TestConfig;
import nl.knmi.geoweb.backend.aviation.FIRStore;
import nl.knmi.geoweb.backend.product.sigmet.Sigmet;
import nl.knmi.geoweb.backend.product.sigmet.converter.SigmetConverter;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { TestConfig.class })
public class VASigmetToIWXXMTest {
@Autowired
@Qualifier("sigmetObjectMapper")
private ObjectMapper sigmetObjectMapper;
@Autowired
private SigmetConverter sigmetConverter;
@Value("classpath:nl/knmi/geoweb/iwxxm_2_1/converter/vasigmet.json")
Resource vaSigmetResource1;
@Value("classpath:nl/knmi/geoweb/iwxxm_2_1/converter/SIGMET_EHDB_2018-11-29T1230_20181129111546.json")
Resource vaSigmetResource2;
@Autowired
FIRStore firStore;
@Test
public void TestConversion (){
List<Resource> vaResources = Arrays.asList(vaSigmetResource1, vaSigmetResource2);
vaResources.forEach(resource -> {
Sigmet vaSigmet = null;
try {
vaSigmet = sigmetObjectMapper.readValue(resource.getInputStream(), Sigmet.class);
} catch (Exception e) {
e.printStackTrace(System.err);
}
String result = sigmetConverter.ToIWXXM_2_1(vaSigmet);
System.err.println(result);
System.err.println("TAC: " + vaSigmet.toTAC(firStore.lookup(vaSigmet.getFirname(), true)));
});
}
}
| UTF-8 | Java | 1,835 | java | VASigmetToIWXXMTest.java | Java | []
| null | []
| package nl.knmi.geoweb.iwxxm_2_1.converter;
import java.util.Arrays;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.test.context.junit4.SpringRunner;
import nl.knmi.geoweb.TestConfig;
import nl.knmi.geoweb.backend.aviation.FIRStore;
import nl.knmi.geoweb.backend.product.sigmet.Sigmet;
import nl.knmi.geoweb.backend.product.sigmet.converter.SigmetConverter;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { TestConfig.class })
public class VASigmetToIWXXMTest {
@Autowired
@Qualifier("sigmetObjectMapper")
private ObjectMapper sigmetObjectMapper;
@Autowired
private SigmetConverter sigmetConverter;
@Value("classpath:nl/knmi/geoweb/iwxxm_2_1/converter/vasigmet.json")
Resource vaSigmetResource1;
@Value("classpath:nl/knmi/geoweb/iwxxm_2_1/converter/SIGMET_EHDB_2018-11-29T1230_20181129111546.json")
Resource vaSigmetResource2;
@Autowired
FIRStore firStore;
@Test
public void TestConversion (){
List<Resource> vaResources = Arrays.asList(vaSigmetResource1, vaSigmetResource2);
vaResources.forEach(resource -> {
Sigmet vaSigmet = null;
try {
vaSigmet = sigmetObjectMapper.readValue(resource.getInputStream(), Sigmet.class);
} catch (Exception e) {
e.printStackTrace(System.err);
}
String result = sigmetConverter.ToIWXXM_2_1(vaSigmet);
System.err.println(result);
System.err.println("TAC: " + vaSigmet.toTAC(firStore.lookup(vaSigmet.getFirname(), true)));
});
}
}
| 1,835 | 0.790191 | 0.768937 | 58 | 30.637932 | 26.943554 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.431034 | false | false | 3 |
93207e8d3202fb8e957666c9b53f0a8607a6b616 | 33,732,673,182,446 | c100f126bc911cf847b0dacb01371286ec6122af | /src/main/java/Operators/Ternary.java | d1e48dac3a07c776b35a53e08061bae2810035d7 | []
| no_license | Bada1208/JavaPractics | https://github.com/Bada1208/JavaPractics | 0f8e01510c7368eeec2562b7c533a23702789f2f | bcf6879584880b655e5830eab85b3644ddb1fd51 | refs/heads/master | 2018-11-10T14:58:38.170000 | 2018-09-01T15:27:36 | 2018-09-01T15:27:36 | 121,045,955 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Operators;
public class Ternary {
public static void main(String args[]){
//Вид:переменная x = (выражение) ? значение if true : значение if false
int a , b;
a = 10;
b = (a == 1) ? 20 : 30;
System.out.println( "Значение b: " + b );
b = (a == 10) ? 20 : 30;
System.out.println( "Значение b: " + b );
}
}
| UTF-8 | Java | 431 | java | Ternary.java | Java | []
| null | []
| package Operators;
public class Ternary {
public static void main(String args[]){
//Вид:переменная x = (выражение) ? значение if true : значение if false
int a , b;
a = 10;
b = (a == 1) ? 20 : 30;
System.out.println( "Значение b: " + b );
b = (a == 10) ? 20 : 30;
System.out.println( "Значение b: " + b );
}
}
| 431 | 0.506631 | 0.472149 | 14 | 25.928572 | 22.275753 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 3 |
74dc59cd8a36ba74a86f72ec84abf653c7dfdf09 | 31,671,088,890,515 | 230845deb85ec977506bbb74174090b2e61cb402 | /Photo gallery/app/src/main/java/com/longtraidep/imagegallery/Object/Video.java | 805a5dd8910cf347642a6e4e9de27ef1e319b5c5 | []
| no_license | nbnlong2712/Test_image_gallery | https://github.com/nbnlong2712/Test_image_gallery | 24768b0829ecf7463f3c967853d7288196083d5d | b696225e4722a03d68ba550229e418f2a1526d29 | refs/heads/master | 2023-05-03T02:20:25.799000 | 2021-05-13T12:17:47 | 2021-05-13T12:17:47 | 366,566,207 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.longtraidep.imagegallery.Object;
import java.util.Date;
public class Video {
private String id;
private String path;
private String thumb;
private Date dateAdded;
private String duration;
private long size;
public Video(String id, String path, String thumb, Date dateAdded, String duration, long size) {
this.id = id;
this.path = path;
this.thumb = thumb;
this.dateAdded = dateAdded;
this.duration = duration;
this.size = size;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getDateAdded() {
return dateAdded;
}
public void setDateAdded(Date dateAdded) {
this.dateAdded = dateAdded;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getThumb() {
return thumb;
}
public void setThumb(String thumb) {
this.thumb = thumb;
}
}
| UTF-8 | Java | 1,348 | java | Video.java | Java | []
| null | []
| package com.longtraidep.imagegallery.Object;
import java.util.Date;
public class Video {
private String id;
private String path;
private String thumb;
private Date dateAdded;
private String duration;
private long size;
public Video(String id, String path, String thumb, Date dateAdded, String duration, long size) {
this.id = id;
this.path = path;
this.thumb = thumb;
this.dateAdded = dateAdded;
this.duration = duration;
this.size = size;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getDateAdded() {
return dateAdded;
}
public void setDateAdded(Date dateAdded) {
this.dateAdded = dateAdded;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getThumb() {
return thumb;
}
public void setThumb(String thumb) {
this.thumb = thumb;
}
}
| 1,348 | 0.586053 | 0.586053 | 70 | 18.257143 | 17.225136 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.442857 | false | false | 3 |
c3bcd429ad76eb8401be6de80ec5866a5694a4cb | 25,039,659,399,972 | 9ba2eea67266abfa51f0f3a1f9a8c746b57ab073 | /experiments/src/tt/TestC60.java | 5d7d3b2127f9bc51ed5e6b3452f8b9671b1b1e21 | []
| no_license | tdddblog/java_3d | https://github.com/tdddblog/java_3d | 82d9aa41020c30b4196bf7240437244f2cf36d1e | 8deed74e38b6244405c3d179dfd99edc40a030af | refs/heads/master | 2019-06-17T05:35:20.758000 | 2017-09-06T00:46:23 | 2017-09-06T00:46:23 | 99,751,788 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tt;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import ek.geom.Vec3;
public class TestC60
{
public static class Edge
{
public int v1;
public int v2;
public Edge()
{
}
public Edge(int v1, int v2)
{
this.v1 = v1;
this.v2 = v2;
}
}
List<Vec3> vertices;
List<Edge> edges;
public static void main(String[] args) throws Exception
{
TestC60 test = new TestC60();
test.vertices = readFile("data/c60.xyz");
test.edges = getEdges(test.vertices);
System.out.format("Vertices = %d, Edges = %d\n",
test.vertices.size(), test.edges.size());
//System.out.println("Vertices:");
//printVertices(test.vertices);
//System.out.println("Edges:");
//printEdges(test.edges);
test.getFaces(test.edges);
}
public void getFaces(List<Edge> edges)
{
// 32 faces (20 hexagons and 12 pentagons where no pentagons share a vertex)
// Hexa:
// 1, 3, 4, 7, 6, 5
// Penta
// 0, 1, 5, 12, 11
Graph graph = new Graph(60);
for(Edge edge: edges)
{
graph.addEdge(edge.v1, edge.v2);
}
graph.getNode(0).findLoops();
}
public static List<Edge> getEdges(List<Vec3> vertices)
{
List<Edge> edges = new ArrayList<Edge>();
for(int i = 0; i < vertices.size()-1; i++)
{
for(int j = i+1; j < vertices.size(); j++)
{
Vec3 v1 = vertices.get(i);
Vec3 v2 = vertices.get(j);
float dist = Vec3.distance(v1, v2);
if(dist < 1.8)
{
Edge edge = new Edge(i, j);
edges.add(edge);
}
}
}
return edges;
}
public static void printVertices(List<Vec3> list)
{
for(Vec3 vec: list)
{
System.out.format("%f %f %f\n", vec.x, vec.y, vec.z);
}
}
public static void printEdges(List<Edge> list)
{
for(Edge edge: list)
{
System.out.format("%d %d\n", edge.v1, edge.v2);
}
}
private static List<Vec3> readFile(String fileName) throws Exception
{
List<Vec3> vertices = new ArrayList<Vec3>();
BufferedReader rd = new BufferedReader(new FileReader(fileName));
// Num atoms
String line = rd.readLine();
int numAtoms = Integer.parseInt(line);
// Description
line = rd.readLine();
for(int i = 0; i < numAtoms; i++)
{
line = rd.readLine();
Vec3 vec = parseCoord(line);
vertices.add(vec);
}
rd.close();
return vertices;
}
private static Vec3 parseCoord(String str)
{
String[] tokens = str.split("\\s+");
if(tokens.length < 4)
{
throw new RuntimeException("Invalid line: " + str);
}
Vec3 vec = new Vec3();
vec.x = Float.parseFloat(tokens[1]);
vec.y = Float.parseFloat(tokens[2]);
vec.z = Float.parseFloat(tokens[3]);
return vec;
}
}
| UTF-8 | Java | 2,741 | java | TestC60.java | Java | []
| null | []
| package tt;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import ek.geom.Vec3;
public class TestC60
{
public static class Edge
{
public int v1;
public int v2;
public Edge()
{
}
public Edge(int v1, int v2)
{
this.v1 = v1;
this.v2 = v2;
}
}
List<Vec3> vertices;
List<Edge> edges;
public static void main(String[] args) throws Exception
{
TestC60 test = new TestC60();
test.vertices = readFile("data/c60.xyz");
test.edges = getEdges(test.vertices);
System.out.format("Vertices = %d, Edges = %d\n",
test.vertices.size(), test.edges.size());
//System.out.println("Vertices:");
//printVertices(test.vertices);
//System.out.println("Edges:");
//printEdges(test.edges);
test.getFaces(test.edges);
}
public void getFaces(List<Edge> edges)
{
// 32 faces (20 hexagons and 12 pentagons where no pentagons share a vertex)
// Hexa:
// 1, 3, 4, 7, 6, 5
// Penta
// 0, 1, 5, 12, 11
Graph graph = new Graph(60);
for(Edge edge: edges)
{
graph.addEdge(edge.v1, edge.v2);
}
graph.getNode(0).findLoops();
}
public static List<Edge> getEdges(List<Vec3> vertices)
{
List<Edge> edges = new ArrayList<Edge>();
for(int i = 0; i < vertices.size()-1; i++)
{
for(int j = i+1; j < vertices.size(); j++)
{
Vec3 v1 = vertices.get(i);
Vec3 v2 = vertices.get(j);
float dist = Vec3.distance(v1, v2);
if(dist < 1.8)
{
Edge edge = new Edge(i, j);
edges.add(edge);
}
}
}
return edges;
}
public static void printVertices(List<Vec3> list)
{
for(Vec3 vec: list)
{
System.out.format("%f %f %f\n", vec.x, vec.y, vec.z);
}
}
public static void printEdges(List<Edge> list)
{
for(Edge edge: list)
{
System.out.format("%d %d\n", edge.v1, edge.v2);
}
}
private static List<Vec3> readFile(String fileName) throws Exception
{
List<Vec3> vertices = new ArrayList<Vec3>();
BufferedReader rd = new BufferedReader(new FileReader(fileName));
// Num atoms
String line = rd.readLine();
int numAtoms = Integer.parseInt(line);
// Description
line = rd.readLine();
for(int i = 0; i < numAtoms; i++)
{
line = rd.readLine();
Vec3 vec = parseCoord(line);
vertices.add(vec);
}
rd.close();
return vertices;
}
private static Vec3 parseCoord(String str)
{
String[] tokens = str.split("\\s+");
if(tokens.length < 4)
{
throw new RuntimeException("Invalid line: " + str);
}
Vec3 vec = new Vec3();
vec.x = Float.parseFloat(tokens[1]);
vec.y = Float.parseFloat(tokens[2]);
vec.z = Float.parseFloat(tokens[3]);
return vec;
}
}
| 2,741 | 0.606348 | 0.580445 | 159 | 16.238995 | 17.882727 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.232704 | false | false | 3 |
1da51b1e0b2277f91214bc3882447a4ef8ee2d08 | 29,686,814,001,030 | c9d3b199383f05939f66181bc7cb54b8a924542f | /src/com/bwat/hmi/prg/ProgramTable.java | b97a023baf4215deda8192fe92ef94cef0a27836 | []
| no_license | BlueWaterAT/TV1000-HMI | https://github.com/BlueWaterAT/TV1000-HMI | 9ec8d3115c93b366515d248176997c21a0e8d6b7 | b954fdbc38013cadb071bf5d16a5ccfd64261390 | refs/heads/master | 2016-09-01T20:20:56.528000 | 2016-02-08T02:53:47 | 2016-02-08T02:53:47 | 41,270,124 | 0 | 0 | null | false | 2016-02-02T22:28:46 | 2015-08-23T22:31:30 | 2016-01-24T23:56:52 | 2016-02-02T22:28:46 | 229 | 0 | 0 | 0 | Java | null | null | package com.bwat.hmi.prg;
import com.bwat.hmi.HMI;
import com.bwat.hmi.ui.KeyboardDialog;
import com.bwat.hmi.ui.KeypadDialog;
import com.bwat.hmi.ui.ListDialog;
import com.bwat.hmi.util.ArrayUtils;
import com.bwat.hmi.util.FileUtils;
import com.bwat.hmi.util.MathUtils;
import com.bwat.hmi.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Vector;
import static com.bwat.hmi.Constants.PROGRAM.*;
/**
* A wrapper around a JTable that gives functionality for loading and saving the table,
* as well as editing the column types
*
* @author Kareem ElFaramawi
*/
public class ProgramTable extends JTable {
Logger log = LoggerFactory.getLogger(getClass());
// List of all column types
private ArrayList<CellType> columnTypes = new ArrayList<CellType>();
// Lists of all the entries for COMBO columns
private HashMap<Integer, String[]> comboValues = new HashMap<Integer, String[]>();
// List of all mouseover tooltip messages
private ArrayList<String> tooltips = new ArrayList<String>();
// Used for keeping track of which column header was clicked
private int popupCol = 0;
public ProgramTable(int numRows, int numColumns) {
super(numRows, numColumns);
initGUI();
// Manually handle click events for certain column types
// to allow for a custom input method
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int r = rowAtPoint(e.getPoint()), c = columnAtPoint(e.getPoint());
if (MathUtils.inRange_in_ex(r, 0, getRowCount()) && MathUtils.inRange_in_ex(c, 0, getColumnCount())) {
switch (getColumnType(c)) {
case TEXT:
// TEXT input should open up a keyboard
setValueAt(KeyboardDialog.showDialog("Enter value: ", ""), r, c);
break;
case COMBO:
String[] vals = comboValues.get(c);
if (vals != null) {
// If this COMBO column contains only numeric entries, we should open up a
// keypad instead of a selection screen
boolean numeric = true;
for (String val : vals) {
if (!StringUtils.isNumber(val)) {
numeric = false;
break;
}
}
String newValue;
if (numeric) {
// Get a new value using the keypad interface
newValue = KeypadDialog.showDialog("Enter Value", "");
// Revert back to the original value if an invalid number is entered,
// or the number entered is not an option
if (!StringUtils.isNumber(newValue) || ArrayUtils.contains(vals, newValue)) {
newValue = (String) getValueAt(r, c);
}
} else {
// Get a new value with an enlarged combo box selection screen
newValue = ListDialog.showDialog("Select a Value", vals, (String) getValueAt(r, c), getFont(), 24f);
}
// Set the new value
setValueAt(newValue, r, c);
}
break;
case NUMBER:
// Get a new value using the keypad interface
String newValue;
newValue = KeypadDialog.showDialog("Enter Value", "");
if (!StringUtils.isNumber(newValue)) {
Object tval = getValueAt(r, c);
newValue = tval == null ? "0" : tval.toString();
}
// Set the new value
setValueAt(StringUtils.isNumber(newValue) ? Integer.parseInt(newValue) : null, r, c);
break;
}
}
}
});
}
/**
* Initializes all GUI components contained in the table
*/
void initGUI() {
// Set all columns to TEXT and set a default tooltip
for (int i = 0; i < getColumnCount(); i++) {
columnTypes.add(null);
setColumnType(i, CellType.TEXT);
tooltips.add("Col " + i);
}
// Initialize all settings for the right click popup menu
final JPopupMenu headerMenu = new JPopupMenu(); // Actual popup menu
// Add a listener to show the menu on right click
getTableHeader().addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
popupCol = getTableHeader().columnAtPoint(e.getPoint());
headerMenu.show(getTableHeader(), e.getX(), e.getY());
}
}
});
// Add a listener to display tooltips on mouse movement over the column header
getTableHeader().addMouseMotionListener(new MouseAdapter() {
public void mouseMoved(MouseEvent e) {
int col = getTableHeader().columnAtPoint(e.getPoint());
getTableHeader().setToolTipText(tooltips.get(col));
}
});
getTableHeader().setReorderingAllowed(false);
getTableHeader().setResizingAllowed(false);
getTableHeader().setBackground(getBackground());
getTableHeader().setForeground(getForeground());
// Initialize everything inside the popup menu
JMenu jmi_type = new JMenu("Column Type"); // Column type submenu
// Column data type choices
JMenuItem jmi_text = new JMenuItem("Text");
JMenuItem jmi_check = new JMenuItem("Checkbox");
JMenuItem jmi_combo = new JMenuItem("Combo Box");
JMenuItem jmi_num = new JMenuItem("Number");
// Text type
jmi_text.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setColumnType(popupCol, CellType.TEXT);
repaint();
}
});
// Checkbox type
jmi_check.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setColumnType(popupCol, CellType.CHECK);
repaint();
}
});
// Combo box type
jmi_combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Ask how many choices should be in the combobox
JSpinner numEntries = new JSpinner();
if (JOptionPane.showConfirmDialog(null, new Object[]{"How many entries?", numEntries}, "Combo Box Options", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
// Generate that many JTextFields and ask for all of the choices
int ents = (int) numEntries.getValue();
if (ents > 0) {
// Array of JTextFields
JTextField[] inputs = new JTextField[ents];
for (int i = 0; i < ents; i++) {
inputs[i] = new JTextField();
}
// Show prompt
if (JOptionPane.showConfirmDialog(null, inputs, "Enter Combo Box Choices", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
// Collect all the combo box choices
String[] entries = new String[ents];
for (int i = 0; i < ents; i++) {
entries[i] = inputs[i].getText();
}
// Set the column type
setColumnType(popupCol, CellType.COMBO, entries);
}
}
}
repaint();
}
});
// Number type
jmi_num.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setColumnType(popupCol, CellType.NUMBER);
repaint();
}
});
jmi_type.add(jmi_text);
jmi_type.add(jmi_check);
jmi_type.add(jmi_combo);
jmi_type.add(jmi_num);
// Option to rename header
JMenuItem jmi_rename = new JMenuItem("Rename");
jmi_rename.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JPanel dialog = new JPanel(new GridLayout(2, 2));
JTextField name = new JTextField(), tooltip = new JTextField();
dialog.add(new JLabel("Name:"));
dialog.add(name);
dialog.add(new JLabel("Tooltip:"));
dialog.add(tooltip);
if (JOptionPane.showConfirmDialog(null, dialog, "Column Settings", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
setColumnHeader(popupCol, name.getText().length() > 0 ? name.getText() : " ");
tooltips.set(popupCol, tooltip.getText().length() > 0 ? tooltip.getText() : " ");
}
repaint();
}
});
// Option to add column
JMenuItem jmi_add = new JMenuItem("Add Column");
final JMenuItem jmi_delete = new JMenuItem("Delete Column");
jmi_add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JPanel dialog = new JPanel(new GridLayout(2, 2));
JTextField name = new JTextField(), tooltip = new JTextField();
dialog.add(new JLabel("Name:"));
dialog.add(name);
dialog.add(new JLabel("Tooltip:"));
dialog.add(tooltip);
if (JOptionPane.showConfirmDialog(null, dialog, "Column Settings", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
getColumnModel().addColumn(new TableColumn());
columnTypes.add(null);
setColumnType(getColumnCount() - 1, CellType.TEXT);
setColumnHeader(getColumnCount() - 1, name.getText());
tooltips.add(tooltip.getText());
if (!jmi_delete.isEnabled()) {
jmi_delete.setEnabled(true);
}
}
repaint();
}
});
// Option to delete column
jmi_delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getColumnModel().removeColumn(getColumnModel().getColumn(popupCol));
columnTypes.remove(popupCol);
tooltips.remove(popupCol);
if (getColumnCount() == 1) {
jmi_delete.setEnabled(false);
}
repaint();
}
});
headerMenu.add(jmi_type);
headerMenu.add(jmi_rename);
headerMenu.add(jmi_add);
headerMenu.add(jmi_delete);
// Disallow column reordering
getTableHeader().setReorderingAllowed(false);
}
/**
* Copies all of the table data into a 2D list
*
* @return List of all table data
*/
public ArrayList<ArrayList<Object>> exportTableData() {
ArrayList<ArrayList<Object>> copy = new ArrayList<ArrayList<Object>>(getRowCount());
for (int row = 0; row < getRowCount(); row++) {
copy.add(new ArrayList<Object>(getColumnCount()));
for (int col = 0; col < getColumnCount(); col++) {
copy.get(row).add(getValueAt(row, col));
}
}
return copy;
}
/**
* Sets the name of a column
*
* @param column Column index
* @param header Name of the column
*/
public void setColumnHeader(int column, String header) {
getColumnModel().getColumn(column).setHeaderValue(header);
}
/**
* Sets a columns to a specific type
*
* @param column Column index
* @param type Column type
* @param comboEntries OPTIONAL, fill only if the type is COMBO, then this is the entries of the that
* combo box
*/
public void setColumnType(final int column, CellType type, final String... comboEntries) {
if (MathUtils.inRange_in_ex(column, 0, getColumnCount())) {
for (int i = 0; i < getRowCount(); i++) {
setValueAt(null, i, column);
}
columnTypes.set(column, type);
// Dummy editor to disable default action when clicking a cell
DefaultCellEditor dummy = new DefaultCellEditor(new JTextField());
dummy.setClickCountToStart(1000); // Nobody's doing that, let the MouseEvent take over
// Set up the column in the JTable
switch (type) {
case COMBO:
// Add entries into type
comboValues.put(column, comboEntries);
// Only set a renderer, editing handled by MouseEvent
JComboBoxCellRenderer renderer = new JComboBoxCellRenderer();
renderer.setModel(new DefaultComboBoxModel<String>(comboEntries));
renderer.setBackground(HMI.getInstance().getBackground());
renderer.setForeground(HMI.getInstance().getForeground());
renderer.setFont(HMI.getInstance().getFont());
getColumnModel().getColumn(column).setCellRenderer(renderer);
break;
case NUMBER:
case TEXT:
// These will all be handled by a MouseEvent
getColumnModel().getColumn(column).setCellEditor(dummy);
getColumnModel().getColumn(column).setCellRenderer(new DefaultTableCellRenderer());
break;
case CHECK:
// CHECK uses a Boolean, which gets represented as a checkbox
getColumnModel().getColumn(column).setCellEditor(getDefaultEditor(Boolean.class));
getColumnModel().getColumn(column).setCellRenderer(getDefaultRenderer(Boolean.class));
break;
}
}
}
/**
* @param col Column index
* @return The CellType of a column
*/
public CellType getColumnType(int col) {
// Range validation
if (!MathUtils.inRange_in_ex(col, 0, columnTypes.size())) {
log.error("Invalid column index: ", col);
return null;
}
return columnTypes.get(col);
}
/**
* Inserts a blank row at the end of the table
*/
public void insertRow() {
((DefaultTableModel) getModel()).addRow(new Vector<Object>());
}
/**
* Deletes all rows from the table
*/
public void deleteAllRows() {
((DefaultTableModel) getModel()).setRowCount(0);
}
/**
* Sets the value of a cell
*
* @param val Cell value
* @param row Row index
* @param col Column index
*/
public void setValueAt(Object val, int row, int col) {
getModel().setValueAt(val, convertRowIndexToModel(row), convertColumnIndexToModel(col));
}
/**
* @param row Row index
* @param col Column index
* @return Cell value at the given location
*/
public Object getValueAt(int row, int col) {
return getModel().getValueAt(row, col);
}
/**
* Loads the JTB data and formats the table
*
* @param path Path to the JTB file
*/
public void loadTableFromFile(String path) {
try {
Scanner scan = new Scanner(FileUtils.getFile(path)); // Open file stream
String[] data; // Holds temp data
// Read and set the column headers
data = nextAvailableLine(scan).split(COMMA);
((DefaultTableModel) getModel()).setColumnCount(data.length); // Set the # of columns
((DefaultTableModel) getModel()).setColumnIdentifiers(data);
// Read and set the column tooltips
data = nextAvailableLine(scan).split(COMMA);
tooltips = new ArrayList<String>(Arrays.asList(data));
// Read and set all the column types
columnTypes.clear();
for (int i = 0; i < getColumnCount(); i++) {
columnTypes.add(null); // Add type placeholder
// Read the next line
data = nextAvailableLine(scan).split(COMMA);
// Set column type based on what was read
String type = data[0];
if (type.equals(CellType.TEXT.getTypeName())) {
setColumnType(i, CellType.TEXT);
} else if (type.equals(CellType.CHECK.getTypeName())) {
setColumnType(i, CellType.CHECK);
} else if (type.equals(CellType.COMBO.getTypeName())) {
// The line for COMBO contains all the entries, so these are set as well
setColumnType(i, CellType.COMBO, Arrays.copyOfRange(data, 1, data.length));
} else if (type.equals(CellType.NUMBER.getTypeName())) {
setColumnType(i, CellType.NUMBER);
}
}
log.info("JTB file \"{}\" successfully loaded", path);
} catch (FileNotFoundException e) {
log.info("JTB file \"{}\" not found", path);
e.printStackTrace();
}
}
/**
* Reads the file until a line that is not a comment and not blank is found
*
* @param scan File Scanner
* @return The next line that has any content
*/
private String nextAvailableLine(Scanner scan) {
String line;
// Keep reading until a line is found
while ((line = scan.nextLine()).startsWith(COMMENT) || line.length() == 0) ;
return line;
}
/**
* Saves the JTB table and creates a blank PRG file
*
* @param path Path to save the JTB
*/
public void saveTableToPath(String path) {
// Extension fix
if (!path.endsWith(EXTENSION)) {
path += EXTENSION;
}
try {
// Save table settings
PrintWriter pw = new PrintWriter(new FileOutputStream(FileUtils.getFile(path)));
pw.println(COMMENT + "Interactive JTable Save Data");
pw.println("\n" + COMMENT + "Column Headers and Tooltips, the number of headers sets the number of columns:");
// Print out all the column headers and tooltips
for (int i = 0; i < getColumnCount(); i++) {
pw.print(getColumnModel().getColumn(i).getHeaderValue() + (i == getColumnCount() - 1 ? "\n" : COMMA));
}
for (int i = 0; i < getColumnCount(); i++) {
pw.print(tooltips.get(i) + (i == getColumnCount() - 1 ? "\n" : COMMA));
}
pw.println("\n" + COMMENT + "The following lines are all the data types of the columns");
pw.println(COMMENT + "There are 4 types: Text, Checkbox, Combo Box, and Number. Their syntax is as follows:");
pw.printf("%s\"%s\"\n", COMMENT, CellType.TEXT.getTypeName());
pw.printf("%s\"%s\"\n", COMMENT, CellType.CHECK.getTypeName());
pw.printf("%s\"%s,choice,choice,choice,...\"\n", COMMENT, CellType.COMBO.getTypeName());
pw.printf("%s\"%s\"\n", COMMENT, CellType.NUMBER.getTypeName());
pw.println(COMMENT + "The number of lines MUST equal the number of columns");
// Print out all of the column types
for (int i = 0; i < getColumnCount(); i++) {
switch (columnTypes.get(i)) {
case TEXT:
pw.println("text");
break;
case CHECK:
pw.println("check");
break;
case COMBO:
pw.print("combo,");
// Print all of the combo box entries on the same line
JComboBox<String> combo = (JComboBox<String>) getColumnModel().getColumn(i).getCellEditor().getTableCellEditorComponent(null, null, false, -1, i);
for (int j = 0; j < combo.getItemCount(); j++) {
pw.print(combo.getItemAt(j) + (j == combo.getItemCount() - 1 ? "\n" : COMMA));
}
break;
case NUMBER:
pw.println(CellType.NUMBER.getTypeName());
break;
}
}
pw.flush();
pw.close();
log.info("JTB file \"{}\" successfully saved", path);
// Create a blank PRG file if it doesn't exist
int index = PROGRAM_DEFAULT;
if (index > 0) {
path = path.substring(0, path.lastIndexOf(EXTENSION)) + "-" + index + PROGRAM_EXTENSION;
if (!(FileUtils.exists(path))) {
pw = new PrintWriter(new FileOutputStream(FileUtils.getFile(path)));
pw.close();
log.info("Blank PRG file successfully saved to \"{}\"", path);
}
}
} catch (FileNotFoundException e) {
log.error("Error creating JTB file");
e.printStackTrace();
}
}
}
| UTF-8 | Java | 23,192 | java | ProgramTable.java | Java | [
{
"context": " as well as editing the column types\n *\n * @author Kareem ElFaramawi\n */\npublic class ProgramTable extends JTable {\n ",
"end": 1517,
"score": 0.9998687505722046,
"start": 1500,
"tag": "NAME",
"value": "Kareem ElFaramawi"
}
]
| null | []
| package com.bwat.hmi.prg;
import com.bwat.hmi.HMI;
import com.bwat.hmi.ui.KeyboardDialog;
import com.bwat.hmi.ui.KeypadDialog;
import com.bwat.hmi.ui.ListDialog;
import com.bwat.hmi.util.ArrayUtils;
import com.bwat.hmi.util.FileUtils;
import com.bwat.hmi.util.MathUtils;
import com.bwat.hmi.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Vector;
import static com.bwat.hmi.Constants.PROGRAM.*;
/**
* A wrapper around a JTable that gives functionality for loading and saving the table,
* as well as editing the column types
*
* @author <NAME>
*/
public class ProgramTable extends JTable {
Logger log = LoggerFactory.getLogger(getClass());
// List of all column types
private ArrayList<CellType> columnTypes = new ArrayList<CellType>();
// Lists of all the entries for COMBO columns
private HashMap<Integer, String[]> comboValues = new HashMap<Integer, String[]>();
// List of all mouseover tooltip messages
private ArrayList<String> tooltips = new ArrayList<String>();
// Used for keeping track of which column header was clicked
private int popupCol = 0;
public ProgramTable(int numRows, int numColumns) {
super(numRows, numColumns);
initGUI();
// Manually handle click events for certain column types
// to allow for a custom input method
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int r = rowAtPoint(e.getPoint()), c = columnAtPoint(e.getPoint());
if (MathUtils.inRange_in_ex(r, 0, getRowCount()) && MathUtils.inRange_in_ex(c, 0, getColumnCount())) {
switch (getColumnType(c)) {
case TEXT:
// TEXT input should open up a keyboard
setValueAt(KeyboardDialog.showDialog("Enter value: ", ""), r, c);
break;
case COMBO:
String[] vals = comboValues.get(c);
if (vals != null) {
// If this COMBO column contains only numeric entries, we should open up a
// keypad instead of a selection screen
boolean numeric = true;
for (String val : vals) {
if (!StringUtils.isNumber(val)) {
numeric = false;
break;
}
}
String newValue;
if (numeric) {
// Get a new value using the keypad interface
newValue = KeypadDialog.showDialog("Enter Value", "");
// Revert back to the original value if an invalid number is entered,
// or the number entered is not an option
if (!StringUtils.isNumber(newValue) || ArrayUtils.contains(vals, newValue)) {
newValue = (String) getValueAt(r, c);
}
} else {
// Get a new value with an enlarged combo box selection screen
newValue = ListDialog.showDialog("Select a Value", vals, (String) getValueAt(r, c), getFont(), 24f);
}
// Set the new value
setValueAt(newValue, r, c);
}
break;
case NUMBER:
// Get a new value using the keypad interface
String newValue;
newValue = KeypadDialog.showDialog("Enter Value", "");
if (!StringUtils.isNumber(newValue)) {
Object tval = getValueAt(r, c);
newValue = tval == null ? "0" : tval.toString();
}
// Set the new value
setValueAt(StringUtils.isNumber(newValue) ? Integer.parseInt(newValue) : null, r, c);
break;
}
}
}
});
}
/**
* Initializes all GUI components contained in the table
*/
void initGUI() {
// Set all columns to TEXT and set a default tooltip
for (int i = 0; i < getColumnCount(); i++) {
columnTypes.add(null);
setColumnType(i, CellType.TEXT);
tooltips.add("Col " + i);
}
// Initialize all settings for the right click popup menu
final JPopupMenu headerMenu = new JPopupMenu(); // Actual popup menu
// Add a listener to show the menu on right click
getTableHeader().addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
popupCol = getTableHeader().columnAtPoint(e.getPoint());
headerMenu.show(getTableHeader(), e.getX(), e.getY());
}
}
});
// Add a listener to display tooltips on mouse movement over the column header
getTableHeader().addMouseMotionListener(new MouseAdapter() {
public void mouseMoved(MouseEvent e) {
int col = getTableHeader().columnAtPoint(e.getPoint());
getTableHeader().setToolTipText(tooltips.get(col));
}
});
getTableHeader().setReorderingAllowed(false);
getTableHeader().setResizingAllowed(false);
getTableHeader().setBackground(getBackground());
getTableHeader().setForeground(getForeground());
// Initialize everything inside the popup menu
JMenu jmi_type = new JMenu("Column Type"); // Column type submenu
// Column data type choices
JMenuItem jmi_text = new JMenuItem("Text");
JMenuItem jmi_check = new JMenuItem("Checkbox");
JMenuItem jmi_combo = new JMenuItem("Combo Box");
JMenuItem jmi_num = new JMenuItem("Number");
// Text type
jmi_text.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setColumnType(popupCol, CellType.TEXT);
repaint();
}
});
// Checkbox type
jmi_check.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setColumnType(popupCol, CellType.CHECK);
repaint();
}
});
// Combo box type
jmi_combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Ask how many choices should be in the combobox
JSpinner numEntries = new JSpinner();
if (JOptionPane.showConfirmDialog(null, new Object[]{"How many entries?", numEntries}, "Combo Box Options", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
// Generate that many JTextFields and ask for all of the choices
int ents = (int) numEntries.getValue();
if (ents > 0) {
// Array of JTextFields
JTextField[] inputs = new JTextField[ents];
for (int i = 0; i < ents; i++) {
inputs[i] = new JTextField();
}
// Show prompt
if (JOptionPane.showConfirmDialog(null, inputs, "Enter Combo Box Choices", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
// Collect all the combo box choices
String[] entries = new String[ents];
for (int i = 0; i < ents; i++) {
entries[i] = inputs[i].getText();
}
// Set the column type
setColumnType(popupCol, CellType.COMBO, entries);
}
}
}
repaint();
}
});
// Number type
jmi_num.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setColumnType(popupCol, CellType.NUMBER);
repaint();
}
});
jmi_type.add(jmi_text);
jmi_type.add(jmi_check);
jmi_type.add(jmi_combo);
jmi_type.add(jmi_num);
// Option to rename header
JMenuItem jmi_rename = new JMenuItem("Rename");
jmi_rename.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JPanel dialog = new JPanel(new GridLayout(2, 2));
JTextField name = new JTextField(), tooltip = new JTextField();
dialog.add(new JLabel("Name:"));
dialog.add(name);
dialog.add(new JLabel("Tooltip:"));
dialog.add(tooltip);
if (JOptionPane.showConfirmDialog(null, dialog, "Column Settings", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
setColumnHeader(popupCol, name.getText().length() > 0 ? name.getText() : " ");
tooltips.set(popupCol, tooltip.getText().length() > 0 ? tooltip.getText() : " ");
}
repaint();
}
});
// Option to add column
JMenuItem jmi_add = new JMenuItem("Add Column");
final JMenuItem jmi_delete = new JMenuItem("Delete Column");
jmi_add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JPanel dialog = new JPanel(new GridLayout(2, 2));
JTextField name = new JTextField(), tooltip = new JTextField();
dialog.add(new JLabel("Name:"));
dialog.add(name);
dialog.add(new JLabel("Tooltip:"));
dialog.add(tooltip);
if (JOptionPane.showConfirmDialog(null, dialog, "Column Settings", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
getColumnModel().addColumn(new TableColumn());
columnTypes.add(null);
setColumnType(getColumnCount() - 1, CellType.TEXT);
setColumnHeader(getColumnCount() - 1, name.getText());
tooltips.add(tooltip.getText());
if (!jmi_delete.isEnabled()) {
jmi_delete.setEnabled(true);
}
}
repaint();
}
});
// Option to delete column
jmi_delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getColumnModel().removeColumn(getColumnModel().getColumn(popupCol));
columnTypes.remove(popupCol);
tooltips.remove(popupCol);
if (getColumnCount() == 1) {
jmi_delete.setEnabled(false);
}
repaint();
}
});
headerMenu.add(jmi_type);
headerMenu.add(jmi_rename);
headerMenu.add(jmi_add);
headerMenu.add(jmi_delete);
// Disallow column reordering
getTableHeader().setReorderingAllowed(false);
}
/**
* Copies all of the table data into a 2D list
*
* @return List of all table data
*/
public ArrayList<ArrayList<Object>> exportTableData() {
ArrayList<ArrayList<Object>> copy = new ArrayList<ArrayList<Object>>(getRowCount());
for (int row = 0; row < getRowCount(); row++) {
copy.add(new ArrayList<Object>(getColumnCount()));
for (int col = 0; col < getColumnCount(); col++) {
copy.get(row).add(getValueAt(row, col));
}
}
return copy;
}
/**
* Sets the name of a column
*
* @param column Column index
* @param header Name of the column
*/
public void setColumnHeader(int column, String header) {
getColumnModel().getColumn(column).setHeaderValue(header);
}
/**
* Sets a columns to a specific type
*
* @param column Column index
* @param type Column type
* @param comboEntries OPTIONAL, fill only if the type is COMBO, then this is the entries of the that
* combo box
*/
public void setColumnType(final int column, CellType type, final String... comboEntries) {
if (MathUtils.inRange_in_ex(column, 0, getColumnCount())) {
for (int i = 0; i < getRowCount(); i++) {
setValueAt(null, i, column);
}
columnTypes.set(column, type);
// Dummy editor to disable default action when clicking a cell
DefaultCellEditor dummy = new DefaultCellEditor(new JTextField());
dummy.setClickCountToStart(1000); // Nobody's doing that, let the MouseEvent take over
// Set up the column in the JTable
switch (type) {
case COMBO:
// Add entries into type
comboValues.put(column, comboEntries);
// Only set a renderer, editing handled by MouseEvent
JComboBoxCellRenderer renderer = new JComboBoxCellRenderer();
renderer.setModel(new DefaultComboBoxModel<String>(comboEntries));
renderer.setBackground(HMI.getInstance().getBackground());
renderer.setForeground(HMI.getInstance().getForeground());
renderer.setFont(HMI.getInstance().getFont());
getColumnModel().getColumn(column).setCellRenderer(renderer);
break;
case NUMBER:
case TEXT:
// These will all be handled by a MouseEvent
getColumnModel().getColumn(column).setCellEditor(dummy);
getColumnModel().getColumn(column).setCellRenderer(new DefaultTableCellRenderer());
break;
case CHECK:
// CHECK uses a Boolean, which gets represented as a checkbox
getColumnModel().getColumn(column).setCellEditor(getDefaultEditor(Boolean.class));
getColumnModel().getColumn(column).setCellRenderer(getDefaultRenderer(Boolean.class));
break;
}
}
}
/**
* @param col Column index
* @return The CellType of a column
*/
public CellType getColumnType(int col) {
// Range validation
if (!MathUtils.inRange_in_ex(col, 0, columnTypes.size())) {
log.error("Invalid column index: ", col);
return null;
}
return columnTypes.get(col);
}
/**
* Inserts a blank row at the end of the table
*/
public void insertRow() {
((DefaultTableModel) getModel()).addRow(new Vector<Object>());
}
/**
* Deletes all rows from the table
*/
public void deleteAllRows() {
((DefaultTableModel) getModel()).setRowCount(0);
}
/**
* Sets the value of a cell
*
* @param val Cell value
* @param row Row index
* @param col Column index
*/
public void setValueAt(Object val, int row, int col) {
getModel().setValueAt(val, convertRowIndexToModel(row), convertColumnIndexToModel(col));
}
/**
* @param row Row index
* @param col Column index
* @return Cell value at the given location
*/
public Object getValueAt(int row, int col) {
return getModel().getValueAt(row, col);
}
/**
* Loads the JTB data and formats the table
*
* @param path Path to the JTB file
*/
public void loadTableFromFile(String path) {
try {
Scanner scan = new Scanner(FileUtils.getFile(path)); // Open file stream
String[] data; // Holds temp data
// Read and set the column headers
data = nextAvailableLine(scan).split(COMMA);
((DefaultTableModel) getModel()).setColumnCount(data.length); // Set the # of columns
((DefaultTableModel) getModel()).setColumnIdentifiers(data);
// Read and set the column tooltips
data = nextAvailableLine(scan).split(COMMA);
tooltips = new ArrayList<String>(Arrays.asList(data));
// Read and set all the column types
columnTypes.clear();
for (int i = 0; i < getColumnCount(); i++) {
columnTypes.add(null); // Add type placeholder
// Read the next line
data = nextAvailableLine(scan).split(COMMA);
// Set column type based on what was read
String type = data[0];
if (type.equals(CellType.TEXT.getTypeName())) {
setColumnType(i, CellType.TEXT);
} else if (type.equals(CellType.CHECK.getTypeName())) {
setColumnType(i, CellType.CHECK);
} else if (type.equals(CellType.COMBO.getTypeName())) {
// The line for COMBO contains all the entries, so these are set as well
setColumnType(i, CellType.COMBO, Arrays.copyOfRange(data, 1, data.length));
} else if (type.equals(CellType.NUMBER.getTypeName())) {
setColumnType(i, CellType.NUMBER);
}
}
log.info("JTB file \"{}\" successfully loaded", path);
} catch (FileNotFoundException e) {
log.info("JTB file \"{}\" not found", path);
e.printStackTrace();
}
}
/**
* Reads the file until a line that is not a comment and not blank is found
*
* @param scan File Scanner
* @return The next line that has any content
*/
private String nextAvailableLine(Scanner scan) {
String line;
// Keep reading until a line is found
while ((line = scan.nextLine()).startsWith(COMMENT) || line.length() == 0) ;
return line;
}
/**
* Saves the JTB table and creates a blank PRG file
*
* @param path Path to save the JTB
*/
public void saveTableToPath(String path) {
// Extension fix
if (!path.endsWith(EXTENSION)) {
path += EXTENSION;
}
try {
// Save table settings
PrintWriter pw = new PrintWriter(new FileOutputStream(FileUtils.getFile(path)));
pw.println(COMMENT + "Interactive JTable Save Data");
pw.println("\n" + COMMENT + "Column Headers and Tooltips, the number of headers sets the number of columns:");
// Print out all the column headers and tooltips
for (int i = 0; i < getColumnCount(); i++) {
pw.print(getColumnModel().getColumn(i).getHeaderValue() + (i == getColumnCount() - 1 ? "\n" : COMMA));
}
for (int i = 0; i < getColumnCount(); i++) {
pw.print(tooltips.get(i) + (i == getColumnCount() - 1 ? "\n" : COMMA));
}
pw.println("\n" + COMMENT + "The following lines are all the data types of the columns");
pw.println(COMMENT + "There are 4 types: Text, Checkbox, Combo Box, and Number. Their syntax is as follows:");
pw.printf("%s\"%s\"\n", COMMENT, CellType.TEXT.getTypeName());
pw.printf("%s\"%s\"\n", COMMENT, CellType.CHECK.getTypeName());
pw.printf("%s\"%s,choice,choice,choice,...\"\n", COMMENT, CellType.COMBO.getTypeName());
pw.printf("%s\"%s\"\n", COMMENT, CellType.NUMBER.getTypeName());
pw.println(COMMENT + "The number of lines MUST equal the number of columns");
// Print out all of the column types
for (int i = 0; i < getColumnCount(); i++) {
switch (columnTypes.get(i)) {
case TEXT:
pw.println("text");
break;
case CHECK:
pw.println("check");
break;
case COMBO:
pw.print("combo,");
// Print all of the combo box entries on the same line
JComboBox<String> combo = (JComboBox<String>) getColumnModel().getColumn(i).getCellEditor().getTableCellEditorComponent(null, null, false, -1, i);
for (int j = 0; j < combo.getItemCount(); j++) {
pw.print(combo.getItemAt(j) + (j == combo.getItemCount() - 1 ? "\n" : COMMA));
}
break;
case NUMBER:
pw.println(CellType.NUMBER.getTypeName());
break;
}
}
pw.flush();
pw.close();
log.info("JTB file \"{}\" successfully saved", path);
// Create a blank PRG file if it doesn't exist
int index = PROGRAM_DEFAULT;
if (index > 0) {
path = path.substring(0, path.lastIndexOf(EXTENSION)) + "-" + index + PROGRAM_EXTENSION;
if (!(FileUtils.exists(path))) {
pw = new PrintWriter(new FileOutputStream(FileUtils.getFile(path)));
pw.close();
log.info("Blank PRG file successfully saved to \"{}\"", path);
}
}
} catch (FileNotFoundException e) {
log.error("Error creating JTB file");
e.printStackTrace();
}
}
}
| 23,181 | 0.536349 | 0.534322 | 553 | 40.938519 | 30.167463 | 181 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.674503 | false | false | 3 |
708a3c066dd7820620f675356db260804697a73a | 30,537,217,499,850 | 588382a90d3c8fe2d6f3c310283eb966aaf8cf9e | /src/BattleshipSearch.java | 67740f33b5b06aed4cfd5cdf1c991b09d32dba9b | []
| no_license | krazygaurav/BattleshipStrategies | https://github.com/krazygaurav/BattleshipStrategies | 4c84c3c94b53bb1676d7e303b9d9180589790c40 | 284165cfef5f4746fb73261895bb41c1eabf5d40 | refs/heads/master | 2021-05-04T12:25:16.478000 | 2018-02-09T17:56:04 | 2018-02-09T17:56:04 | 120,293,866 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class BattleshipSearch {
int grid[][];
public BattleshipSearch() {
grid = new int[25][25];
}
public void resetGrid() {
for (int row = 0; row < grid[0].length; row++) {
for (int column = 0; column < grid[0].length; column++) {
grid[row][column] = -1;
}
}
}
public List<String> readInput(String fileName) {
List<String> lines = null;
try {
lines = Files.readAllLines(Paths.get(fileName));
} catch (IOException e) {
e.printStackTrace();
}
return lines;
}
/*
* Initialize Grid with Carrier and Submarine 1 -> Carrier 2 -> Submarine
*/
public void prepareGrid(String str) {
resetGrid();
str = str.substring(1, str.length() - 1);
String[] parts = str.split("\\)\\(");
for (int i = 0; i < parts.length; i++) {
String coordinates[] = parts[i].split(",");
int x = Integer.parseInt(coordinates[0]);
int y = Integer.parseInt(coordinates[1]);
if (i < 5) {
grid[x][y] = 1;
} else {
grid[x][y] = 2;
}
}
}
// Showing the Grid to the User
public void showGrid() {
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == -1)
System.out.print("~ ");
else if (grid[i][j] == 1)
System.out.print("C ");
else if (grid[i][j] == 2)
System.out.print("S ");
}
System.out.println();
}
}
public void playGame() {
Strategy strategy = new HorizontalSweep();
strategy.search(grid);
strategy = new RandomSweep();
strategy.search(grid);
strategy = new StrategicSweep();
strategy.search(grid);
}
public static void main(String[] args) {
BattleshipSearch battleship = new BattleshipSearch();
int game_counter = 1;
List<String> game_lines = battleship.readInput("input.txt");
for (String str : game_lines) {
battleship.prepareGrid(str);
// battleship.showGrid();
System.out.println("Game "+(game_counter++)+":");
battleship.playGame();
}
}
} | UTF-8 | Java | 2,027 | java | BattleshipSearch.java | Java | []
| null | []
| import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class BattleshipSearch {
int grid[][];
public BattleshipSearch() {
grid = new int[25][25];
}
public void resetGrid() {
for (int row = 0; row < grid[0].length; row++) {
for (int column = 0; column < grid[0].length; column++) {
grid[row][column] = -1;
}
}
}
public List<String> readInput(String fileName) {
List<String> lines = null;
try {
lines = Files.readAllLines(Paths.get(fileName));
} catch (IOException e) {
e.printStackTrace();
}
return lines;
}
/*
* Initialize Grid with Carrier and Submarine 1 -> Carrier 2 -> Submarine
*/
public void prepareGrid(String str) {
resetGrid();
str = str.substring(1, str.length() - 1);
String[] parts = str.split("\\)\\(");
for (int i = 0; i < parts.length; i++) {
String coordinates[] = parts[i].split(",");
int x = Integer.parseInt(coordinates[0]);
int y = Integer.parseInt(coordinates[1]);
if (i < 5) {
grid[x][y] = 1;
} else {
grid[x][y] = 2;
}
}
}
// Showing the Grid to the User
public void showGrid() {
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == -1)
System.out.print("~ ");
else if (grid[i][j] == 1)
System.out.print("C ");
else if (grid[i][j] == 2)
System.out.print("S ");
}
System.out.println();
}
}
public void playGame() {
Strategy strategy = new HorizontalSweep();
strategy.search(grid);
strategy = new RandomSweep();
strategy.search(grid);
strategy = new StrategicSweep();
strategy.search(grid);
}
public static void main(String[] args) {
BattleshipSearch battleship = new BattleshipSearch();
int game_counter = 1;
List<String> game_lines = battleship.readInput("input.txt");
for (String str : game_lines) {
battleship.prepareGrid(str);
// battleship.showGrid();
System.out.println("Game "+(game_counter++)+":");
battleship.playGame();
}
}
} | 2,027 | 0.608288 | 0.595955 | 85 | 22.858824 | 17.826717 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.458823 | false | false | 3 |
5d364c6a716c925d158db2af7612608b228a2719 | 11,330,123,795,190 | 86f6bf9f7fb5a80551b239de793e41c05dde4c24 | /src/main/java/com/plopcas/bb/model/Image.java | 21b6f8b1a481fa8ea3331572ad1d7821d7f6daea | [
"MIT"
]
| permissive | plopcas/background-battle | https://github.com/plopcas/background-battle | 389759e1ad742a8d599988b1ca2782a2e4472f78 | 105723190bcc94d5d4312c14dae1e5d8f40c3db5 | refs/heads/master | 2022-08-28T00:36:58.691000 | 2020-05-24T15:54:54 | 2020-05-24T15:54:54 | 257,004,264 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.plopcas.bb.model;
public class Image {
private ImageData data;
public ImageData getData() {
return data;
}
public void setData(ImageData data) {
this.data = data;
}
}
| UTF-8 | Java | 219 | java | Image.java | Java | []
| null | []
| package com.plopcas.bb.model;
public class Image {
private ImageData data;
public ImageData getData() {
return data;
}
public void setData(ImageData data) {
this.data = data;
}
}
| 219 | 0.611872 | 0.611872 | 14 | 14.642858 | 14.013295 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 3 |
7f193ea477128cac80a1d2cc9343da1d84caa884 | 13,537,736,966,632 | abcbc6295dfc5cfaeeb0688553c8aae3835831d7 | /test/graphUtils/GraphUtilsTest.java | 498a47949a9aca072966ac532e9c2aba2b8c54cd | []
| no_license | albertpatterson/practice_algorithms | https://github.com/albertpatterson/practice_algorithms | 1fd4b1374f81ad2c783f0a8fb330b6801cc9012e | 50e86c0932431950a915dfd1c34262ebeb60d8de | refs/heads/master | 2021-01-01T04:55:04.653000 | 2017-11-04T14:05:41 | 2017-11-04T14:05:41 | 97,276,602 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package graphUtils;
import org.junit.Test;
import java.util.Arrays;
import java.util.LinkedList;
import static org.junit.Assert.*;
/**
* Created by apatters on 8/15/2017.
*/
public class GraphUtilsTest {
@Test
public void topoSort() throws Exception {
GraphUtils myUtils = new GraphUtils();
LinkedList<LinkedList<Integer>> graph = new LinkedList<>();
graph.add(0, new LinkedList<Integer>(Arrays.asList(1,2)));
graph.add(1, new LinkedList<Integer>());
graph.add(2, new LinkedList<Integer>(Arrays.asList(1)));
graph.add(3, new LinkedList<Integer>(Arrays.asList(1)));
graph.add(4, new LinkedList<Integer>(Arrays.asList(2)));
LinkedList<Integer> actSorting = myUtils.topoSort(graph);
LinkedList<Integer> expSorting = new LinkedList<>(Arrays.asList(4, 3, 0, 2, 1));
assertEquals(expSorting, actSorting);
}
} | UTF-8 | Java | 903 | java | GraphUtilsTest.java | Java | [
{
"context": "port static org.junit.Assert.*;\n\n/**\n * Created by apatters on 8/15/2017.\n */\npublic class GraphUtilsTest {\n ",
"end": 161,
"score": 0.9996739029884338,
"start": 153,
"tag": "USERNAME",
"value": "apatters"
}
]
| null | []
| package graphUtils;
import org.junit.Test;
import java.util.Arrays;
import java.util.LinkedList;
import static org.junit.Assert.*;
/**
* Created by apatters on 8/15/2017.
*/
public class GraphUtilsTest {
@Test
public void topoSort() throws Exception {
GraphUtils myUtils = new GraphUtils();
LinkedList<LinkedList<Integer>> graph = new LinkedList<>();
graph.add(0, new LinkedList<Integer>(Arrays.asList(1,2)));
graph.add(1, new LinkedList<Integer>());
graph.add(2, new LinkedList<Integer>(Arrays.asList(1)));
graph.add(3, new LinkedList<Integer>(Arrays.asList(1)));
graph.add(4, new LinkedList<Integer>(Arrays.asList(2)));
LinkedList<Integer> actSorting = myUtils.topoSort(graph);
LinkedList<Integer> expSorting = new LinkedList<>(Arrays.asList(4, 3, 0, 2, 1));
assertEquals(expSorting, actSorting);
}
} | 903 | 0.666667 | 0.642303 | 30 | 29.133333 | 26.873447 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.866667 | false | false | 3 |
7cb84fd28e6e551240017d8b3c9f9cc578598caf | 5,798,205,866,092 | 0c5aad336ffa576b7fdf6c8d4d595022b29701a2 | /SlotsScheduler.java | bcfbcdf3d90ab64bbc64aed1898450275e88159a | []
| no_license | PabloPessolani/slots | https://github.com/PabloPessolani/slots | b7b10c2d1cf7cafda99783c583dcd62e8e53d139 | ca65cea1731290cb0f834f499e1a875cd65f969a | refs/heads/master | 2020-03-19T09:44:18.069000 | 2018-06-06T10:42:11 | 2018-06-06T10:42:11 | 68,021,941 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import daj.Scheduler;
public class SlotsScheduler extends Scheduler {
private int last = -1;
// --------------------------------------------------------------------------
// return index of next program for execution (-1, if none)
// --------------------------------------------------------------------------
@Override
public int nextProgram() {
int n = getNumber();
boolean reset = false;
if(isReady(0)) {
return -1;
}
do {
incTime();
last++;
if (last == n) {
last = 0;
if (reset) return -1;
reset = true;
}
}
while (!isReady(last));
return last;
}
} | UTF-8 | Java | 673 | java | SlotsScheduler.java | Java | []
| null | []
|
import daj.Scheduler;
public class SlotsScheduler extends Scheduler {
private int last = -1;
// --------------------------------------------------------------------------
// return index of next program for execution (-1, if none)
// --------------------------------------------------------------------------
@Override
public int nextProgram() {
int n = getNumber();
boolean reset = false;
if(isReady(0)) {
return -1;
}
do {
incTime();
last++;
if (last == n) {
last = 0;
if (reset) return -1;
reset = true;
}
}
while (!isReady(last));
return last;
}
} | 673 | 0.395245 | 0.38633 | 29 | 22.206896 | 20.62536 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.896552 | false | false | 3 |
69ad93977da128479c9f9eb1c8a08ca9ad41836b | 22,711,787,077,270 | e869aedfba62bc6fffbffbb8fd5dfb3b68591326 | /src/main/java/ua/aval/cmd/conference/service/ConferenceServiceImpl.java | bb6e93b07f71a6afd17281bcb715487d064daca5 | []
| no_license | FeschenkoNatalia/conference-service | https://github.com/FeschenkoNatalia/conference-service | 5e1de15e7e9027d6d5f3f0aca429eab2353bb593 | 8f9e61135464c9db539868269f282124dc220a6c | refs/heads/master | 2023-03-20T18:47:48.836000 | 2021-03-16T10:44:15 | 2021-03-16T10:44:15 | 348,306,406 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ua.aval.cmd.conference.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import ua.aval.cmd.conference.adaptors.persistence.ConferenceDao;
import ua.aval.cmd.conference.domain.Conference;
import ua.aval.cmd.conference.exception.ConferenceNotFoundException;
import ua.aval.cmd.conference.service.validate.ValidationService;
import java.util.List;
import java.util.Optional;
@Slf4j
@Service
@RequiredArgsConstructor
public class ConferenceServiceImpl implements ConferenceService {
private final ConferenceDao conferenceDao;
private final ValidationService validationService;
@Override
public Conference saveConference(Conference conference) {
validationService.checkIfValidConference(conference);
return conferenceDao.save(conference);
}
@Override
public List<Conference> findAllConference() {
return conferenceDao.findAll();
}
@Override
public void updateConference(Long id, Conference conference) {
validationService.checkIfValidConference(conference);
Optional<Conference> conf = conferenceDao.findConferenceById(id);
conf.ifPresentOrElse(
c -> {
conference.setId(id);
conferenceDao.save(conference);
},
() -> {
throw new ConferenceNotFoundException(id);
});
}
}
| UTF-8 | Java | 1,314 | java | ConferenceServiceImpl.java | Java | []
| null | []
| package ua.aval.cmd.conference.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import ua.aval.cmd.conference.adaptors.persistence.ConferenceDao;
import ua.aval.cmd.conference.domain.Conference;
import ua.aval.cmd.conference.exception.ConferenceNotFoundException;
import ua.aval.cmd.conference.service.validate.ValidationService;
import java.util.List;
import java.util.Optional;
@Slf4j
@Service
@RequiredArgsConstructor
public class ConferenceServiceImpl implements ConferenceService {
private final ConferenceDao conferenceDao;
private final ValidationService validationService;
@Override
public Conference saveConference(Conference conference) {
validationService.checkIfValidConference(conference);
return conferenceDao.save(conference);
}
@Override
public List<Conference> findAllConference() {
return conferenceDao.findAll();
}
@Override
public void updateConference(Long id, Conference conference) {
validationService.checkIfValidConference(conference);
Optional<Conference> conf = conferenceDao.findConferenceById(id);
conf.ifPresentOrElse(
c -> {
conference.setId(id);
conferenceDao.save(conference);
},
() -> {
throw new ConferenceNotFoundException(id);
});
}
}
| 1,314 | 0.796804 | 0.794521 | 47 | 26.957447 | 23.479242 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.638298 | false | false | 3 |
c4a0127f6d42d3c3ba3d2efdcf7017e1067da537 | 27,058,293,982,294 | b2dceb4d9496d0b732a0ff69f869cba42abd4773 | /src/FinalAssignment/Tabs.java | ce3e36eab38e4542d411d31ce1918f30231abe2a | [
"BSD-2-Clause"
]
| permissive | dborncamp/OO_methodology | https://github.com/dborncamp/OO_methodology | 147c6a4853402a9624e2259bf54979550e5c53b5 | 6ea0ed8c2e4b3c07ea6742923bf1c08b705c5226 | refs/heads/master | 2021-01-21T11:44:52.163000 | 2016-05-14T16:25:37 | 2016-05-14T16:25:37 | 51,211,517 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package FinalAssignment;
import java.util.ArrayList;
/**
*
* @author Dave Borncamp <dbornc1@students.towson.edu>
* @date Apr 12, 2016
*
* Created for COSC 716 Spring 2016 at Towson University.
*
*
*/
public class Tabs {
private ArrayList<OrderItems> tabArray; // the list of things on the tab
private static int tabId = 0; // Auto increments when default constructor called.
public Tabs(){
Tabs.tabId ++;
}
/**
* Copy Constructor for a menu
* @param oldTab - old menu to copy.
*
* The tabId will not be incremented when this is called.
*/
public Tabs(Tabs oldTab){
settabs(oldTab.getAlltabs());
}
/**
* Constructor for making a tab out of orders.
* @param orders - Orders that will make up the tab.
*/
public Tabs(Orders orders){
settabs(orders.getAllOrders());
}
/**
* Add an item to the ArrayList or tabArray items.
* @param item - Item to add.
*/
public void addItem(OrderItems item){
tabArray.add(item);
}
/**
* Add an item to the ArrayList or tabArray items but builds the MenuItem in place.
*
* @param name - Name of item.
* @param descrip - Description of Item.
* @param price - Price of item
* @param ingredients - Ingredients for MenuItem
*/
public void addItem(String name, String descrip, double price, ArrayList ingredients){
MenuItems tmpMenu = new MenuItems(name, descrip, price, ingredients);
OrderItems tmpOrder = new OrderItems( tmpMenu);
tabArray.add(tmpOrder);
}
/**
* Removes a given item from the tabArray items
* @param item - Item to remove.
*/
public void removeItem(MenuItems item){
tabArray.remove(item);
}
public int getTabId(){
return this.tabId;
}
/**
* Get the total price of the items in the tab.
* @return - Total price of items in tabArray.
*/
private double getTotal(){
double sum = 0.0;
for (OrderItems i:tabArray){
sum += i.getOrderedItem().getPrice();
}
return sum;
}
// Should only be called by copy constructor
private ArrayList getAlltabs(){
return tabArray;
}
// Should only be called by copy constructor
private void settabs(ArrayList tab){
for (OrderItems i:tabArray){
try{
addItem(i);
} catch(Exception e){
System.out.println("Somehow encountered a non-menu item in Tabs...");
e.printStackTrace();
}
}
}
}
| UTF-8 | Java | 2,693 | java | Tabs.java | Java | [
{
"context": "t;\n\nimport java.util.ArrayList;\n\n/**\n *\n * @author Dave Borncamp <dbornc1@students.towson.edu>\n * @date Apr 12, 20",
"end": 86,
"score": 0.9998489618301392,
"start": 73,
"tag": "NAME",
"value": "Dave Borncamp"
},
{
"context": "util.ArrayList;\n\n/**\n *\n * @author Dave Borncamp <dbornc1@students.towson.edu>\n * @date Apr 12, 2016\n * \n * Created for COSC 71",
"end": 115,
"score": 0.999935507774353,
"start": 88,
"tag": "EMAIL",
"value": "dbornc1@students.towson.edu"
}
]
| null | []
| package FinalAssignment;
import java.util.ArrayList;
/**
*
* @author <NAME> <<EMAIL>>
* @date Apr 12, 2016
*
* Created for COSC 716 Spring 2016 at Towson University.
*
*
*/
public class Tabs {
private ArrayList<OrderItems> tabArray; // the list of things on the tab
private static int tabId = 0; // Auto increments when default constructor called.
public Tabs(){
Tabs.tabId ++;
}
/**
* Copy Constructor for a menu
* @param oldTab - old menu to copy.
*
* The tabId will not be incremented when this is called.
*/
public Tabs(Tabs oldTab){
settabs(oldTab.getAlltabs());
}
/**
* Constructor for making a tab out of orders.
* @param orders - Orders that will make up the tab.
*/
public Tabs(Orders orders){
settabs(orders.getAllOrders());
}
/**
* Add an item to the ArrayList or tabArray items.
* @param item - Item to add.
*/
public void addItem(OrderItems item){
tabArray.add(item);
}
/**
* Add an item to the ArrayList or tabArray items but builds the MenuItem in place.
*
* @param name - Name of item.
* @param descrip - Description of Item.
* @param price - Price of item
* @param ingredients - Ingredients for MenuItem
*/
public void addItem(String name, String descrip, double price, ArrayList ingredients){
MenuItems tmpMenu = new MenuItems(name, descrip, price, ingredients);
OrderItems tmpOrder = new OrderItems( tmpMenu);
tabArray.add(tmpOrder);
}
/**
* Removes a given item from the tabArray items
* @param item - Item to remove.
*/
public void removeItem(MenuItems item){
tabArray.remove(item);
}
public int getTabId(){
return this.tabId;
}
/**
* Get the total price of the items in the tab.
* @return - Total price of items in tabArray.
*/
private double getTotal(){
double sum = 0.0;
for (OrderItems i:tabArray){
sum += i.getOrderedItem().getPrice();
}
return sum;
}
// Should only be called by copy constructor
private ArrayList getAlltabs(){
return tabArray;
}
// Should only be called by copy constructor
private void settabs(ArrayList tab){
for (OrderItems i:tabArray){
try{
addItem(i);
} catch(Exception e){
System.out.println("Somehow encountered a non-menu item in Tabs...");
e.printStackTrace();
}
}
}
}
| 2,666 | 0.580394 | 0.574081 | 102 | 25.40196 | 22.782543 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.264706 | false | false | 3 |
20a83e4898d1e0c903bdd44ddd81de82923dae4c | 28,484,223,126,618 | 7bcb9b7de0175feeaa6f77f6d6009cc3191aaac0 | /app/src/main/java/com/agilie/internship/ui/splash/SplashContract.java | aac082bcca76a20789465b64ae4e7f6a49210676 | []
| no_license | akotsuba/InternshipChat | https://github.com/akotsuba/InternshipChat | 29cb36a0511d1b233c21cd5e957edb25fb42646a | ffb1c5e6e08dfc3d6a1a194eb31f3ebc95f18fff | refs/heads/master | 2021-01-11T21:05:56.111000 | 2017-02-01T14:09:53 | 2017-02-01T14:09:53 | 79,243,577 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.agilie.internship.ui.splash;
public interface SplashContract {
interface Model {
}
interface View {
void navigateToRegistration();
}
interface Presenter {
void resume();
void pause();
}
}
| UTF-8 | Java | 253 | java | SplashContract.java | Java | []
| null | []
| package com.agilie.internship.ui.splash;
public interface SplashContract {
interface Model {
}
interface View {
void navigateToRegistration();
}
interface Presenter {
void resume();
void pause();
}
}
| 253 | 0.604743 | 0.604743 | 17 | 13.882353 | 13.982688 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.235294 | false | false | 3 |
f225bc34c60d8d8ae96cbd768bc1ebb88c2bf058 | 19,447,611,939,645 | 88500f616a2c69315e45e2130fb756388c5a8da9 | /src/Lab1/ProposedExercices/LabTimeExercices/waitnotify/sync/LockSyncRunner.java | 8dbcd13139a5a19cb0e36f5d93a9a04ca2eee3bf | []
| no_license | AlexandruM98/Laboratoare-CPD | https://github.com/AlexandruM98/Laboratoare-CPD | d5d80022b28162544e748c3097b175c5ab8a05e9 | d18d26a83b56bed071b960b2f86b4eef7125e0b6 | refs/heads/main | 2023-03-16T06:08:23.231000 | 2021-03-04T17:48:19 | 2021-03-04T17:48:19 | 343,503,554 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Lab1.ProposedExercices.LabTimeExercices.waitnotify.sync;
public class LockSyncRunner {
public static void run() {
Data dataObj = new Data();
System.out.println("Initialize threads synchronized by lock");
Producer p = new Producer(1000, dataObj);
Consumer c = new Consumer(3000, dataObj);
System.out.println("Start threads synchronized by lock");
p.start();
c.start();
}
}
| UTF-8 | Java | 416 | java | LockSyncRunner.java | Java | []
| null | []
| package Lab1.ProposedExercices.LabTimeExercices.waitnotify.sync;
public class LockSyncRunner {
public static void run() {
Data dataObj = new Data();
System.out.println("Initialize threads synchronized by lock");
Producer p = new Producer(1000, dataObj);
Consumer c = new Consumer(3000, dataObj);
System.out.println("Start threads synchronized by lock");
p.start();
c.start();
}
}
| 416 | 0.699519 | 0.677885 | 16 | 25 | 23.913908 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false | 3 |
a9570d326949067d518092f9abe08ec5efbc5522 | 2,594,160,268,553 | cfcaf63b3c25b30d3c383c9399b2f38c581eda86 | /leetcode_notes/leetcode_cn/0200.岛屿数量/0200-岛屿数量.java | e108a39466909bb4464414868a5c1bc58804ef99 | [
"BSD-3-Clause"
]
| permissive | robinali/java_notes | https://github.com/robinali/java_notes | f361f525599495f8709691d60885a0a3faeb897b | b462c75851c1cd234b4027cd2b6181f0fbb0ef60 | refs/heads/master | 2021-06-18T09:23:33.244000 | 2021-04-13T02:32:33 | 2021-04-13T02:32:33 | 200,970,947 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Solution {
// 200
// Reference: Huahua
// DFS
private final List<int[]> DIRECTIONS = Arrays.asList(
new int[] {0, 1},
new int[] {0, -1},
new int[] {1, 0},
new int[] {-1, 0});
public int numIslands(char[][] grid) {
// Time: O(mn) Space: O(mn)
int m = grid.length;
if(m == 0) return 0;
int n = grid[0].length;
if(n == 0) return 0;
int ans = 0;
for(int y = 0; y < m; y++) {
for(int x = 0; x < n; x++) {
if(grid[y][x] == '1') {
ans++;
dfs(grid, x, y, n, m);
}
}
}
return ans;
}
private void dfs(char[][] grid, int x, int y, int n, int m) {
if(x < 0 || y < 0 || x >= n || y >= m || grid[y][x] == '0') {
return;
}
grid[y][x] = '0';
for(int[] direction : DIRECTIONS) {
dfs(grid, x + direction[0], y + direction[1], n, m);
}
}
} | UTF-8 | Java | 1,035 | java | 0200-岛屿数量.java | Java | [
{
"context": "class Solution {\n // 200\n // Reference: Huahua\n // DFS\n\n private final List<int[]> DIR",
"end": 48,
"score": 0.6639492511749268,
"start": 46,
"tag": "NAME",
"value": "Hu"
}
]
| null | []
| class Solution {
// 200
// Reference: Huahua
// DFS
private final List<int[]> DIRECTIONS = Arrays.asList(
new int[] {0, 1},
new int[] {0, -1},
new int[] {1, 0},
new int[] {-1, 0});
public int numIslands(char[][] grid) {
// Time: O(mn) Space: O(mn)
int m = grid.length;
if(m == 0) return 0;
int n = grid[0].length;
if(n == 0) return 0;
int ans = 0;
for(int y = 0; y < m; y++) {
for(int x = 0; x < n; x++) {
if(grid[y][x] == '1') {
ans++;
dfs(grid, x, y, n, m);
}
}
}
return ans;
}
private void dfs(char[][] grid, int x, int y, int n, int m) {
if(x < 0 || y < 0 || x >= n || y >= m || grid[y][x] == '0') {
return;
}
grid[y][x] = '0';
for(int[] direction : DIRECTIONS) {
dfs(grid, x + direction[0], y + direction[1], n, m);
}
}
} | 1,035 | 0.371981 | 0.34686 | 41 | 24.268293 | 17.653887 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.04878 | false | false | 3 |
bc156f34aa24f37f93b2822d737662f2ed316c9e | 2,594,160,268,927 | d433c425662a30dc46695c1158ed2a8a6bdcaa66 | /qbo-modules/qbo-admin/src/main/java/com/qbo/educate/admin/mapper/GateLogMapper.java | 3a38b5b9c33c63d1ef514e3d56050bbe6a5d24d8 | [
"Apache-2.0"
]
| permissive | zhangzhenguan/qbo-cloud | https://github.com/zhangzhenguan/qbo-cloud | 79b5e3a2621fe0d652ede30e8671052717252dc2 | cc70292587f84f0eda5fb667ee36bf5830aa7e38 | refs/heads/master | 2022-07-24T12:30:19.406000 | 2019-08-01T07:02:55 | 2019-08-01T07:02:55 | 198,814,149 | 0 | 0 | Apache-2.0 | false | 2022-06-21T01:33:15 | 2019-07-25T10:56:10 | 2019-08-01T09:58:40 | 2022-06-21T01:33:11 | 66,552 | 0 | 0 | 9 | JavaScript | false | false | package com.qbo.educate.admin.mapper;
import com.qbo.educate.admin.entity.GateLog;
import tk.mybatis.mapper.common.Mapper;
public interface GateLogMapper extends Mapper<GateLog> {
} | UTF-8 | Java | 183 | java | GateLogMapper.java | Java | []
| null | []
| package com.qbo.educate.admin.mapper;
import com.qbo.educate.admin.entity.GateLog;
import tk.mybatis.mapper.common.Mapper;
public interface GateLogMapper extends Mapper<GateLog> {
} | 183 | 0.814208 | 0.814208 | 7 | 25.285715 | 22.320486 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 3 |
200f65d491b158168985abed4eefc3e7af049160 | 11,115,375,386,151 | b26c328181b4839f9a650a34a73b2c108c7287a4 | /src/org/ifraytech/tools/ScalaSlickMappingGenerator.java | 33e1ebaff87c1c400aebb70d5b41f1a676b6d1a1 | []
| no_license | ifelere/play.evolutions.entities.generator | https://github.com/ifelere/play.evolutions.entities.generator | cac7457f37da4d78724fdccd2acd4e3d28a1f539 | 726f53f17d915bc8c82387c2534ed4fa395386fd | refs/heads/master | 2023-07-13T08:43:10.924000 | 2021-08-28T01:18:48 | 2021-08-28T01:18:48 | 400,669,774 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 org.ifraytech.tools;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.ifraytech.tools.ui.SlickMappingOptions;
/**
* A generate that generates slick mapping for entities using an embedded Velocity template
* @author ifelere
*/
public class ScalaSlickMappingGenerator extends SlickMappingGenerator {
@Override
public void write(EntityCollection collection, SlickMappingOptions options, GeneratorListener listener) throws IOException {
listener.calculatedWorkSize(10);
File outputFile = new File(options.getDestination(), String.format("%s.scala", options.getWrappClassName()));
listener.onMessage(String.format("Will be generated to %s", outputFile.getAbsolutePath()));
if (outputFile.exists()) {
outputFile.delete();
}
try (
FileWriter writer = new FileWriter(outputFile)
) {
VelocityEngine engine = new VelocityEngine();
engine.setProperty(RuntimeConstants.RESOURCE_LOADERS, "class");
engine.setProperty("resource.loader.class.class", ClasspathResourceLoader.class.getName());
engine.init();
Template t = engine.getTemplate("/org/ifraytech/tools/resources/play.slick-table.schema.template");
listener.onWorkDone(3);
listener.onMessage("Loaded mapping template");
VelocityContext ctx = new VelocityContext();
ctx.put("helper", new SlickMappingVelocityHelper());
ctx.put("collection", collection);
ctx.put("schemaPackageName", options.getPackageName());
ctx.put("entitiesPackage", getEntityPackageName());
ctx.put("wrapperClassName", options.getWrappClassName());
ctx.put("slickProfile", options.getSlickProfile());
ctx.put("additionalImports", stringToList(options.getAdditionalImports()));
ctx.put("extensions", stringToList(options.getExtensions()));
listener.onWorkDone(5);
t.merge(ctx, writer);
listener.onWorkDone(10);
listener.onMessage(String.format("Generated to %s successfully", outputFile.getAbsolutePath()));
listener.onComplete();
}
}
private static List<String> stringToList(String text) {
if (StringUtils.isBlank(text)) {
return Collections.EMPTY_LIST;
}
try (
BufferedReader reader = new BufferedReader(new StringReader(text))
) {
return reader.lines()
.map(x -> x.trim())
.filter(x -> !x.isEmpty())
.collect(Collectors.toList());
} catch (IOException ex) {
Logger.getLogger(ScalaSlickMappingGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
return Collections.EMPTY_LIST;
}
}
| UTF-8 | Java | 3,755 | java | ScalaSlickMappingGenerator.java | Java | [
{
"context": "ies using an embedded Velocity template\n * @author ifelere\n */\npublic class ScalaSlickMappingGenerator exten",
"end": 973,
"score": 0.9989030957221985,
"start": 966,
"tag": "USERNAME",
"value": "ifelere"
}
]
| null | []
| /*
* 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 org.ifraytech.tools;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.ifraytech.tools.ui.SlickMappingOptions;
/**
* A generate that generates slick mapping for entities using an embedded Velocity template
* @author ifelere
*/
public class ScalaSlickMappingGenerator extends SlickMappingGenerator {
@Override
public void write(EntityCollection collection, SlickMappingOptions options, GeneratorListener listener) throws IOException {
listener.calculatedWorkSize(10);
File outputFile = new File(options.getDestination(), String.format("%s.scala", options.getWrappClassName()));
listener.onMessage(String.format("Will be generated to %s", outputFile.getAbsolutePath()));
if (outputFile.exists()) {
outputFile.delete();
}
try (
FileWriter writer = new FileWriter(outputFile)
) {
VelocityEngine engine = new VelocityEngine();
engine.setProperty(RuntimeConstants.RESOURCE_LOADERS, "class");
engine.setProperty("resource.loader.class.class", ClasspathResourceLoader.class.getName());
engine.init();
Template t = engine.getTemplate("/org/ifraytech/tools/resources/play.slick-table.schema.template");
listener.onWorkDone(3);
listener.onMessage("Loaded mapping template");
VelocityContext ctx = new VelocityContext();
ctx.put("helper", new SlickMappingVelocityHelper());
ctx.put("collection", collection);
ctx.put("schemaPackageName", options.getPackageName());
ctx.put("entitiesPackage", getEntityPackageName());
ctx.put("wrapperClassName", options.getWrappClassName());
ctx.put("slickProfile", options.getSlickProfile());
ctx.put("additionalImports", stringToList(options.getAdditionalImports()));
ctx.put("extensions", stringToList(options.getExtensions()));
listener.onWorkDone(5);
t.merge(ctx, writer);
listener.onWorkDone(10);
listener.onMessage(String.format("Generated to %s successfully", outputFile.getAbsolutePath()));
listener.onComplete();
}
}
private static List<String> stringToList(String text) {
if (StringUtils.isBlank(text)) {
return Collections.EMPTY_LIST;
}
try (
BufferedReader reader = new BufferedReader(new StringReader(text))
) {
return reader.lines()
.map(x -> x.trim())
.filter(x -> !x.isEmpty())
.collect(Collectors.toList());
} catch (IOException ex) {
Logger.getLogger(ScalaSlickMappingGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
return Collections.EMPTY_LIST;
}
}
| 3,755 | 0.643142 | 0.641278 | 101 | 36.178219 | 30.777514 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.683168 | false | false | 3 |
7de88b76b1dd7bcf0404d3a8aae2e8b6e7f0a117 | 6,227,702,624,231 | 43001f68dbced30dfae9c474a953edea667ae119 | /nutricounter/src/main/java/com/irenailieva/nutricounter/services/implementations/DiaryServiceImpl.java | ce017e184cfbe8fa1f09bbd5557ad43da5425cda | [
"MIT"
]
| permissive | irenailieva/nutricounter | https://github.com/irenailieva/nutricounter | 030a61aa5be4a176303d0e964d8e7733238577d6 | 6e73205ac5fdc95b7d492f808c25e9ed595e3df2 | refs/heads/master | 2020-03-09T23:29:56.549000 | 2019-01-02T09:03:31 | 2019-01-02T09:03:31 | 129,059,323 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.irenailieva.nutricounter.services.implementations;
import com.irenailieva.nutricounter.entities.DiaryEntry;
import com.irenailieva.nutricounter.entities.User;
import com.irenailieva.nutricounter.models.view.DiaryEntryViewModel;
import com.irenailieva.nutricounter.repositories.DiaryEntryRepository;
import com.irenailieva.nutricounter.services.interfaces.DiaryService;
import com.irenailieva.nutricounter.services.interfaces.UserService;
import com.irenailieva.nutricounter.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
@Service
@Transactional
public class DiaryServiceImpl implements DiaryService {
private DiaryEntryRepository diaryEntryRepository;
private UserService userService;
@Autowired
public DiaryServiceImpl(DiaryEntryRepository diaryEntryRepository, UserService userService) {
this.diaryEntryRepository = diaryEntryRepository;
this.userService = userService;
}
@Override
public DiaryEntry addDiaryEntry(int completionPercentage, String username) {
User user = this.userService.findByUsername(username);
DiaryEntry newDiaryEntry = new DiaryEntry();
newDiaryEntry.setUser(user);
newDiaryEntry.setDate(DateUtil.getToday());
newDiaryEntry.setCompletionPercentage(completionPercentage);
this.diaryEntryRepository.saveAndFlush(newDiaryEntry);
return newDiaryEntry;
}
@Override
public List<DiaryEntryViewModel> getDiaryHistory(String username) {
User user = this.userService.findByUsername(username);
List<DiaryEntry> diaryEntries = this.diaryEntryRepository.findAllByUserOrderByIdDesc(user);
List<DiaryEntryViewModel> diaryEntryViewModels = new ArrayList<>();
for (DiaryEntry diaryEntry : diaryEntries) {
DiaryEntryViewModel entryViewModel = new DiaryEntryViewModel();
entryViewModel.setCompletionPercentage(diaryEntry.getCompletionPercentage());
entryViewModel.setDate(DateUtil.getDateAsString(diaryEntry.getDate()));
diaryEntryViewModels.add(entryViewModel);
}
return diaryEntryViewModels;
}
}
| UTF-8 | Java | 2,310 | java | DiaryServiceImpl.java | Java | []
| null | []
| package com.irenailieva.nutricounter.services.implementations;
import com.irenailieva.nutricounter.entities.DiaryEntry;
import com.irenailieva.nutricounter.entities.User;
import com.irenailieva.nutricounter.models.view.DiaryEntryViewModel;
import com.irenailieva.nutricounter.repositories.DiaryEntryRepository;
import com.irenailieva.nutricounter.services.interfaces.DiaryService;
import com.irenailieva.nutricounter.services.interfaces.UserService;
import com.irenailieva.nutricounter.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
@Service
@Transactional
public class DiaryServiceImpl implements DiaryService {
private DiaryEntryRepository diaryEntryRepository;
private UserService userService;
@Autowired
public DiaryServiceImpl(DiaryEntryRepository diaryEntryRepository, UserService userService) {
this.diaryEntryRepository = diaryEntryRepository;
this.userService = userService;
}
@Override
public DiaryEntry addDiaryEntry(int completionPercentage, String username) {
User user = this.userService.findByUsername(username);
DiaryEntry newDiaryEntry = new DiaryEntry();
newDiaryEntry.setUser(user);
newDiaryEntry.setDate(DateUtil.getToday());
newDiaryEntry.setCompletionPercentage(completionPercentage);
this.diaryEntryRepository.saveAndFlush(newDiaryEntry);
return newDiaryEntry;
}
@Override
public List<DiaryEntryViewModel> getDiaryHistory(String username) {
User user = this.userService.findByUsername(username);
List<DiaryEntry> diaryEntries = this.diaryEntryRepository.findAllByUserOrderByIdDesc(user);
List<DiaryEntryViewModel> diaryEntryViewModels = new ArrayList<>();
for (DiaryEntry diaryEntry : diaryEntries) {
DiaryEntryViewModel entryViewModel = new DiaryEntryViewModel();
entryViewModel.setCompletionPercentage(diaryEntry.getCompletionPercentage());
entryViewModel.setDate(DateUtil.getDateAsString(diaryEntry.getDate()));
diaryEntryViewModels.add(entryViewModel);
}
return diaryEntryViewModels;
}
}
| 2,310 | 0.775325 | 0.775325 | 61 | 36.868851 | 30.498844 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.557377 | false | false | 3 |
0bb3d32e4a4c56edd25488e28a8c871c664e7f36 | 31,894,427,192,325 | c658630391931f4da3a0730394b4630bf5d475c6 | /src/main/java/com/julius/user/service/impl/UserServiceImpl.java | 12a457facab4d06d71f8b4186eb8dc8609d4fa89 | []
| no_license | juliuszhang/PiKaEmonBBS | https://github.com/juliuszhang/PiKaEmonBBS | 61164bb20142b6a71585d56ed75a062ea4ee2ecf | 1187e835d479e1ee1074b7da2d48fcff508ce14b | refs/heads/master | 2016-08-31T13:34:59.402000 | 2016-06-22T15:03:58 | 2016-06-22T15:03:58 | 40,640,901 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (C) 2006-2015
* 本系统是商用软件,未经授权擅自复制或传播本程序的部分或全部将是非法的.
========================================
* FileName: UserServiceImpl.java
* Created: [2015年8月19日 下午3:07:33] by julius
* 更新:$Date$
* 作者:$Author$
* 版本:$Rev$
* ID:$Id$
========================================
* ProjectName: PiKaEmonBBS
* Description: 用户Service实现
======================================*/
package com.julius.user.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.julius.common.service.impl.BaseServiceImpl;
import com.julius.user.dao.UserDao;
import com.julius.user.model.UserModel;
import com.julius.user.service.UserService;
/**
* Description:用户Service实现
* @author julius
*/
@Service
public class UserServiceImpl extends BaseServiceImpl<UserModel, UserDao> implements UserService {
@Autowired
private UserDao userDao;
public void addRollBackTest() throws Exception{
int i=0;
UserModel user1 = new UserModel();
user1.setNickName("张三");
userDao.save(user1);
UserModel user2 = new UserModel();
user2.setNickName("李四");
userDao.save(user2);
}
}
| UTF-8 | Java | 1,323 | java | UserServiceImpl.java | Java | [
{
"context": "e;\r\n\r\n/** \r\n * Description:用户Service实现\r\n * @author julius\r\n */\r\n@Service\r\npublic class UserServiceImpl exte",
"end": 784,
"score": 0.9996035695075989,
"start": 778,
"tag": "USERNAME",
"value": "julius"
},
{
"context": "el user1 = new UserModel();\r\n\t\tuser1.setNickName(\"张三\");\r\n\t\tuserDao.save(user1);\r\n\t\t\r\n\t\tUserModel user2",
"end": 1073,
"score": 0.9986109733581543,
"start": 1071,
"tag": "NAME",
"value": "张三"
},
{
"context": "el user2 = new UserModel();\r\n\t\tuser2.setNickName(\"李四\");\r\n\t\tuserDao.save(user2);\r\n\t}\r\n}\r\n",
"end": 1167,
"score": 0.9973113536834717,
"start": 1165,
"tag": "NAME",
"value": "李四"
}
]
| null | []
| /*
* Copyright (C) 2006-2015
* 本系统是商用软件,未经授权擅自复制或传播本程序的部分或全部将是非法的.
========================================
* FileName: UserServiceImpl.java
* Created: [2015年8月19日 下午3:07:33] by julius
* 更新:$Date$
* 作者:$Author$
* 版本:$Rev$
* ID:$Id$
========================================
* ProjectName: PiKaEmonBBS
* Description: 用户Service实现
======================================*/
package com.julius.user.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.julius.common.service.impl.BaseServiceImpl;
import com.julius.user.dao.UserDao;
import com.julius.user.model.UserModel;
import com.julius.user.service.UserService;
/**
* Description:用户Service实现
* @author julius
*/
@Service
public class UserServiceImpl extends BaseServiceImpl<UserModel, UserDao> implements UserService {
@Autowired
private UserDao userDao;
public void addRollBackTest() throws Exception{
int i=0;
UserModel user1 = new UserModel();
user1.setNickName("张三");
userDao.save(user1);
UserModel user2 = new UserModel();
user2.setNickName("李四");
userDao.save(user2);
}
}
| 1,323 | 0.640898 | 0.618454 | 46 | 24.152174 | 20.207582 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.891304 | false | false | 3 |
e6df1078f73677d8b9b764e656eafd41ce1dc462 | 9,251,359,620,787 | b811b2d81bf8cf5f8c20b091dbfa45dc8badbfef | /YiJi/Client/app/src/main/java/com/example/bing/yiji/Model/Transaction.java | 2527c9fda26cdbe783d1f012dac0f9b03f3e2354 | [
"MIT"
]
| permissive | bing-zhub/AndroidLearning | https://github.com/bing-zhub/AndroidLearning | 70a45af8709eb7f6ac061db54569c39321f07b56 | 54c8151dfdd5ee1c1c8c6b5b3a1a208f03349c65 | refs/heads/master | 2020-03-26T18:37:04.676000 | 2018-12-27T13:45:53 | 2018-12-27T13:45:53 | 145,221,920 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.bing.yiji.Model;
import java.util.Date;
public class Transaction {
private String type;
private int money;
private Date date;
private boolean income;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public boolean isIncome() {
return income;
}
public void setIncome(boolean income) {
this.income = income;
}
}
| UTF-8 | Java | 719 | java | Transaction.java | Java | []
| null | []
| package com.example.bing.yiji.Model;
import java.util.Date;
public class Transaction {
private String type;
private int money;
private Date date;
private boolean income;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public boolean isIncome() {
return income;
}
public void setIncome(boolean income) {
this.income = income;
}
}
| 719 | 0.581363 | 0.581363 | 42 | 16.119047 | 13.610575 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 3 |
6b9c9cd40f87c698aedb5352f6b6fb234787e3cc | 19,756,849,624,679 | 99df686878f922050030a0bebf917e611699ef38 | /src/entity/Userinfo.java | 89576522d01f2c76b8a8d7560e4533fe8a3b4f15 | []
| no_license | Qijiale110/alipayTest | https://github.com/Qijiale110/alipayTest | f387a602ea5228b9cafbacb4665487a9203042ee | 2c56af32b5f547f549604bbacf805a3f8b877b61 | refs/heads/master | 2020-04-07T22:28:50.396000 | 2018-11-23T02:51:34 | 2018-11-23T02:51:34 | 158,772,373 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package entity;
public class Userinfo {
private Integer userid;
private String username;
private String userpassword;
private String sex;
private String phone;
private String photo;
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserpassword() {
return userpassword;
}
public void setUserpassword(String userpassword) {
this.userpassword = userpassword;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "Userinfo [userid=" + userid + ", username=" + username
+ ", userpassword=" + userpassword + ", sex=" + sex
+ ", phone=" + phone + ", photo=" + photo + "]";
}
}
| UTF-8 | Java | 1,183 | java | Userinfo.java | Java | [
{
"context": "rid;\r\n\t}\r\n\tpublic String getUsername() {\r\n\t\treturn username;\r\n\t}\r\n\tpublic void setUsername(String username) {",
"end": 490,
"score": 0.8941758275032043,
"start": 482,
"tag": "USERNAME",
"value": "username"
},
{
"context": " setUsername(String username) {\r\n\t\tthis.username = username;\r\n\t}\r\n\tpublic String getUserpassword() {\r\n\t\tretur",
"end": 568,
"score": 0.9864845871925354,
"start": 560,
"tag": "USERNAME",
"value": "username"
},
{
"context": "word(String userpassword) {\r\n\t\tthis.userpassword = userpassword;\r\n\t}\r\n\tpublic String getSex() {\r\n\t\treturn sex;\r\n\t",
"end": 726,
"score": 0.8274797201156616,
"start": 714,
"tag": "PASSWORD",
"value": "userpassword"
},
{
"context": "urn \"Userinfo [userid=\" + userid + \", username=\" + username\r\n\t\t\t\t+ \", userpassword=\" + userpassword + \", sex=",
"end": 1058,
"score": 0.9978102445602417,
"start": 1050,
"tag": "USERNAME",
"value": "username"
},
{
"context": ", username=\" + username\r\n\t\t\t\t+ \", userpassword=\" + userpassword + \", sex=\" + sex\r\n\t\t\t\t+ \", phone=\" + phon",
"end": 1090,
"score": 0.896194577217102,
"start": 1086,
"tag": "PASSWORD",
"value": "user"
}
]
| null | []
| package entity;
public class Userinfo {
private Integer userid;
private String username;
private String userpassword;
private String sex;
private String phone;
private String photo;
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserpassword() {
return userpassword;
}
public void setUserpassword(String userpassword) {
this.userpassword = <PASSWORD>;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "Userinfo [userid=" + userid + ", username=" + username
+ ", userpassword=" + <PASSWORD>password + ", sex=" + sex
+ ", phone=" + phone + ", photo=" + photo + "]";
}
}
| 1,187 | 0.650888 | 0.650888 | 55 | 19.50909 | 16.030508 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.709091 | false | false | 3 |
8f6c455a8f1085f35af51f233302d0ce80a69ead | 2,370,821,997,226 | df6302474e5edeb1cce34dbc3fa1c0c4e6097619 | /src/dazuoye/timer.java | 589c4275e168e8f12a905c12d688fb3c193107b6 | []
| no_license | chenz12/java-project | https://github.com/chenz12/java-project | 5b4a4f689ebf4ccd624bcd3010387b1ab5ef7dde | e901670a7e588ca00419acf2bfd6954a588e0807 | refs/heads/master | 2021-01-10T13:35:03.140000 | 2016-01-02T07:41:57 | 2016-01-02T07:41:57 | 48,744,391 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dazuoye;
public class timer {
public double speed;
public long start;
public long dif;
timer(double d){
speed = d;
start = System.nanoTime();
}
public boolean iscycled(){
long temp = System.nanoTime();
dif = temp - start;
if(dif >= 1.0/(speed*Math.pow(10, -9))){
start = System.nanoTime();
return true;
}
return false;
}
public void pause(){
start = System.nanoTime();
}
public void reset(){
speed = 1;
start = System.currentTimeMillis();
dif = 0;
}
}
| UTF-8 | Java | 500 | java | timer.java | Java | []
| null | []
| package dazuoye;
public class timer {
public double speed;
public long start;
public long dif;
timer(double d){
speed = d;
start = System.nanoTime();
}
public boolean iscycled(){
long temp = System.nanoTime();
dif = temp - start;
if(dif >= 1.0/(speed*Math.pow(10, -9))){
start = System.nanoTime();
return true;
}
return false;
}
public void pause(){
start = System.nanoTime();
}
public void reset(){
speed = 1;
start = System.currentTimeMillis();
dif = 0;
}
}
| 500 | 0.632 | 0.618 | 28 | 16.857143 | 11.278027 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.964286 | false | false | 3 |
926a2e7c462d47a4176056ec003c06497e2bedb7 | 9,251,359,624,003 | 4913ef8eb5cde6e3b1ee74a27c3f3d54319148d9 | /allbinary_src/ViewsJavaLibraryM/src/main/java/views/admin/customizers/CustomizersView.java | 53214484fa0eebbb160f86e228ff838d084e11e5 | [
"LicenseRef-scancode-warranty-disclaimer"
]
| no_license | AllBinary/AllBinary-Platform | https://github.com/AllBinary/AllBinary-Platform | 0876cfbe8f0d003b628181551f90df36f6203c6a | 92adcd63427fcacbfac9cb4a6b47b92a3c2acaa7 | refs/heads/master | 2023-08-18T23:24:09.932000 | 2023-08-15T03:09:32 | 2023-08-15T03:09:32 | 1,953,077 | 16 | 3 | NOASSERTION | false | 2023-07-05T00:52:21 | 2011-06-25T18:29:09 | 2023-02-09T05:34:30 | 2023-07-05T00:52:20 | 11,391 | 24 | 11 | 1 | Java | false | false | /*
* AllBinary Open License Version 1
* Copyright (c) 2011 AllBinary
*
* By agreeing to this license you and any business entity you represent are
* legally bound to the AllBinary Open License Version 1 legal agreement.
*
* You may obtain the AllBinary Open License Version 1 legal agreement from
* AllBinary or the root directory of AllBinary's AllBinary Platform repository.
*
* Created By: Travis Berthelot
*
*/
package views.admin.customizers;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Vector;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import views.business.context.modules.storefront.HttpStoreComponentView;
import org.allbinary.logic.communication.log.LogFactory;
import org.allbinary.logic.communication.log.LogUtil;
import org.allbinary.data.tables.transform.info.TransformInfoEntityBuilder;
import org.allbinary.data.tree.dom.DomNodeInterface;
import org.allbinary.data.tree.dom.ModDomHelper;
import org.allbinary.globals.GLOBALS2;
import org.allbinary.logic.basic.string.CommonStrings;
import org.allbinary.logic.control.sort.StringComparator;
import org.allbinary.logic.visual.transform.info.CustomizerTransformInfoData;
import org.allbinary.logic.visual.transform.info.TransformInfoInterface;
import org.allbinary.logic.visual.transform.template.customizer.TransformTemplateCustomizerData;
import org.allbinary.logic.visual.transform.template.customizer.TransformTemplateCustomizersData;
import org.allbinary.logic.visual.transform.template.customizer.bodies.BodyData;
import org.allbinary.logic.visual.transform.template.customizer.widgets.title.TitleData;
import org.allbinary.logic.visual.transform.template.util.TransformTemplateCustomizerUtil;
public class CustomizersView extends HttpStoreComponentView implements DomNodeInterface {
private final CommonStrings commonStrings = CommonStrings.getInstance();
protected final Vector customizersVector;
public CustomizersView(TransformInfoInterface transformInfoInterface) throws Exception {
super(transformInfoInterface);
//String storeName = ;
this.customizersVector
= TransformInfoEntityBuilder.getInstance().getNames(this.getWeblisketSession().getStoreName());
}
public Node toXmlNode(final Document document) {
try {
final Node node = document.createElement(TransformTemplateCustomizersData.NAME);
final Iterator iter = customizersVector.iterator();
final Vector unsortedCustomizerViewVector = new Vector();
while (iter.hasNext()) {
final String viewName = (String) iter.next();
if (viewName.indexOf(CustomizerTransformInfoData.NAME) > 0
&& viewName.indexOf(GLOBALS2.EDIT) > 0
&& viewName.indexOf(BodyData.getInstance().VIEWNAMEKEY) > 0
&& viewName.indexOf(TitleData.getInstance().VIEWNAMEKEY) > 0) //TransformTemplateCustomizerData.EDITNAMEKEY
{
unsortedCustomizerViewVector.add(viewName);
}
}
final Object objectArray[] = (Object[]) unsortedCustomizerViewVector.toArray();
//String customizerViews[] = (String[]) objectArray;
Arrays.sort(objectArray, new StringComparator());
for (int index = 0; index < objectArray.length; index++) {
final String viewName = (String) objectArray[index];
final Node viewNameNode
= ModDomHelper.createNameValueNodes(
document, TransformTemplateCustomizerData.NAME, viewName,
TransformTemplateCustomizerUtil.getInstance().getPageNameHack(
viewName,
this.getWeblisketSession().getStoreName()));
//+ " " + TransformInfoObjectConfigData.BODY
node.appendChild(viewNameNode);
}
return node;
} catch (Exception e) {
if (org.allbinary.logic.communication.log.config.type.LogConfigTypes.LOGGING.contains(org.allbinary.logic.communication.log.config.type.LogConfigTypeFactory.getInstance().XSLLOGGINGERROR)) {
LogUtil.put(LogFactory.getInstance(this.commonStrings.FAILURE, this, "toXmlNode", e));
}
return null;
}
}
public void addDomNodeInterfaces() {
this.addDomNodeInterface((DomNodeInterface) this);
}
public String view() throws Exception {
try {
this.addDomNodeInterfaces();
return super.view();
} catch (Exception e) {
final String error = "Failed to view Mini Basket";
if (org.allbinary.logic.communication.log.config.type.LogConfigTypes.LOGGING.contains(org.allbinary.logic.communication.log.config.type.LogConfigTypeFactory.getInstance().TAGHELPERERROR)) {
LogUtil.put(LogFactory.getInstance(error, this, "view()", e));
}
throw e;
}
}
}
| UTF-8 | Java | 5,099 | java | CustomizersView.java | Java | [
{
"context": "'s AllBinary Platform repository.\n* \n* Created By: Travis Berthelot\n* \n */\npackage views.admin.customizers;\n\nimport j",
"end": 412,
"score": 0.9998815655708313,
"start": 396,
"tag": "NAME",
"value": "Travis Berthelot"
}
]
| null | []
| /*
* AllBinary Open License Version 1
* Copyright (c) 2011 AllBinary
*
* By agreeing to this license you and any business entity you represent are
* legally bound to the AllBinary Open License Version 1 legal agreement.
*
* You may obtain the AllBinary Open License Version 1 legal agreement from
* AllBinary or the root directory of AllBinary's AllBinary Platform repository.
*
* Created By: <NAME>
*
*/
package views.admin.customizers;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Vector;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import views.business.context.modules.storefront.HttpStoreComponentView;
import org.allbinary.logic.communication.log.LogFactory;
import org.allbinary.logic.communication.log.LogUtil;
import org.allbinary.data.tables.transform.info.TransformInfoEntityBuilder;
import org.allbinary.data.tree.dom.DomNodeInterface;
import org.allbinary.data.tree.dom.ModDomHelper;
import org.allbinary.globals.GLOBALS2;
import org.allbinary.logic.basic.string.CommonStrings;
import org.allbinary.logic.control.sort.StringComparator;
import org.allbinary.logic.visual.transform.info.CustomizerTransformInfoData;
import org.allbinary.logic.visual.transform.info.TransformInfoInterface;
import org.allbinary.logic.visual.transform.template.customizer.TransformTemplateCustomizerData;
import org.allbinary.logic.visual.transform.template.customizer.TransformTemplateCustomizersData;
import org.allbinary.logic.visual.transform.template.customizer.bodies.BodyData;
import org.allbinary.logic.visual.transform.template.customizer.widgets.title.TitleData;
import org.allbinary.logic.visual.transform.template.util.TransformTemplateCustomizerUtil;
public class CustomizersView extends HttpStoreComponentView implements DomNodeInterface {
private final CommonStrings commonStrings = CommonStrings.getInstance();
protected final Vector customizersVector;
public CustomizersView(TransformInfoInterface transformInfoInterface) throws Exception {
super(transformInfoInterface);
//String storeName = ;
this.customizersVector
= TransformInfoEntityBuilder.getInstance().getNames(this.getWeblisketSession().getStoreName());
}
public Node toXmlNode(final Document document) {
try {
final Node node = document.createElement(TransformTemplateCustomizersData.NAME);
final Iterator iter = customizersVector.iterator();
final Vector unsortedCustomizerViewVector = new Vector();
while (iter.hasNext()) {
final String viewName = (String) iter.next();
if (viewName.indexOf(CustomizerTransformInfoData.NAME) > 0
&& viewName.indexOf(GLOBALS2.EDIT) > 0
&& viewName.indexOf(BodyData.getInstance().VIEWNAMEKEY) > 0
&& viewName.indexOf(TitleData.getInstance().VIEWNAMEKEY) > 0) //TransformTemplateCustomizerData.EDITNAMEKEY
{
unsortedCustomizerViewVector.add(viewName);
}
}
final Object objectArray[] = (Object[]) unsortedCustomizerViewVector.toArray();
//String customizerViews[] = (String[]) objectArray;
Arrays.sort(objectArray, new StringComparator());
for (int index = 0; index < objectArray.length; index++) {
final String viewName = (String) objectArray[index];
final Node viewNameNode
= ModDomHelper.createNameValueNodes(
document, TransformTemplateCustomizerData.NAME, viewName,
TransformTemplateCustomizerUtil.getInstance().getPageNameHack(
viewName,
this.getWeblisketSession().getStoreName()));
//+ " " + TransformInfoObjectConfigData.BODY
node.appendChild(viewNameNode);
}
return node;
} catch (Exception e) {
if (org.allbinary.logic.communication.log.config.type.LogConfigTypes.LOGGING.contains(org.allbinary.logic.communication.log.config.type.LogConfigTypeFactory.getInstance().XSLLOGGINGERROR)) {
LogUtil.put(LogFactory.getInstance(this.commonStrings.FAILURE, this, "toXmlNode", e));
}
return null;
}
}
public void addDomNodeInterfaces() {
this.addDomNodeInterface((DomNodeInterface) this);
}
public String view() throws Exception {
try {
this.addDomNodeInterfaces();
return super.view();
} catch (Exception e) {
final String error = "Failed to view Mini Basket";
if (org.allbinary.logic.communication.log.config.type.LogConfigTypes.LOGGING.contains(org.allbinary.logic.communication.log.config.type.LogConfigTypeFactory.getInstance().TAGHELPERERROR)) {
LogUtil.put(LogFactory.getInstance(error, this, "view()", e));
}
throw e;
}
}
}
| 5,089 | 0.686997 | 0.68386 | 117 | 42.581196 | 39.224369 | 202 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.512821 | false | false | 3 |
742b378955db7b4a07edaa528c23d08f827afc5b | 20,255,065,821,941 | 10af04a7d5807b022de4a6f36d985403feb02c46 | /dataStructure/src/main/java/com/wallet/datastrucure/queue/impl/ArrayQueue.java | f0d6a7cae29d3e9e9d34f631a55aec3f55370f51 | []
| no_license | Anymous526/javase-parent | https://github.com/Anymous526/javase-parent | 38c90902626e472f329c983cc0703ae7e1a1d59b | dd0756d1fdb077028dd32b2dd0b3ab146ef199e5 | refs/heads/master | 2019-04-09T08:07:37.368000 | 2019-03-31T03:11:38 | 2019-03-31T03:11:38 | 26,983,534 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wallet.datastrucure.queue.impl;
import com.wallet.datastrucure.queue.Queue;
public class ArrayQueue<E> implements Queue<E> {
private Object[] elementData;
private int number;
private int head;
private int tail;
@Override
public void enqueue(E e) {
if ((head - tail + 1) == elementData.length)
reSize(2 * elementData.length);
elementData[tail++] = e;
}
@Override
@SuppressWarnings("unchecked")
public E dequeue() {
E temp = (E) elementData[--head];
elementData[head] = null;
if (head > 0 && (tail - head + 1) == elementData.length / 4)
reSize(elementData.length / 2);
return temp;
}
@Override
public boolean isEmpty() {
return number == 0;
}
@Override
public synchronized int size() {
return number;
}
private void reSize(int capacity) {
Object[] newElementData = new Object[capacity];
for (int i = 0; i < elementData.length; i++)
newElementData[i] = elementData[i];
elementData = newElementData;
}
}
| UTF-8 | Java | 1,028 | java | ArrayQueue.java | Java | []
| null | []
| package com.wallet.datastrucure.queue.impl;
import com.wallet.datastrucure.queue.Queue;
public class ArrayQueue<E> implements Queue<E> {
private Object[] elementData;
private int number;
private int head;
private int tail;
@Override
public void enqueue(E e) {
if ((head - tail + 1) == elementData.length)
reSize(2 * elementData.length);
elementData[tail++] = e;
}
@Override
@SuppressWarnings("unchecked")
public E dequeue() {
E temp = (E) elementData[--head];
elementData[head] = null;
if (head > 0 && (tail - head + 1) == elementData.length / 4)
reSize(elementData.length / 2);
return temp;
}
@Override
public boolean isEmpty() {
return number == 0;
}
@Override
public synchronized int size() {
return number;
}
private void reSize(int capacity) {
Object[] newElementData = new Object[capacity];
for (int i = 0; i < elementData.length; i++)
newElementData[i] = elementData[i];
elementData = newElementData;
}
}
| 1,028 | 0.642023 | 0.634241 | 51 | 19.156862 | 17.351467 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.647059 | false | false | 3 |
7865287fc28b27ea8dd13d0b6c3ecaffa71208b6 | 18,640,158,123,508 | 0a94e4bb6bdf5c54ebba25cecafa72215266843a | /2.JavaCore/src/com/javarush/task/task18/task1823/Solution.java | 2c7496564441aeb7ca94e434ae5c34153862d546 | []
| no_license | Senat77/JavaRush | https://github.com/Senat77/JavaRush | 8d8fb6e59375656a545825585118febd2e1637f4 | 68dc0139da96617ebcad967331dcd24f9875d8ee | refs/heads/master | 2020-05-19T18:50:31.534000 | 2018-09-25T14:00:31 | 2018-09-25T14:00:31 | 185,160,609 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.javarush.task.task18.task1823;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
/*
Нити и байты
Читайте с консоли имена файлов, пока не будет введено слово "exit".
Передайте имя файла в нить ReadThread.
Нить ReadThread должна найти байт, который встречается в файле максимальное число раз, и добавить его в словарь
resultMap,
где параметр String - это имя файла, параметр Integer - это искомый байт.
Закрыть потоки.
Требования:
1. Программа должна считывать имена файлов с консоли, пока не будет введено слово "exit".
2. Для каждого файла создай нить ReadThread и запусти ее.
3. После запуска каждая нить ReadThread должна создать свой поток для чтения из файла.
4. Затем нити должны найти максимально встречающийся байт в своем файле и добавить его в словарь resultMap.
5. Поток для чтения из файла в каждой нити должен быть закрыт.
*/
public class Solution
{
public static Map<String, Integer> resultMap = new HashMap<String, Integer>();
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = "";
while(true)
{
str = br.readLine();
if("exit".equals(str))
break;
ReadThread rt = new ReadThread(str);
rt.start();
}
br.close();
}
public static class ReadThread extends Thread
{
String fileName;
public ReadThread(String fileName)
{
//implement constructor body
this.fileName = fileName;
}
// implement file reading here - реализуйте чтение из файла тут
public void task() throws IOException
{
FileInputStream fis;
fis = new FileInputStream(fileName);
byte[] arr = new byte[fis.available()];
fis.read(arr);
fis.close();
// Находим самый частовстречающийся символ
HashMap<Byte,Integer> map = new HashMap<>();
for (int i = 0; i < arr.length; i++)
{
if(map.containsKey(arr[i]))
{
map.replace(arr[i],map.get(arr[i])+1);
}
else
{
map.put(arr[i],1);
}
}
byte key = 0;
int value = 0;
for (Map.Entry<Byte,Integer> e : map.entrySet())
{
if(e.getValue() > value)
{
value = e.getValue();
key = e.getKey();
}
}
resultMap.put(this.fileName,(int)key);
//System.out.println(this.fileName + " " + (char)key);
}
@Override
public void run()
{
//super.run();
//try
//{
try
{
this.task();
}
catch (IOException e) {}
//}
//catch (FileNotFoundException e1) {}
}
}
}
| UTF-8 | Java | 3,703 | java | Solution.java | Java | []
| null | []
| package com.javarush.task.task18.task1823;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
/*
Нити и байты
Читайте с консоли имена файлов, пока не будет введено слово "exit".
Передайте имя файла в нить ReadThread.
Нить ReadThread должна найти байт, который встречается в файле максимальное число раз, и добавить его в словарь
resultMap,
где параметр String - это имя файла, параметр Integer - это искомый байт.
Закрыть потоки.
Требования:
1. Программа должна считывать имена файлов с консоли, пока не будет введено слово "exit".
2. Для каждого файла создай нить ReadThread и запусти ее.
3. После запуска каждая нить ReadThread должна создать свой поток для чтения из файла.
4. Затем нити должны найти максимально встречающийся байт в своем файле и добавить его в словарь resultMap.
5. Поток для чтения из файла в каждой нити должен быть закрыт.
*/
public class Solution
{
public static Map<String, Integer> resultMap = new HashMap<String, Integer>();
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = "";
while(true)
{
str = br.readLine();
if("exit".equals(str))
break;
ReadThread rt = new ReadThread(str);
rt.start();
}
br.close();
}
public static class ReadThread extends Thread
{
String fileName;
public ReadThread(String fileName)
{
//implement constructor body
this.fileName = fileName;
}
// implement file reading here - реализуйте чтение из файла тут
public void task() throws IOException
{
FileInputStream fis;
fis = new FileInputStream(fileName);
byte[] arr = new byte[fis.available()];
fis.read(arr);
fis.close();
// Находим самый частовстречающийся символ
HashMap<Byte,Integer> map = new HashMap<>();
for (int i = 0; i < arr.length; i++)
{
if(map.containsKey(arr[i]))
{
map.replace(arr[i],map.get(arr[i])+1);
}
else
{
map.put(arr[i],1);
}
}
byte key = 0;
int value = 0;
for (Map.Entry<Byte,Integer> e : map.entrySet())
{
if(e.getValue() > value)
{
value = e.getValue();
key = e.getKey();
}
}
resultMap.put(this.fileName,(int)key);
//System.out.println(this.fileName + " " + (char)key);
}
@Override
public void run()
{
//super.run();
//try
//{
try
{
this.task();
}
catch (IOException e) {}
//}
//catch (FileNotFoundException e1) {}
}
}
}
| 3,703 | 0.533098 | 0.527635 | 110 | 27.290909 | 24.992489 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.409091 | false | false | 3 |
2c1080ab584f707e6c718312e0306a65019a8ccf | 1,365,799,652,869 | feef12c64281080af1723994d065c6b6c89ade17 | /src/main/java/com/example/demo/services/ModuleService.java | 78d7c94a91b4a01d2719f2756cf9d4fe5a333b28 | []
| no_license | roch51/demohci | https://github.com/roch51/demohci | 726f253561dc9856a39f684d0cb664096fd9a1f0 | e3d4935fa0191af3a881711bb4265bd3baa6bc5a | refs/heads/master | 2020-08-30T15:47:07.677000 | 2019-10-30T11:34:44 | 2019-10-30T11:34:44 | 218,425,122 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.services;
import com.example.demo.dto.ModuleByUserDto;
import com.example.demo.repositories.UserModuleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
@Service
public class ModuleService {
@Autowired
UserModuleRepository userModuleRepository ;
public HashMap<String, Object> findByUserId(Long userId) {
List<ModuleByUserDto> modules = userModuleRepository.findByUserId(userId) ;
HashMap<String, Object> response = new HashMap<>();
response.put("modules",modules) ;
return response ;
}
}
| UTF-8 | Java | 689 | java | ModuleService.java | Java | []
| null | []
| package com.example.demo.services;
import com.example.demo.dto.ModuleByUserDto;
import com.example.demo.repositories.UserModuleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
@Service
public class ModuleService {
@Autowired
UserModuleRepository userModuleRepository ;
public HashMap<String, Object> findByUserId(Long userId) {
List<ModuleByUserDto> modules = userModuleRepository.findByUserId(userId) ;
HashMap<String, Object> response = new HashMap<>();
response.put("modules",modules) ;
return response ;
}
}
| 689 | 0.756168 | 0.756168 | 25 | 26.559999 | 25.050478 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 3 |
1dfee5ea6e9d81cf61fdc448dc3d274ad1b70aff | 18,141,941,911,062 | 9f8b459060ed54a9b087806b1ca52cede02fd74a | /plugins/com.agritrace.edairy.desktop.install/src/com/agritrace/edairy/desktop/install/MemberImportTool.java | ab437540796b5294d80fc8c50117eda6a99bf938 | []
| no_license | oraclebill/edairy_desktop | https://github.com/oraclebill/edairy_desktop | 7ddb61b2d3dcd0ddba89abe89e10c376f37c5fba | f9b775f2086fdcb3a4027d68f950a41e7ec50aa4 | refs/heads/master | 2020-04-10T14:55:40.472000 | 2011-03-30T11:46:55 | 2011-03-30T11:46:55 | 571,107 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.agritrace.edairy.desktop.install;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Formatter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.ecore.EObject;
import com.agritrace.edairy.desktop.common.model.dairy.Dairy;
import com.agritrace.edairy.desktop.common.model.dairy.DairyLocation;
import com.agritrace.edairy.desktop.common.model.dairy.Membership;
import com.agritrace.edairy.desktop.common.model.dairy.MembershipStatus;
import com.agritrace.edairy.desktop.common.model.dairy.account.Account;
import com.agritrace.edairy.desktop.common.model.dairy.account.AccountFactory;
import com.agritrace.edairy.desktop.common.model.dairy.account.AccountStatus;
import com.agritrace.edairy.desktop.common.model.tracking.Farm;
import com.agritrace.edairy.desktop.common.model.tracking.Farmer;
import com.agritrace.edairy.desktop.common.model.util.DairyUtil;
import com.agritrace.edairy.desktop.common.persistence.dao.IDairyRepository;
import com.google.inject.Inject;
public class MemberImportTool extends AbstractImportTool {
private static final Date DEFAULT_IMPORT_DATE = getDefaultDate();
public static final int MEMBER_NUMBER = 2;
public static final int MEMBER_ACCOUNT_NUMBER = 1;
public static final int MEMBER_DEFAULT_ROUTE = 3;
public static final int MEMBER_GIVEN_NAME = 6;
public static final int MEMBER_FAMILY_NAME = 7;
// private DairyRepository dairyRepo;
// private Dairy dairy;
private final Map<String, Membership> memberCache = new HashMap<String, Membership>();
private final Map<String, DairyLocation> routeCache = new HashMap<String, DairyLocation>();
private Collection<Membership> memberCollection;
private Map<String, List<String[]>> failedRecords;
public int count = 0;
public int errors = 0;
private final IDairyRepository repo;
@Inject
public MemberImportTool(IDairyRepository repo) {
this.repo = repo;
}
public void processFile(InputStream stream, List<Membership> memberCollection,
Map<String, List<String[]>> failedRecords, IProgressMonitor monitor) throws IOException {
setReader(new InputStreamReader(stream));
setMonitor(monitor);
this.memberCollection = memberCollection;
this.failedRecords = failedRecords;
final Dairy dairy = repo.getLocalDairy();
System.err.println(">>>>>>>>> Adding branches to cache");
for (final DairyLocation route : dairy.getBranchLocations()) {
System.err.println(">>>>>>>>> Adding " + route + " to cache");
routeCache.put(route.getCode(), route);
}
System.err.println(">>>>>>>>> Adding existing members to cache");
for (final Membership member : dairy.getMemberships()) {
System.err.println(">>>>>>>>> Adding " + member + " to cache");
memberCache.put(member.getMemberNumber(), member);
}
super.processFile();
}
@Override
protected void processRecord(String[] values) {
count += 1;
// validate
Membership membership = memberCache.get(values[MEMBER_NUMBER]);
if (membership != null) {
addFailure("Member already exists!", values);
return;
} else {
try {
membership = createMembership(values);
memberCollection.add(membership);
} catch (final Exception e) {
addFailure(e.getMessage(), values);
}
}
}
private void addFailure(String message, String[] values) {
errors += 1;
List<String[]> records = failedRecords.get(message);
if (records == null) {
records = new LinkedList<String[]>();
failedRecords.put(message, records);
}
records.add(values);
}
public Membership createMembership(String[] values) {
Membership membership = null;
final String givenName = values[MEMBER_GIVEN_NAME];
final String familyNames = values[MEMBER_FAMILY_NAME];
final String accountNumber = values[MEMBER_ACCOUNT_NUMBER];
final String membershipNumber = values[MEMBER_NUMBER];
final String defaultRoute = values[MEMBER_DEFAULT_ROUTE];
final Formatter formatter = new Formatter();
formatter.format("%s %s (%s) Farm", givenName, familyNames, membershipNumber);
final Farm farm = DairyUtil.createFarm(formatter.toString(), DairyUtil.createLocation(null, null, null));
final Farmer farmer = DairyUtil.createFarmer(givenName, "", familyNames, "<missing>", farm);
membership = DairyUtil.createMembership(DEFAULT_IMPORT_DATE, DEFAULT_IMPORT_DATE, farmer);
// membership.setMemberId(key);
membership.setMemberNumber(membershipNumber);
membership.setStatus(MembershipStatus.ACTIVE);
membership.setDefaultRoute(getRoute(defaultRoute));
final Account account = AccountFactory.eINSTANCE.createAccount();
account.setMember(membership);
// account.setAccountNumber("V"+membership.getMemberNumber());
account.setAccountNumber(accountNumber);
account.setStatus(AccountStatus.ACTIVE);
account.setEstablished(DEFAULT_IMPORT_DATE);
return membership;
}
private DairyLocation getRoute(String string) {
return routeCache.get(string);
}
@Override
protected void doImportComplete(int okCount, int failCount) {
// done();
}
private static Date getDefaultDate() {
final Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 1970);
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
return calendar.getTime();
}
@Override
protected void saveImportedEntity(Object entity) {
// TODO Auto-generated method stub
}
@Override
protected String[] getExpectedHeaders() {
return new String[] { null, "account-name", "membership-name", "default-route", null, null, "given-name",
"family-name" };
}
@Override
protected EObject createBlankEntity() {
// TODO Auto-generated method stub
return null;
}
@Override
protected List<Entry> getFields() {
// TODO Auto-generated method stub
return null;
}
}
| UTF-8 | Java | 5,947 | java | MemberImportTool.java | Java | []
| null | []
| package com.agritrace.edairy.desktop.install;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Formatter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.ecore.EObject;
import com.agritrace.edairy.desktop.common.model.dairy.Dairy;
import com.agritrace.edairy.desktop.common.model.dairy.DairyLocation;
import com.agritrace.edairy.desktop.common.model.dairy.Membership;
import com.agritrace.edairy.desktop.common.model.dairy.MembershipStatus;
import com.agritrace.edairy.desktop.common.model.dairy.account.Account;
import com.agritrace.edairy.desktop.common.model.dairy.account.AccountFactory;
import com.agritrace.edairy.desktop.common.model.dairy.account.AccountStatus;
import com.agritrace.edairy.desktop.common.model.tracking.Farm;
import com.agritrace.edairy.desktop.common.model.tracking.Farmer;
import com.agritrace.edairy.desktop.common.model.util.DairyUtil;
import com.agritrace.edairy.desktop.common.persistence.dao.IDairyRepository;
import com.google.inject.Inject;
public class MemberImportTool extends AbstractImportTool {
private static final Date DEFAULT_IMPORT_DATE = getDefaultDate();
public static final int MEMBER_NUMBER = 2;
public static final int MEMBER_ACCOUNT_NUMBER = 1;
public static final int MEMBER_DEFAULT_ROUTE = 3;
public static final int MEMBER_GIVEN_NAME = 6;
public static final int MEMBER_FAMILY_NAME = 7;
// private DairyRepository dairyRepo;
// private Dairy dairy;
private final Map<String, Membership> memberCache = new HashMap<String, Membership>();
private final Map<String, DairyLocation> routeCache = new HashMap<String, DairyLocation>();
private Collection<Membership> memberCollection;
private Map<String, List<String[]>> failedRecords;
public int count = 0;
public int errors = 0;
private final IDairyRepository repo;
@Inject
public MemberImportTool(IDairyRepository repo) {
this.repo = repo;
}
public void processFile(InputStream stream, List<Membership> memberCollection,
Map<String, List<String[]>> failedRecords, IProgressMonitor monitor) throws IOException {
setReader(new InputStreamReader(stream));
setMonitor(monitor);
this.memberCollection = memberCollection;
this.failedRecords = failedRecords;
final Dairy dairy = repo.getLocalDairy();
System.err.println(">>>>>>>>> Adding branches to cache");
for (final DairyLocation route : dairy.getBranchLocations()) {
System.err.println(">>>>>>>>> Adding " + route + " to cache");
routeCache.put(route.getCode(), route);
}
System.err.println(">>>>>>>>> Adding existing members to cache");
for (final Membership member : dairy.getMemberships()) {
System.err.println(">>>>>>>>> Adding " + member + " to cache");
memberCache.put(member.getMemberNumber(), member);
}
super.processFile();
}
@Override
protected void processRecord(String[] values) {
count += 1;
// validate
Membership membership = memberCache.get(values[MEMBER_NUMBER]);
if (membership != null) {
addFailure("Member already exists!", values);
return;
} else {
try {
membership = createMembership(values);
memberCollection.add(membership);
} catch (final Exception e) {
addFailure(e.getMessage(), values);
}
}
}
private void addFailure(String message, String[] values) {
errors += 1;
List<String[]> records = failedRecords.get(message);
if (records == null) {
records = new LinkedList<String[]>();
failedRecords.put(message, records);
}
records.add(values);
}
public Membership createMembership(String[] values) {
Membership membership = null;
final String givenName = values[MEMBER_GIVEN_NAME];
final String familyNames = values[MEMBER_FAMILY_NAME];
final String accountNumber = values[MEMBER_ACCOUNT_NUMBER];
final String membershipNumber = values[MEMBER_NUMBER];
final String defaultRoute = values[MEMBER_DEFAULT_ROUTE];
final Formatter formatter = new Formatter();
formatter.format("%s %s (%s) Farm", givenName, familyNames, membershipNumber);
final Farm farm = DairyUtil.createFarm(formatter.toString(), DairyUtil.createLocation(null, null, null));
final Farmer farmer = DairyUtil.createFarmer(givenName, "", familyNames, "<missing>", farm);
membership = DairyUtil.createMembership(DEFAULT_IMPORT_DATE, DEFAULT_IMPORT_DATE, farmer);
// membership.setMemberId(key);
membership.setMemberNumber(membershipNumber);
membership.setStatus(MembershipStatus.ACTIVE);
membership.setDefaultRoute(getRoute(defaultRoute));
final Account account = AccountFactory.eINSTANCE.createAccount();
account.setMember(membership);
// account.setAccountNumber("V"+membership.getMemberNumber());
account.setAccountNumber(accountNumber);
account.setStatus(AccountStatus.ACTIVE);
account.setEstablished(DEFAULT_IMPORT_DATE);
return membership;
}
private DairyLocation getRoute(String string) {
return routeCache.get(string);
}
@Override
protected void doImportComplete(int okCount, int failCount) {
// done();
}
private static Date getDefaultDate() {
final Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 1970);
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
return calendar.getTime();
}
@Override
protected void saveImportedEntity(Object entity) {
// TODO Auto-generated method stub
}
@Override
protected String[] getExpectedHeaders() {
return new String[] { null, "account-name", "membership-name", "default-route", null, null, "given-name",
"family-name" };
}
@Override
protected EObject createBlankEntity() {
// TODO Auto-generated method stub
return null;
}
@Override
protected List<Entry> getFields() {
// TODO Auto-generated method stub
return null;
}
}
| 5,947 | 0.753657 | 0.751135 | 177 | 32.598869 | 26.740702 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.988701 | false | false | 3 |
592e0111808a2fb9bb203f6ebb186767a40fe2c2 | 33,913,061,802,464 | ad05c335236458dfb782abe0e7dd9466b8a56a84 | /app/src/main/java/com/example/dine_and_donate/CustomViewPager.java | 86c0fd9cd1d5db0a518be521eef75f71f00341ee | []
| no_license | facebook-university/team_project | https://github.com/facebook-university/team_project | 06fac67c3b7543ab69edcc09bc2b69c1c1af431a | dd61217888e9c939708d1c94fd92798d159a6763 | refs/heads/master | 2020-06-16T01:53:52.558000 | 2019-08-13T21:32:32 | 2019-08-13T21:32:32 | 195,448,443 | 0 | 1 | null | false | 2019-08-12T15:42:40 | 2019-07-05T17:50:51 | 2019-08-12T06:40:06 | 2019-08-12T15:42:40 | 2,387 | 0 | 1 | 4 | Java | false | false | package com.example.dine_and_donate;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.TranslateAnimation;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;
import com.example.dine_and_donate.HomeFragments.MapFragment;
import com.example.dine_and_donate.Listeners.OnSwipeTouchListener;
public class CustomViewPager extends ViewPager {
private static final int SWIPE_THRESHOLD = 50;
private float x1, x2, y1, y2;
private Boolean result = true;
public CustomViewPager(@NonNull Context context) {
super(context);
}
public CustomViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
y1 = event.getRawY();
x1 = event.getRawX();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
y2 = event.getRawY();
x2 = event.getRawX();
float diffY = y2 - y1;
float diffX = x2 - x1;
x1 = 0;
x2 = 0;
y1 = 0;
y2 = 0;
if (Math.abs(diffX) > Math.abs(diffY)) {
result = true;
return super.onTouchEvent(event);
} else if (diffY > SWIPE_THRESHOLD) {
result = false;
return onTouchEvent(event);
}
break;
}
return super.dispatchTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (result) {
return super.onTouchEvent(event);
} else {
result = true;
View slideView = getRootView().findViewById(R.id.slide_menu);
MapFragment mapFragment = new MapFragment();
mapFragment.slideDownMenu(slideView);
return false;
}
}
}
| UTF-8 | Java | 2,286 | java | CustomViewPager.java | Java | []
| null | []
| package com.example.dine_and_donate;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.TranslateAnimation;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;
import com.example.dine_and_donate.HomeFragments.MapFragment;
import com.example.dine_and_donate.Listeners.OnSwipeTouchListener;
public class CustomViewPager extends ViewPager {
private static final int SWIPE_THRESHOLD = 50;
private float x1, x2, y1, y2;
private Boolean result = true;
public CustomViewPager(@NonNull Context context) {
super(context);
}
public CustomViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
y1 = event.getRawY();
x1 = event.getRawX();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
y2 = event.getRawY();
x2 = event.getRawX();
float diffY = y2 - y1;
float diffX = x2 - x1;
x1 = 0;
x2 = 0;
y1 = 0;
y2 = 0;
if (Math.abs(diffX) > Math.abs(diffY)) {
result = true;
return super.onTouchEvent(event);
} else if (diffY > SWIPE_THRESHOLD) {
result = false;
return onTouchEvent(event);
}
break;
}
return super.dispatchTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (result) {
return super.onTouchEvent(event);
} else {
result = true;
View slideView = getRootView().findViewById(R.id.slide_menu);
MapFragment mapFragment = new MapFragment();
mapFragment.slideDownMenu(slideView);
return false;
}
}
}
| 2,286 | 0.583115 | 0.573491 | 74 | 29.891891 | 19.94829 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.621622 | false | false | 3 |
b92501411cb95bbee5ea27245f64b477bac793a8 | 18,451,179,553,301 | 8c9e56076ec59a8d1fbca733410b974ea2c41bb9 | /nifi-commons/nifi-record/src/test/java/org/apache/nifi/serialization/record/field/ObjectTimestampFieldConverterTest.java | 9424d0fa1b08a9025933e3c3ac1bed472f5b617c | [
"CC0-1.0",
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown"
]
| permissive | apache/nifi | https://github.com/apache/nifi | 70329dca21ce61a643d5fac263ab101ae9313f5a | 2b330d9feea82764721e6190f7320d49c73986b0 | refs/heads/main | 2023-09-04T00:50:15.639000 | 2023-08-31T16:41:08 | 2023-08-31T16:41:08 | 27,911,088 | 4,182 | 3,345 | Apache-2.0 | false | 2023-09-14T20:56:07 | 2014-12-12T08:00:05 | 2023-09-14T10:07:16 | 2023-09-14T20:56:07 | 236,539 | 3,988 | 2,530 | 30 | Java | false | false | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.serialization.record.field;
import org.apache.nifi.serialization.record.RecordFieldType;
import org.apache.nifi.serialization.record.util.IllegalTypeConversionException;
import org.junit.jupiter.api.Test;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ObjectTimestampFieldConverterTest {
private static final ObjectTimestampFieldConverter CONVERTER = new ObjectTimestampFieldConverter();
private static final Optional<String> DEFAULT_PATTERN = Optional.of(RecordFieldType.TIMESTAMP.getDefaultFormat());
private static final String FIELD_NAME = Timestamp.class.getSimpleName();
private static final String EMPTY = "";
private static final String DATE_TIME_DEFAULT = "2000-01-01 12:00:00";
private static final Optional<String> DATE_TIME_NANOSECONDS_PATTERN = Optional.of("yyyy-MM-dd HH:mm:ss.SSSSSSSSS");
private static final String DATE_TIME_NANOSECONDS = "2000-01-01 12:00:00.123456789";
@Test
public void testConvertFieldNull() {
final Timestamp timestamp = CONVERTER.convertField(null, DEFAULT_PATTERN, FIELD_NAME);
assertNull(timestamp);
}
@Test
public void testConvertFieldTimestamp() {
final Timestamp field = new Timestamp(System.currentTimeMillis());
final Timestamp timestamp = CONVERTER.convertField(field, DEFAULT_PATTERN, FIELD_NAME);
assertEquals(field, timestamp);
}
@Test
public void testConvertFieldDate() {
final Date field = new Date();
final Timestamp timestamp = CONVERTER.convertField(field, DEFAULT_PATTERN, FIELD_NAME);
assertEquals(field.getTime(), timestamp.getTime());
}
@Test
public void testConvertFieldLong() {
final long field = System.currentTimeMillis();
final Timestamp timestamp = CONVERTER.convertField(field, DEFAULT_PATTERN, FIELD_NAME);
assertEquals(field, timestamp.getTime());
}
@Test
public void testConvertFieldStringEmpty() {
final Timestamp timestamp = CONVERTER.convertField(EMPTY, DEFAULT_PATTERN, FIELD_NAME);
assertNull(timestamp);
}
@Test
public void testConvertFieldStringFormatNull() {
final long currentTime = System.currentTimeMillis();
final String field = Long.toString(currentTime);
final Timestamp timestamp = CONVERTER.convertField(field, Optional.empty(), FIELD_NAME);
assertEquals(currentTime, timestamp.getTime());
}
@Test
public void testConvertFieldStringFormatNullNumberFormatException() {
final String field = String.class.getSimpleName();
final IllegalTypeConversionException exception = assertThrows(IllegalTypeConversionException.class, () -> CONVERTER.convertField(field, Optional.empty(), FIELD_NAME));
assertTrue(exception.getMessage().contains(field));
}
@Test
public void testConvertFieldStringFormatDefault() {
final Timestamp timestamp = CONVERTER.convertField(DATE_TIME_DEFAULT, DEFAULT_PATTERN, FIELD_NAME);
final Timestamp expected = Timestamp.valueOf(DATE_TIME_DEFAULT);
assertEquals(expected, timestamp);
}
@Test
public void testConvertFieldStringFormatCustomNanoseconds() {
final Timestamp timestamp = CONVERTER.convertField(DATE_TIME_NANOSECONDS, DATE_TIME_NANOSECONDS_PATTERN, FIELD_NAME);
final Timestamp expected = Timestamp.valueOf(DATE_TIME_NANOSECONDS);
assertEquals(expected, timestamp);
}
@Test
public void testConvertFieldStringFormatCustomFormatterException() {
final IllegalTypeConversionException exception = assertThrows(IllegalTypeConversionException.class, () -> CONVERTER.convertField(DATE_TIME_DEFAULT, DATE_TIME_NANOSECONDS_PATTERN, FIELD_NAME));
assertTrue(exception.getMessage().contains(DATE_TIME_DEFAULT));
}
}
| UTF-8 | Java | 4,916 | java | ObjectTimestampFieldConverterTest.java | Java | []
| null | []
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.serialization.record.field;
import org.apache.nifi.serialization.record.RecordFieldType;
import org.apache.nifi.serialization.record.util.IllegalTypeConversionException;
import org.junit.jupiter.api.Test;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ObjectTimestampFieldConverterTest {
private static final ObjectTimestampFieldConverter CONVERTER = new ObjectTimestampFieldConverter();
private static final Optional<String> DEFAULT_PATTERN = Optional.of(RecordFieldType.TIMESTAMP.getDefaultFormat());
private static final String FIELD_NAME = Timestamp.class.getSimpleName();
private static final String EMPTY = "";
private static final String DATE_TIME_DEFAULT = "2000-01-01 12:00:00";
private static final Optional<String> DATE_TIME_NANOSECONDS_PATTERN = Optional.of("yyyy-MM-dd HH:mm:ss.SSSSSSSSS");
private static final String DATE_TIME_NANOSECONDS = "2000-01-01 12:00:00.123456789";
@Test
public void testConvertFieldNull() {
final Timestamp timestamp = CONVERTER.convertField(null, DEFAULT_PATTERN, FIELD_NAME);
assertNull(timestamp);
}
@Test
public void testConvertFieldTimestamp() {
final Timestamp field = new Timestamp(System.currentTimeMillis());
final Timestamp timestamp = CONVERTER.convertField(field, DEFAULT_PATTERN, FIELD_NAME);
assertEquals(field, timestamp);
}
@Test
public void testConvertFieldDate() {
final Date field = new Date();
final Timestamp timestamp = CONVERTER.convertField(field, DEFAULT_PATTERN, FIELD_NAME);
assertEquals(field.getTime(), timestamp.getTime());
}
@Test
public void testConvertFieldLong() {
final long field = System.currentTimeMillis();
final Timestamp timestamp = CONVERTER.convertField(field, DEFAULT_PATTERN, FIELD_NAME);
assertEquals(field, timestamp.getTime());
}
@Test
public void testConvertFieldStringEmpty() {
final Timestamp timestamp = CONVERTER.convertField(EMPTY, DEFAULT_PATTERN, FIELD_NAME);
assertNull(timestamp);
}
@Test
public void testConvertFieldStringFormatNull() {
final long currentTime = System.currentTimeMillis();
final String field = Long.toString(currentTime);
final Timestamp timestamp = CONVERTER.convertField(field, Optional.empty(), FIELD_NAME);
assertEquals(currentTime, timestamp.getTime());
}
@Test
public void testConvertFieldStringFormatNullNumberFormatException() {
final String field = String.class.getSimpleName();
final IllegalTypeConversionException exception = assertThrows(IllegalTypeConversionException.class, () -> CONVERTER.convertField(field, Optional.empty(), FIELD_NAME));
assertTrue(exception.getMessage().contains(field));
}
@Test
public void testConvertFieldStringFormatDefault() {
final Timestamp timestamp = CONVERTER.convertField(DATE_TIME_DEFAULT, DEFAULT_PATTERN, FIELD_NAME);
final Timestamp expected = Timestamp.valueOf(DATE_TIME_DEFAULT);
assertEquals(expected, timestamp);
}
@Test
public void testConvertFieldStringFormatCustomNanoseconds() {
final Timestamp timestamp = CONVERTER.convertField(DATE_TIME_NANOSECONDS, DATE_TIME_NANOSECONDS_PATTERN, FIELD_NAME);
final Timestamp expected = Timestamp.valueOf(DATE_TIME_NANOSECONDS);
assertEquals(expected, timestamp);
}
@Test
public void testConvertFieldStringFormatCustomFormatterException() {
final IllegalTypeConversionException exception = assertThrows(IllegalTypeConversionException.class, () -> CONVERTER.convertField(DATE_TIME_DEFAULT, DATE_TIME_NANOSECONDS_PATTERN, FIELD_NAME));
assertTrue(exception.getMessage().contains(DATE_TIME_DEFAULT));
}
}
| 4,916 | 0.74227 | 0.73393 | 114 | 42.122807 | 39.613071 | 200 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.692982 | false | false | 3 |
d91f159f5a311534ec3f0ee82f3b2c56d12cbda7 | 8,538,395,052,073 | e14bb6400366264c0a14b29aa44e4d9d51476ce4 | /src/assignment6/AVehicleDriver.java | dd526e990f215d9c614fd2aadf3cbae56ef30eaf | []
| no_license | sreya92/Comp110Projects | https://github.com/sreya92/Comp110Projects | b2f590931cac24f0beafe753586c8460cf089cd2 | 433dae14248a3e07b6f51c6741e1b25369ae19fb | refs/heads/master | 2016-09-05T19:57:16.205000 | 2013-07-31T03:37:16 | 2013-07-31T03:37:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package assignment6;
import assignment8.AVehicle;
import bus.uigen.ObjectEditor;
public class AVehicleDriver
{
/**
* @param args
*/
public static void main(String[] args)
{
System.out.println("Please enter the width");
int theWidth= Console.readInt();
System.out.println("Please enter the height");
int theHeight=Console.readInt();
AVehicle vehicle= new AVehicle(theWidth, theHeight);
print(vehicle);
ObjectEditor.edit(vehicle);
System.out.println("Please enter a command (move, scale, quit)");
String command=Console.readString();
while (!command.equals("quit"))
{
if (command.equals("move"))
{
System.out.println("Enter the new OffsetX Value");
int newOffsetX=Console.readInt();
vehicle.setOffsetX(newOffsetX);
System.out.println("Enter the new OffsetY Value");
int newOffsetY=Console.readInt();
vehicle.setOffsetY(newOffsetY);
print(vehicle);
}
if (command.equals("scale"))
{
System.out.println("Enter the new Scale Value");
int newScale=Console.readInt();
vehicle.setScaleFactor(newScale);
print(vehicle);
}
System.out.println("Please enter a command (move, scale, quit)");
command=Console.readString();
}
}
public static void print(AVehicle vehicle)
{
System.out.println("-------------------------");
System.out.println("Car Information");
System.out.println("****Cabin Information:****");
System.out.println("Upper-left corner");
System.out.println("OffsetX: "+ vehicle.getCabin().getLocation().getX()+ " OffsetY: "+vehicle.getCabin().getLocation().getY());
System.out.println("Width: "+ vehicle.getCabin().getWidth()+ " Height: "+vehicle.getCabin().getHeight());
System.out.println("****Body Information****");
System.out.println("Upper-left corner");
System.out.println("OffsetX: "+vehicle.getBody().getLocation().getX()+ " OffsetY: "+vehicle.getBody().getLocation().getY());
System.out.println("Width: "+vehicle.getBody().getWidth()+" Height: "+vehicle.getBody().getHeight());
System.out.println("****Front Tire Information****");
System.out.println("Upper-left corner");
System.out.println("OffsetX: " +vehicle.getRightTire().getX()+ " OffsetY: " +vehicle.getRightTire().getY());
System.out.println("Width: " +vehicle.getRightTire().getWidth()+ " Height: "+vehicle.getRightTire().getHeight());
System.out.println("****Rear Tire Information****");
System.out.println("Upper-left corner");
System.out.println("OffsetX: " +vehicle.getLeftTire().getX()+ " OffsetY: " +vehicle.getLeftTire().getX());
System.out.println("Width: "+vehicle.getLeftTire().getWidth()+ " Height: " +vehicle.getLeftTire().getHeight());
}
}
| UTF-8 | Java | 2,729 | java | AVehicleDriver.java | Java | []
| null | []
| package assignment6;
import assignment8.AVehicle;
import bus.uigen.ObjectEditor;
public class AVehicleDriver
{
/**
* @param args
*/
public static void main(String[] args)
{
System.out.println("Please enter the width");
int theWidth= Console.readInt();
System.out.println("Please enter the height");
int theHeight=Console.readInt();
AVehicle vehicle= new AVehicle(theWidth, theHeight);
print(vehicle);
ObjectEditor.edit(vehicle);
System.out.println("Please enter a command (move, scale, quit)");
String command=Console.readString();
while (!command.equals("quit"))
{
if (command.equals("move"))
{
System.out.println("Enter the new OffsetX Value");
int newOffsetX=Console.readInt();
vehicle.setOffsetX(newOffsetX);
System.out.println("Enter the new OffsetY Value");
int newOffsetY=Console.readInt();
vehicle.setOffsetY(newOffsetY);
print(vehicle);
}
if (command.equals("scale"))
{
System.out.println("Enter the new Scale Value");
int newScale=Console.readInt();
vehicle.setScaleFactor(newScale);
print(vehicle);
}
System.out.println("Please enter a command (move, scale, quit)");
command=Console.readString();
}
}
public static void print(AVehicle vehicle)
{
System.out.println("-------------------------");
System.out.println("Car Information");
System.out.println("****Cabin Information:****");
System.out.println("Upper-left corner");
System.out.println("OffsetX: "+ vehicle.getCabin().getLocation().getX()+ " OffsetY: "+vehicle.getCabin().getLocation().getY());
System.out.println("Width: "+ vehicle.getCabin().getWidth()+ " Height: "+vehicle.getCabin().getHeight());
System.out.println("****Body Information****");
System.out.println("Upper-left corner");
System.out.println("OffsetX: "+vehicle.getBody().getLocation().getX()+ " OffsetY: "+vehicle.getBody().getLocation().getY());
System.out.println("Width: "+vehicle.getBody().getWidth()+" Height: "+vehicle.getBody().getHeight());
System.out.println("****Front Tire Information****");
System.out.println("Upper-left corner");
System.out.println("OffsetX: " +vehicle.getRightTire().getX()+ " OffsetY: " +vehicle.getRightTire().getY());
System.out.println("Width: " +vehicle.getRightTire().getWidth()+ " Height: "+vehicle.getRightTire().getHeight());
System.out.println("****Rear Tire Information****");
System.out.println("Upper-left corner");
System.out.println("OffsetX: " +vehicle.getLeftTire().getX()+ " OffsetY: " +vehicle.getLeftTire().getX());
System.out.println("Width: "+vehicle.getLeftTire().getWidth()+ " Height: " +vehicle.getLeftTire().getHeight());
}
}
| 2,729 | 0.667277 | 0.666544 | 66 | 40.348484 | 33.721001 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.787879 | false | false | 3 |
036dbc4732bf0dfde9d98b4404e95c0311f058d4 | 26,164,940,816,113 | 26740edd92f52c8d4d91af60f2b087923a64ff77 | /JianzhiOfferListNode/src/com/jianzhioffer/www/No_20_string_isNumeric.java | 5eb677afabcebdd6a88054f8445f7b77bb138de4 | []
| no_license | Gcoooooo/IdeaProjects | https://github.com/Gcoooooo/IdeaProjects | 97561f1e36f0af4a559a980a1ab833e279101f8a | bffa6c04720da954f6efbe840e08e3af536aa4fa | refs/heads/master | 2020-06-03T15:04:24.613000 | 2019-06-12T17:46:22 | 2019-06-12T17:46:22 | 191,618,523 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jianzhioffer.www;
import java.util.Collections;
public class No_20_string_isNumeric {
int index = 0; //指向当前字符
/*
* 分别需要扫描整数部分、小数点、小数部分、e或E、指数部分
* 整数部分和指数部分可以带正负号,小数部分不能带正负号
* 从前往后依次进行扫描,设置一个全局的指针,指向字符串中的字符
* 每个部分若符合要求,则返回true,指针也后移
* 若不符合要求,则函数会返回false,指针也不会移动,下一次调用函数扫描时,仍然从该处开始扫描
*/
public boolean isNumeric(char[] str) {
if (str.length == 0 || str == null) {
return false;
}
//开头:1) 无符号整数; 2)有符号整数; 3)小数点
boolean numeric = scanInteger(str); //扫描有符号整数或无符号整数,若扫描符合,则index就会一直移动,直到发现非0~9的字符
//当遇到小数点时的处理,开头就是小数点也在这里扫描
if (index < str.length && str[index] == '.') {
index++; //跳过小数点比较接下来的东西
numeric = scanUnsignedInteger(str) || numeric; //小数点前有整数,即可返回ture,小数点后使用scanUnsignedInteger扫描后续部分
//****特别注意,此处不能调换顺序,否则根据短路原则,有可能不执行scanUnsignedInteger,忽略扫描小数部分
//对于abc.123这种无效字符串,由于abc不符合要求,故最开始的判断会返回false,即numeric为false,且指针不会右移
//此时调用scanUnsignedInteger,就需要从头开始扫描,仍然会返回false
}
//遇到e或E时的处理
if (index < str.length && (str[index] == 'e' || str[index] == 'E')) {
index++;
numeric = numeric && scanInteger(str); //e前面必须有整数,且指数部分也需要有整数
}
return numeric && (index == str.length); //当扫描完整个字符串且numeric为true时就返回true
}
//+123和123都返回true,返回false时index不会移动
public boolean scanInteger(char[] str) { //用于扫描字符串中以 +或-开头的0~9数位(是否是带符号整数),或不带符号的0~9数位
if (index < str.length && (str[index] == '+' || str[index] == '-')) { //判断是否是以"+"或"-"开头,是的话index后移
//不是就不做任何操作,此时相当于直接调用scanUnsignedInteger
index++;
}
return scanUnsignedInteger(str); //若含有正负号,则此时输入扫描的是正负号之后的内容,若不含正负号,则相当于直接调用scanUnsignedInteger
}
//123返回true,返回false时index不会移动
private boolean scanUnsignedInteger(char[] str) { //用于扫描字符串中0~9的数位(是否是无符号整数)
int start = index; //若是0~9的数字,则index必定后移
while (index < str.length && (str[index] >= '0' && str[index] <= '9')) {
index++;
}
return start < index; //若index后移了,则表明扫描到了无符号整数
}
}
| GB18030 | Java | 3,433 | java | No_20_string_isNumeric.java | Java | []
| null | []
| package com.jianzhioffer.www;
import java.util.Collections;
public class No_20_string_isNumeric {
int index = 0; //指向当前字符
/*
* 分别需要扫描整数部分、小数点、小数部分、e或E、指数部分
* 整数部分和指数部分可以带正负号,小数部分不能带正负号
* 从前往后依次进行扫描,设置一个全局的指针,指向字符串中的字符
* 每个部分若符合要求,则返回true,指针也后移
* 若不符合要求,则函数会返回false,指针也不会移动,下一次调用函数扫描时,仍然从该处开始扫描
*/
public boolean isNumeric(char[] str) {
if (str.length == 0 || str == null) {
return false;
}
//开头:1) 无符号整数; 2)有符号整数; 3)小数点
boolean numeric = scanInteger(str); //扫描有符号整数或无符号整数,若扫描符合,则index就会一直移动,直到发现非0~9的字符
//当遇到小数点时的处理,开头就是小数点也在这里扫描
if (index < str.length && str[index] == '.') {
index++; //跳过小数点比较接下来的东西
numeric = scanUnsignedInteger(str) || numeric; //小数点前有整数,即可返回ture,小数点后使用scanUnsignedInteger扫描后续部分
//****特别注意,此处不能调换顺序,否则根据短路原则,有可能不执行scanUnsignedInteger,忽略扫描小数部分
//对于abc.123这种无效字符串,由于abc不符合要求,故最开始的判断会返回false,即numeric为false,且指针不会右移
//此时调用scanUnsignedInteger,就需要从头开始扫描,仍然会返回false
}
//遇到e或E时的处理
if (index < str.length && (str[index] == 'e' || str[index] == 'E')) {
index++;
numeric = numeric && scanInteger(str); //e前面必须有整数,且指数部分也需要有整数
}
return numeric && (index == str.length); //当扫描完整个字符串且numeric为true时就返回true
}
//+123和123都返回true,返回false时index不会移动
public boolean scanInteger(char[] str) { //用于扫描字符串中以 +或-开头的0~9数位(是否是带符号整数),或不带符号的0~9数位
if (index < str.length && (str[index] == '+' || str[index] == '-')) { //判断是否是以"+"或"-"开头,是的话index后移
//不是就不做任何操作,此时相当于直接调用scanUnsignedInteger
index++;
}
return scanUnsignedInteger(str); //若含有正负号,则此时输入扫描的是正负号之后的内容,若不含正负号,则相当于直接调用scanUnsignedInteger
}
//123返回true,返回false时index不会移动
private boolean scanUnsignedInteger(char[] str) { //用于扫描字符串中0~9的数位(是否是无符号整数)
int start = index; //若是0~9的数字,则index必定后移
while (index < str.length && (str[index] >= '0' && str[index] <= '9')) {
index++;
}
return start < index; //若index后移了,则表明扫描到了无符号整数
}
}
| 3,433 | 0.574571 | 0.560933 | 62 | 34.661289 | 33.385792 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.919355 | false | false | 3 |
90f1be96e5537f0e5ec9c1cc1372390553375171 | 36,240,934,065,309 | 2fda0a2f1f5f5d4e7d72ff15a73a4d3e1e93abeb | /proFL-plugin-2.0.3/org/netbeans/lib/cvsclient/file/WindowsFileReadOnlyHandler.java | 3024dc23e4a3ddf10d84c50f7cb98beb0b29819b | [
"MIT"
]
| permissive | ycj123/Research-Project | https://github.com/ycj123/Research-Project | d1a939d99d62dc4b02d9a8b7ecbf66210cceb345 | 08296e0075ba0c13204944b1bc1a96a7b8d2f023 | refs/heads/main | 2023-05-29T11:02:41.099000 | 2021-06-08T13:33:26 | 2021-06-08T13:33:26 | 374,899,147 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //
// Decompiled by Procyon v0.5.36
//
package org.netbeans.lib.cvsclient.file;
import java.io.IOException;
import org.netbeans.lib.cvsclient.util.BugLog;
import java.io.File;
public class WindowsFileReadOnlyHandler implements FileReadOnlyHandler
{
public void setFileReadOnly(final File file, final boolean b) throws IOException {
if (file == null) {
throw new IllegalArgumentException("file must not be null");
}
try {
Runtime.getRuntime().exec(new String[] { "attrib", b ? "+r" : "-r", file.getName() }, null, file.getParentFile()).waitFor();
}
catch (InterruptedException ex) {
BugLog.getInstance().showException(ex);
}
}
}
| UTF-8 | Java | 725 | java | WindowsFileReadOnlyHandler.java | Java | []
| null | []
| //
// Decompiled by Procyon v0.5.36
//
package org.netbeans.lib.cvsclient.file;
import java.io.IOException;
import org.netbeans.lib.cvsclient.util.BugLog;
import java.io.File;
public class WindowsFileReadOnlyHandler implements FileReadOnlyHandler
{
public void setFileReadOnly(final File file, final boolean b) throws IOException {
if (file == null) {
throw new IllegalArgumentException("file must not be null");
}
try {
Runtime.getRuntime().exec(new String[] { "attrib", b ? "+r" : "-r", file.getName() }, null, file.getParentFile()).waitFor();
}
catch (InterruptedException ex) {
BugLog.getInstance().showException(ex);
}
}
}
| 725 | 0.646897 | 0.641379 | 24 | 29.208334 | 33.44022 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 3 |
ed5e4117e8e41ae3230d343657be817ff5f45e12 | 33,870,112,136,965 | b51c5ff1efde3194d028bd533ecc6e7e50d44ba5 | /app/src/main/java/com/yeohe/rxdemo/MainActivity.java | e05c0f11c47120c63672aed8e2428f81bcd45a33 | []
| no_license | laiyongshan/RxDemo | https://github.com/laiyongshan/RxDemo | cf98ad34692ae6944f7900128d3e32e212028970 | 9114eeab5bdf0529e237a66ec6d0c37c60213260 | refs/heads/master | 2021-05-12T05:54:49.414000 | 2018-01-19T08:11:46 | 2018-01-19T08:11:46 | 117,205,677 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yeohe.rxdemo;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import com.yeohe.rxdemo.adapter.TypeAdapter;
import com.yeohe.rxdemo.ui.WXArticle.WXArticleActivity;
import com.yeohe.rxdemo.ui.ari.AriActivity;
import com.yeohe.rxdemo.ui.boxoffice.BoxOfficeActivity;
import com.yeohe.rxdemo.ui.exchange.RateActivity;
import com.yeohe.rxdemo.ui.lottery.LotteryActivity;
import com.yeohe.rxdemo.ui.mobileAddress.MobileAddressActivity;
import com.yeohe.rxdemo.ui.postCode.PostCodeActivitry;
import com.yeohe.rxdemo.ui.share.ShareDemoActivity;
import com.yeohe.rxdemo.ui.tiku.TikuActivity;
import com.yeohe.rxdemo.utils.ToastUtil;
import com.yeohe.rxdemo.widgets.MyGridView;
import java.util.ArrayList;
import static android.support.v4.content.ContextCompat.checkSelfPermission;
public class MainActivity extends AppCompatActivity {
private MyGridView gv_type;//新增功能按钮
private ArrayList<Integer> types;
private TypeAdapter typeAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData(this);
}
Intent intent;
private void initData(final Context context){
gv_type=findViewById(R.id.gv_type);
String[] type_strArr = {"手机号码归属地", "邮编查询", "空气质量", "驾考题库", "电影票房", "货币汇率","彩票开奖结果","微信精选","分享Demo"};
types = new ArrayList<Integer>();
types.add(R.drawable.ic_launcher_foreground);//手机号码归属地
types.add(R.drawable.ic_launcher_foreground);//邮编查询
types.add(R.drawable.ic_launcher_foreground);//空气质量
types.add(R.drawable.ic_launcher_foreground);//驾考题库
types.add(R.drawable.ic_launcher_foreground);//电影票房
types.add(R.drawable.ic_launcher_foreground);//货币汇率
types.add(R.drawable.ic_launcher_foreground);//彩票开奖结果
types.add(R.drawable.ic_launcher_foreground);//微信精选
types.add(R.drawable.ic_launcher_foreground);//Android系统分享Demo
typeAdapter = new TypeAdapter(types, context, type_strArr, 2);
gv_type.setAdapter(typeAdapter);
gv_type.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
switch (position) {
case 0:
intent=new Intent(MainActivity.this, MobileAddressActivity.class);
break;
case 1:
intent=new Intent(MainActivity.this, PostCodeActivitry.class);
break;
case 2:
intent=new Intent(MainActivity.this, AriActivity.class);
break;
case 3:
intent=new Intent(MainActivity.this, TikuActivity.class);
break;
case 4:
intent=new Intent(MainActivity.this, BoxOfficeActivity.class);
break;
case 5:
intent=new Intent(MainActivity.this, RateActivity.class);
break;
case 6:
intent=new Intent(MainActivity.this, LotteryActivity.class);
break;
case 7:
intent=new Intent(MainActivity.this, WXArticleActivity.class);
break;
case 8:
intent=new Intent(MainActivity.this, ShareDemoActivity.class);
break;
}
startActivity(intent);
}
});
}
//退出时的时间
private long mExitTime;
//对返回键进行监听
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
exit();
return true;
}
return super.onKeyDown(keyCode, event);
}
public void exit() {
if ((System.currentTimeMillis() - mExitTime) > 2000) {
ToastUtil.showMessage(MainActivity.this, "再按一次退出应用", Toast.LENGTH_SHORT);
mExitTime = System.currentTimeMillis();
} else {
// MyConfig.clearSharePre(this, "users");
finish();
System.exit(0);
}
}
}
| UTF-8 | Java | 4,948 | java | MainActivity.java | Java | []
| null | []
| package com.yeohe.rxdemo;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import com.yeohe.rxdemo.adapter.TypeAdapter;
import com.yeohe.rxdemo.ui.WXArticle.WXArticleActivity;
import com.yeohe.rxdemo.ui.ari.AriActivity;
import com.yeohe.rxdemo.ui.boxoffice.BoxOfficeActivity;
import com.yeohe.rxdemo.ui.exchange.RateActivity;
import com.yeohe.rxdemo.ui.lottery.LotteryActivity;
import com.yeohe.rxdemo.ui.mobileAddress.MobileAddressActivity;
import com.yeohe.rxdemo.ui.postCode.PostCodeActivitry;
import com.yeohe.rxdemo.ui.share.ShareDemoActivity;
import com.yeohe.rxdemo.ui.tiku.TikuActivity;
import com.yeohe.rxdemo.utils.ToastUtil;
import com.yeohe.rxdemo.widgets.MyGridView;
import java.util.ArrayList;
import static android.support.v4.content.ContextCompat.checkSelfPermission;
public class MainActivity extends AppCompatActivity {
private MyGridView gv_type;//新增功能按钮
private ArrayList<Integer> types;
private TypeAdapter typeAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData(this);
}
Intent intent;
private void initData(final Context context){
gv_type=findViewById(R.id.gv_type);
String[] type_strArr = {"手机号码归属地", "邮编查询", "空气质量", "驾考题库", "电影票房", "货币汇率","彩票开奖结果","微信精选","分享Demo"};
types = new ArrayList<Integer>();
types.add(R.drawable.ic_launcher_foreground);//手机号码归属地
types.add(R.drawable.ic_launcher_foreground);//邮编查询
types.add(R.drawable.ic_launcher_foreground);//空气质量
types.add(R.drawable.ic_launcher_foreground);//驾考题库
types.add(R.drawable.ic_launcher_foreground);//电影票房
types.add(R.drawable.ic_launcher_foreground);//货币汇率
types.add(R.drawable.ic_launcher_foreground);//彩票开奖结果
types.add(R.drawable.ic_launcher_foreground);//微信精选
types.add(R.drawable.ic_launcher_foreground);//Android系统分享Demo
typeAdapter = new TypeAdapter(types, context, type_strArr, 2);
gv_type.setAdapter(typeAdapter);
gv_type.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
switch (position) {
case 0:
intent=new Intent(MainActivity.this, MobileAddressActivity.class);
break;
case 1:
intent=new Intent(MainActivity.this, PostCodeActivitry.class);
break;
case 2:
intent=new Intent(MainActivity.this, AriActivity.class);
break;
case 3:
intent=new Intent(MainActivity.this, TikuActivity.class);
break;
case 4:
intent=new Intent(MainActivity.this, BoxOfficeActivity.class);
break;
case 5:
intent=new Intent(MainActivity.this, RateActivity.class);
break;
case 6:
intent=new Intent(MainActivity.this, LotteryActivity.class);
break;
case 7:
intent=new Intent(MainActivity.this, WXArticleActivity.class);
break;
case 8:
intent=new Intent(MainActivity.this, ShareDemoActivity.class);
break;
}
startActivity(intent);
}
});
}
//退出时的时间
private long mExitTime;
//对返回键进行监听
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
exit();
return true;
}
return super.onKeyDown(keyCode, event);
}
public void exit() {
if ((System.currentTimeMillis() - mExitTime) > 2000) {
ToastUtil.showMessage(MainActivity.this, "再按一次退出应用", Toast.LENGTH_SHORT);
mExitTime = System.currentTimeMillis();
} else {
// MyConfig.clearSharePre(this, "users");
finish();
System.exit(0);
}
}
}
| 4,948 | 0.616019 | 0.612003 | 135 | 34.051853 | 26.703119 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.77037 | false | false | 3 |
26794e63ae079140294ad8031e1b5eb8a894b713 | 31,825,707,726,195 | 404a189c16767191ffb172572d36eca7db5571fb | /service/src/java/gov/georgia/dhr/dfcs/sacwis/service/assessment/.svn/text-base/SaveServicesAndReferrals.java.svn-base | 6bb1d41cab74b170656cf7442b300e0c6c89f7e9 | []
| no_license | tayduivn/training | https://github.com/tayduivn/training | 648a8e9e91194156fb4ffb631749e6d4bf2d0590 | 95078fb2c7e21bf2bba31e2bbd5e404ac428da2f | refs/heads/master | 2021-06-13T16:20:41.293000 | 2017-05-08T21:37:59 | 2017-05-08T21:37:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gov.georgia.dhr.dfcs.sacwis.service.assessment;
import gov.georgia.dhr.dfcs.sacwis.structs.input.CINV55SI;
import gov.georgia.dhr.dfcs.sacwis.structs.output.CINV55SO;
public interface SaveServicesAndReferrals {
/**
* This service calls DAMS CAUDE3D.pc and CAUDE4D.pc. This service will save or update all columns on the CPS_CHKLST
* table. It will also insert or delete one or more rows from the CPS_CHKLST_ITEM table, depending on what was
* changed in the Services and Referrals Checklist window.
*
* @param cinv55si The input object populated with method parameters.
* @return CINV55SO The output object populated with the retrieved row/column values.
*/
public CINV55SO saveServicesAndReferralsInformation(CINV55SI cinv55si);
}
| UTF-8 | Java | 786 | SaveServicesAndReferrals.java.svn-base | Java | []
| null | []
| package gov.georgia.dhr.dfcs.sacwis.service.assessment;
import gov.georgia.dhr.dfcs.sacwis.structs.input.CINV55SI;
import gov.georgia.dhr.dfcs.sacwis.structs.output.CINV55SO;
public interface SaveServicesAndReferrals {
/**
* This service calls DAMS CAUDE3D.pc and CAUDE4D.pc. This service will save or update all columns on the CPS_CHKLST
* table. It will also insert or delete one or more rows from the CPS_CHKLST_ITEM table, depending on what was
* changed in the Services and Referrals Checklist window.
*
* @param cinv55si The input object populated with method parameters.
* @return CINV55SO The output object populated with the retrieved row/column values.
*/
public CINV55SO saveServicesAndReferralsInformation(CINV55SI cinv55si);
}
| 786 | 0.762087 | 0.74173 | 17 | 44.235294 | 39.670006 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.294118 | false | false | 3 |
|
120f7c4c64cc6fb6fa09b0276a0207c7753a0871 | 31,825,707,725,796 | 39b24478fbb771fd1f6946a6e2ee9b33270e1610 | /lms/src/main/java/ukma/baratheons/lms/util/LevenshteinDistance.java | c6d4745fff052bd8be8d33f1d25d017dd7953a32 | []
| no_license | Baratheons/LMS | https://github.com/Baratheons/LMS | 68455d69e7f5034ca3be1c7c67b2e7c6ed88e03e | 914e4955f137cf011063ef3c5dea969dff2e9215 | refs/heads/master | 2016-09-01T08:20:27.933000 | 2015-12-04T10:45:13 | 2015-12-04T10:45:13 | 45,261,783 | 4 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ukma.baratheons.lms.util;
public class LevenshteinDistance {
/**
* Calculates levenshtein distance
* @param str1 - the first string to compare
* @param str2 - the second string to compare
* */
public static int editdist(final String str1, final String str2) {
if(str1 == null)
throw new IllegalArgumentException("str1 == null");
if(str2 == null)
throw new IllegalArgumentException("str2 == null");
int m = str1.length(), n = str2.length();
int[] D1;
int[] D2 = new int[n + 1];
for(int i = 0; i <= n; i ++)
D2[i] = i;
for(int i = 1; i <= m; i ++) {
D1 = D2;
D2 = new int[n + 1];
for(int j = 0; j <= n; j ++) {
if(j == 0) D2[j] = i;
else {
int cost = (str1.charAt(i - 1) != str2.charAt(j - 1)) ? 1 : 0;
if(D2[j - 1] < D1[j] && D2[j - 1] < D1[j - 1] + cost)
D2[j] = D2[j - 1] + 1;
else if(D1[j] < D1[j - 1] + cost)
D2[j] = D1[j] + 1;
else
D2[j] = D1[j - 1] + cost;
}
}
}
return D2[n];
}
}
| UTF-8 | Java | 1,053 | java | LevenshteinDistance.java | Java | []
| null | []
| package ukma.baratheons.lms.util;
public class LevenshteinDistance {
/**
* Calculates levenshtein distance
* @param str1 - the first string to compare
* @param str2 - the second string to compare
* */
public static int editdist(final String str1, final String str2) {
if(str1 == null)
throw new IllegalArgumentException("str1 == null");
if(str2 == null)
throw new IllegalArgumentException("str2 == null");
int m = str1.length(), n = str2.length();
int[] D1;
int[] D2 = new int[n + 1];
for(int i = 0; i <= n; i ++)
D2[i] = i;
for(int i = 1; i <= m; i ++) {
D1 = D2;
D2 = new int[n + 1];
for(int j = 0; j <= n; j ++) {
if(j == 0) D2[j] = i;
else {
int cost = (str1.charAt(i - 1) != str2.charAt(j - 1)) ? 1 : 0;
if(D2[j - 1] < D1[j] && D2[j - 1] < D1[j - 1] + cost)
D2[j] = D2[j - 1] + 1;
else if(D1[j] < D1[j - 1] + cost)
D2[j] = D1[j] + 1;
else
D2[j] = D1[j - 1] + cost;
}
}
}
return D2[n];
}
}
| 1,053 | 0.494777 | 0.447293 | 44 | 21.931818 | 19.523176 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.863636 | false | false | 3 |
acf98a8e50252dfa101a52229236ac3216cc68a8 | 3,375,844,364,183 | 49826547249cb09dc74580a272a92aaf6b79669d | /src/main/java/org/ayaic/web/administrarpacientes/ListarPacientesSpamPDF.java | bb19a845f3d5bdd8592a6d7cb35fc944d4dee279 | []
| no_license | eloyreinaga/hospital | https://github.com/eloyreinaga/hospital | 824d3b35d675ce1568dd6022f68497b3a7af0221 | bc503941b5974bfa1f3dcdf93ca5d896baed2b9b | refs/heads/master | 2020-03-30T03:08:38.592000 | 2018-09-27T20:02:01 | 2018-09-27T20:02:01 | 150,671,383 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.ayaic.web.administrarpacientes;
import java.awt.Color;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.document.AbstractPdfView;
import java.util.*;
import java.text.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import org.ayaic.domain.Clientes;
import org.ayaic.domain.Historiales;
public class ListarPacientesSpamPDF extends AbstractPdfView {
private static final Font TITULO_FONT = new Font(Font.HELVETICA, 12, Font.BOLD, Color.black);
private static final Font CABEZA_COLUMNA_FONT = new Font(Font.HELVETICA, 8, Font.ITALIC, Color.black);
private static final Font DATO_FONT = new Font(Font.HELVETICA, 8, Font.NORMAL, Color.black);
private static final Font DATO_FONT_BOLD = new Font(Font.HELVETICA, 8, Font.BOLD, Color.black);
private static final int MARGIN = 32;
protected void buildPdfMetadata(Map model, Document document, HttpServletRequest request) {
document.setPageSize(PageSize.LEGAL.rotate());
document.setMargins(70, 20, 80, 20);
}
protected void buildPdfDocument(Map model, Document document, PdfWriter writer, HttpServletRequest req, HttpServletResponse resp) throws Exception {
java.util.List lFopos = (java.util.List) model.get("milistaSpam");
Clientes dato = (Clientes) model.get("dato");
Image escudo = Image.getInstance("/opt/imagenes/lescudo.bmp");
Paragraph p = new Paragraph("PACIENTES SSPAM\n", new Font(Font.HELVETICA, 14, Font.BOLDITALIC, new Color(0, 0, 0)));
p.setAlignment(Element.ALIGN_CENTER);
PdfPCell cell;
PdfPTable tablex = new PdfPTable(3);
int[] fxwidths = {15, 70, 15}; // percentage
tablex.setWidths(fxwidths);
tablex.setWidthPercentage(100);
cell = new PdfPCell(escudo);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setBorder(Rectangle.NO_BORDER);
tablex.addCell(cell);
cell = new PdfPCell(p);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setBorder(Rectangle.NO_BORDER);
tablex.addCell(cell);
document.add(tablex);
int[] sumas = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int NumColumns = 9;
int una, filas = 30;
if (lFopos.size() == 0) {
Paragraph p1 = new Paragraph("No existe Datos", new Font(Font.HELVETICA, 22, Font.BOLDITALIC, new Color(0, 0, 0)));
document.add(p1);
}
if (lFopos.size() % filas == 0) {
una = 0;
} else {
una = 1;
}
for (int pag = 0; pag < lFopos.size() / filas + una; pag++) {
Paragraph p1;
// PdfPCell cell;
PdfPTable table = new PdfPTable(NumColumns);
int[] fwidths = {5, 10, 10, 10, 6, 25, 40, 40, 8};
table.setWidths(fwidths);
table.setWidthPercentage(100);
cell = new PdfPCell(new Phrase("REGISTRO PACIENTES SSPAM", TITULO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setColspan(NumColumns);
table.addCell(cell);
cell = new PdfPCell(new Phrase("No.", CABEZA_COLUMNA_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase("Fecha Atencion", CABEZA_COLUMNA_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase("Numero HCL", CABEZA_COLUMNA_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase("Numero Registro", CABEZA_COLUMNA_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase("Edad", CABEZA_COLUMNA_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase("Apellidos y Nombres PAciente", CABEZA_COLUMNA_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase("DIAGNOSTICO", CABEZA_COLUMNA_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase("PAN DE ACCION", CABEZA_COLUMNA_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase("Fecha Afiliacion", CABEZA_COLUMNA_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
// coloca el detalle de loS datos
for (int i = pag * filas + 0; i < pag * filas + filas && i < lFopos.size(); i++) {
Historiales datopac = (Historiales) lFopos.get(i);
cell = new PdfPCell(new Phrase(Integer.toString(i + 1), DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
cell = new PdfPCell(new Phrase(format(datopac.getFecha(), "dd/MM/yyyy"), DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
cell = new PdfPCell(new Phrase(datopac.getRegistro(), DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
cell = new PdfPCell(new Phrase(datopac.getRegistro(), DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
cell = new PdfPCell(new Phrase(Integer.toString(datopac.getEdad()), DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
cell = new PdfPCell(new Phrase(datopac.getPaterno() + " " + datopac.getMaterno() + " " + datopac.getNombre(), DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
if (datopac.getDiagnostico() == null || "null".equals(datopac.getDiagnostico())) {
datopac.setDiagnostico("");
} else {
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("<p>", " "));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("</p>", " "));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll(" ", ""));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("<strong>", " "));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("</strong>", " "));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("<br />", " "));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("<u>", " "));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("</u>", " "));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("ñ", "n"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("Ñ", "N"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("Á", "A"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("É", "E"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("Í", "I"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("Ó", "O"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("Ú", "U"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("á", "a"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("é", "e"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("í", "i"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("ó", "o"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("ú", "u"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll(""", "'"));
}
cell = new PdfPCell(new Phrase((datopac.getDiagnostico()) + "-->" + datopac.getTipo(), DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
if (datopac.getAccion() == null) {
} else {
datopac.setAccion(datopac.getAccion().replaceAll("<p>", " "));
datopac.setAccion(datopac.getAccion().replaceAll("</p>", " "));
datopac.setAccion(datopac.getAccion().replaceAll(" ", ""));
datopac.setAccion(datopac.getAccion().replaceAll("<strong>", " "));
datopac.setAccion(datopac.getAccion().replaceAll("</strong>", " "));
datopac.setAccion(datopac.getAccion().replaceAll("<br />", " "));
datopac.setAccion(datopac.getAccion().replaceAll("<u>", " "));
datopac.setAccion(datopac.getAccion().replaceAll("</u>", " "));
datopac.setAccion(datopac.getAccion().replaceAll("ñ", "n"));
datopac.setAccion(datopac.getAccion().replaceAll("Ñ", "N"));
datopac.setAccion(datopac.getAccion().replaceAll("Ú", "U"));
datopac.setAccion(datopac.getAccion().replaceAll("Ó", "O"));
datopac.setAccion(datopac.getAccion().replaceAll("Í", "I"));
datopac.setAccion(datopac.getAccion().replaceAll("Á", "A"));
datopac.setAccion(datopac.getAccion().replaceAll("É", "E"));
datopac.setAccion(datopac.getAccion().replaceAll("ú", "u"));
datopac.setAccion(datopac.getAccion().replaceAll("ó", "o"));
datopac.setAccion(datopac.getAccion().replaceAll("í", "i"));
datopac.setAccion(datopac.getAccion().replaceAll("á", "a"));
datopac.setAccion(datopac.getAccion().replaceAll("é", "e"));
datopac.setAccion(datopac.getAccion().replaceAll(""", "'"));
}
cell = new PdfPCell(new Phrase((datopac.getAccion()), DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
cell = new PdfPCell(new Phrase(("R".equals(datopac.getRepetida())) ? "" : "", DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
}
for (int i = lFopos.size(); i < pag * filas + filas; i++) {
cell = new PdfPCell(new Phrase(Integer.toString(i + 1), DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
for (int j = 1; j < NumColumns; j++) {
cell = new PdfPCell(new Phrase("", DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
}
}
cell = new PdfPCell(new Phrase("", DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
document.add(table);
document.newPage();
}
}
public static void addtitulofila3(PdfPTable table, String cadena, String a, String b, String c) {
PdfPCell cell;
int NumColumns = 3;
PdfPTable table11 = new PdfPTable(NumColumns);
table11.setWidthPercentage(100);
cell = new PdfPCell(new Phrase(cadena, CABEZA_COLUMNA_FONT));
cell.setColspan(3);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table11.addCell(cell);
cell = new PdfPCell(new Phrase(a, DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table11.addCell(cell);
cell = new PdfPCell(new Phrase(b, DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table11.addCell(cell);
cell = new PdfPCell(new Phrase(c, DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table11.addCell(cell);
cell = new PdfPCell(table11);
cell.setColspan(3);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
}
public static String format(Date dia, String formato) {
if (dia == null) {
return "";
}
SimpleDateFormat formatDate = new SimpleDateFormat(formato);
return formatDate.format(dia);
}
}
| UTF-8 | Java | 13,066 | java | ListarPacientesSpamPDF.java | Java | []
| null | []
| package org.ayaic.web.administrarpacientes;
import java.awt.Color;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.document.AbstractPdfView;
import java.util.*;
import java.text.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import org.ayaic.domain.Clientes;
import org.ayaic.domain.Historiales;
public class ListarPacientesSpamPDF extends AbstractPdfView {
private static final Font TITULO_FONT = new Font(Font.HELVETICA, 12, Font.BOLD, Color.black);
private static final Font CABEZA_COLUMNA_FONT = new Font(Font.HELVETICA, 8, Font.ITALIC, Color.black);
private static final Font DATO_FONT = new Font(Font.HELVETICA, 8, Font.NORMAL, Color.black);
private static final Font DATO_FONT_BOLD = new Font(Font.HELVETICA, 8, Font.BOLD, Color.black);
private static final int MARGIN = 32;
protected void buildPdfMetadata(Map model, Document document, HttpServletRequest request) {
document.setPageSize(PageSize.LEGAL.rotate());
document.setMargins(70, 20, 80, 20);
}
protected void buildPdfDocument(Map model, Document document, PdfWriter writer, HttpServletRequest req, HttpServletResponse resp) throws Exception {
java.util.List lFopos = (java.util.List) model.get("milistaSpam");
Clientes dato = (Clientes) model.get("dato");
Image escudo = Image.getInstance("/opt/imagenes/lescudo.bmp");
Paragraph p = new Paragraph("PACIENTES SSPAM\n", new Font(Font.HELVETICA, 14, Font.BOLDITALIC, new Color(0, 0, 0)));
p.setAlignment(Element.ALIGN_CENTER);
PdfPCell cell;
PdfPTable tablex = new PdfPTable(3);
int[] fxwidths = {15, 70, 15}; // percentage
tablex.setWidths(fxwidths);
tablex.setWidthPercentage(100);
cell = new PdfPCell(escudo);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setBorder(Rectangle.NO_BORDER);
tablex.addCell(cell);
cell = new PdfPCell(p);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setBorder(Rectangle.NO_BORDER);
tablex.addCell(cell);
document.add(tablex);
int[] sumas = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int NumColumns = 9;
int una, filas = 30;
if (lFopos.size() == 0) {
Paragraph p1 = new Paragraph("No existe Datos", new Font(Font.HELVETICA, 22, Font.BOLDITALIC, new Color(0, 0, 0)));
document.add(p1);
}
if (lFopos.size() % filas == 0) {
una = 0;
} else {
una = 1;
}
for (int pag = 0; pag < lFopos.size() / filas + una; pag++) {
Paragraph p1;
// PdfPCell cell;
PdfPTable table = new PdfPTable(NumColumns);
int[] fwidths = {5, 10, 10, 10, 6, 25, 40, 40, 8};
table.setWidths(fwidths);
table.setWidthPercentage(100);
cell = new PdfPCell(new Phrase("REGISTRO PACIENTES SSPAM", TITULO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setColspan(NumColumns);
table.addCell(cell);
cell = new PdfPCell(new Phrase("No.", CABEZA_COLUMNA_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase("Fecha Atencion", CABEZA_COLUMNA_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase("Numero HCL", CABEZA_COLUMNA_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase("Numero Registro", CABEZA_COLUMNA_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase("Edad", CABEZA_COLUMNA_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase("Apellidos y Nombres PAciente", CABEZA_COLUMNA_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase("DIAGNOSTICO", CABEZA_COLUMNA_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase("PAN DE ACCION", CABEZA_COLUMNA_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase("Fecha Afiliacion", CABEZA_COLUMNA_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
// coloca el detalle de loS datos
for (int i = pag * filas + 0; i < pag * filas + filas && i < lFopos.size(); i++) {
Historiales datopac = (Historiales) lFopos.get(i);
cell = new PdfPCell(new Phrase(Integer.toString(i + 1), DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
cell = new PdfPCell(new Phrase(format(datopac.getFecha(), "dd/MM/yyyy"), DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
cell = new PdfPCell(new Phrase(datopac.getRegistro(), DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
cell = new PdfPCell(new Phrase(datopac.getRegistro(), DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
cell = new PdfPCell(new Phrase(Integer.toString(datopac.getEdad()), DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
cell = new PdfPCell(new Phrase(datopac.getPaterno() + " " + datopac.getMaterno() + " " + datopac.getNombre(), DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
if (datopac.getDiagnostico() == null || "null".equals(datopac.getDiagnostico())) {
datopac.setDiagnostico("");
} else {
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("<p>", " "));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("</p>", " "));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll(" ", ""));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("<strong>", " "));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("</strong>", " "));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("<br />", " "));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("<u>", " "));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("</u>", " "));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("ñ", "n"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("Ñ", "N"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("Á", "A"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("É", "E"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("Í", "I"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("Ó", "O"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("Ú", "U"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("á", "a"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("é", "e"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("í", "i"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("ó", "o"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll("ú", "u"));
datopac.setDiagnostico(datopac.getDiagnostico().replaceAll(""", "'"));
}
cell = new PdfPCell(new Phrase((datopac.getDiagnostico()) + "-->" + datopac.getTipo(), DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
if (datopac.getAccion() == null) {
} else {
datopac.setAccion(datopac.getAccion().replaceAll("<p>", " "));
datopac.setAccion(datopac.getAccion().replaceAll("</p>", " "));
datopac.setAccion(datopac.getAccion().replaceAll(" ", ""));
datopac.setAccion(datopac.getAccion().replaceAll("<strong>", " "));
datopac.setAccion(datopac.getAccion().replaceAll("</strong>", " "));
datopac.setAccion(datopac.getAccion().replaceAll("<br />", " "));
datopac.setAccion(datopac.getAccion().replaceAll("<u>", " "));
datopac.setAccion(datopac.getAccion().replaceAll("</u>", " "));
datopac.setAccion(datopac.getAccion().replaceAll("ñ", "n"));
datopac.setAccion(datopac.getAccion().replaceAll("Ñ", "N"));
datopac.setAccion(datopac.getAccion().replaceAll("Ú", "U"));
datopac.setAccion(datopac.getAccion().replaceAll("Ó", "O"));
datopac.setAccion(datopac.getAccion().replaceAll("Í", "I"));
datopac.setAccion(datopac.getAccion().replaceAll("Á", "A"));
datopac.setAccion(datopac.getAccion().replaceAll("É", "E"));
datopac.setAccion(datopac.getAccion().replaceAll("ú", "u"));
datopac.setAccion(datopac.getAccion().replaceAll("ó", "o"));
datopac.setAccion(datopac.getAccion().replaceAll("í", "i"));
datopac.setAccion(datopac.getAccion().replaceAll("á", "a"));
datopac.setAccion(datopac.getAccion().replaceAll("é", "e"));
datopac.setAccion(datopac.getAccion().replaceAll(""", "'"));
}
cell = new PdfPCell(new Phrase((datopac.getAccion()), DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
cell = new PdfPCell(new Phrase(("R".equals(datopac.getRepetida())) ? "" : "", DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
}
for (int i = lFopos.size(); i < pag * filas + filas; i++) {
cell = new PdfPCell(new Phrase(Integer.toString(i + 1), DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
for (int j = 1; j < NumColumns; j++) {
cell = new PdfPCell(new Phrase("", DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
}
}
cell = new PdfPCell(new Phrase("", DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
document.add(table);
document.newPage();
}
}
public static void addtitulofila3(PdfPTable table, String cadena, String a, String b, String c) {
PdfPCell cell;
int NumColumns = 3;
PdfPTable table11 = new PdfPTable(NumColumns);
table11.setWidthPercentage(100);
cell = new PdfPCell(new Phrase(cadena, CABEZA_COLUMNA_FONT));
cell.setColspan(3);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table11.addCell(cell);
cell = new PdfPCell(new Phrase(a, DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table11.addCell(cell);
cell = new PdfPCell(new Phrase(b, DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table11.addCell(cell);
cell = new PdfPCell(new Phrase(c, DATO_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table11.addCell(cell);
cell = new PdfPCell(table11);
cell.setColspan(3);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
}
public static String format(Date dia, String formato) {
if (dia == null) {
return "";
}
SimpleDateFormat formatDate = new SimpleDateFormat(formato);
return formatDate.format(dia);
}
}
| 13,066 | 0.590617 | 0.582275 | 269 | 47.572491 | 35.070606 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.345725 | false | false | 3 |
8b3d5a0ea688c44e0ff15fc33974552cede271fe | 867,583,437,421 | f315651879a7c9f7967cfe09e02dd9d9e9424476 | /HireCarJpaWebservice/src/main/java/com/example/controller/VehicleApiRestController.java | aba00675e2b212e384b44c94fb42824b9754de8c | []
| no_license | hamsuhi/IFI-exactly | https://github.com/hamsuhi/IFI-exactly | 668291c1635ee51460a7cbbda3d05c43da2f4a70 | 9d08100bf99c90b82c023db1d9b1087f75be4a8e | refs/heads/master | 2021-04-30T08:14:41.097000 | 2018-03-21T10:41:18 | 2018-03-21T10:41:18 | 121,368,993 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.controller;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import com.example.model.Model;
import com.example.model.Vehicle;
import com.example.model.VehicleCategory;
import com.example.repository.IVehicleRepository;
import com.example.service.ModelService;
import com.example.service.VehicleCategoryService;
import com.example.service.VehicleService;
@RestController
@RequestMapping("/api")
public class VehicleApiRestController {
private static final SimpleDateFormat formatDate = new SimpleDateFormat("dd/mm/yyyy");
@Autowired
private VehicleService vehicleService;
@Autowired
private IVehicleRepository vehicleRepository;
@Autowired
private ModelService modelService;
@Autowired
private VehicleCategoryService vehicleCategoryService;
@RequestMapping(value = "/vehicle", method = RequestMethod.GET)
private ResponseEntity<List<Vehicle>> getAllVehicle() {
List<Vehicle> vehicle = vehicleService.findAllVehicle();
if (vehicle.isEmpty()) {
return new ResponseEntity<List<Vehicle>>(vehicle, HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<Vehicle>>(vehicle, HttpStatus.OK);
}
@RequestMapping(value = "/vehicle/{id}", method = RequestMethod.GET)
private ResponseEntity<?> getVehicleById(@PathVariable("id") int id) {
Vehicle vehicle = vehicleService.findVehicleById(id);
if (vehicle != null) {
return new ResponseEntity<Vehicle>(vehicle, HttpStatus.OK);
}
return new ResponseEntity<Vehicle>(vehicle, HttpStatus.NO_CONTENT);
}
@RequestMapping(value = "/vehicle/", method = RequestMethod.POST)
private ResponseEntity<?> addVehicle(String vehicleCategoryCode, String modelCode, String currentMileage,
String dailyMotDue, String engineSize, UriComponentsBuilder ucBuilder) throws ParseException {
Model model = modelService.findModelById(Integer.parseInt(modelCode));
VehicleCategory vc = vehicleCategoryService.findByIdVehicleCategory(Integer.parseInt(vehicleCategoryCode));
Vehicle test = vehicleService.addVehicle(currentMileage, formatDate.parse(dailyMotDue), engineSize, model, vc);
if (test == null) {
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
HttpHeaders header = new HttpHeaders();
header.setLocation(ucBuilder.path("/api/vehicle/{id}").buildAndExpand(test.getRegNumber()).toUri());
return new ResponseEntity<Void>(header, HttpStatus.CREATED);
}
@RequestMapping(value = "/vehicle/{id}", method = RequestMethod.POST)
private ResponseEntity<?> updateVehicle(@PathVariable int id, String vehicleCategoryCode, String modelCode,
String currentMileage, String dailyMotDue, String engineSize) throws ParseException {
Model model = modelService.findModelById(Integer.parseInt(modelCode));
VehicleCategory vc = vehicleCategoryService.findByIdVehicleCategory(Integer.parseInt(vehicleCategoryCode));
Vehicle vehicle = vehicleRepository.getOne(id);
boolean test = vehicleService.updateVehicle(id, currentMileage, formatDate.parse(dailyMotDue), engineSize,
model, vc);
if (test == true) {
return new ResponseEntity<Vehicle>(vehicle, HttpStatus.OK);
}
return new ResponseEntity<Vehicle>(HttpStatus.NOT_FOUND);
}
@RequestMapping(value = "/vehicle/{id}", method = RequestMethod.DELETE)
private ResponseEntity<?> deleteVehicle(@PathVariable int id) {
if (vehicleService.deleteVehicle(id) == false) {
return new ResponseEntity<Vehicle>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<Vehicle>(HttpStatus.NO_CONTENT);
}
} | UTF-8 | Java | 4,107 | java | VehicleApiRestController.java | Java | []
| null | []
| package com.example.controller;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import com.example.model.Model;
import com.example.model.Vehicle;
import com.example.model.VehicleCategory;
import com.example.repository.IVehicleRepository;
import com.example.service.ModelService;
import com.example.service.VehicleCategoryService;
import com.example.service.VehicleService;
@RestController
@RequestMapping("/api")
public class VehicleApiRestController {
private static final SimpleDateFormat formatDate = new SimpleDateFormat("dd/mm/yyyy");
@Autowired
private VehicleService vehicleService;
@Autowired
private IVehicleRepository vehicleRepository;
@Autowired
private ModelService modelService;
@Autowired
private VehicleCategoryService vehicleCategoryService;
@RequestMapping(value = "/vehicle", method = RequestMethod.GET)
private ResponseEntity<List<Vehicle>> getAllVehicle() {
List<Vehicle> vehicle = vehicleService.findAllVehicle();
if (vehicle.isEmpty()) {
return new ResponseEntity<List<Vehicle>>(vehicle, HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<Vehicle>>(vehicle, HttpStatus.OK);
}
@RequestMapping(value = "/vehicle/{id}", method = RequestMethod.GET)
private ResponseEntity<?> getVehicleById(@PathVariable("id") int id) {
Vehicle vehicle = vehicleService.findVehicleById(id);
if (vehicle != null) {
return new ResponseEntity<Vehicle>(vehicle, HttpStatus.OK);
}
return new ResponseEntity<Vehicle>(vehicle, HttpStatus.NO_CONTENT);
}
@RequestMapping(value = "/vehicle/", method = RequestMethod.POST)
private ResponseEntity<?> addVehicle(String vehicleCategoryCode, String modelCode, String currentMileage,
String dailyMotDue, String engineSize, UriComponentsBuilder ucBuilder) throws ParseException {
Model model = modelService.findModelById(Integer.parseInt(modelCode));
VehicleCategory vc = vehicleCategoryService.findByIdVehicleCategory(Integer.parseInt(vehicleCategoryCode));
Vehicle test = vehicleService.addVehicle(currentMileage, formatDate.parse(dailyMotDue), engineSize, model, vc);
if (test == null) {
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
HttpHeaders header = new HttpHeaders();
header.setLocation(ucBuilder.path("/api/vehicle/{id}").buildAndExpand(test.getRegNumber()).toUri());
return new ResponseEntity<Void>(header, HttpStatus.CREATED);
}
@RequestMapping(value = "/vehicle/{id}", method = RequestMethod.POST)
private ResponseEntity<?> updateVehicle(@PathVariable int id, String vehicleCategoryCode, String modelCode,
String currentMileage, String dailyMotDue, String engineSize) throws ParseException {
Model model = modelService.findModelById(Integer.parseInt(modelCode));
VehicleCategory vc = vehicleCategoryService.findByIdVehicleCategory(Integer.parseInt(vehicleCategoryCode));
Vehicle vehicle = vehicleRepository.getOne(id);
boolean test = vehicleService.updateVehicle(id, currentMileage, formatDate.parse(dailyMotDue), engineSize,
model, vc);
if (test == true) {
return new ResponseEntity<Vehicle>(vehicle, HttpStatus.OK);
}
return new ResponseEntity<Vehicle>(HttpStatus.NOT_FOUND);
}
@RequestMapping(value = "/vehicle/{id}", method = RequestMethod.DELETE)
private ResponseEntity<?> deleteVehicle(@PathVariable int id) {
if (vehicleService.deleteVehicle(id) == false) {
return new ResponseEntity<Vehicle>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<Vehicle>(HttpStatus.NO_CONTENT);
}
} | 4,107 | 0.795228 | 0.795228 | 100 | 40.080002 | 32.524967 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.84 | false | false | 3 |
a9e1fe98ce3b3ddba73cdbfcf052ed033170241e | 36,679,020,734,604 | 4a28d23577d9dc900addf015bd481625b8de28e3 | /server/src/main/java/generated/TokensEntity.java | fe758cee8ba34c3f3d8baf6770bb7c9395b4a802 | []
| no_license | Meyttt/Auth | https://github.com/Meyttt/Auth | 50e08f2b6c7a9c4145682d1f577873236ba3db30 | 87991f1f327a14970acfee5d30f6275b6bab4a5c | refs/heads/master | 2021-08-06T19:04:53.999000 | 2017-11-06T20:01:44 | 2017-11-06T20:01:44 | 108,601,702 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package generated;
import org.hibernate.annotations.*;
import org.hibernate.annotations.CascadeType;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Date;
import java.util.UUID;
/**
* Created by Meyttt on 27.10.2017.
*/
@Entity
@Table(name = "tokens", schema = "public", catalog = "auth")
public class TokensEntity {
private Long id;
private UUID value;
private Timestamp expiredDate;
private Collection<SessionsEntity> sessionsById;
private Collection<SessionsEntity> sessionsById_0;
public TokensEntity(Date date) {
this.expiredDate=new Timestamp(date.getTime());
}
public TokensEntity() {
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false, insertable = false, updatable = false)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Basic
@Column(name = "value", nullable = false, insertable = false, updatable = false)
public UUID getValue() {
return value;
}
public void setValue(UUID value) {
this.value = value;
}
@Basic
@Column(name = "expired_date", nullable = true)
public Timestamp getExpiredDate() {
return expiredDate;
}
public void setExpiredDate(Timestamp expiredDate) {
this.expiredDate = expiredDate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TokensEntity that = (TokensEntity) o;
if (id != that.id) return false;
if (value != null ? !value.equals(that.value) : that.value != null) return false;
if (expiredDate != null ? !expiredDate.equals(that.expiredDate) : that.expiredDate != null) return false;
return true;
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + (value != null ? value.hashCode() : 0);
result = 31 * result + (expiredDate != null ? expiredDate.hashCode() : 0);
return result;
}
@OneToMany(mappedBy = "refreshToken")
public Collection<SessionsEntity> getSessionsById() {
return sessionsById;
}
public void setSessionsById(Collection<SessionsEntity> sessionsById) {
this.sessionsById = sessionsById;
}
@OneToMany(mappedBy = "accessToken")
public Collection<SessionsEntity> getSessionsById_0() {
return sessionsById_0;
}
public void setSessionsById_0(Collection<SessionsEntity> sessionsById_0) {
this.sessionsById_0 = sessionsById_0;
}
}
| UTF-8 | Java | 2,804 | java | TokensEntity.java | Java | [
{
"context": "il.Date;\nimport java.util.UUID;\n\n/**\n * Created by Meyttt on 27.10.2017.\n */\n@Entity\n@Table(name = \"tokens\"",
"end": 352,
"score": 0.9995218515396118,
"start": 346,
"tag": "USERNAME",
"value": "Meyttt"
}
]
| null | []
| package generated;
import org.hibernate.annotations.*;
import org.hibernate.annotations.CascadeType;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Date;
import java.util.UUID;
/**
* Created by Meyttt on 27.10.2017.
*/
@Entity
@Table(name = "tokens", schema = "public", catalog = "auth")
public class TokensEntity {
private Long id;
private UUID value;
private Timestamp expiredDate;
private Collection<SessionsEntity> sessionsById;
private Collection<SessionsEntity> sessionsById_0;
public TokensEntity(Date date) {
this.expiredDate=new Timestamp(date.getTime());
}
public TokensEntity() {
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false, insertable = false, updatable = false)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Basic
@Column(name = "value", nullable = false, insertable = false, updatable = false)
public UUID getValue() {
return value;
}
public void setValue(UUID value) {
this.value = value;
}
@Basic
@Column(name = "expired_date", nullable = true)
public Timestamp getExpiredDate() {
return expiredDate;
}
public void setExpiredDate(Timestamp expiredDate) {
this.expiredDate = expiredDate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TokensEntity that = (TokensEntity) o;
if (id != that.id) return false;
if (value != null ? !value.equals(that.value) : that.value != null) return false;
if (expiredDate != null ? !expiredDate.equals(that.expiredDate) : that.expiredDate != null) return false;
return true;
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + (value != null ? value.hashCode() : 0);
result = 31 * result + (expiredDate != null ? expiredDate.hashCode() : 0);
return result;
}
@OneToMany(mappedBy = "refreshToken")
public Collection<SessionsEntity> getSessionsById() {
return sessionsById;
}
public void setSessionsById(Collection<SessionsEntity> sessionsById) {
this.sessionsById = sessionsById;
}
@OneToMany(mappedBy = "accessToken")
public Collection<SessionsEntity> getSessionsById_0() {
return sessionsById_0;
}
public void setSessionsById_0(Collection<SessionsEntity> sessionsById_0) {
this.sessionsById_0 = sessionsById_0;
}
}
| 2,804 | 0.645863 | 0.637661 | 104 | 25.961538 | 24.835583 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.471154 | false | false | 3 |
951fb08d95b7ca3e5913481453ef8fd20e559013 | 36,679,020,734,230 | 8970e402a8748b89834b64d8b8fc72dcde1cdaa1 | /src/main/java/Executor.java | 9be14619095a4021d0482c2844cb3a5adddb2f5f | []
| no_license | xiader/matrix_operations | https://github.com/xiader/matrix_operations | c8756acd56d1b6bb12fb681593739cd7c91429c5 | eda835ea589e5d2f8332413e3b841f9fc0fa31e6 | refs/heads/master | 2022-12-21T06:29:39.602000 | 2020-10-01T08:59:27 | 2020-10-01T08:59:27 | 292,487,876 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
/**
* @author Alexander
* @version 1.0
*/
public class Executor {
private final InputResolver inputResolver = new InputResolver();
private final List<String> matrixDefinitions;
private final String expression;
/**
* creates executor to perform actions over incoming parameters
*
* @param expression - variables with operators, example: P+Q*P+Q
* @param args - strings in format like: Q=[2 -8 8 0; -1 2 -4 2]
*/
public Executor(String expression, String... args) {
this.matrixDefinitions = Arrays.asList(args);
this.expression = expression;
}
/**
* starts execution
*/
public void doExecute() {
Map<String, MatrixContainer> nameAndMatrixValue = new HashMap<>();
for (String oneDefinition : this.matrixDefinitions) {
MatrixContainer matrixContainer;
try {
matrixContainer = this.inputResolver.parse(oneDefinition);
nameAndMatrixValue.put(matrixContainer.getMatrixName(), matrixContainer);
} catch (IllegalArgumentException e) {
ConsoleOutPut.printError("Exception caught: " + e.getClass().getSimpleName() + ". Can't " + e.getMessage() + ".");
return;
}
}
String[] expressionAsTokes = this.inputResolver.parseInputExpression(expression);
String[] expressionAsReversePolishNotation = ExpressionResolver.infixToRPN(expressionAsTokes);
MatrixContainer result;
try {
result = calculateExpression(expressionAsReversePolishNotation, nameAndMatrixValue);
} catch (IllegalArgumentException e) {
ConsoleOutPut.printError("Exception caught: " + e.getClass().getSimpleName() + ". Can't " + e.getMessage() + ".");
return;
}
int[][] arr = result.getMatrixTemplate();
ConsoleOutPut.print(arr);
}
//performs operations in required order
private static MatrixContainer calculateExpression(String[] tokens, Map<String, MatrixContainer> matrixContainerMap) {
String operators = "+-*";
MatrixOperationsImpl matrixOperations = new MatrixOperationsImpl();
Deque<MatrixContainer> stack = new ArrayDeque<>();
for (String t : tokens) {
//push to stack if it is a matrix name
if (!operators.contains(t)) {
MatrixContainer mc = getByName(matrixContainerMap, t);
stack.push(mc);
} else {
MatrixContainer right = stack.pop();
MatrixContainer left = stack.pop();
switch (t) {
case "+":
stack.push(matrixOperations.add(left, right));
break;
case "-":
stack.push(matrixOperations.subtract(left, right));
break;
case "*":
stack.push(matrixOperations.multiply(left, right));
break;
default:
throw new UnsupportedOperationException("unrecognisable operand" + t);
}
}
}
return stack.pop();
}
private static MatrixContainer getByName(Map<String, MatrixContainer> mCm, String key) {
return mCm.get(key);
}
}
| UTF-8 | Java | 2,813 | java | Executor.java | Java | [
{
"context": "import java.util.*;\n\n/**\n * @author Alexander\n * @version 1.0\n */\npublic class Executor {\n\n\tpri",
"end": 45,
"score": 0.9996023178100586,
"start": 36,
"tag": "NAME",
"value": "Alexander"
}
]
| null | []
| import java.util.*;
/**
* @author Alexander
* @version 1.0
*/
public class Executor {
private final InputResolver inputResolver = new InputResolver();
private final List<String> matrixDefinitions;
private final String expression;
/**
* creates executor to perform actions over incoming parameters
*
* @param expression - variables with operators, example: P+Q*P+Q
* @param args - strings in format like: Q=[2 -8 8 0; -1 2 -4 2]
*/
public Executor(String expression, String... args) {
this.matrixDefinitions = Arrays.asList(args);
this.expression = expression;
}
/**
* starts execution
*/
public void doExecute() {
Map<String, MatrixContainer> nameAndMatrixValue = new HashMap<>();
for (String oneDefinition : this.matrixDefinitions) {
MatrixContainer matrixContainer;
try {
matrixContainer = this.inputResolver.parse(oneDefinition);
nameAndMatrixValue.put(matrixContainer.getMatrixName(), matrixContainer);
} catch (IllegalArgumentException e) {
ConsoleOutPut.printError("Exception caught: " + e.getClass().getSimpleName() + ". Can't " + e.getMessage() + ".");
return;
}
}
String[] expressionAsTokes = this.inputResolver.parseInputExpression(expression);
String[] expressionAsReversePolishNotation = ExpressionResolver.infixToRPN(expressionAsTokes);
MatrixContainer result;
try {
result = calculateExpression(expressionAsReversePolishNotation, nameAndMatrixValue);
} catch (IllegalArgumentException e) {
ConsoleOutPut.printError("Exception caught: " + e.getClass().getSimpleName() + ". Can't " + e.getMessage() + ".");
return;
}
int[][] arr = result.getMatrixTemplate();
ConsoleOutPut.print(arr);
}
//performs operations in required order
private static MatrixContainer calculateExpression(String[] tokens, Map<String, MatrixContainer> matrixContainerMap) {
String operators = "+-*";
MatrixOperationsImpl matrixOperations = new MatrixOperationsImpl();
Deque<MatrixContainer> stack = new ArrayDeque<>();
for (String t : tokens) {
//push to stack if it is a matrix name
if (!operators.contains(t)) {
MatrixContainer mc = getByName(matrixContainerMap, t);
stack.push(mc);
} else {
MatrixContainer right = stack.pop();
MatrixContainer left = stack.pop();
switch (t) {
case "+":
stack.push(matrixOperations.add(left, right));
break;
case "-":
stack.push(matrixOperations.subtract(left, right));
break;
case "*":
stack.push(matrixOperations.multiply(left, right));
break;
default:
throw new UnsupportedOperationException("unrecognisable operand" + t);
}
}
}
return stack.pop();
}
private static MatrixContainer getByName(Map<String, MatrixContainer> mCm, String key) {
return mCm.get(key);
}
}
| 2,813 | 0.699253 | 0.695699 | 93 | 29.247313 | 30.499306 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.645161 | false | false | 3 |
5135ca9e9fc90b471cb69fe16efc7baa984528e7 | 36,679,020,732,959 | 4827b0d7d7ea277c1c6060e1296ade7cefb272f3 | /app/src/main/java/loginandregister/com/squliteoperation/MainActivity.java | 993fa744a1b296661081f2f82e801fca374320a1 | []
| no_license | Varun789/SqliteOperations | https://github.com/Varun789/SqliteOperations | 7df6ca83538530ebc566de30ae1113f4a1a2069f | 11fa0e1680f6bcea4c026860a30ffd1a256c6073 | refs/heads/master | 2022-08-29T01:50:35.553000 | 2020-05-23T08:12:22 | 2020-05-23T08:12:22 | 266,282,560 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package loginandregister.com.squliteoperation;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText name,password;
Button view,add;
myDBAdapter Helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText)findViewById(R.id.edt_username);
password=(EditText)findViewById(R.id.)
}
}
| UTF-8 | Java | 619 | java | MainActivity.java | Java | []
| null | []
| package loginandregister.com.squliteoperation;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText name,password;
Button view,add;
myDBAdapter Helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText)findViewById(R.id.edt_username);
password=(EditText)findViewById(R.id.)
}
}
| 619 | 0.754443 | 0.752827 | 20 | 29.950001 | 18.526939 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.7 | false | false | 3 |
1f5b1a4bc125a9cd77a66c9517ae2a41ff7934ac | 29,454,885,774,129 | 25ac20db150c57e8a880889fff6a63279b6e9468 | /src/main/java/GameQRcodeMaker/database/league.java | d7732a070b850d7a5dc6e0bda2238070440eda57 | []
| no_license | akuuua/GameQRcodeMaker | https://github.com/akuuua/GameQRcodeMaker | dcd421d96a2b06d69806157e9bec2322e40c4e91 | dc1065c0a11e3aa2ccc1f8ba6b69badc6ee581c0 | refs/heads/main | 2023-06-03T20:09:26.214000 | 2021-06-25T11:57:38 | 2021-06-25T11:57:38 | 380,151,149 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package GameQRcodeMaker.database;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class league {
private JSONObject json;
private JSONArray array;
public league(JSONObject json){
this.json = json;
this.array = array = json.getJSONArray("League List");
}
public String getId(int index){
String result = array.getJSONObject(index).get("id").toString();
return result;
}
public String getName(int index){
String result = array.getJSONObject(index).get("name").toString();
return result;
}
public String getSeries(int index){
String result = array.getJSONObject(index).get("series").toString();
return result;
}
public String getUrl(int index){
String result = array.getJSONObject(index).get("url").toString();
return result;
}
public String getImage_url(int index){
String result = array.getJSONObject(index).get("image_url").toString();
return result;
}
public String getVideoGame(int index){
String result = array.getJSONObject(index).get("videogame").toString();
return result;
}
public String getModified_at(int index){
String result = array.getJSONObject(index).get("modified_at").toString();
return result;
}
public String getSlug(int index){
String result = array.getJSONObject(index).get("slug").toString();
return result;
}
} | UTF-8 | Java | 1,540 | java | league.java | Java | []
| null | []
| package GameQRcodeMaker.database;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class league {
private JSONObject json;
private JSONArray array;
public league(JSONObject json){
this.json = json;
this.array = array = json.getJSONArray("League List");
}
public String getId(int index){
String result = array.getJSONObject(index).get("id").toString();
return result;
}
public String getName(int index){
String result = array.getJSONObject(index).get("name").toString();
return result;
}
public String getSeries(int index){
String result = array.getJSONObject(index).get("series").toString();
return result;
}
public String getUrl(int index){
String result = array.getJSONObject(index).get("url").toString();
return result;
}
public String getImage_url(int index){
String result = array.getJSONObject(index).get("image_url").toString();
return result;
}
public String getVideoGame(int index){
String result = array.getJSONObject(index).get("videogame").toString();
return result;
}
public String getModified_at(int index){
String result = array.getJSONObject(index).get("modified_at").toString();
return result;
}
public String getSlug(int index){
String result = array.getJSONObject(index).get("slug").toString();
return result;
}
} | 1,540 | 0.644805 | 0.644805 | 65 | 22.707693 | 24.967501 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 3 |
4ff99bfcf28611a385c838a59c34962c44e7480f | 38,397,007,637,020 | 80bb6ef59669ff8703441b19be27e30b37bfc64d | /complexCalculator/src/com/company/Calc.java | 5c3f616b7e548b0b3a12f42eb9ab044350cb8557 | []
| no_license | ilyaonishenko/java | https://github.com/ilyaonishenko/java | 0f393dcf7d73a61360a94fcb268e6138e78edc97 | 7236759a1e0d4c7778446a3131c24062a882f965 | refs/heads/master | 2021-06-10T14:37:31.979000 | 2017-02-03T07:14:39 | 2017-02-03T07:14:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
/**
* Created by wopqw on 02.02.17.
*/
public class Calc {
Stack<Double> nums = new Stack<Double>();
Stack<String> ops = new Stack<String>();
HashMap<String, Integer> prioirty = new HashMap<String, Integer>();
List<String> sep = Arrays.asList("(",")","+","-","*","/");
Parser parser = new Parser();
public Calc(){
prioirty.put(")",1);
prioirty.put("(",1);
prioirty.put("/",2);
prioirty.put("*",2);
prioirty.put("+",3);
prioirty.put("-",3);
}
public double evaluate(String text){
text = "("+text+")";
String[] numbers = parser.parse(text);
String[] operations = parser.getOps().toArray(new String[parser.getOps().size()]);
boolean allowPush = true;
for(int i = 0; i<operations.length; i++){
if(numbers[i].length()!=0)
nums.push(Double.parseDouble(numbers[i]));
while (true){
if(ops.isEmpty()||operations[i].equals("(")||prioirty.get(operations[i])>prioirty.get(ops.peek())){
ops.push(operations[i]);
break;
}
String op = ops.pop();
if (op.equals("(")||nums.size()<2)
{
break;
}
else
{
double d2 = nums.pop();
double d1 = nums.pop();
nums.push(eval(op,d1,d2));
}
}
}
while (!ops.isEmpty())
{
String op = ops.pop();
double val2 = nums.pop();
double val1 = nums.pop();
nums.push(eval(op, val1, val2));
}
double answer = nums.pop();
return answer;
}
public static double eval(String operation, double d1, double d2){
switch (operation){
case "+":
return d1+d2;
case "-":
return d1-d2;
case "*":
return d1*d2;
case "/":
return d1/d2;
}
return 0;
}
}
| UTF-8 | Java | 2,235 | java | Calc.java | Java | [
{
"context": "HashMap;\nimport java.util.List;\n\n/**\n * Created by wopqw on 02.02.17.\n */\npublic class Calc {\n\n Stack<D",
"end": 120,
"score": 0.999687671661377,
"start": 115,
"tag": "USERNAME",
"value": "wopqw"
}
]
| null | []
| package com.company;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
/**
* Created by wopqw on 02.02.17.
*/
public class Calc {
Stack<Double> nums = new Stack<Double>();
Stack<String> ops = new Stack<String>();
HashMap<String, Integer> prioirty = new HashMap<String, Integer>();
List<String> sep = Arrays.asList("(",")","+","-","*","/");
Parser parser = new Parser();
public Calc(){
prioirty.put(")",1);
prioirty.put("(",1);
prioirty.put("/",2);
prioirty.put("*",2);
prioirty.put("+",3);
prioirty.put("-",3);
}
public double evaluate(String text){
text = "("+text+")";
String[] numbers = parser.parse(text);
String[] operations = parser.getOps().toArray(new String[parser.getOps().size()]);
boolean allowPush = true;
for(int i = 0; i<operations.length; i++){
if(numbers[i].length()!=0)
nums.push(Double.parseDouble(numbers[i]));
while (true){
if(ops.isEmpty()||operations[i].equals("(")||prioirty.get(operations[i])>prioirty.get(ops.peek())){
ops.push(operations[i]);
break;
}
String op = ops.pop();
if (op.equals("(")||nums.size()<2)
{
break;
}
else
{
double d2 = nums.pop();
double d1 = nums.pop();
nums.push(eval(op,d1,d2));
}
}
}
while (!ops.isEmpty())
{
String op = ops.pop();
double val2 = nums.pop();
double val1 = nums.pop();
nums.push(eval(op, val1, val2));
}
double answer = nums.pop();
return answer;
}
public static double eval(String operation, double d1, double d2){
switch (operation){
case "+":
return d1+d2;
case "-":
return d1-d2;
case "*":
return d1*d2;
case "/":
return d1/d2;
}
return 0;
}
}
| 2,235 | 0.451454 | 0.436242 | 84 | 25.607143 | 21.024372 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.77381 | false | false | 3 |
55a5e679625d9e1d9086ef8f0731f165a3576fb7 | 38,766,374,813,796 | 882c6c142c4e9a5fe7fb94cc92c25f7c71662c47 | /src/it/ubix/model/Product.java | d196387f81ad44906a5816fab43cff415141657f | []
| no_license | ftruono/Ubix | https://github.com/ftruono/Ubix | c0e8c621eee2062f732ae3d42a5a44729ea23eac | cda6f0ea522d589148d45f89e7f43bebf4a5c662 | refs/heads/master | 2020-07-21T06:27:53.807000 | 2019-09-06T10:27:30 | 2019-09-06T10:27:30 | 206,770,197 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package it.ubix.model;
import java.io.Serializable;
import java.util.List;
public abstract class Product implements Serializable,Cloneable{
private String nome,descrizione,cast,img;
private int type,id; //0 : film - 1: serie tv
private boolean sellable,hot;
private float price;
public abstract <T> T getSrc();
public abstract <T> void setSrc(String path,String src);
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDescrizione() {
return descrizione;
}
public void setDescrizione(String descrizione) {
this.descrizione = descrizione;
}
public String getCast() {
return cast;
}
public void setCast(String cast) {
this.cast = cast;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public boolean isSellable() {
return sellable;
}
public void setSellable(boolean sellable) {
this.sellable = sellable;
}
public boolean isHot() {
return hot;
}
public void setHot(boolean hot) {
this.hot = hot;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean equals(Object o) {
if (o==null) return false;
if(o.getClass().equals(this.getClass())) {
Product temp=(Product)o;
return temp.id==this.id;
}
return false;
}
public Product clone() {
Product v1;
try {
v1 = (Product) super.clone();
return v1;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
| UTF-8 | Java | 1,746 | java | Product.java | Java | []
| null | []
| package it.ubix.model;
import java.io.Serializable;
import java.util.List;
public abstract class Product implements Serializable,Cloneable{
private String nome,descrizione,cast,img;
private int type,id; //0 : film - 1: serie tv
private boolean sellable,hot;
private float price;
public abstract <T> T getSrc();
public abstract <T> void setSrc(String path,String src);
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDescrizione() {
return descrizione;
}
public void setDescrizione(String descrizione) {
this.descrizione = descrizione;
}
public String getCast() {
return cast;
}
public void setCast(String cast) {
this.cast = cast;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public boolean isSellable() {
return sellable;
}
public void setSellable(boolean sellable) {
this.sellable = sellable;
}
public boolean isHot() {
return hot;
}
public void setHot(boolean hot) {
this.hot = hot;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean equals(Object o) {
if (o==null) return false;
if(o.getClass().equals(this.getClass())) {
Product temp=(Product)o;
return temp.id==this.id;
}
return false;
}
public Product clone() {
Product v1;
try {
v1 = (Product) super.clone();
return v1;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
| 1,746 | 0.671821 | 0.668958 | 98 | 16.816326 | 15.119488 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.704082 | false | false | 3 |
78571dd4e1b55ac1cb2b953cfb5d8910a1dfb5f6 | 38,525,856,650,109 | 5cc0b832d5628d6b620ae68b1621547ea776ff95 | /social-diagnostica-service/src/main/java/socialDiagnosticaApi/persistence/dto/mappers/DiagnosticTestMapper.java | cea66903c1cc187bd5f3b9ef5257f3ecd5fb2a99 | []
| no_license | AlexDvoretskiy/socialDiagnostica | https://github.com/AlexDvoretskiy/socialDiagnostica | 7c9563f4bf2e1d8fb176351ec950373535bee160 | 7ee212c0ee4c994858cb135fb2888d7e157331b1 | refs/heads/master | 2022-12-23T21:52:01.667000 | 2020-09-23T19:37:35 | 2020-09-23T19:37:35 | 286,824,269 | 0 | 0 | null | false | 2020-09-23T19:37:36 | 2020-08-11T18:53:52 | 2020-09-09T20:34:46 | 2020-09-23T19:37:36 | 2,113 | 0 | 0 | 0 | CSS | false | false | package socialDiagnosticaApi.persistence.dto.mappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import socialDiagnosticaApi.persistence.dto.DiagnosticMetricDto;
import socialDiagnosticaApi.persistence.dto.DiagnosticTestDto;
import socialDiagnosticaApi.persistence.entities.DiagnosticTest;
@Slf4j
@Service
@RequiredArgsConstructor
public class DiagnosticTestMapper {
private final DiagnosticQuestionMapper diagnosticQuestionMapper;
public DiagnosticTestDto mapDiagnosticTestToDto(DiagnosticTest diagnosticTest) {
DiagnosticMetricDto diagnosticMetricDto = DiagnosticMetricDto.builder()
.metricFormula(diagnosticTest.getDiagnosticMetric().getFormula())
.description(diagnosticTest.getDiagnosticMetric().getDescription())
.build();
return DiagnosticTestDto.builder()
.id(diagnosticTest.getId())
.name(diagnosticTest.getName())
.description(diagnosticTest.getDescription())
.questionCount(diagnosticTest.getQuestionCount())
.duration(diagnosticTest.getDuration())
.diagnosticMetric(diagnosticMetricDto)
.build();
}
public DiagnosticTestDto mapDiagnosticTestWithQuestionsToDto(DiagnosticTest diagnosticTest) {
return DiagnosticTestDto.builder()
.id(diagnosticTest.getId())
.name(diagnosticTest.getName())
.description(diagnosticTest.getDescription())
.questionCount(diagnosticTest.getQuestionCount())
.duration(diagnosticTest.getDuration())
.diagnosticQuestions(diagnosticQuestionMapper.mapDiagnosticQuestionToDto(diagnosticTest.getDiagnosticQuestions()))
.build();
}
public DiagnosticTest mapDiagnosticTestFromDto(DiagnosticTestDto diagnosticTestDto) {
return DiagnosticTest.builder()
.name(diagnosticTestDto.getName())
.description(diagnosticTestDto.getDescription())
.questionCount(diagnosticTestDto.getQuestionCount())
.duration(diagnosticTestDto.getDuration())
.build();
}
public DiagnosticTestDto mapDiagnosticTestWithNameOnlyToDto(DiagnosticTest diagnosticTest) {
return new DiagnosticTestDto(diagnosticTest.getId(), diagnosticTest.getName());
}
public DiagnosticTestDto mapDiagnosticTestWithDescToDto(DiagnosticTest diagnosticTest) {
return DiagnosticTestDto.builder()
.id(diagnosticTest.getId())
.name(diagnosticTest.getName())
.description(diagnosticTest.getDescription())
.questionCount(diagnosticTest.getQuestionCount())
.duration(diagnosticTest.getDuration())
.build();
}
}
| UTF-8 | Java | 2,497 | java | DiagnosticTestMapper.java | Java | []
| null | []
| package socialDiagnosticaApi.persistence.dto.mappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import socialDiagnosticaApi.persistence.dto.DiagnosticMetricDto;
import socialDiagnosticaApi.persistence.dto.DiagnosticTestDto;
import socialDiagnosticaApi.persistence.entities.DiagnosticTest;
@Slf4j
@Service
@RequiredArgsConstructor
public class DiagnosticTestMapper {
private final DiagnosticQuestionMapper diagnosticQuestionMapper;
public DiagnosticTestDto mapDiagnosticTestToDto(DiagnosticTest diagnosticTest) {
DiagnosticMetricDto diagnosticMetricDto = DiagnosticMetricDto.builder()
.metricFormula(diagnosticTest.getDiagnosticMetric().getFormula())
.description(diagnosticTest.getDiagnosticMetric().getDescription())
.build();
return DiagnosticTestDto.builder()
.id(diagnosticTest.getId())
.name(diagnosticTest.getName())
.description(diagnosticTest.getDescription())
.questionCount(diagnosticTest.getQuestionCount())
.duration(diagnosticTest.getDuration())
.diagnosticMetric(diagnosticMetricDto)
.build();
}
public DiagnosticTestDto mapDiagnosticTestWithQuestionsToDto(DiagnosticTest diagnosticTest) {
return DiagnosticTestDto.builder()
.id(diagnosticTest.getId())
.name(diagnosticTest.getName())
.description(diagnosticTest.getDescription())
.questionCount(diagnosticTest.getQuestionCount())
.duration(diagnosticTest.getDuration())
.diagnosticQuestions(diagnosticQuestionMapper.mapDiagnosticQuestionToDto(diagnosticTest.getDiagnosticQuestions()))
.build();
}
public DiagnosticTest mapDiagnosticTestFromDto(DiagnosticTestDto diagnosticTestDto) {
return DiagnosticTest.builder()
.name(diagnosticTestDto.getName())
.description(diagnosticTestDto.getDescription())
.questionCount(diagnosticTestDto.getQuestionCount())
.duration(diagnosticTestDto.getDuration())
.build();
}
public DiagnosticTestDto mapDiagnosticTestWithNameOnlyToDto(DiagnosticTest diagnosticTest) {
return new DiagnosticTestDto(diagnosticTest.getId(), diagnosticTest.getName());
}
public DiagnosticTestDto mapDiagnosticTestWithDescToDto(DiagnosticTest diagnosticTest) {
return DiagnosticTestDto.builder()
.id(diagnosticTest.getId())
.name(diagnosticTest.getName())
.description(diagnosticTest.getDescription())
.questionCount(diagnosticTest.getQuestionCount())
.duration(diagnosticTest.getDuration())
.build();
}
}
| 2,497 | 0.807769 | 0.806568 | 70 | 34.671429 | 29.508701 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false | 3 |
401320e1cefbb6626eb264852889289a8c0a745f | 36,137,854,850,044 | 7b82ceedd090eb433ca28787536e7bb18ac9f563 | /Coursera/Android/POSA/POSA-14/grading-drivers/week-5-assignment-4/W5-A4-Android/src/edu/vuum/mocca/ConsolePlatformStrategy.java | c83233f16cdc0c9331123795271fd054b93b2781 | []
| no_license | traveling-desi/Courses | https://github.com/traveling-desi/Courses | 62311437442fd35599544ccadfee86a17fef66a8 | 8d9fb0dcb08a080a755115347aa53c6ecafb383b | refs/heads/master | 2023-01-13T00:00:52.364000 | 2016-09-22T23:00:54 | 2016-09-22T23:00:54 | 66,979,647 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.vuum.mocca;
import java.util.concurrent.CountDownLatch;
import java.io.PrintStream;
/**
* @class ConsolePlatformStrategy
*
* @brief Provides methods that define a platform-independent API for
* output data to the console window and synchronizing on
* thread completion in the ping/pong game. It plays the role
* of the "Concrete Strategy" in the Strategy pattern.
*/
public class ConsolePlatformStrategy extends PlatformStrategy
{
/**
* Latch to decrement each time a thread exits to control when the
* play() method returns.
*/
private static CountDownLatch mLatch = null;
/** Contains information for outputting to console window. */
PrintStream mOutput;
/** Ctor. */
public ConsolePlatformStrategy(Object output)
{
mOutput = (PrintStream) output;
}
/** Do any initialization needed to start a new game. */
public void begin()
{
mLatch = new CountDownLatch(NUMBER_OF_THREADS);
}
/** Print the outputString to the display. */
public void print(String outputString)
{
/** Print to the console window. */
mOutput.println(outputString);
}
/** Indicate that a game thread has finished running. */
public void done()
{
mLatch.countDown();
}
/** Barrier that waits for all the game threads to finish. */
public void awaitDone()
{
try {
mLatch.await();
} catch(java.lang.InterruptedException e) {
}
}
/**
* Error log formats the message and displays it for the debugging
* purposes.
*/
public void errorLog(String javaFile, String errorMessage)
{
mOutput.println(javaFile + " " + errorMessage);
}
}
| UTF-8 | Java | 1,777 | java | ConsolePlatformStrategy.java | Java | []
| null | []
| package edu.vuum.mocca;
import java.util.concurrent.CountDownLatch;
import java.io.PrintStream;
/**
* @class ConsolePlatformStrategy
*
* @brief Provides methods that define a platform-independent API for
* output data to the console window and synchronizing on
* thread completion in the ping/pong game. It plays the role
* of the "Concrete Strategy" in the Strategy pattern.
*/
public class ConsolePlatformStrategy extends PlatformStrategy
{
/**
* Latch to decrement each time a thread exits to control when the
* play() method returns.
*/
private static CountDownLatch mLatch = null;
/** Contains information for outputting to console window. */
PrintStream mOutput;
/** Ctor. */
public ConsolePlatformStrategy(Object output)
{
mOutput = (PrintStream) output;
}
/** Do any initialization needed to start a new game. */
public void begin()
{
mLatch = new CountDownLatch(NUMBER_OF_THREADS);
}
/** Print the outputString to the display. */
public void print(String outputString)
{
/** Print to the console window. */
mOutput.println(outputString);
}
/** Indicate that a game thread has finished running. */
public void done()
{
mLatch.countDown();
}
/** Barrier that waits for all the game threads to finish. */
public void awaitDone()
{
try {
mLatch.await();
} catch(java.lang.InterruptedException e) {
}
}
/**
* Error log formats the message and displays it for the debugging
* purposes.
*/
public void errorLog(String javaFile, String errorMessage)
{
mOutput.println(javaFile + " " + errorMessage);
}
}
| 1,777 | 0.634778 | 0.634778 | 67 | 25.507463 | 24.260017 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.19403 | false | false | 3 |
c472fa18fce5263f034ee120e4090472c236bc5a | 22,789,096,490,623 | 4c78946befef7ae7270a3b4e65aa7ad773eae788 | /src/main/java/com/playbasis/pbcore/domain/interactor/player/SetupPhoneInteractor.java | 82c27c2596f45fe4fddf29a9ab1ddc5982eaaa5d | []
| no_license | playbasis/native-sdk-android | https://github.com/playbasis/native-sdk-android | 8fe478feb203743e444d6b6ea2fc1742079da173 | f461ab54cd72a1dbc852fbcf47ef2a390add421e | refs/heads/target-21 | 2020-09-23T03:16:51.887000 | 2017-01-05T09:15:01 | 2017-01-05T09:15:01 | 66,616,364 | 0 | 1 | null | false | 2017-02-16T08:12:44 | 2016-08-26T04:24:19 | 2016-08-31T05:03:35 | 2017-02-16T08:12:43 | 581 | 0 | 1 | 0 | Java | null | null | package com.playbasis.pbcore.domain.interactor.player;
import com.playbasis.pbcore.domain.executor.PBPostExecutionThread;
import com.playbasis.pbcore.domain.executor.PBThreadExecutor;
import com.playbasis.pbcore.domain.interactor.PlayBasisApiInteractor;
import com.playbasis.pbcore.domain.interactor.RequestTokenInteractor;
import com.playbasis.pbcore.rest.PBApiErrorCheckFunc;
import com.playbasis.pbcore.rest.RestClient;
import com.playbasis.pbcore.rest.form.player.SetupPhoneForm;
import com.playbasis.pbcore.rest.result.player.SetupPhoneApiResult;
import javax.inject.Inject;
import rx.Observable;
/**
* Created by Tar on 4/21/16 AD.
*/
public class SetupPhoneInteractor extends PlayBasisApiInteractor {
public static final String TAG = "SetupPhoneInteractor";
protected SetupPhoneForm setupPhoneForm;
@Inject
public SetupPhoneInteractor(PBThreadExecutor threadExecutor,
PBPostExecutionThread postExecutionThread,
RestClient restClient,
RequestTokenInteractor requestTokenInteractor) {
super(threadExecutor, postExecutionThread, restClient, requestTokenInteractor);
}
@Override
public Observable buildApiUseCaseObservable() {
return restClient.getPlayerService()
.setupPhone(
setupPhoneForm.getPlayerId(),
getApiToken(),
setupPhoneForm.getPhoneNumber(),
setupPhoneForm.getFields()
).map(new PBApiErrorCheckFunc<SetupPhoneApiResult>());
}
public void setSetupPhoneForm(SetupPhoneForm setupPhoneForm) {
this.setupPhoneForm = setupPhoneForm;
}
}
| UTF-8 | Java | 1,644 | java | SetupPhoneInteractor.java | Java | []
| null | []
| package com.playbasis.pbcore.domain.interactor.player;
import com.playbasis.pbcore.domain.executor.PBPostExecutionThread;
import com.playbasis.pbcore.domain.executor.PBThreadExecutor;
import com.playbasis.pbcore.domain.interactor.PlayBasisApiInteractor;
import com.playbasis.pbcore.domain.interactor.RequestTokenInteractor;
import com.playbasis.pbcore.rest.PBApiErrorCheckFunc;
import com.playbasis.pbcore.rest.RestClient;
import com.playbasis.pbcore.rest.form.player.SetupPhoneForm;
import com.playbasis.pbcore.rest.result.player.SetupPhoneApiResult;
import javax.inject.Inject;
import rx.Observable;
/**
* Created by Tar on 4/21/16 AD.
*/
public class SetupPhoneInteractor extends PlayBasisApiInteractor {
public static final String TAG = "SetupPhoneInteractor";
protected SetupPhoneForm setupPhoneForm;
@Inject
public SetupPhoneInteractor(PBThreadExecutor threadExecutor,
PBPostExecutionThread postExecutionThread,
RestClient restClient,
RequestTokenInteractor requestTokenInteractor) {
super(threadExecutor, postExecutionThread, restClient, requestTokenInteractor);
}
@Override
public Observable buildApiUseCaseObservable() {
return restClient.getPlayerService()
.setupPhone(
setupPhoneForm.getPlayerId(),
getApiToken(),
setupPhoneForm.getPhoneNumber(),
setupPhoneForm.getFields()
).map(new PBApiErrorCheckFunc<SetupPhoneApiResult>());
}
public void setSetupPhoneForm(SetupPhoneForm setupPhoneForm) {
this.setupPhoneForm = setupPhoneForm;
}
}
| 1,644 | 0.748175 | 0.745134 | 47 | 33.978722 | 27.473383 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.531915 | false | false | 3 |
6ad676c4d4d38231917b84be4dc09f372246ab5c | 22,789,096,488,956 | 84eff9cd3e2fe0e8dc7fc600ecdab7c7bf2cdfc8 | /rule/Workflow/Resources/scripts/workflow/domain/ReportDomain.java | 46003720456417965bf847d86f156f0fb12e1b47 | []
| no_license | nzimas/poema | https://github.com/nzimas/poema | add3bb1231bbacca3c608b7d2187e1e15a2b5769 | 1d1a92da523f3de1129f906d55d3dbf8c967f538 | refs/heads/master | 2021-01-23T05:14:14.758000 | 2017-05-31T11:37:23 | 2017-05-31T11:37:23 | 92,960,969 | 0 | 0 | null | true | 2017-05-31T15:30:55 | 2017-05-31T15:30:54 | 2016-11-16T13:09:22 | 2017-05-31T11:37:27 | 71,403 | 0 | 0 | 0 | null | null | null | package workflow.domain;
import com.exponentus.common.domain.DTOService;
import com.exponentus.common.domain.IValidation;
import com.exponentus.common.model.ACL;
import com.exponentus.dataengine.exception.DAOException;
import com.exponentus.rest.outgoingdto.Outcome;
import com.exponentus.rest.validation.exception.DTOException;
import com.exponentus.scripting._Session;
import staff.dao.EmployeeDAO;
import staff.model.Employee;
import staff.model.embedded.Observer;
import workflow.dao.ReportDAO;
import workflow.model.Assignment;
import workflow.model.Report;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ReportDomain extends DTOService<Report> {
public ReportDomain(_Session ses) throws DAOException {
super(ses);
dao = new ReportDAO(ses);
}
public Report composeNew(Employee author, Assignment parent) {
if (parent == null) {
throw new IllegalArgumentException("parent null");
}
Report entity = new Report();
entity.setAuthor(author.getUser());
entity.setAppliedAuthor(author);
entity.setAppliedRegDate(new Date());
entity.setParent(parent);
return entity;
}
@Override
public Report fillFromDto(Report dto, IValidation<Report> validation, String fsid) throws DTOException, DAOException {
validation.check(dto);
Report entity;
if (dto.isNew()) {
entity = new Report();
} else {
entity = dao.findById(dto.getId());
}
EmployeeDAO eDao = new EmployeeDAO(ses);
if (entity.isNew()) {
if (dto.getParent() == null) {
throw new DTOException("assignment", "required", "field_is_empty");
}
entity.setAppliedAuthor(eDao.findById(dto.getAppliedAuthor().getId()));
entity.setAppliedRegDate(dto.getAppliedRegDate());
entity.setParent(dto.getParent());
entity.setAuthor(ses.getUser());
}
entity.setTitle(dto.getTitle());
entity.setBody(dto.getBody());
entity.setAppliedAuthor(dto.getAppliedAuthor());
entity.setAppliedRegDate(dto.getAppliedRegDate());
List<Observer> observers = new ArrayList<Observer>();
for (Observer o : dto.getObservers()) {
Observer observer = new Observer();
observer.setEmployee(eDao.findById(o.getEmployee().getId()));
observers.add(observer);
}
entity.setObservers(observers);
dto.setAttachments(getActualAttachments(entity.getAttachments(), dto.getAttachments(), fsid));
calculateReadersEditors(entity);
return entity;
}
private void calculateReadersEditors(Report entity) {
entity.addReaderEditor(entity.getAuthor());
}
@Override
public Outcome getOutcome(Report entity) {
Outcome outcome = new Outcome();
outcome.setTitle(entity.getTitle());
outcome.addPayload(entity);
outcome.addPayload("assignment", entity.getParent());
if (!entity.isNew()) {
outcome.addPayload(new ACL(entity));
}
return outcome;
}
}
| UTF-8 | Java | 3,199 | java | ReportDomain.java | Java | []
| null | []
| package workflow.domain;
import com.exponentus.common.domain.DTOService;
import com.exponentus.common.domain.IValidation;
import com.exponentus.common.model.ACL;
import com.exponentus.dataengine.exception.DAOException;
import com.exponentus.rest.outgoingdto.Outcome;
import com.exponentus.rest.validation.exception.DTOException;
import com.exponentus.scripting._Session;
import staff.dao.EmployeeDAO;
import staff.model.Employee;
import staff.model.embedded.Observer;
import workflow.dao.ReportDAO;
import workflow.model.Assignment;
import workflow.model.Report;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ReportDomain extends DTOService<Report> {
public ReportDomain(_Session ses) throws DAOException {
super(ses);
dao = new ReportDAO(ses);
}
public Report composeNew(Employee author, Assignment parent) {
if (parent == null) {
throw new IllegalArgumentException("parent null");
}
Report entity = new Report();
entity.setAuthor(author.getUser());
entity.setAppliedAuthor(author);
entity.setAppliedRegDate(new Date());
entity.setParent(parent);
return entity;
}
@Override
public Report fillFromDto(Report dto, IValidation<Report> validation, String fsid) throws DTOException, DAOException {
validation.check(dto);
Report entity;
if (dto.isNew()) {
entity = new Report();
} else {
entity = dao.findById(dto.getId());
}
EmployeeDAO eDao = new EmployeeDAO(ses);
if (entity.isNew()) {
if (dto.getParent() == null) {
throw new DTOException("assignment", "required", "field_is_empty");
}
entity.setAppliedAuthor(eDao.findById(dto.getAppliedAuthor().getId()));
entity.setAppliedRegDate(dto.getAppliedRegDate());
entity.setParent(dto.getParent());
entity.setAuthor(ses.getUser());
}
entity.setTitle(dto.getTitle());
entity.setBody(dto.getBody());
entity.setAppliedAuthor(dto.getAppliedAuthor());
entity.setAppliedRegDate(dto.getAppliedRegDate());
List<Observer> observers = new ArrayList<Observer>();
for (Observer o : dto.getObservers()) {
Observer observer = new Observer();
observer.setEmployee(eDao.findById(o.getEmployee().getId()));
observers.add(observer);
}
entity.setObservers(observers);
dto.setAttachments(getActualAttachments(entity.getAttachments(), dto.getAttachments(), fsid));
calculateReadersEditors(entity);
return entity;
}
private void calculateReadersEditors(Report entity) {
entity.addReaderEditor(entity.getAuthor());
}
@Override
public Outcome getOutcome(Report entity) {
Outcome outcome = new Outcome();
outcome.setTitle(entity.getTitle());
outcome.addPayload(entity);
outcome.addPayload("assignment", entity.getParent());
if (!entity.isNew()) {
outcome.addPayload(new ACL(entity));
}
return outcome;
}
}
| 3,199 | 0.655517 | 0.655517 | 99 | 31.313131 | 24.576265 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.646465 | false | false | 3 |
620bfa071c41826e98483789b67b6efdf9566d12 | 26,310,969,657,080 | 95c49f466673952b465e19a5ee3ae6eff76bee00 | /src/main/java/com/zhihu/android/argus/anr/AnrDetailsCollector.java | 162c99cb3183e77aeddb2137edfbd3fa1a9382c6 | []
| no_license | Phantoms007/zhihuAPK | https://github.com/Phantoms007/zhihuAPK | 58889c399ae56b16a9160a5f48b807e02c87797e | dcdbd103436a187f9c8b4be8f71bdf7813b6d201 | refs/heads/main | 2023-01-24T01:34:18.716000 | 2020-11-25T17:14:55 | 2020-11-25T17:14:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zhihu.android.argus.anr;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Process;
import com.secneo.apkwrapper.C6969H;
import com.zhihu.android.argus.AbstractC17150h;
import com.zhihu.android.argus.Client;
import com.zhihu.android.argus.p1374a.DeliveryStyle;
import com.zhihu.android.argus.p1376c.Error;
import com.zhihu.android.p966ae.p967a.RulerHandlerThread;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import kotlin.Metadata;
import kotlin.TypeCastException;
import kotlin.collections.CollectionsKt;
import kotlin.p2243e.p2245b.C32569u;
import kotlin.p2243e.p2245b.DefaultConstructorMarker;
import kotlin.p2253l.C32646n;
@Metadata
/* renamed from: com.zhihu.android.argus.anr.a */
/* compiled from: AnrDetailsCollector.kt */
public final class AnrDetailsCollector {
/* renamed from: a */
public static final C17136a f60107a = new C17136a(null);
/* renamed from: b */
private final HandlerThread f60108b = new RulerHandlerThread(C6969H.m41409d("G6891D20FAC7DAA27F4439347FEE9C6D47D8CC7"));
public AnrDetailsCollector() {
this.f60108b.start();
}
@Metadata
/* renamed from: com.zhihu.android.argus.anr.a$a */
/* compiled from: AnrDetailsCollector.kt */
public static final class C17136a {
private C17136a() {
}
public /* synthetic */ C17136a(DefaultConstructorMarker pVar) {
this();
}
}
/* renamed from: a */
public final ActivityManager.ProcessErrorStateInfo mo83350a(Context context) {
C32569u.m150519b(context, C6969H.m41409d("G6A97CD"));
Object systemService = context.getSystemService(C6969H.m41409d("G6880C113A939BF30"));
if (systemService != null) {
return mo83349a((ActivityManager) systemService, Process.myPid());
}
throw new TypeCastException(C6969H.m41409d("G6796D916FF33AA27E8018408F0E083D46890C15AAB3FEB27E900DD46E7E9CF977D9AC51FFF31A52DF401994CBCE4D3C727A2D60EB626A23DFF239146F3E2C6C5"));
}
/* renamed from: a */
public final ActivityManager.ProcessErrorStateInfo mo83349a(ActivityManager activityManager, int i) {
T t;
boolean z;
C32569u.m150519b(activityManager, "am");
try {
List<ActivityManager.ProcessErrorStateInfo> processesInErrorState = activityManager.getProcessesInErrorState();
if (processesInErrorState == null) {
processesInErrorState = CollectionsKt.emptyList();
}
Iterator<T> it = processesInErrorState.iterator();
while (true) {
if (!it.hasNext()) {
t = null;
break;
}
t = it.next();
if (((ActivityManager.ProcessErrorStateInfo) t).pid == i) {
z = true;
continue;
} else {
z = false;
continue;
}
if (z) {
break;
}
}
return t;
} catch (RuntimeException unused) {
return null;
}
}
/* renamed from: a */
public final void mo83351a(Error eVar, ActivityManager.ProcessErrorStateInfo processErrorStateInfo) {
C32569u.m150519b(eVar, C6969H.m41409d("G6C91C715AD"));
C32569u.m150519b(processErrorStateInfo, C6969H.m41409d("G688DC729AB31BF2C"));
String str = processErrorStateInfo.shortMsg;
C32569u.m150513a((Object) str, "msg");
if (C32646n.m150701b(str, "ANR", false, 2, (Object) null)) {
str = C32646n.m150699b(str, C6969H.m41409d("G48ADE7"), "", false, 4, (Object) null);
}
eVar.mo83399c(str);
}
/* renamed from: a */
public final void mo83352a(Client iVar, Error eVar) {
C32569u.m150519b(iVar, C6969H.m41409d("G6A8FDC1FB124"));
C32569u.m150519b(eVar, C6969H.m41409d("G6C91C715AD"));
Handler handler = new Handler(this.f60108b.getLooper());
handler.post(new RunnableC17137b(this, iVar, new AtomicInteger(), handler, eVar));
}
@Metadata
/* renamed from: com.zhihu.android.argus.anr.a$b */
/* compiled from: AnrDetailsCollector.kt */
public static final class RunnableC17137b implements Runnable {
/* renamed from: a */
final /* synthetic */ AnrDetailsCollector f60109a;
/* renamed from: b */
final /* synthetic */ Client f60110b;
/* renamed from: c */
final /* synthetic */ AtomicInteger f60111c;
/* renamed from: d */
final /* synthetic */ Handler f60112d;
/* renamed from: e */
final /* synthetic */ Error f60113e;
RunnableC17137b(AnrDetailsCollector aVar, Client iVar, AtomicInteger atomicInteger, Handler handler, Error eVar) {
this.f60109a = aVar;
this.f60110b = iVar;
this.f60111c = atomicInteger;
this.f60112d = handler;
this.f60113e = eVar;
}
public void run() {
AnrDetailsCollector aVar = this.f60109a;
Context context = this.f60110b.f60215b;
C32569u.m150513a((Object) context, C6969H.m41409d("G6A8FDC1FB124E528F61EB347FCF1C6CF7D"));
ActivityManager.ProcessErrorStateInfo a = aVar.mo83350a(context);
if (a != null) {
this.f60109a.mo83351a(this.f60113e, a);
this.f60110b.mo83459a(this.f60113e, DeliveryStyle.ASYNC_WITH_CACHE, (AbstractC17150h) null);
} else if (this.f60111c.getAndIncrement() < 300) {
this.f60112d.postDelayed(this, 100);
}
}
}
}
| UTF-8 | Java | 5,813 | java | AnrDetailsCollector.java | Java | []
| null | []
| package com.zhihu.android.argus.anr;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Process;
import com.secneo.apkwrapper.C6969H;
import com.zhihu.android.argus.AbstractC17150h;
import com.zhihu.android.argus.Client;
import com.zhihu.android.argus.p1374a.DeliveryStyle;
import com.zhihu.android.argus.p1376c.Error;
import com.zhihu.android.p966ae.p967a.RulerHandlerThread;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import kotlin.Metadata;
import kotlin.TypeCastException;
import kotlin.collections.CollectionsKt;
import kotlin.p2243e.p2245b.C32569u;
import kotlin.p2243e.p2245b.DefaultConstructorMarker;
import kotlin.p2253l.C32646n;
@Metadata
/* renamed from: com.zhihu.android.argus.anr.a */
/* compiled from: AnrDetailsCollector.kt */
public final class AnrDetailsCollector {
/* renamed from: a */
public static final C17136a f60107a = new C17136a(null);
/* renamed from: b */
private final HandlerThread f60108b = new RulerHandlerThread(C6969H.m41409d("G6891D20FAC7DAA27F4439347FEE9C6D47D8CC7"));
public AnrDetailsCollector() {
this.f60108b.start();
}
@Metadata
/* renamed from: com.zhihu.android.argus.anr.a$a */
/* compiled from: AnrDetailsCollector.kt */
public static final class C17136a {
private C17136a() {
}
public /* synthetic */ C17136a(DefaultConstructorMarker pVar) {
this();
}
}
/* renamed from: a */
public final ActivityManager.ProcessErrorStateInfo mo83350a(Context context) {
C32569u.m150519b(context, C6969H.m41409d("G6A97CD"));
Object systemService = context.getSystemService(C6969H.m41409d("G6880C113A939BF30"));
if (systemService != null) {
return mo83349a((ActivityManager) systemService, Process.myPid());
}
throw new TypeCastException(C6969H.m41409d("G6796D916FF33AA27E8018408F0E083D46890C15AAB3FEB27E900DD46E7E9CF977D9AC51FFF31A52DF401994CBCE4D3C727A2D60EB626A23DFF239146F3E2C6C5"));
}
/* renamed from: a */
public final ActivityManager.ProcessErrorStateInfo mo83349a(ActivityManager activityManager, int i) {
T t;
boolean z;
C32569u.m150519b(activityManager, "am");
try {
List<ActivityManager.ProcessErrorStateInfo> processesInErrorState = activityManager.getProcessesInErrorState();
if (processesInErrorState == null) {
processesInErrorState = CollectionsKt.emptyList();
}
Iterator<T> it = processesInErrorState.iterator();
while (true) {
if (!it.hasNext()) {
t = null;
break;
}
t = it.next();
if (((ActivityManager.ProcessErrorStateInfo) t).pid == i) {
z = true;
continue;
} else {
z = false;
continue;
}
if (z) {
break;
}
}
return t;
} catch (RuntimeException unused) {
return null;
}
}
/* renamed from: a */
public final void mo83351a(Error eVar, ActivityManager.ProcessErrorStateInfo processErrorStateInfo) {
C32569u.m150519b(eVar, C6969H.m41409d("G6C91C715AD"));
C32569u.m150519b(processErrorStateInfo, C6969H.m41409d("G688DC729AB31BF2C"));
String str = processErrorStateInfo.shortMsg;
C32569u.m150513a((Object) str, "msg");
if (C32646n.m150701b(str, "ANR", false, 2, (Object) null)) {
str = C32646n.m150699b(str, C6969H.m41409d("G48ADE7"), "", false, 4, (Object) null);
}
eVar.mo83399c(str);
}
/* renamed from: a */
public final void mo83352a(Client iVar, Error eVar) {
C32569u.m150519b(iVar, C6969H.m41409d("G6A8FDC1FB124"));
C32569u.m150519b(eVar, C6969H.m41409d("G6C91C715AD"));
Handler handler = new Handler(this.f60108b.getLooper());
handler.post(new RunnableC17137b(this, iVar, new AtomicInteger(), handler, eVar));
}
@Metadata
/* renamed from: com.zhihu.android.argus.anr.a$b */
/* compiled from: AnrDetailsCollector.kt */
public static final class RunnableC17137b implements Runnable {
/* renamed from: a */
final /* synthetic */ AnrDetailsCollector f60109a;
/* renamed from: b */
final /* synthetic */ Client f60110b;
/* renamed from: c */
final /* synthetic */ AtomicInteger f60111c;
/* renamed from: d */
final /* synthetic */ Handler f60112d;
/* renamed from: e */
final /* synthetic */ Error f60113e;
RunnableC17137b(AnrDetailsCollector aVar, Client iVar, AtomicInteger atomicInteger, Handler handler, Error eVar) {
this.f60109a = aVar;
this.f60110b = iVar;
this.f60111c = atomicInteger;
this.f60112d = handler;
this.f60113e = eVar;
}
public void run() {
AnrDetailsCollector aVar = this.f60109a;
Context context = this.f60110b.f60215b;
C32569u.m150513a((Object) context, C6969H.m41409d("G6A8FDC1FB124E528F61EB347FCF1C6CF7D"));
ActivityManager.ProcessErrorStateInfo a = aVar.mo83350a(context);
if (a != null) {
this.f60109a.mo83351a(this.f60113e, a);
this.f60110b.mo83459a(this.f60113e, DeliveryStyle.ASYNC_WITH_CACHE, (AbstractC17150h) null);
} else if (this.f60111c.getAndIncrement() < 300) {
this.f60112d.postDelayed(this, 100);
}
}
}
}
| 5,813 | 0.63272 | 0.524686 | 156 | 36.262821 | 30.574858 | 185 | false | false | 0 | 0 | 0 | 0 | 129 | 0.022192 | 0.673077 | false | false | 3 |
61f8255e810cf4c806c6dca2e652608f5414c184 | 27,470,610,883,405 | cc9f69c85a7b6c211547a470400849d43492b0e0 | /ssh/src/com/dao/GphotoDao.java | 296d95eaa3cef349028686332701af16b546a715 | []
| no_license | jefferyqjy/graduationproject | https://github.com/jefferyqjy/graduationproject | a495a3ae2620adedf957f4a313ac73c9be684346 | d24a31d3b78e6385cf44c1fc49248e31be023ef1 | refs/heads/master | 2021-01-24T18:39:45.851000 | 2017-04-09T03:21:31 | 2017-04-09T03:21:38 | 84,468,390 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dao;
import java.util.List;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.hibernate.GPhoto;
public class GphotoDao extends HibernateDaoSupport{
public int photosize(String sql){
return this.getHibernateTemplate().find(sql).size();
}
public int deletePhoto(String sql) {
Query q = this.getSession().createQuery(sql);
return q.executeUpdate();
}
public GPhoto getFindById(String sql){
Query q = this.getSession().createQuery(sql);
List list = q.list();
GPhoto phot = new GPhoto();
if(list != null && list.size() > 0){
phot = (GPhoto)list.get(0);
}
return phot;
}
public GPhoto getId(int pageindex,int pagecount,String sql){
Query q = this.getSession().createQuery(sql);
q.setFirstResult((pageindex-1)*pagecount);
q.setMaxResults(pagecount);
List list = q.list();
GPhoto gp = new GPhoto();
if(list != null && list.size() > 0)
gp = (GPhoto)list.get(0);
return gp;
}
public List getAll(int pagecount ,int pageindex, String sql) {
Query q = this.getSession().createQuery(sql);
q.setFirstResult((pageindex-1)*pagecount);
q.setMaxResults(pagecount);
return q.list();
}
public int getSize(String sql){
return this.getHibernateTemplate().find(sql).size();
}
public int savePhoto(GPhoto photo) {
int a =0;
try{
this.getSession().save(photo);
a = 1;
}catch(Exception e){
a =0;
e.printStackTrace();
}
return a;
}
public List getFive(String sql){
Query q = this.getSession().createQuery(sql);
q.setFirstResult(0);
q.setMaxResults(4);
return q.list();
}
}
| UTF-8 | Java | 1,625 | java | GphotoDao.java | Java | []
| null | []
| package com.dao;
import java.util.List;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.hibernate.GPhoto;
public class GphotoDao extends HibernateDaoSupport{
public int photosize(String sql){
return this.getHibernateTemplate().find(sql).size();
}
public int deletePhoto(String sql) {
Query q = this.getSession().createQuery(sql);
return q.executeUpdate();
}
public GPhoto getFindById(String sql){
Query q = this.getSession().createQuery(sql);
List list = q.list();
GPhoto phot = new GPhoto();
if(list != null && list.size() > 0){
phot = (GPhoto)list.get(0);
}
return phot;
}
public GPhoto getId(int pageindex,int pagecount,String sql){
Query q = this.getSession().createQuery(sql);
q.setFirstResult((pageindex-1)*pagecount);
q.setMaxResults(pagecount);
List list = q.list();
GPhoto gp = new GPhoto();
if(list != null && list.size() > 0)
gp = (GPhoto)list.get(0);
return gp;
}
public List getAll(int pagecount ,int pageindex, String sql) {
Query q = this.getSession().createQuery(sql);
q.setFirstResult((pageindex-1)*pagecount);
q.setMaxResults(pagecount);
return q.list();
}
public int getSize(String sql){
return this.getHibernateTemplate().find(sql).size();
}
public int savePhoto(GPhoto photo) {
int a =0;
try{
this.getSession().save(photo);
a = 1;
}catch(Exception e){
a =0;
e.printStackTrace();
}
return a;
}
public List getFive(String sql){
Query q = this.getSession().createQuery(sql);
q.setFirstResult(0);
q.setMaxResults(4);
return q.list();
}
}
| 1,625 | 0.688 | 0.680615 | 70 | 22.214285 | 18.975843 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.942857 | false | false | 3 |
d44bb82ac60e3d063f9030fb5fa1c0aa8b88ac2f | 32,976,758,969,462 | 83893f7eccf5381fb9ff3377e5767145daa601c9 | /src/main/java/bbsmt/bloqq/bloqq/controller/BloqqPostController.java | b08b110554be45c1e73874961c75151ac6612139 | []
| no_license | keSt93/spring-bloqq | https://github.com/keSt93/spring-bloqq | ab526169177a6542b4c47161ca3ddd9a5357f75c | 02c493361e437babf139c161bd157e80bb45789b | refs/heads/master | 2021-04-30T08:14:21.410000 | 2018-05-02T12:22:14 | 2018-05-02T12:22:14 | 121,368,352 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bbsmt.bloqq.bloqq.controller;
import bbsmt.bloqq.bloqq.entities.BloqqPost;
import bbsmt.bloqq.bloqq.entities.Kommentar;
import bbsmt.bloqq.bloqq.entities.Tags;
import bbsmt.bloqq.bloqq.entities.User;
import bbsmt.bloqq.bloqq.models.PageModel;
import bbsmt.bloqq.bloqq.repository.BloqqRepository;
import bbsmt.bloqq.bloqq.repository.KommentarRepository;
import bbsmt.bloqq.bloqq.repository.TagRepository;
import bbsmt.bloqq.bloqq.repository.UserRepository;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.security.Principal;
import java.util.Date;
import java.util.Optional;
@Controller
@RequestMapping("/bp")
public class BloqqPostController {
@Autowired
private BloqqRepository bloqqRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private KommentarRepository kommentarRepository;
@Autowired
private TagRepository tagRepository;
@GetMapping("/all")
public ModelAndView bloqqPosts(){
ModelAndView modelAndView = new ModelAndView("multipleBloqqPosts");
Iterable<BloqqPost> bloqqlist = bloqqRepository.findAllByOrderByCreateDateDesc();
modelAndView.addObject("bloqqlist",bloqqlist);
return modelAndView;
}
@GetMapping("/id/{id}")
public ModelAndView singleBloqqPost(@PathVariable int id){
BloqqPost currentBloqqPost = bloqqRepository.findById(id);
User currentUser = currentBloqqPost.getUser();
Iterable<Kommentar> kommentarList = kommentarRepository.getAllByBloqqPost(currentBloqqPost);
ModelAndView modelAndView = new ModelAndView("singleBloqqPost");
modelAndView.addObject("kommentarObject", new Kommentar());
modelAndView.addObject("tagObject", new Tags());
modelAndView.addObject("bloqqpost", currentBloqqPost);
modelAndView.addObject("kommentarListe", kommentarRepository.getAllByBloqqPostOrderByCreationDateDesc(currentBloqqPost));
modelAndView.addObject("mehrVonUserListe", bloqqRepository.findAllByUserAndIdNotOrderByCreateDateDesc(currentUser,currentBloqqPost.getId()));
return modelAndView;
}
@PostMapping(value = "/postKommentarAction/{bloqqId}")
private String saveView(Kommentar kommentarObject, Principal currentUser, @PathVariable int bloqqId) {
BloqqPost currBloqqPost = bloqqRepository.findById(bloqqId);
User currUser;
try {
currUser = userRepository.findByUserNameEquals(currentUser.getName());
} catch (Exception x) {
currUser = userRepository.findById(-1);
System.out.print("User not found.");
}
if(StringUtils.isNotEmpty(kommentarObject.getKommentarText()) && currBloqqPost != null) {
kommentarObject.setUser(currUser);
kommentarObject.setKommentarText(kommentarObject.getKommentarText());
kommentarObject.setCreationDate(new Date());
kommentarObject.setBloqqPost(currBloqqPost);
kommentarRepository.save(kommentarObject);
return "redirect:/bp/id/"+bloqqId;
} else {
return "redirect:/";
}
}
}
| UTF-8 | Java | 3,448 | java | BloqqPostController.java | Java | []
| null | []
| package bbsmt.bloqq.bloqq.controller;
import bbsmt.bloqq.bloqq.entities.BloqqPost;
import bbsmt.bloqq.bloqq.entities.Kommentar;
import bbsmt.bloqq.bloqq.entities.Tags;
import bbsmt.bloqq.bloqq.entities.User;
import bbsmt.bloqq.bloqq.models.PageModel;
import bbsmt.bloqq.bloqq.repository.BloqqRepository;
import bbsmt.bloqq.bloqq.repository.KommentarRepository;
import bbsmt.bloqq.bloqq.repository.TagRepository;
import bbsmt.bloqq.bloqq.repository.UserRepository;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.security.Principal;
import java.util.Date;
import java.util.Optional;
@Controller
@RequestMapping("/bp")
public class BloqqPostController {
@Autowired
private BloqqRepository bloqqRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private KommentarRepository kommentarRepository;
@Autowired
private TagRepository tagRepository;
@GetMapping("/all")
public ModelAndView bloqqPosts(){
ModelAndView modelAndView = new ModelAndView("multipleBloqqPosts");
Iterable<BloqqPost> bloqqlist = bloqqRepository.findAllByOrderByCreateDateDesc();
modelAndView.addObject("bloqqlist",bloqqlist);
return modelAndView;
}
@GetMapping("/id/{id}")
public ModelAndView singleBloqqPost(@PathVariable int id){
BloqqPost currentBloqqPost = bloqqRepository.findById(id);
User currentUser = currentBloqqPost.getUser();
Iterable<Kommentar> kommentarList = kommentarRepository.getAllByBloqqPost(currentBloqqPost);
ModelAndView modelAndView = new ModelAndView("singleBloqqPost");
modelAndView.addObject("kommentarObject", new Kommentar());
modelAndView.addObject("tagObject", new Tags());
modelAndView.addObject("bloqqpost", currentBloqqPost);
modelAndView.addObject("kommentarListe", kommentarRepository.getAllByBloqqPostOrderByCreationDateDesc(currentBloqqPost));
modelAndView.addObject("mehrVonUserListe", bloqqRepository.findAllByUserAndIdNotOrderByCreateDateDesc(currentUser,currentBloqqPost.getId()));
return modelAndView;
}
@PostMapping(value = "/postKommentarAction/{bloqqId}")
private String saveView(Kommentar kommentarObject, Principal currentUser, @PathVariable int bloqqId) {
BloqqPost currBloqqPost = bloqqRepository.findById(bloqqId);
User currUser;
try {
currUser = userRepository.findByUserNameEquals(currentUser.getName());
} catch (Exception x) {
currUser = userRepository.findById(-1);
System.out.print("User not found.");
}
if(StringUtils.isNotEmpty(kommentarObject.getKommentarText()) && currBloqqPost != null) {
kommentarObject.setUser(currUser);
kommentarObject.setKommentarText(kommentarObject.getKommentarText());
kommentarObject.setCreationDate(new Date());
kommentarObject.setBloqqPost(currBloqqPost);
kommentarRepository.save(kommentarObject);
return "redirect:/bp/id/"+bloqqId;
} else {
return "redirect:/";
}
}
}
| 3,448 | 0.741879 | 0.741589 | 88 | 38.18182 | 30.888195 | 149 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.670455 | false | false | 3 |
7fe2f64242139eff2363ef631868de44fa20a800 | 32,976,758,967,924 | 9262837f5b8ae9743e9f87fea799d2a4026d7657 | /flowee-core/src/test/java/com/jramoyo/flowee/core/task/AbstractIfElseTaskTest.java | dd6f76d8e53798f1b66816ed75042ddd20b78fc1 | [
"Apache-2.0"
]
| permissive | jramoyo/flowee | https://github.com/jramoyo/flowee | 9c8c92e1c56a3c9ef4848a30ec063e233d4ed271 | 8ea587d956b1707efaf82f2cb0196fb642e15e5e | refs/heads/master | 2021-01-01T18:43:11.075000 | 2014-07-03T11:05:08 | 2014-07-03T11:05:08 | 16,980,909 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* AbstractIfElseTaskTest.java
* May 16, 2013
*/
package com.jramoyo.flowee.core.task;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.mockito.Mock;
import com.jramoyo.flowee.core.WorkflowContext;
import com.jramoyo.flowee.core.WorkflowException;
/**
* AbstractIfElseTaskTest
*
* @author jramoyo
*/
@RunWith(BlockJUnit4ClassRunner.class)
public class AbstractIfElseTaskTest {
@Mock
private Task<String, WorkflowContext> ifTask;
@Mock
private Task<String, WorkflowContext> elseTask;
private TestIfElseTask ifElseTask = new TestIfElseTask("TEST_IF_ELSE");
@Before
public void before() {
initMocks(this);
ifElseTask.setIfTask(ifTask);
ifElseTask.setElseTask(elseTask);
}
@Test
public void testTrue() throws WorkflowException {
WorkflowContext context = new WorkflowContext();
ifElseTask.execute("true", context);
verify(ifTask).execute("true", context);
}
@Test
public void testFalse() throws WorkflowException {
WorkflowContext context = new WorkflowContext();
ifElseTask.execute("false", context);
verify(elseTask).execute("false", context);
}
private static class TestIfElseTask extends AbstractIfElseTask<String, WorkflowContext> {
public TestIfElseTask(String name) {
super(name);
}
@Override
protected boolean isTrue(String request, WorkflowContext context) {
return "true".equals(request);
}
}
}
| UTF-8 | Java | 1,567 | java | AbstractIfElseTaskTest.java | Java | [
{
"context": "ion;\n\n/**\n * AbstractIfElseTaskTest\n * \n * @author jramoyo\n */\n@RunWith(BlockJUnit4ClassRunner.class)\npublic",
"end": 500,
"score": 0.9996559619903564,
"start": 493,
"tag": "USERNAME",
"value": "jramoyo"
}
]
| null | []
| /*
* AbstractIfElseTaskTest.java
* May 16, 2013
*/
package com.jramoyo.flowee.core.task;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.mockito.Mock;
import com.jramoyo.flowee.core.WorkflowContext;
import com.jramoyo.flowee.core.WorkflowException;
/**
* AbstractIfElseTaskTest
*
* @author jramoyo
*/
@RunWith(BlockJUnit4ClassRunner.class)
public class AbstractIfElseTaskTest {
@Mock
private Task<String, WorkflowContext> ifTask;
@Mock
private Task<String, WorkflowContext> elseTask;
private TestIfElseTask ifElseTask = new TestIfElseTask("TEST_IF_ELSE");
@Before
public void before() {
initMocks(this);
ifElseTask.setIfTask(ifTask);
ifElseTask.setElseTask(elseTask);
}
@Test
public void testTrue() throws WorkflowException {
WorkflowContext context = new WorkflowContext();
ifElseTask.execute("true", context);
verify(ifTask).execute("true", context);
}
@Test
public void testFalse() throws WorkflowException {
WorkflowContext context = new WorkflowContext();
ifElseTask.execute("false", context);
verify(elseTask).execute("false", context);
}
private static class TestIfElseTask extends AbstractIfElseTask<String, WorkflowContext> {
public TestIfElseTask(String name) {
super(name);
}
@Override
protected boolean isTrue(String request, WorkflowContext context) {
return "true".equals(request);
}
}
}
| 1,567 | 0.761327 | 0.756222 | 69 | 21.710144 | 22.05599 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.202899 | false | false | 3 |
91b0bfd0cfd98156699a4bbd0b9f800372b14f50 | 2,851,858,314,600 | e503095a5e68957dfa09f5af2b2ac1330e37d808 | /src/others/ErrorMsg.java | 89916e735cdca89cfdae9c2aa58512efd404fc0a | []
| no_license | ZJT26142/scratch | https://github.com/ZJT26142/scratch | f0bcd2363a84ea20fbc56a8d5887ad6e2c54e6b1 | bb2c535782fe589791319b096d55c0076f41cbec | refs/heads/master | 2022-11-05T17:03:30.886000 | 2020-06-24T22:33:25 | 2020-06-24T22:33:25 | 274,716,328 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package others;
public enum ErrorMsg {
// Add more error types after the comma
INVALID_COMMAND("Error: Not able to execute command: %s%n"),
FILE_NOT_EXIST("Error: File not found: %s%n"),
DIRECTORY_NOT_EXIST("Error: Directory not found: %s%n"),
;
private String errorString;
private ErrorMsg(String errorString) {
this.errorString = errorString;
}
/**
* Print the error message
* @param error the error type
* @param args details about the error
* Usage:
* ErrorMsg.print(ErrorMsg.FILE_NOT_EXIST, "testfile.txt");
*/
public static void print(ErrorMsg error, String args) {
System.err.printf(error.errorString, args);
}
}
| UTF-8 | Java | 676 | java | ErrorMsg.java | Java | []
| null | []
| package others;
public enum ErrorMsg {
// Add more error types after the comma
INVALID_COMMAND("Error: Not able to execute command: %s%n"),
FILE_NOT_EXIST("Error: File not found: %s%n"),
DIRECTORY_NOT_EXIST("Error: Directory not found: %s%n"),
;
private String errorString;
private ErrorMsg(String errorString) {
this.errorString = errorString;
}
/**
* Print the error message
* @param error the error type
* @param args details about the error
* Usage:
* ErrorMsg.print(ErrorMsg.FILE_NOT_EXIST, "testfile.txt");
*/
public static void print(ErrorMsg error, String args) {
System.err.printf(error.errorString, args);
}
}
| 676 | 0.677515 | 0.677515 | 26 | 25 | 21.583469 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false | 3 |
658b00d4854f5656d8c8b43c6fc7c178aa033e3e | 9,397,388,493,085 | acedfac2a8f7b3a8d9cc60136a4ca8e77a8ed3bd | /java8Test/src/main/java/com/yt/serial/package-info.java | f01ec091debe37b2610f94eddc0efcf5b540b124 | []
| no_license | YuChangTao/java-base | https://github.com/YuChangTao/java-base | 0f37bc04423d34bfd84e8800c51f5fc514a19967 | d1f38d195943c15b6ac09d05b05d3dec0af9b987 | refs/heads/master | 2023-07-19T18:01:24.819000 | 2021-09-02T02:39:15 | 2021-09-02T02:39:15 | 369,784,848 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yt.serial;
/**
*
* 序列化:
*
* transient 关键字可以阻止属性序列化和反序列化
*
* 1.jdk自带序列化ObjectOutputStream和ObjectInputStream,
* 特点:
* 头部数据用来声明序列化协议、版本,用于高版本向后兼容
* 对象数据主要包括类名、签名、属性名、属性类型及属性值、开头结尾数据
* 存在对象引用、继承的情况下,递归遍历写对象逻辑
*
* 缺点:
* 序列化后数组过大,且存在安全漏洞,一般不建议使用
* 无法跨语言
*
* 2.JSON
* 特点:
* 文本型序列化框架,跨语言
* 基于Http的RPC框架常用
*
* 缺点:
* 序列化开销比较大,对于java需要通过反射生成对象
*
* 3.Hessian
* 特点:
* 动态类型、二进制、紧凑的、可跨语言移植的一种序列化框架,要比JDK、JSON更加紧凑,性能要比JDK、JSON序列化高效很多,而且生成的字节数也更小
*
* 缺点:
* 主要集中在对Java一些常见类型不支持,LinkedHashMap、LinkedHashSet,
* Byte/Short反序列化为Integer
*
*
* 4.Kryo
*
* 5.XStream
*
* 6.protobuf
* 需要启服务
*
* 7.Avro
*
* 8.Thrift
*/ | UTF-8 | Java | 1,223 | java | package-info.java | Java | []
| null | []
| package com.yt.serial;
/**
*
* 序列化:
*
* transient 关键字可以阻止属性序列化和反序列化
*
* 1.jdk自带序列化ObjectOutputStream和ObjectInputStream,
* 特点:
* 头部数据用来声明序列化协议、版本,用于高版本向后兼容
* 对象数据主要包括类名、签名、属性名、属性类型及属性值、开头结尾数据
* 存在对象引用、继承的情况下,递归遍历写对象逻辑
*
* 缺点:
* 序列化后数组过大,且存在安全漏洞,一般不建议使用
* 无法跨语言
*
* 2.JSON
* 特点:
* 文本型序列化框架,跨语言
* 基于Http的RPC框架常用
*
* 缺点:
* 序列化开销比较大,对于java需要通过反射生成对象
*
* 3.Hessian
* 特点:
* 动态类型、二进制、紧凑的、可跨语言移植的一种序列化框架,要比JDK、JSON更加紧凑,性能要比JDK、JSON序列化高效很多,而且生成的字节数也更小
*
* 缺点:
* 主要集中在对Java一些常见类型不支持,LinkedHashMap、LinkedHashSet,
* Byte/Short反序列化为Integer
*
*
* 4.Kryo
*
* 5.XStream
*
* 6.protobuf
* 需要启服务
*
* 7.Avro
*
* 8.Thrift
*/ | 1,223 | 0.67075 | 0.658499 | 46 | 13.217391 | 15.77548 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.021739 | false | false | 3 |
922a3e190d6fbd16e3969c86e39fa01ad07d8467 | 26,852,135,564,696 | 3b4171878a58bdd1e60c364695b55ca0645cf54c | /branches/lmoore/platu/platu/src/platu/Interpretor.java | 1ac9511fb8f66c6eaa819ca53b0c0870901b8fb5 | []
| no_license | cao2/usf.1 | https://github.com/cao2/usf.1 | 17229846cc1a05295ec85476003c8f2176485b15 | 827cc3daa238ac3fdba68672e2d814a5f7a479c1 | refs/heads/master | 2021-01-22T14:40:14.208000 | 2014-10-23T19:15:15 | 2014-10-23T19:15:15 | 25,648,085 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package platu;
import java.io.File;
import java.io.FileNotFoundException;
import platu.project.Project;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import platu.lpn.LPN;
import platu.lpn.io.WriteLPN;
import platu.stategraph.StateGraph;
import platu.stategraph.TimedStateGraph;
public class Interpretor extends Common {
public static boolean OLD_LPN = false;
private boolean readFlag = false;
final int MAXHISTORY = 10;
boolean FLATMODEL = false;
String[] commandHistory = new String[MAXHISTORY];
static final LinkedHashMap<enCMD, String> mapCMD = (new LinkedHashMap<enCMD, String>(20));
static final LinkedHashMap<enCMD, String> mapDesc = (new LinkedHashMap<enCMD, String>(20));
enum enCMD {
compAnalysis, findallsg, loadall, skip, set, last, liststg, sglist, readcsp,
setinterface, savesg, savelpn, join, compose, removedummypn,
rdpn, findsg, findrsg, simulate, sim, getrsgflatabs, getsg, addenv,
flattenpns, mergebgpnall, getsgmaximal, getsgmaxenv, getsgflat,
mergesg, sgabst, abstractsg, sgaf, autofailure,
sgreduce, reduce, deletesg, help, quit, q, interactive,
print, chkpie, sghide, abstStateTran, hidevar, readrsg,
readlpn, chkpi, del, draw
};
static final String[] CMD = {"compAnalysis", "findallsg", "loadall", "skip", "set", "last", "liststg", "sglist", "readcsp",
"setinterface", "savesg", "savelpn", "join", "compose", "removedummypn",
"rdpn", "findsg", "findrsg", "simulate", "sim", "getrsgflatabs", "getsg", "addenv",
"flattenpns", "mergebgpnall", "getsgmaximal", "getsgmaxenv", "getsgflat",
"mergesg", "sgabst", "abstractsg", "sgaf", "autofailure",
"sgreduce", "reduce", "deletesg", "help", "quit", "q", "interactive",
"print", "chkpie", "sghide", "abstStateTran", "hidevar", "readrsg",
"readlpn", "chkpi", "del", "draw"
};
static final String[] CMDDesc = {
"[compAnalysis]", "[findallsg]", "[loadall]", " [skip]", " [set]", "re-enter last command", " [liststg]", " [sglist]", " [readcsp]",
" [setinterface]", "+ [savesg]", "+ [savelpn]", "+ [join]", "+ [compose]", " [removedummypn]",
" [rdpn]", "+ [findsg]", "+ [findrsg]", "+ [simulate]", "+ [sim]", " [getrsgflatabs]", "+ [getsg]", " [addenv]",
" [flattenpns]", "+ [mergebgpnall]", " [getsgmaximal]", " [getsgmaxenv]", " [getsgflat]",
" [mergesg]", " [sgabst]", " [abstractsg]", " [sgaf]", " [autofailure]",
" [sgreduce]", " [reduce]", " [deletesg]", "+ [help]", "+ [quit]", "+ [q]", "+ [interactive]",
"+ [print]", " [chkpie]", " [sghide]", " [abstStateTran]", " [hidevar]", " [readrsg]",
"+ [readlpn]", " [chkpi]", " [del]", " [draw]"
};
static {
int x = 0;
for (enCMD en : enCMD.values()) {
mapCMD.put(en, CMD[x]);
mapDesc.put(en, CMDDesc[x]);
// prln(x + ": " + CMD[x] + "\t" + CMDDesc[x]);
x++;
}
}
public int interpretcommand(Project prj, final String commandline) {
if (prj == null) {
new Exception("Main: interpretcommand: prj is NULL").printStackTrace();
}
String systemcommand = commandline;
systemcommand += " ";
LinkedList<String> arguments = new LinkedList<String>();
String command;
String argument1 = "";
String argument2 = "";
String argument3 = "";
// parse commandline and place command and arguements into list
String buffer = commandline;
StringTokenizer tk = new StringTokenizer(buffer, " ");
while (tk.hasMoreTokens()) {
arguments.add(tk.nextToken());
}
// make sure there is a command to execute
if (arguments.size() == 0) {
return 0;
}
// remove command from argument list
command = arguments.removeFirst();//front();
int argumentcount = 0;
if (arguments.size() > 0) {
argument1 = arguments.peekFirst();//front();
argumentcount++;
}
if (arguments.size() > 1) {
argument2 = arguments.get(1);
argumentcount++;
}
if (arguments.size() > 2) {
argument3 = arguments.get(2);
argumentcount++;
argumentcount++;
}
// mode changes
if (command.charAt(0) == '/' && command.charAt(1) == '/') {
return 0;
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.skip)) == 0) {
return 0;
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.del)) == 0) {
// DesignUnit[] duList = (new LinkedList<LPN>(
// prj.getDesignUnitSet())).toArray(new DesignUnit[0]);
for (LPN lpn : prj.getDesignUnitSet()) {
if (lpn.getLabel().compareTo(argument1) == 0) {
prj.getDesignUnitSet().remove(lpn);
}
}
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.last)) == 0) {
int x = 1;
for (; x < MAXHISTORY; x++) {
System.out.printf("\t%d\t%s\n", x, commandHistory[x]);
}
System.out.printf("enter choice: ");
try {
x = System.in.read() - '0';
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
int ret = interpretcommand(prj, commandHistory[x]);//!!
return (ret);
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.rdpn)) == 0
|| command.compareToIgnoreCase(mapCMD.get(enCMD.removedummypn)) == 0) {
//if( argument1 != "" )
//prj.removeDummyPN( argument1 );
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.findsg)) == 0) {
if (argumentcount > 0) {
prj.search();
} else {
prj.search();
}
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.getrsgflatabs)) == 0) {
//project.findFlatRSGabs( String("flatrsgabs") );
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.loadall)) == 0) {
try {
File[] files = new File(argument1).listFiles();
if (files == null) {
new FileNotFoundException("Invalid directory: " + argument1).printStackTrace();
}
for (File f : files) {
String s = f.getName().toLowerCase();
if (s.endsWith(".lpn") || s.endsWith(".xml") || s.endsWith(".xlpn")) {
try {
Set<LPN> lpnSet = prj.readLpn(f.getAbsolutePath());
for (LPN lpn : lpnSet) {
WriteLPN.write(TimedStateGraph.LPN_PATH + "\\"
+ Main.RESULT_FOLDER + "\\" + f.getName() + "_" + lpn.getLabel(), lpn);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.findallsg)) == 0) {
prj.findLocalSG();
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.findrsg)) == 0) {
prj.compositionalAnalysis();
}else if (command.compareToIgnoreCase(mapCMD.get(enCMD.compAnalysis)) == 0) {
prj.compositionalAnalysis();
}else if (command.compareToIgnoreCase(mapCMD.get(enCMD.draw)) == 0){
if(argumentcount > 0){
for(LPN lpn : prj.getDesignUnitSet()){
if(argument1.equals(lpn.getLabel())){
StateGraph sg = (StateGraph) lpn;
System.out.print("drawing " + lpn.getLabel() + "...");
sg.draw();
System.out.println("Done");
}
}
}
else{
for(LPN lpn : prj.getDesignUnitSet()){
StateGraph sg = (StateGraph) lpn;
System.out.print("drawing " + lpn.getLabel() + "...");
sg.draw();
System.out.println("Done");
}
}
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.help)) == 0) {
System.out.printf("%15s | %s\n"
+ "----------------------------------------------------\n", "Command", "Description");
for (enCMD cmd : enCMD.values()) {//!!
System.out.printf("%15s | %s\n", mapCMD.get(cmd), mapDesc.get(cmd));
//prln( CMD[cmd] + " | " + CMDDESC[cmd] );
}
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.q)) == 0
|| command.compareToIgnoreCase(mapCMD.get(enCMD.quit)) == 0) {
return 1;
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.print)) == 0) {
prln(argument1);
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.readlpn)) == 0) {
if(Options.getNewParser()){
if(!readFlag){
readFlag = true;
LinkedList<String> fileList = new LinkedList<String>();
for(String arg : arguments){
File f = new File(arg);
fileList.add(f.getAbsolutePath());
}
prj.readLpn(fileList);
}
else{
System.err.println("error: only one readLpn command is allowed");
System.exit(1);
}
}
else{
File f = new File(argument1);
prj.readLpn(f.getAbsolutePath());
}
}
return 0;
}
String mergeColumns(String a, String b) {
String ret = "";
StringTokenizer tk1 = new StringTokenizer(a, "\n");
StringTokenizer tk2 = new StringTokenizer(b, "\n");
while (tk1.hasMoreTokens() && tk2.hasMoreTokens()) {
ret += tk1.nextToken() + "\t" + tk2.hasMoreTokens() + "\n";
}
while (tk1.hasMoreTokens()) {
ret += tk1.nextToken() + "\n";
}
while (tk2.hasMoreTokens()) {
ret += tk2.hasMoreTokens() + "\n";
}
return ret;
}
}
| UTF-8 | Java | 10,733 | java | Interpretor.java | Java | []
| null | []
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package platu;
import java.io.File;
import java.io.FileNotFoundException;
import platu.project.Project;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import platu.lpn.LPN;
import platu.lpn.io.WriteLPN;
import platu.stategraph.StateGraph;
import platu.stategraph.TimedStateGraph;
public class Interpretor extends Common {
public static boolean OLD_LPN = false;
private boolean readFlag = false;
final int MAXHISTORY = 10;
boolean FLATMODEL = false;
String[] commandHistory = new String[MAXHISTORY];
static final LinkedHashMap<enCMD, String> mapCMD = (new LinkedHashMap<enCMD, String>(20));
static final LinkedHashMap<enCMD, String> mapDesc = (new LinkedHashMap<enCMD, String>(20));
enum enCMD {
compAnalysis, findallsg, loadall, skip, set, last, liststg, sglist, readcsp,
setinterface, savesg, savelpn, join, compose, removedummypn,
rdpn, findsg, findrsg, simulate, sim, getrsgflatabs, getsg, addenv,
flattenpns, mergebgpnall, getsgmaximal, getsgmaxenv, getsgflat,
mergesg, sgabst, abstractsg, sgaf, autofailure,
sgreduce, reduce, deletesg, help, quit, q, interactive,
print, chkpie, sghide, abstStateTran, hidevar, readrsg,
readlpn, chkpi, del, draw
};
static final String[] CMD = {"compAnalysis", "findallsg", "loadall", "skip", "set", "last", "liststg", "sglist", "readcsp",
"setinterface", "savesg", "savelpn", "join", "compose", "removedummypn",
"rdpn", "findsg", "findrsg", "simulate", "sim", "getrsgflatabs", "getsg", "addenv",
"flattenpns", "mergebgpnall", "getsgmaximal", "getsgmaxenv", "getsgflat",
"mergesg", "sgabst", "abstractsg", "sgaf", "autofailure",
"sgreduce", "reduce", "deletesg", "help", "quit", "q", "interactive",
"print", "chkpie", "sghide", "abstStateTran", "hidevar", "readrsg",
"readlpn", "chkpi", "del", "draw"
};
static final String[] CMDDesc = {
"[compAnalysis]", "[findallsg]", "[loadall]", " [skip]", " [set]", "re-enter last command", " [liststg]", " [sglist]", " [readcsp]",
" [setinterface]", "+ [savesg]", "+ [savelpn]", "+ [join]", "+ [compose]", " [removedummypn]",
" [rdpn]", "+ [findsg]", "+ [findrsg]", "+ [simulate]", "+ [sim]", " [getrsgflatabs]", "+ [getsg]", " [addenv]",
" [flattenpns]", "+ [mergebgpnall]", " [getsgmaximal]", " [getsgmaxenv]", " [getsgflat]",
" [mergesg]", " [sgabst]", " [abstractsg]", " [sgaf]", " [autofailure]",
" [sgreduce]", " [reduce]", " [deletesg]", "+ [help]", "+ [quit]", "+ [q]", "+ [interactive]",
"+ [print]", " [chkpie]", " [sghide]", " [abstStateTran]", " [hidevar]", " [readrsg]",
"+ [readlpn]", " [chkpi]", " [del]", " [draw]"
};
static {
int x = 0;
for (enCMD en : enCMD.values()) {
mapCMD.put(en, CMD[x]);
mapDesc.put(en, CMDDesc[x]);
// prln(x + ": " + CMD[x] + "\t" + CMDDesc[x]);
x++;
}
}
public int interpretcommand(Project prj, final String commandline) {
if (prj == null) {
new Exception("Main: interpretcommand: prj is NULL").printStackTrace();
}
String systemcommand = commandline;
systemcommand += " ";
LinkedList<String> arguments = new LinkedList<String>();
String command;
String argument1 = "";
String argument2 = "";
String argument3 = "";
// parse commandline and place command and arguements into list
String buffer = commandline;
StringTokenizer tk = new StringTokenizer(buffer, " ");
while (tk.hasMoreTokens()) {
arguments.add(tk.nextToken());
}
// make sure there is a command to execute
if (arguments.size() == 0) {
return 0;
}
// remove command from argument list
command = arguments.removeFirst();//front();
int argumentcount = 0;
if (arguments.size() > 0) {
argument1 = arguments.peekFirst();//front();
argumentcount++;
}
if (arguments.size() > 1) {
argument2 = arguments.get(1);
argumentcount++;
}
if (arguments.size() > 2) {
argument3 = arguments.get(2);
argumentcount++;
argumentcount++;
}
// mode changes
if (command.charAt(0) == '/' && command.charAt(1) == '/') {
return 0;
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.skip)) == 0) {
return 0;
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.del)) == 0) {
// DesignUnit[] duList = (new LinkedList<LPN>(
// prj.getDesignUnitSet())).toArray(new DesignUnit[0]);
for (LPN lpn : prj.getDesignUnitSet()) {
if (lpn.getLabel().compareTo(argument1) == 0) {
prj.getDesignUnitSet().remove(lpn);
}
}
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.last)) == 0) {
int x = 1;
for (; x < MAXHISTORY; x++) {
System.out.printf("\t%d\t%s\n", x, commandHistory[x]);
}
System.out.printf("enter choice: ");
try {
x = System.in.read() - '0';
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
int ret = interpretcommand(prj, commandHistory[x]);//!!
return (ret);
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.rdpn)) == 0
|| command.compareToIgnoreCase(mapCMD.get(enCMD.removedummypn)) == 0) {
//if( argument1 != "" )
//prj.removeDummyPN( argument1 );
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.findsg)) == 0) {
if (argumentcount > 0) {
prj.search();
} else {
prj.search();
}
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.getrsgflatabs)) == 0) {
//project.findFlatRSGabs( String("flatrsgabs") );
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.loadall)) == 0) {
try {
File[] files = new File(argument1).listFiles();
if (files == null) {
new FileNotFoundException("Invalid directory: " + argument1).printStackTrace();
}
for (File f : files) {
String s = f.getName().toLowerCase();
if (s.endsWith(".lpn") || s.endsWith(".xml") || s.endsWith(".xlpn")) {
try {
Set<LPN> lpnSet = prj.readLpn(f.getAbsolutePath());
for (LPN lpn : lpnSet) {
WriteLPN.write(TimedStateGraph.LPN_PATH + "\\"
+ Main.RESULT_FOLDER + "\\" + f.getName() + "_" + lpn.getLabel(), lpn);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.findallsg)) == 0) {
prj.findLocalSG();
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.findrsg)) == 0) {
prj.compositionalAnalysis();
}else if (command.compareToIgnoreCase(mapCMD.get(enCMD.compAnalysis)) == 0) {
prj.compositionalAnalysis();
}else if (command.compareToIgnoreCase(mapCMD.get(enCMD.draw)) == 0){
if(argumentcount > 0){
for(LPN lpn : prj.getDesignUnitSet()){
if(argument1.equals(lpn.getLabel())){
StateGraph sg = (StateGraph) lpn;
System.out.print("drawing " + lpn.getLabel() + "...");
sg.draw();
System.out.println("Done");
}
}
}
else{
for(LPN lpn : prj.getDesignUnitSet()){
StateGraph sg = (StateGraph) lpn;
System.out.print("drawing " + lpn.getLabel() + "...");
sg.draw();
System.out.println("Done");
}
}
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.help)) == 0) {
System.out.printf("%15s | %s\n"
+ "----------------------------------------------------\n", "Command", "Description");
for (enCMD cmd : enCMD.values()) {//!!
System.out.printf("%15s | %s\n", mapCMD.get(cmd), mapDesc.get(cmd));
//prln( CMD[cmd] + " | " + CMDDESC[cmd] );
}
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.q)) == 0
|| command.compareToIgnoreCase(mapCMD.get(enCMD.quit)) == 0) {
return 1;
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.print)) == 0) {
prln(argument1);
} else if (command.compareToIgnoreCase(mapCMD.get(enCMD.readlpn)) == 0) {
if(Options.getNewParser()){
if(!readFlag){
readFlag = true;
LinkedList<String> fileList = new LinkedList<String>();
for(String arg : arguments){
File f = new File(arg);
fileList.add(f.getAbsolutePath());
}
prj.readLpn(fileList);
}
else{
System.err.println("error: only one readLpn command is allowed");
System.exit(1);
}
}
else{
File f = new File(argument1);
prj.readLpn(f.getAbsolutePath());
}
}
return 0;
}
String mergeColumns(String a, String b) {
String ret = "";
StringTokenizer tk1 = new StringTokenizer(a, "\n");
StringTokenizer tk2 = new StringTokenizer(b, "\n");
while (tk1.hasMoreTokens() && tk2.hasMoreTokens()) {
ret += tk1.nextToken() + "\t" + tk2.hasMoreTokens() + "\n";
}
while (tk1.hasMoreTokens()) {
ret += tk1.nextToken() + "\n";
}
while (tk2.hasMoreTokens()) {
ret += tk2.hasMoreTokens() + "\n";
}
return ret;
}
}
| 10,733 | 0.518867 | 0.512066 | 259 | 40.440155 | 28.893616 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.478765 | false | false | 3 |
7187c99eb29751305a33ed94ee648041b644c525 | 19,327,352,848,013 | 282b2650588c7a517a3abcef2d9e0d0a13b21691 | /src/main/java/com/example/service/IBookMenuService.java | 0dff269a947c90a237c707dec78edbbe773d4ce6 | []
| no_license | chuxiwen-forever/WriterAssistant | https://github.com/chuxiwen-forever/WriterAssistant | 2d5bfd0ac31fca2656aa1a88fa8cfb3271b3928e | 69ccacec405caf9590f59a489d748e8fcef38e25 | refs/heads/main | 2023-07-10T23:02:08.752000 | 2021-08-25T09:09:17 | 2021-08-25T09:09:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.entity.BookMenu;
import com.example.util.result.Result;
/**
* <p>
* 服务类
* </p>
*
* @author liu
* @since 2021-08-23
*/
public interface IBookMenuService extends IService<BookMenu> {
Result getAllPassages();
Result addOnePassage(Integer id, String passageName);
Result updatePassage(Integer passageId, String passageName, String stage);
Result deletePassage(Integer id);
Result getOnePassageContent(Integer id);
Result addOnePassageContent(Integer id,String passageContent);
}
| UTF-8 | Java | 629 | java | IBookMenuService.java | Java | [
{
"context": ".Result;\n\n/**\n * <p>\n * 服务类\n * </p>\n *\n * @author liu\n * @since 2021-08-23\n */\npublic interface IBookMe",
"end": 210,
"score": 0.974879801273346,
"start": 207,
"tag": "USERNAME",
"value": "liu"
}
]
| null | []
| package com.example.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.entity.BookMenu;
import com.example.util.result.Result;
/**
* <p>
* 服务类
* </p>
*
* @author liu
* @since 2021-08-23
*/
public interface IBookMenuService extends IService<BookMenu> {
Result getAllPassages();
Result addOnePassage(Integer id, String passageName);
Result updatePassage(Integer passageId, String passageName, String stage);
Result deletePassage(Integer id);
Result getOnePassageContent(Integer id);
Result addOnePassageContent(Integer id,String passageContent);
}
| 629 | 0.746388 | 0.733547 | 28 | 21.25 | 24.396465 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 3 |
2290fb9ffaa8332bbb579bd078490e9addf4da4e | 30,176,440,225,060 | 7d1d75adb5c4e2a7dd56d84de6dd9cb6ddbaa641 | /PriActTrainer/src/main/java/gumtree/PageGumtreeThread.java | 08ef1c35aa2cfa3d9e93ad4ebfa5d6459eab7b88 | []
| no_license | pguz/PriAct | https://github.com/pguz/PriAct | 168ced2f8b018c14bc78bbc69506f67a1a9c7744 | 0744e1f50117cfefe66c8a958148fbd2881fc806 | refs/heads/master | 2016-09-10T17:30:33.692000 | 2015-06-18T04:11:30 | 2015-06-18T04:11:30 | 33,880,542 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gumtree;
import com.google.common.collect.Sets;
import common.Product;
import org.apache.commons.lang3.tuple.Pair;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
/**
* Created by sopello on 01.06.2015.
*/
public class PageGumtreeThread extends Thread {
private Set<Pair<Product, Boolean>> productsFromPage;
private static final Logger log = LoggerFactory.getLogger(PageGumtreeThread.class);
private boolean result;
private Document doc;
private String category;
private String productQuery;
public PageGumtreeThread(Document doc, String category, Set<Pair<Product, Boolean>> productsFromPage, String productQuery) {
super();
this.doc = doc;
this.category = category;
this.productsFromPage = productsFromPage;
this.productQuery = productQuery;
}
private void performPageProcessing() {
Element productTable = doc.body().getElementById(GumtreeAnalyzer.productTableId);
Elements iteration = productTable.getElementsByClass(GumtreeAnalyzer.iterableClass);
Set<Thread> processThreads = Sets.newHashSet();
for (Element currentProduct : iteration) {
ProcessGumtreeThread processGumtreeThread = new ProcessGumtreeThread(category, productsFromPage, currentProduct, productQuery);
processThreads.add(processGumtreeThread);
}
for (Thread t : processThreads) {
t.start();
try {
Thread.sleep(2 * GumtreeAnalyzer.threadFiringInterval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (Thread t : processThreads) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
continue;
}
}
}
public void run() {
performPageProcessing();
}
}
| UTF-8 | Java | 2,058 | java | PageGumtreeThread.java | Java | [
{
"context": "Factory;\n\nimport java.util.Set;\n\n/**\n * Created by sopello on 01.06.2015.\n */\npublic class PageGumtreeThread",
"end": 329,
"score": 0.9996287226676941,
"start": 322,
"tag": "USERNAME",
"value": "sopello"
}
]
| null | []
| package gumtree;
import com.google.common.collect.Sets;
import common.Product;
import org.apache.commons.lang3.tuple.Pair;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
/**
* Created by sopello on 01.06.2015.
*/
public class PageGumtreeThread extends Thread {
private Set<Pair<Product, Boolean>> productsFromPage;
private static final Logger log = LoggerFactory.getLogger(PageGumtreeThread.class);
private boolean result;
private Document doc;
private String category;
private String productQuery;
public PageGumtreeThread(Document doc, String category, Set<Pair<Product, Boolean>> productsFromPage, String productQuery) {
super();
this.doc = doc;
this.category = category;
this.productsFromPage = productsFromPage;
this.productQuery = productQuery;
}
private void performPageProcessing() {
Element productTable = doc.body().getElementById(GumtreeAnalyzer.productTableId);
Elements iteration = productTable.getElementsByClass(GumtreeAnalyzer.iterableClass);
Set<Thread> processThreads = Sets.newHashSet();
for (Element currentProduct : iteration) {
ProcessGumtreeThread processGumtreeThread = new ProcessGumtreeThread(category, productsFromPage, currentProduct, productQuery);
processThreads.add(processGumtreeThread);
}
for (Thread t : processThreads) {
t.start();
try {
Thread.sleep(2 * GumtreeAnalyzer.threadFiringInterval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (Thread t : processThreads) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
continue;
}
}
}
public void run() {
performPageProcessing();
}
}
| 2,058 | 0.655005 | 0.649174 | 65 | 30.661539 | 28.655125 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.630769 | false | false | 3 |
95d85a486eefdee077cd5934248158e53f6baa41 | 15,152,644,629,006 | 6ca5c7f79f39e6752dfd4347b3f89e84ebd868dc | /code/src/Fenshu.java | ae40a0fdf50eaea12211c385ca0ca2aa4f197719 | []
| no_license | SandraSix/My_Everything | https://github.com/SandraSix/My_Everything | f9acdfe8c33416ca9da3a2d6fbeefa74957731f4 | a6324995bb96523799a5320198f2b3a040a0fe0e | refs/heads/master | 2020-05-02T01:38:27.079000 | 2019-04-03T09:17:28 | 2019-04-03T09:17:28 | 177,689,738 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class Fenshu {
private static int num(int n,int[] arr,int fenshu){
int nums=0;
for (int i=0;i<n;i++){
if (arr[i]==fenshu){
nums++;
}
}
System.out.println(nums);
return nums;
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int i=0;
int n=0;
int tmp=0;
while(i<3){
n=scanner.nextInt(); //存人数
i++;
int[] arr=new int[n];
for (int j=0;j<n;j++){ //存储分数
arr[j]=scanner.nextInt();
if (j==n){
break;
}
}
i++;
tmp=scanner.nextInt();
i++;
num(n,arr,tmp);
}
}
}
| UTF-8 | Java | 861 | java | Fenshu.java | Java | []
| null | []
| import java.util.Scanner;
public class Fenshu {
private static int num(int n,int[] arr,int fenshu){
int nums=0;
for (int i=0;i<n;i++){
if (arr[i]==fenshu){
nums++;
}
}
System.out.println(nums);
return nums;
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int i=0;
int n=0;
int tmp=0;
while(i<3){
n=scanner.nextInt(); //存人数
i++;
int[] arr=new int[n];
for (int j=0;j<n;j++){ //存储分数
arr[j]=scanner.nextInt();
if (j==n){
break;
}
}
i++;
tmp=scanner.nextInt();
i++;
num(n,arr,tmp);
}
}
}
| 861 | 0.38961 | 0.381346 | 36 | 22.527779 | 13.785028 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.722222 | false | false | 3 |
b14a8aed287914a4d4d464bff3eba4c8f39c48af | 27,633,819,613,872 | eb97ee5d4f19d7bf028ae9a400642a8c644f8fe3 | /trunk/seasar-benchmark/src/main/java/benchmark/many/b07/NullBean07794.java | cbf2bf3cb4b4562abd3e174e259ecd9a7f42ccd8 | []
| no_license | svn2github/s2container | https://github.com/svn2github/s2container | 54ca27cf0c1200a93e1cb88884eb8226a9be677d | 625adc6c4e1396654a7297d00ec206c077a78696 | refs/heads/master | 2020-06-04T17:15:02.140000 | 2013-08-09T09:38:15 | 2013-08-09T09:38:15 | 10,850,644 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package benchmark.many.b07;
public class NullBean07794 {
}
| UTF-8 | Java | 62 | java | NullBean07794.java | Java | []
| null | []
| package benchmark.many.b07;
public class NullBean07794 {
}
| 62 | 0.758065 | 0.645161 | 3 | 18.666666 | 12.498889 | 28 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 3 |
2c50539cac34176b429afe4b355ca545e08fd740 | 31,585,189,556,134 | 7513bb1fe00b5d40682e0de945b49bf4c905841b | /ProjetBanque/src/main/java/com/adaming/myapp/dao/ICompteDao.java | 9a3c7c9ea13722af3eb6eed96dce9b159a16096f | []
| no_license | driatv/projetBanque | https://github.com/driatv/projetBanque | cbfad6f9e40091585a039a43cbc0a844456d2f25 | bc2698d5ffdea3020e0e99afa4a2baf7c1ad2aba | refs/heads/master | 2019-06-04T04:02:33.263000 | 2016-11-22T09:56:02 | 2016-11-22T09:56:02 | 74,457,076 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.adaming.myapp.dao;
public interface ICompteDao {
}
| UTF-8 | Java | 70 | java | ICompteDao.java | Java | []
| null | []
| package com.adaming.myapp.dao;
public interface ICompteDao {
}
| 70 | 0.714286 | 0.714286 | 5 | 12 | 14.296853 | 30 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 3 |
e606ce07c5a1a31cefcf58b41e2c3d1b377e0592 | 31,585,189,559,569 | 9e64d53b69c90e582fd8d8d79fb8a7e7dc93fb17 | /ch.elexis.connect.afinion/src/ch/elexis/connect/afinion/Preferences.java | 5f8697570806164cbac66357f3f9be3650b108b4 | []
| no_license | jsigle/elexis-base | https://github.com/jsigle/elexis-base | e89e277516f2eb94d870f399266560700820dcc5 | fbda2efb49220b61ef81da58c1fa4b68c28bbcd4 | refs/heads/master | 2021-01-17T00:08:29.782000 | 2013-05-05T18:12:15 | 2013-05-05T18:12:15 | 6,995,370 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ch.elexis.connect.afinion;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import ch.elexis.Hub;
import ch.elexis.preferences.SettingsPreferenceStore;
import ch.elexis.rs232.Connection;
import ch.elexis.util.Log;
import ch.elexis.util.SWTHelper;
public class Preferences extends PreferencePage implements IWorkbenchPreferencePage {
public static final String AFINION_BASE = "connectors/afinion/"; //$NON-NLS-1$
public static final String PORT = AFINION_BASE + "port"; //$NON-NLS-1$
public static final String TIMEOUT = AFINION_BASE + "timeout"; //$NON-NLS-1$
public static final String PARAMS = AFINION_BASE + "params"; //$NON-NLS-1$
public static final String LOG = AFINION_BASE + "log"; //$NON-NLS-1$
public static final String BACKGROUND = AFINION_BASE + "background"; //$NON-NLS-1$
Combo ports;
Text speed, data, stop, timeout, logFile;
Button parity, log, background;
public Preferences(){
super(Messages.getString("AfinionAS100Action.ButtonName")); //$NON-NLS-1$
setPreferenceStore(new SettingsPreferenceStore(Hub.localCfg));
}
@Override
protected Control createContents(final Composite parent){
Hub.log.log("Start von createContents", Log.DEBUGMSG); //$NON-NLS-1$
String[] param = Hub.localCfg.get(PARAMS, "9600,8,n,1").split(","); //$NON-NLS-1$ //$NON-NLS-2$
Composite ret = new Composite(parent, SWT.NONE);
ret.setLayout(new GridLayout(2, false));
ret.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true));
Label lblPorts = new Label(ret, SWT.NONE);
lblPorts.setText(Messages.getString("Preferences.Port")); //$NON-NLS-1$
lblPorts.setLayoutData(new GridData(SWT.NONE));
ports = new Combo(ret, SWT.SINGLE);
ports.setItems(Connection.getComPorts());
ports.setText(Hub.localCfg.get(PORT, Messages.getString("AfinionAS100Action.DefaultPort"))); //$NON-NLS-1$
Label lblSpeed = new Label(ret, SWT.NONE);
lblSpeed.setText(Messages.getString("Preferences.Baud")); //$NON-NLS-1$
lblSpeed.setLayoutData(new GridData(SWT.NONE));
speed = new Text(ret, SWT.BORDER);
speed.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
speed.setText(param[0]);
Label lblData = new Label(ret, SWT.NONE);
lblData.setText(Messages.getString("Preferences.Databits")); //$NON-NLS-1$
lblData.setLayoutData(new GridData(SWT.NONE));
data = new Text(ret, SWT.BORDER);
data.setText(param[1]);
Label lblParity = new Label(ret, SWT.NONE);
lblParity.setText(Messages.getString("Preferences.Parity")); //$NON-NLS-1$
lblParity.setLayoutData(new GridData(SWT.NONE));
parity = new Button(ret, SWT.CHECK);
parity.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
parity.setSelection(!param[2].equalsIgnoreCase("n")); //$NON-NLS-1$
Label lblStop = new Label(ret, SWT.NONE);
lblStop.setText(Messages.getString("Preferences.Stopbits")); //$NON-NLS-1$
lblStop.setLayoutData(new GridData(SWT.NONE));
stop = new Text(ret, SWT.BORDER);
stop.setText(param[3]);
Label lblTimeout = new Label(ret, SWT.NONE);
lblTimeout.setText(Messages.getString("Preferences.Timeout")); //$NON-NLS-1$
lblTimeout.setLayoutData(new GridData(SWT.NONE));
String timeoutStr =
Hub.localCfg.get(TIMEOUT, Messages.getString("AfinionAS100Action.DefaultTimeout")); //$NON-NLS-1$
timeout = new Text(ret, SWT.BORDER);
timeout.setText(timeoutStr);
new Label(ret, SWT.NONE).setText(Messages.getString("Preferences.Backgroundprocess")); //$NON-NLS-1$
background = new Button(ret, SWT.CHECK);
background.setSelection(Hub.localCfg.get(BACKGROUND, "n").equalsIgnoreCase("y")); //$NON-NLS-1$ //$NON-NLS-2$
new Label(ret, SWT.NONE).setText(Messages.getString("Preferences.Log")); //$NON-NLS-1$
log = new Button(ret, SWT.CHECK);
log.setSelection(Hub.localCfg.get(LOG, "n").equalsIgnoreCase("y")); //$NON-NLS-1$ //$NON-NLS-2$
return ret;
}
public void init(final IWorkbench workbench){
// TODO Auto-generated method stub
}
@Override
public boolean performOk(){
StringBuilder sb = new StringBuilder();
sb.append(speed.getText()).append(",") //$NON-NLS-1$
.append(data.getText()).append(",") //$NON-NLS-1$
.append(parity.getSelection() ? "y" : "n").append(",") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
.append(stop.getText());
Hub.localCfg.set(PARAMS, sb.toString());
Hub.localCfg.set(PORT, ports.getText());
Hub.localCfg.set(TIMEOUT, timeout.getText());
Hub.localCfg.set(LOG, log.getSelection() ? "y" : "n"); //$NON-NLS-1$ //$NON-NLS-2$
Hub.localCfg.set(BACKGROUND, background.getSelection() ? "y" : "n"); //$NON-NLS-1$ //$NON-NLS-2$
Hub.localCfg.flush();
return super.performOk();
}
} | UTF-8 | Java | 5,049 | java | Preferences.java | Java | []
| null | []
| package ch.elexis.connect.afinion;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import ch.elexis.Hub;
import ch.elexis.preferences.SettingsPreferenceStore;
import ch.elexis.rs232.Connection;
import ch.elexis.util.Log;
import ch.elexis.util.SWTHelper;
public class Preferences extends PreferencePage implements IWorkbenchPreferencePage {
public static final String AFINION_BASE = "connectors/afinion/"; //$NON-NLS-1$
public static final String PORT = AFINION_BASE + "port"; //$NON-NLS-1$
public static final String TIMEOUT = AFINION_BASE + "timeout"; //$NON-NLS-1$
public static final String PARAMS = AFINION_BASE + "params"; //$NON-NLS-1$
public static final String LOG = AFINION_BASE + "log"; //$NON-NLS-1$
public static final String BACKGROUND = AFINION_BASE + "background"; //$NON-NLS-1$
Combo ports;
Text speed, data, stop, timeout, logFile;
Button parity, log, background;
public Preferences(){
super(Messages.getString("AfinionAS100Action.ButtonName")); //$NON-NLS-1$
setPreferenceStore(new SettingsPreferenceStore(Hub.localCfg));
}
@Override
protected Control createContents(final Composite parent){
Hub.log.log("Start von createContents", Log.DEBUGMSG); //$NON-NLS-1$
String[] param = Hub.localCfg.get(PARAMS, "9600,8,n,1").split(","); //$NON-NLS-1$ //$NON-NLS-2$
Composite ret = new Composite(parent, SWT.NONE);
ret.setLayout(new GridLayout(2, false));
ret.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true));
Label lblPorts = new Label(ret, SWT.NONE);
lblPorts.setText(Messages.getString("Preferences.Port")); //$NON-NLS-1$
lblPorts.setLayoutData(new GridData(SWT.NONE));
ports = new Combo(ret, SWT.SINGLE);
ports.setItems(Connection.getComPorts());
ports.setText(Hub.localCfg.get(PORT, Messages.getString("AfinionAS100Action.DefaultPort"))); //$NON-NLS-1$
Label lblSpeed = new Label(ret, SWT.NONE);
lblSpeed.setText(Messages.getString("Preferences.Baud")); //$NON-NLS-1$
lblSpeed.setLayoutData(new GridData(SWT.NONE));
speed = new Text(ret, SWT.BORDER);
speed.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
speed.setText(param[0]);
Label lblData = new Label(ret, SWT.NONE);
lblData.setText(Messages.getString("Preferences.Databits")); //$NON-NLS-1$
lblData.setLayoutData(new GridData(SWT.NONE));
data = new Text(ret, SWT.BORDER);
data.setText(param[1]);
Label lblParity = new Label(ret, SWT.NONE);
lblParity.setText(Messages.getString("Preferences.Parity")); //$NON-NLS-1$
lblParity.setLayoutData(new GridData(SWT.NONE));
parity = new Button(ret, SWT.CHECK);
parity.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
parity.setSelection(!param[2].equalsIgnoreCase("n")); //$NON-NLS-1$
Label lblStop = new Label(ret, SWT.NONE);
lblStop.setText(Messages.getString("Preferences.Stopbits")); //$NON-NLS-1$
lblStop.setLayoutData(new GridData(SWT.NONE));
stop = new Text(ret, SWT.BORDER);
stop.setText(param[3]);
Label lblTimeout = new Label(ret, SWT.NONE);
lblTimeout.setText(Messages.getString("Preferences.Timeout")); //$NON-NLS-1$
lblTimeout.setLayoutData(new GridData(SWT.NONE));
String timeoutStr =
Hub.localCfg.get(TIMEOUT, Messages.getString("AfinionAS100Action.DefaultTimeout")); //$NON-NLS-1$
timeout = new Text(ret, SWT.BORDER);
timeout.setText(timeoutStr);
new Label(ret, SWT.NONE).setText(Messages.getString("Preferences.Backgroundprocess")); //$NON-NLS-1$
background = new Button(ret, SWT.CHECK);
background.setSelection(Hub.localCfg.get(BACKGROUND, "n").equalsIgnoreCase("y")); //$NON-NLS-1$ //$NON-NLS-2$
new Label(ret, SWT.NONE).setText(Messages.getString("Preferences.Log")); //$NON-NLS-1$
log = new Button(ret, SWT.CHECK);
log.setSelection(Hub.localCfg.get(LOG, "n").equalsIgnoreCase("y")); //$NON-NLS-1$ //$NON-NLS-2$
return ret;
}
public void init(final IWorkbench workbench){
// TODO Auto-generated method stub
}
@Override
public boolean performOk(){
StringBuilder sb = new StringBuilder();
sb.append(speed.getText()).append(",") //$NON-NLS-1$
.append(data.getText()).append(",") //$NON-NLS-1$
.append(parity.getSelection() ? "y" : "n").append(",") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
.append(stop.getText());
Hub.localCfg.set(PARAMS, sb.toString());
Hub.localCfg.set(PORT, ports.getText());
Hub.localCfg.set(TIMEOUT, timeout.getText());
Hub.localCfg.set(LOG, log.getSelection() ? "y" : "n"); //$NON-NLS-1$ //$NON-NLS-2$
Hub.localCfg.set(BACKGROUND, background.getSelection() ? "y" : "n"); //$NON-NLS-1$ //$NON-NLS-2$
Hub.localCfg.flush();
return super.performOk();
}
} | 5,049 | 0.719548 | 0.707863 | 121 | 40.735538 | 29.127184 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.512397 | false | false | 3 |
65a37de94f7abb362616b8283b662540d96523e6 | 7,352,984,022,169 | 05c8e6cbb54754e799c0affc0be3ab7d4831c760 | /src/chapter9/HorrorShow.java | b1214cbf2b7105ac2c51d76dd874d96800a4a6ae | []
| no_license | shadowwingz/ThinkingInJava | https://github.com/shadowwingz/ThinkingInJava | cade8a8142083f086d81aacedc7f745b20e7fc21 | 215e443db11b1a9ba1ca73583d5ff8855f2da61f | refs/heads/master | 2021-06-23T10:59:20.471000 | 2020-12-08T12:38:40 | 2020-12-08T12:38:40 | 134,130,672 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package chapter9;
/**
* Created by shadowwingz on 2018/6/9 0009.
*
* menace 恐吓
* lethal 致命
* vampire 吸血鬼
*
* Java 中只能 extends 一个类,
* 但是可以 implements 多个接口,
* 而且接口也可以 extends 接口
*/
interface Monster {
void menace();
}
/**
* 接口可以多重继承
*/
interface DangerousMonster extends Monster {
void destroy();
}
interface Lethal {
void kill();
}
class DragonZilla implements DangerousMonster {
@Override
public void menace() {
}
@Override
public void destroy() {
}
}
interface Vampire extends DangerousMonster, Lethal {
void drinkBlood();
}
class VeryBadVampire implements Vampire {
@Override
public void menace() {
}
@Override
public void destroy() {
}
@Override
public void kill() {
}
@Override
public void drinkBlood() {
}
}
public class HorrorShow {
static void u(Monster b) {
b.menace();
}
static void v(DangerousMonster d) {
d.menace();
d.destroy();
}
static void w(Lethal l) {
l.kill();
}
public static void main(String[] args) {
/**
* DangerousMonster barney = new DragonZilla();
*
* 左边的 DangerousMonster 是接口,右边的 DragonZilla 是实现类,
* 引用用接口,创建对象用实现类,这样有一个好处,就是多态,
* 说的更直白点,就是,调用 barney.menace() 方法的时候,
* 如果实现类是 DragonZilla,那我们实际上调用的是 DragonZilla 的 menace 方法,
* 如果实现类是别的类,那我们实现上调用的是别的类的 menace 方法,这样会很灵活。
*
* 如果我们这样写
* DragonZilla barney = new DragonZilla();
*
* 那我们调用 barney.menace() 方法时,
* 调用的只能是 DragonZilla 的 menace 方法,缺乏灵活性。
*/
DangerousMonster barney = new DragonZilla();
u(barney);
v(barney);
Vampire vlad = new VeryBadVampire();
u(vlad);
v(vlad);
w(vlad);
}
}
| UTF-8 | Java | 2,209 | java | HorrorShow.java | Java | [
{
"context": "package chapter9;\n\n/**\n * Created by shadowwingz on 2018/6/9 0009.\n *\n * menace 恐吓\n * lethal 致命\n *",
"end": 48,
"score": 0.9996563792228699,
"start": 37,
"tag": "USERNAME",
"value": "shadowwingz"
}
]
| null | []
| package chapter9;
/**
* Created by shadowwingz on 2018/6/9 0009.
*
* menace 恐吓
* lethal 致命
* vampire 吸血鬼
*
* Java 中只能 extends 一个类,
* 但是可以 implements 多个接口,
* 而且接口也可以 extends 接口
*/
interface Monster {
void menace();
}
/**
* 接口可以多重继承
*/
interface DangerousMonster extends Monster {
void destroy();
}
interface Lethal {
void kill();
}
class DragonZilla implements DangerousMonster {
@Override
public void menace() {
}
@Override
public void destroy() {
}
}
interface Vampire extends DangerousMonster, Lethal {
void drinkBlood();
}
class VeryBadVampire implements Vampire {
@Override
public void menace() {
}
@Override
public void destroy() {
}
@Override
public void kill() {
}
@Override
public void drinkBlood() {
}
}
public class HorrorShow {
static void u(Monster b) {
b.menace();
}
static void v(DangerousMonster d) {
d.menace();
d.destroy();
}
static void w(Lethal l) {
l.kill();
}
public static void main(String[] args) {
/**
* DangerousMonster barney = new DragonZilla();
*
* 左边的 DangerousMonster 是接口,右边的 DragonZilla 是实现类,
* 引用用接口,创建对象用实现类,这样有一个好处,就是多态,
* 说的更直白点,就是,调用 barney.menace() 方法的时候,
* 如果实现类是 DragonZilla,那我们实际上调用的是 DragonZilla 的 menace 方法,
* 如果实现类是别的类,那我们实现上调用的是别的类的 menace 方法,这样会很灵活。
*
* 如果我们这样写
* DragonZilla barney = new DragonZilla();
*
* 那我们调用 barney.menace() 方法时,
* 调用的只能是 DragonZilla 的 menace 方法,缺乏灵活性。
*/
DangerousMonster barney = new DragonZilla();
u(barney);
v(barney);
Vampire vlad = new VeryBadVampire();
u(vlad);
v(vlad);
w(vlad);
}
}
| 2,209 | 0.573923 | 0.567921 | 106 | 16.292454 | 16.742764 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.179245 | false | false | 3 |
fde5bfa3d7d298ff78b75b0b6482fa56c9db610d | 30,253,749,661,768 | 275747dce844063ce5ea63ee0601f8bdf87c3496 | /googlectf2018/shallweplaythegame/source/src/android/support/v4/c/h.java | 157b99a9fdd0e356ceb742470cce5ec589753a5b | []
| no_license | GNUp/CTF-problem | https://github.com/GNUp/CTF-problem | 6d706be5503f5c710f205459dbe33dbe59baf08d | 47a7c1b2de695c1fae24c37b3d3d8babb5461320 | refs/heads/master | 2018-11-17T18:49:36.391000 | 2018-11-06T03:13:34 | 2018-11-06T03:13:34 | 112,566,374 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package android.support.v4.c;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Resources;
import android.net.Uri;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.os.Process;
import android.util.Log;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class h
{
public static File a(Context context)
{
String s;
int i;
s = (new StringBuilder()).append(".font").append(Process.myPid()).append("-").append(Process.myTid()).append("-").toString();
i = 0;
_L3:
if (i >= 100) goto _L2; else goto _L1
_L1:
File file = new File(context.getCacheDir(), (new StringBuilder()).append(s).append(i).toString());
boolean flag = file.createNewFile();
if (flag)
{
return file;
}
continue; /* Loop/switch isn't completed */
IOException ioexception;
ioexception;
i++;
goto _L3
_L2:
return null;
}
public static ByteBuffer a(Context context, Resources resources, int i)
{
context = a(context);
if (context == null)
{
return null;
}
boolean flag = a(((File) (context)), resources, i);
if (!flag)
{
context.delete();
return null;
}
resources = a(((File) (context)));
context.delete();
return resources;
resources;
context.delete();
throw resources;
}
public static ByteBuffer a(Context context, CancellationSignal cancellationsignal, Uri uri)
{
Object obj;
context = context.getContentResolver();
long l;
try
{
uri = context.openFileDescriptor(uri, "r", cancellationsignal);
}
// Misplaced declaration of an exception variable
catch (Context context)
{
return null;
}
obj = new FileInputStream(uri.getFileDescriptor());
context = ((FileInputStream) (obj)).getChannel();
l = context.size();
context = context.map(java.nio.channels.FileChannel.MapMode.READ_ONLY, 0L, l);
if (obj == null) goto _L2; else goto _L1
_L1:
if (true) goto _L4; else goto _L3
_L3:
((FileInputStream) (obj)).close();
_L2:
if (uri == null) goto _L6; else goto _L5
_L5:
if (true) goto _L8; else goto _L7
_L7:
uri.close();
_L6:
return context;
context;
try
{
throw new NullPointerException();
}
// Misplaced declaration of an exception variable
catch (Context context) { }
finally
{
context = null;
}
throw context;
cancellationsignal;
if (uri == null) goto _L10; else goto _L9
_L9:
if (context == null) goto _L12; else goto _L11
_L11:
uri.close();
_L10:
throw cancellationsignal;
_L4:
((FileInputStream) (obj)).close();
goto _L2
context;
throw new NullPointerException();
_L8:
uri.close();
return context;
context;
throw context;
cancellationsignal;
_L18:
if (obj == null) goto _L14; else goto _L13
_L13:
if (context == null) goto _L16; else goto _L15
_L15:
((FileInputStream) (obj)).close();
_L14:
throw cancellationsignal;
obj;
context.addSuppressed(((Throwable) (obj)));
continue; /* Loop/switch isn't completed */
_L16:
((FileInputStream) (obj)).close();
if (true) goto _L14; else goto _L17
_L17:
uri;
context.addSuppressed(uri);
goto _L10
_L12:
uri.close();
goto _L10
cancellationsignal;
context = null;
goto _L18
}
private static ByteBuffer a(File file)
{
Throwable throwable;
Object obj;
long l;
try
{
obj = new FileInputStream(file);
}
// Misplaced declaration of an exception variable
catch (File file)
{
return null;
}
file = ((FileInputStream) (obj)).getChannel();
l = file.size();
file = file.map(java.nio.channels.FileChannel.MapMode.READ_ONLY, 0L, l);
if (obj == null)
{
break MISSING_BLOCK_LABEL_41;
}
if (true)
{
break MISSING_BLOCK_LABEL_52;
}
((FileInputStream) (obj)).close();
return file;
file;
throw new NullPointerException();
((FileInputStream) (obj)).close();
return file;
throwable;
throw throwable;
file;
_L3:
if (obj == null)
{
break MISSING_BLOCK_LABEL_74;
}
if (throwable == null)
{
break MISSING_BLOCK_LABEL_85;
}
((FileInputStream) (obj)).close();
_L1:
throw file;
obj;
throwable.addSuppressed(((Throwable) (obj)));
goto _L1
((FileInputStream) (obj)).close();
goto _L1
file;
throwable = null;
if (true) goto _L3; else goto _L2
_L2:
}
public static void a(Closeable closeable)
{
if (closeable == null)
{
break MISSING_BLOCK_LABEL_10;
}
closeable.close();
return;
closeable;
}
public static boolean a(File file, Resources resources, int i)
{
Resources resources1 = null;
resources = resources.openRawResource(i);
resources1 = resources;
boolean flag = a(file, ((InputStream) (resources)));
a(((Closeable) (resources)));
return flag;
file;
a(((Closeable) (resources1)));
throw file;
}
public static boolean a(File file, InputStream inputstream)
{
Object obj = new FileOutputStream(file, false);
file = ((File) (obj));
byte abyte0[] = new byte[1024];
_L2:
file = ((File) (obj));
int i = inputstream.read(abyte0);
if (i == -1)
{
break; /* Loop/switch isn't completed */
}
file = ((File) (obj));
((FileOutputStream) (obj)).write(abyte0, 0, i);
if (true) goto _L2; else goto _L1
file;
inputstream = ((InputStream) (obj));
obj = file;
_L6:
file = inputstream;
Log.e("TypefaceCompatUtil", (new StringBuilder()).append("Error copying resource contents to temp file: ").append(((IOException) (obj)).getMessage()).toString());
a(((Closeable) (inputstream)));
return false;
_L1:
a(((Closeable) (obj)));
return true;
inputstream;
file = null;
_L4:
a(((Closeable) (file)));
throw inputstream;
inputstream;
if (true) goto _L4; else goto _L3
_L3:
obj;
inputstream = null;
if (true) goto _L6; else goto _L5
_L5:
}
}
| UTF-8 | Java | 7,375 | java | h.java | Java | [
{
"context": "// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.geocities.com/kpdus",
"end": 61,
"score": 0.9997084140777588,
"start": 45,
"tag": "NAME",
"value": "Pavel Kouznetsov"
}
]
| null | []
| // Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package android.support.v4.c;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Resources;
import android.net.Uri;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.os.Process;
import android.util.Log;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class h
{
public static File a(Context context)
{
String s;
int i;
s = (new StringBuilder()).append(".font").append(Process.myPid()).append("-").append(Process.myTid()).append("-").toString();
i = 0;
_L3:
if (i >= 100) goto _L2; else goto _L1
_L1:
File file = new File(context.getCacheDir(), (new StringBuilder()).append(s).append(i).toString());
boolean flag = file.createNewFile();
if (flag)
{
return file;
}
continue; /* Loop/switch isn't completed */
IOException ioexception;
ioexception;
i++;
goto _L3
_L2:
return null;
}
public static ByteBuffer a(Context context, Resources resources, int i)
{
context = a(context);
if (context == null)
{
return null;
}
boolean flag = a(((File) (context)), resources, i);
if (!flag)
{
context.delete();
return null;
}
resources = a(((File) (context)));
context.delete();
return resources;
resources;
context.delete();
throw resources;
}
public static ByteBuffer a(Context context, CancellationSignal cancellationsignal, Uri uri)
{
Object obj;
context = context.getContentResolver();
long l;
try
{
uri = context.openFileDescriptor(uri, "r", cancellationsignal);
}
// Misplaced declaration of an exception variable
catch (Context context)
{
return null;
}
obj = new FileInputStream(uri.getFileDescriptor());
context = ((FileInputStream) (obj)).getChannel();
l = context.size();
context = context.map(java.nio.channels.FileChannel.MapMode.READ_ONLY, 0L, l);
if (obj == null) goto _L2; else goto _L1
_L1:
if (true) goto _L4; else goto _L3
_L3:
((FileInputStream) (obj)).close();
_L2:
if (uri == null) goto _L6; else goto _L5
_L5:
if (true) goto _L8; else goto _L7
_L7:
uri.close();
_L6:
return context;
context;
try
{
throw new NullPointerException();
}
// Misplaced declaration of an exception variable
catch (Context context) { }
finally
{
context = null;
}
throw context;
cancellationsignal;
if (uri == null) goto _L10; else goto _L9
_L9:
if (context == null) goto _L12; else goto _L11
_L11:
uri.close();
_L10:
throw cancellationsignal;
_L4:
((FileInputStream) (obj)).close();
goto _L2
context;
throw new NullPointerException();
_L8:
uri.close();
return context;
context;
throw context;
cancellationsignal;
_L18:
if (obj == null) goto _L14; else goto _L13
_L13:
if (context == null) goto _L16; else goto _L15
_L15:
((FileInputStream) (obj)).close();
_L14:
throw cancellationsignal;
obj;
context.addSuppressed(((Throwable) (obj)));
continue; /* Loop/switch isn't completed */
_L16:
((FileInputStream) (obj)).close();
if (true) goto _L14; else goto _L17
_L17:
uri;
context.addSuppressed(uri);
goto _L10
_L12:
uri.close();
goto _L10
cancellationsignal;
context = null;
goto _L18
}
private static ByteBuffer a(File file)
{
Throwable throwable;
Object obj;
long l;
try
{
obj = new FileInputStream(file);
}
// Misplaced declaration of an exception variable
catch (File file)
{
return null;
}
file = ((FileInputStream) (obj)).getChannel();
l = file.size();
file = file.map(java.nio.channels.FileChannel.MapMode.READ_ONLY, 0L, l);
if (obj == null)
{
break MISSING_BLOCK_LABEL_41;
}
if (true)
{
break MISSING_BLOCK_LABEL_52;
}
((FileInputStream) (obj)).close();
return file;
file;
throw new NullPointerException();
((FileInputStream) (obj)).close();
return file;
throwable;
throw throwable;
file;
_L3:
if (obj == null)
{
break MISSING_BLOCK_LABEL_74;
}
if (throwable == null)
{
break MISSING_BLOCK_LABEL_85;
}
((FileInputStream) (obj)).close();
_L1:
throw file;
obj;
throwable.addSuppressed(((Throwable) (obj)));
goto _L1
((FileInputStream) (obj)).close();
goto _L1
file;
throwable = null;
if (true) goto _L3; else goto _L2
_L2:
}
public static void a(Closeable closeable)
{
if (closeable == null)
{
break MISSING_BLOCK_LABEL_10;
}
closeable.close();
return;
closeable;
}
public static boolean a(File file, Resources resources, int i)
{
Resources resources1 = null;
resources = resources.openRawResource(i);
resources1 = resources;
boolean flag = a(file, ((InputStream) (resources)));
a(((Closeable) (resources)));
return flag;
file;
a(((Closeable) (resources1)));
throw file;
}
public static boolean a(File file, InputStream inputstream)
{
Object obj = new FileOutputStream(file, false);
file = ((File) (obj));
byte abyte0[] = new byte[1024];
_L2:
file = ((File) (obj));
int i = inputstream.read(abyte0);
if (i == -1)
{
break; /* Loop/switch isn't completed */
}
file = ((File) (obj));
((FileOutputStream) (obj)).write(abyte0, 0, i);
if (true) goto _L2; else goto _L1
file;
inputstream = ((InputStream) (obj));
obj = file;
_L6:
file = inputstream;
Log.e("TypefaceCompatUtil", (new StringBuilder()).append("Error copying resource contents to temp file: ").append(((IOException) (obj)).getMessage()).toString());
a(((Closeable) (inputstream)));
return false;
_L1:
a(((Closeable) (obj)));
return true;
inputstream;
file = null;
_L4:
a(((Closeable) (file)));
throw inputstream;
inputstream;
if (true) goto _L4; else goto _L3
_L3:
obj;
inputstream = null;
if (true) goto _L6; else goto _L5
_L5:
}
}
| 7,365 | 0.544542 | 0.528 | 280 | 25.339285 | 21.614542 | 170 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.635714 | false | false | 3 |
be7ed5f41b0ce7df6c9cd46a2a7d7654cd8638b4 | 15,522,011,822,272 | 3452a347eec8628a98b0be59458e4e87822ef635 | /src/main/java/io/aro/library/data/objects/UserPassword.java | d92996da548ba6c9c36582a4607975d643bcd72f | [
"MIT"
]
| permissive | aroooo/library | https://github.com/aroooo/library | 4f41009df291492b56ee5bf09fb24c11daf31ca6 | 5f6ae152b1d5695b732221bd8427b0f374b1298d | refs/heads/master | 2018-11-14T06:41:56.158000 | 2018-09-21T16:51:45 | 2018-09-21T16:51:45 | 140,901,495 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.aro.library.data.objects;
/**
* Represent a User/Password.
*
* @author Antoine "Aro" ROCHAS
* @since 1.0
*/
public class UserPassword
{
private String user, password;
public UserPassword(String user, String password)
{
this.user = user;
this.password = password;
}
public String getUser()
{
return user;
}
public String getPassword()
{
return password;
}
}
| UTF-8 | Java | 449 | java | UserPassword.java | Java | [
{
"context": ";\n\n/**\n * Represent a User/Password.\n *\n * @author Antoine \"Aro\" ROCHAS\n * @since 1.0\n */\npublic class UserP",
"end": 93,
"score": 0.9996314644813538,
"start": 86,
"tag": "NAME",
"value": "Antoine"
},
{
"context": "Represent a User/Password.\n *\n * @author Antoine \"Aro\" ROCHAS\n * @since 1.0\n */\npublic class UserPasswo",
"end": 98,
"score": 0.871618390083313,
"start": 95,
"tag": "USERNAME",
"value": "Aro"
},
{
"context": "esent a User/Password.\n *\n * @author Antoine \"Aro\" ROCHAS\n * @since 1.0\n */\npublic class UserPassword\n{\n ",
"end": 106,
"score": 0.9938848614692688,
"start": 100,
"tag": "NAME",
"value": "ROCHAS"
},
{
"context": "\n this.user = user;\n this.password = password;\n }\n\n public String getUser()\n {\n ",
"end": 307,
"score": 0.9170069098472595,
"start": 299,
"tag": "PASSWORD",
"value": "password"
}
]
| null | []
| package io.aro.library.data.objects;
/**
* Represent a User/Password.
*
* @author Antoine "Aro" ROCHAS
* @since 1.0
*/
public class UserPassword
{
private String user, password;
public UserPassword(String user, String password)
{
this.user = user;
this.password = <PASSWORD>;
}
public String getUser()
{
return user;
}
public String getPassword()
{
return password;
}
}
| 451 | 0.599109 | 0.594655 | 28 | 15.035714 | 14.736937 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 3 |
c6f730ac1559190a50b037bd5dd60190395829a1 | 26,774,826,162,001 | 1a4ec52a9b8980b2f59d83774c33ec5c4959b1f1 | /SoloLeveling/app/src/main/java/com/royce/sololeveling/MainActivity.java | 8173187ef097dcd3a2ec1aba339ec602953251d4 | []
| no_license | rmorga51/Android-Application-with-NFC | https://github.com/rmorga51/Android-Application-with-NFC | 4148522a80e93dd80efeddfe7187c91a46af5dfb | d30947cf0eb1360d94b1dcdde8ebe60b7ecdccb9 | refs/heads/master | 2020-05-15T20:19:15.151000 | 2020-01-15T23:37:21 | 2020-01-15T23:37:21 | 182,478,961 | 0 | 0 | null | true | 2019-04-27T00:12:43 | 2019-04-21T02:34:08 | 2019-04-24T21:31:50 | 2019-04-24T21:31:48 | 314 | 0 | 0 | 1 | Java | false | false | package com.royce.sololeveling;
import android.app.Notification;
import android.app.NotificationManager;
import android.arch.persistence.room.Room;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends AppCompatActivity implements TimePickerFragment.TimePickedListener, DatePickerFragment.DatePickedListener {
public static FragmentManager fragmentManager;
public static Database database;
Add_Mission_Fragment addMissionFragment;
/* int numOfLines = 0;
int fontSize = 15;*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// TODO: add push notifications
/*NotificationManager nm;
nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
String title = "Test Push Notification";
Notification notification = new Notification(android.R.drawable.stat_notify_more,title,System.currentTimeMillis()
);
*/
/////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////adds home fragment to the main activity//////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
fragmentManager = getSupportFragmentManager();
database = Room.databaseBuilder(getApplicationContext(), Database.class, "userdb").allowMainThreadQueries().build();
Intent intent = getIntent();
String missionName = intent.getStringExtra("KEY");
int missionID = intent.getIntExtra("ID", 0);
if(intent != null){
if(missionName != null && missionID != 0){
MissionScreen missionScreen = new MissionScreen();
Bundle bundle = new Bundle();
bundle.putString("KEY", missionName);
bundle.putInt("ID", missionID);
missionScreen.setArguments(bundle);
MainActivity.fragmentManager.beginTransaction().replace(R.id.fragmentContainer, missionScreen).commit();
}
}
if(findViewById(R.id.fragmentContainer) != null && !intent.getAction().equals("ACTION")){
if(savedInstanceState != null){
return;
}
fragmentManager.beginTransaction().add(R.id.fragmentContainer, new HomeFragment()).commit();
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/*TableLayout missionDisplay = findViewById(R.id.missionDisplay);
TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
TableRow.LayoutParams rowParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xFF00FF00); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(5);
//missionDisplay.setLayoutParams(rowParams);
FloatingActionButton createMission = findViewById(R.id.floatingActionButton); // button for adding a new mission/quest
final Intent changeToCreateMission = new Intent(MainActivity.this, CreateMission.class); // set intent to change pages when the add mission button is activated
createMission.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(changeToCreateMission);
}
});
Bundle extras = getIntent().getExtras();
if (extras != null){
String [][] goalsAndTasks = (String[][]) extras.getSerializable("MISSION");
for (int i=0; i<goalsAndTasks.length; i++) {
TableRow tableRow = new TableRow(MainActivity.this);
tableRow.setPadding(0,0,0,10);
tableRow.setLayoutParams(rowParams);
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
TextView task = new TextView(MainActivity.this);
task.setHeight(100);
task.setBackground(gd);
task.setPadding(0,0,0,0);
task.setTextSize(fontSize);
task.setText(goalsAndTasks[i][0]);
task.setId(numOfLines+1);
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
TextView goal = new TextView(MainActivity.this);
goal.setBackground(gd);
goal.setPadding(496,0,0,0);
task.setGravity(Gravity.LEFT);
goal.setTextSize(fontSize);
goal.setId(numOfLines+1);
goal.setText(goalsAndTasks[i][1]);
tableRow.addView(task);
tableRow.addView(goal);
if(tableRow.getParent() != null){
((ViewGroup) tableRow.getParent()).removeView(tableRow);
}
missionDisplay.addView(tableRow);
numOfLines++;
}
}*/
}
@Override
public void pickedTime(String time) {
addMissionFragment = (Add_Mission_Fragment) getSupportFragmentManager().findFragmentByTag("add_mission");
addMissionFragment.setTimeView(time);
}
@Override
public void pickedDate(String date) {
addMissionFragment = (Add_Mission_Fragment) getSupportFragmentManager().findFragmentByTag("add_mission");
addMissionFragment.setDateView(date);
}
}
/* TODO add table layer for mission name and goal. decide on color scheme
TODO: Figure out how to make a TextView appear in layout programatically
TODO : May be able to move the get extras code to a void method that will be called after a mission has been submitted; using a boolean
* */ | UTF-8 | Java | 6,835 | java | MainActivity.java | Java | []
| null | []
| package com.royce.sololeveling;
import android.app.Notification;
import android.app.NotificationManager;
import android.arch.persistence.room.Room;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends AppCompatActivity implements TimePickerFragment.TimePickedListener, DatePickerFragment.DatePickedListener {
public static FragmentManager fragmentManager;
public static Database database;
Add_Mission_Fragment addMissionFragment;
/* int numOfLines = 0;
int fontSize = 15;*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// TODO: add push notifications
/*NotificationManager nm;
nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
String title = "Test Push Notification";
Notification notification = new Notification(android.R.drawable.stat_notify_more,title,System.currentTimeMillis()
);
*/
/////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////adds home fragment to the main activity//////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
fragmentManager = getSupportFragmentManager();
database = Room.databaseBuilder(getApplicationContext(), Database.class, "userdb").allowMainThreadQueries().build();
Intent intent = getIntent();
String missionName = intent.getStringExtra("KEY");
int missionID = intent.getIntExtra("ID", 0);
if(intent != null){
if(missionName != null && missionID != 0){
MissionScreen missionScreen = new MissionScreen();
Bundle bundle = new Bundle();
bundle.putString("KEY", missionName);
bundle.putInt("ID", missionID);
missionScreen.setArguments(bundle);
MainActivity.fragmentManager.beginTransaction().replace(R.id.fragmentContainer, missionScreen).commit();
}
}
if(findViewById(R.id.fragmentContainer) != null && !intent.getAction().equals("ACTION")){
if(savedInstanceState != null){
return;
}
fragmentManager.beginTransaction().add(R.id.fragmentContainer, new HomeFragment()).commit();
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/*TableLayout missionDisplay = findViewById(R.id.missionDisplay);
TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
TableRow.LayoutParams rowParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xFF00FF00); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(5);
//missionDisplay.setLayoutParams(rowParams);
FloatingActionButton createMission = findViewById(R.id.floatingActionButton); // button for adding a new mission/quest
final Intent changeToCreateMission = new Intent(MainActivity.this, CreateMission.class); // set intent to change pages when the add mission button is activated
createMission.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(changeToCreateMission);
}
});
Bundle extras = getIntent().getExtras();
if (extras != null){
String [][] goalsAndTasks = (String[][]) extras.getSerializable("MISSION");
for (int i=0; i<goalsAndTasks.length; i++) {
TableRow tableRow = new TableRow(MainActivity.this);
tableRow.setPadding(0,0,0,10);
tableRow.setLayoutParams(rowParams);
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
TextView task = new TextView(MainActivity.this);
task.setHeight(100);
task.setBackground(gd);
task.setPadding(0,0,0,0);
task.setTextSize(fontSize);
task.setText(goalsAndTasks[i][0]);
task.setId(numOfLines+1);
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
TextView goal = new TextView(MainActivity.this);
goal.setBackground(gd);
goal.setPadding(496,0,0,0);
task.setGravity(Gravity.LEFT);
goal.setTextSize(fontSize);
goal.setId(numOfLines+1);
goal.setText(goalsAndTasks[i][1]);
tableRow.addView(task);
tableRow.addView(goal);
if(tableRow.getParent() != null){
((ViewGroup) tableRow.getParent()).removeView(tableRow);
}
missionDisplay.addView(tableRow);
numOfLines++;
}
}*/
}
@Override
public void pickedTime(String time) {
addMissionFragment = (Add_Mission_Fragment) getSupportFragmentManager().findFragmentByTag("add_mission");
addMissionFragment.setTimeView(time);
}
@Override
public void pickedDate(String date) {
addMissionFragment = (Add_Mission_Fragment) getSupportFragmentManager().findFragmentByTag("add_mission");
addMissionFragment.setDateView(date);
}
}
/* TODO add table layer for mission name and goal. decide on color scheme
TODO: Figure out how to make a TextView appear in layout programatically
TODO : May be able to move the get extras code to a void method that will be called after a mission has been submitted; using a boolean
* */ | 6,835 | 0.579664 | 0.57425 | 143 | 46.804195 | 36.642719 | 167 | false | false | 0 | 0 | 0 | 0 | 100 | 0.071982 | 0.748252 | false | false | 3 |
599b30e346ab82df0a90b4e7488bf8bd445dd504 | 25,220,047,969,898 | 9a514d467fbc9e289443f5f252b3da16ed150342 | /app/src/main/java/ru/ifmo/droid2016/hw3/EnormousPictureLoader.java | 2bc2041a34434b406bf93ffaf958f400ed272fc6 | []
| no_license | mvv-1/homework3 | https://github.com/mvv-1/homework3 | 2f97c124a91dbaa90e25663cb9cc56f0db1ce218 | 82b208413c2a5b096a301ffaf950fa1a08c14f96 | refs/heads/master | 2020-06-17T04:34:06.945000 | 2016-11-30T21:08:53 | 2016-11-30T21:08:53 | 75,040,852 | 0 | 0 | null | true | 2016-11-29T03:50:21 | 2016-11-29T03:50:21 | 2016-10-28T08:26:48 | 2016-11-28T21:57:23 | 2 | 0 | 0 | 0 | null | null | null | package ru.ifmo.droid2016.hw3;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.atomic.AtomicBoolean;
public class EnormousPictureLoader extends Service {
private static final int MB = 8388608; // 1 MB
private String PIC = null;
private AtomicBoolean busy = new AtomicBoolean(false);
private BroadcastReceiver receiver = null;
private Callback<Boolean> saved = null;
public EnormousPictureLoader() {
super();
Log.d("SRV", "CREAT");
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
@Override
public void onCreate() {
super.onCreate();
PIC = getFilesDir().toString() + "/gosha.jpg";
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (saved != null) loadPicture(new Callback<Byte>() {
@Override
public void call(Byte arg) {
}
}, new Callback<Boolean>() {
@Override
public void call(Boolean arg) {
saved.call(arg);
}
});
}
};
IntentFilter fil = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(receiver, fil);
}
private boolean existsPic() {
return new File(PIC).exists();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return new Binder();
}
private boolean loadPicture(Callback<Byte> progress, Callback<Boolean> onFinish) {
if (busy.get()) {
return false;
}
if (existsPic()) onFinish.call(true);
else {
busy.set(true);
new Downloader(progress, onFinish).execute(getResources().getString(R.string.picture_url_key));
}
return true;
}
public interface Callback<A> {
void call(A arg);
}
public class Binder extends android.os.Binder {
public final File pictureFile = new File(PIC);
public boolean getPicture(Callback<Byte> progress, Callback<Boolean> onFinish) {
return loadPicture(progress, onFinish);
}
public void doWhenPicWillBeLoaded(Callback<Boolean> callback) {
saved = callback;
}
}
private class Downloader extends AsyncTask<String, Byte, Boolean> {
private final Callback<Boolean> action;
private final Callback<Byte> progress;
public Downloader(Callback<Byte> progress, Callback<Boolean> result) {
super();
this.action = result;
this.progress = progress;
Log.d("AT", "constr");
}
@Override
protected Boolean doInBackground(String... params) {
Log.d("AT", "DIB");
final URL url;
try {
url = new URL(params[0]);
//intent.getStringExtra(getResources().getString(R.string.picture_url_key)));
} catch (MalformedURLException e) {
Log.wtf("MF URL", e.getMessage());
return false;
}
HttpURLConnection connection = null;
BufferedInputStream input = null;
FileOutputStream output = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.connect();
Log.d("CODE", String.valueOf(connection.getResponseCode()));
int length = connection.getContentLength();
input = new BufferedInputStream(connection.getInputStream(), MB);
output = new FileOutputStream(PIC);
byte[] buffer = new byte[MB];
int count;
int done = 0;
while ((count = input.read(buffer)) != -1) {
done += count;
publishProgress((byte) (done * 100 / length));
output.write(buffer, 0, count);
}
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
if (input != null) input.close();
if (output != null) output.close();
if (connection != null) connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
return true;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.d("AT", "Pre");
if (new File(PIC).exists()) {
this.cancel(false);
action.call(true);
busy.set(false);
}
}
@Override
protected void onPostExecute(Boolean result) {
Log.d("AT", "Post");
if (!result) (new File(PIC)).delete();
busy.set(false);
action.call(result);
}
@Override
protected void onProgressUpdate(Byte... values) {
super.onProgressUpdate(values);
Log.d("AT", "PU");
progress.call(values[0]);
}
}
}
| UTF-8 | Java | 5,904 | java | EnormousPictureLoader.java | Java | []
| null | []
| package ru.ifmo.droid2016.hw3;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.atomic.AtomicBoolean;
public class EnormousPictureLoader extends Service {
private static final int MB = 8388608; // 1 MB
private String PIC = null;
private AtomicBoolean busy = new AtomicBoolean(false);
private BroadcastReceiver receiver = null;
private Callback<Boolean> saved = null;
public EnormousPictureLoader() {
super();
Log.d("SRV", "CREAT");
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
@Override
public void onCreate() {
super.onCreate();
PIC = getFilesDir().toString() + "/gosha.jpg";
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (saved != null) loadPicture(new Callback<Byte>() {
@Override
public void call(Byte arg) {
}
}, new Callback<Boolean>() {
@Override
public void call(Boolean arg) {
saved.call(arg);
}
});
}
};
IntentFilter fil = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(receiver, fil);
}
private boolean existsPic() {
return new File(PIC).exists();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return new Binder();
}
private boolean loadPicture(Callback<Byte> progress, Callback<Boolean> onFinish) {
if (busy.get()) {
return false;
}
if (existsPic()) onFinish.call(true);
else {
busy.set(true);
new Downloader(progress, onFinish).execute(getResources().getString(R.string.picture_url_key));
}
return true;
}
public interface Callback<A> {
void call(A arg);
}
public class Binder extends android.os.Binder {
public final File pictureFile = new File(PIC);
public boolean getPicture(Callback<Byte> progress, Callback<Boolean> onFinish) {
return loadPicture(progress, onFinish);
}
public void doWhenPicWillBeLoaded(Callback<Boolean> callback) {
saved = callback;
}
}
private class Downloader extends AsyncTask<String, Byte, Boolean> {
private final Callback<Boolean> action;
private final Callback<Byte> progress;
public Downloader(Callback<Byte> progress, Callback<Boolean> result) {
super();
this.action = result;
this.progress = progress;
Log.d("AT", "constr");
}
@Override
protected Boolean doInBackground(String... params) {
Log.d("AT", "DIB");
final URL url;
try {
url = new URL(params[0]);
//intent.getStringExtra(getResources().getString(R.string.picture_url_key)));
} catch (MalformedURLException e) {
Log.wtf("MF URL", e.getMessage());
return false;
}
HttpURLConnection connection = null;
BufferedInputStream input = null;
FileOutputStream output = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.connect();
Log.d("CODE", String.valueOf(connection.getResponseCode()));
int length = connection.getContentLength();
input = new BufferedInputStream(connection.getInputStream(), MB);
output = new FileOutputStream(PIC);
byte[] buffer = new byte[MB];
int count;
int done = 0;
while ((count = input.read(buffer)) != -1) {
done += count;
publishProgress((byte) (done * 100 / length));
output.write(buffer, 0, count);
}
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
if (input != null) input.close();
if (output != null) output.close();
if (connection != null) connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
return true;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.d("AT", "Pre");
if (new File(PIC).exists()) {
this.cancel(false);
action.call(true);
busy.set(false);
}
}
@Override
protected void onPostExecute(Boolean result) {
Log.d("AT", "Post");
if (!result) (new File(PIC)).delete();
busy.set(false);
action.call(result);
}
@Override
protected void onProgressUpdate(Byte... values) {
super.onProgressUpdate(values);
Log.d("AT", "PU");
progress.call(values[0]);
}
}
}
| 5,904 | 0.54336 | 0.539804 | 187 | 30.572193 | 21.948381 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.614973 | false | false | 3 |
300683dd238a7b85314e5d3aba2e925c03455a72 | 34,660,386,080,665 | 1ca97ed08f60d4c9e0ff51978a0cce31bde02cc3 | /lesson_10_session_cookie/practises/coorki_user/src/main/java/com/example/coorki_user/CoorkiUserApplication.java | f1ea9399c4ff7e249ad4ce7be2aef74da4a70132 | []
| no_license | sangle173/C1220G2-Le-Duc-Sang-Module-4 | https://github.com/sangle173/C1220G2-Le-Duc-Sang-Module-4 | 8a65874ae4592decdb80d8377d7c25c544fc336a | 1a672259425e49a468892c5e73c1dfb76f1e88d4 | refs/heads/main | 2023-04-28T19:21:05.469000 | 2021-05-26T09:36:30 | 2021-05-26T09:36:30 | 361,644,828 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.coorki_user;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CoorkiUserApplication {
public static void main(String[] args) {
SpringApplication.run(CoorkiUserApplication.class, args);
}
}
| UTF-8 | Java | 336 | java | CoorkiUserApplication.java | Java | []
| null | []
| package com.example.coorki_user;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CoorkiUserApplication {
public static void main(String[] args) {
SpringApplication.run(CoorkiUserApplication.class, args);
}
}
| 336 | 0.794643 | 0.794643 | 13 | 24.846153 | 24.945621 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 3 |
bd8a628f6260df4a9b2d113bb03ec12628b051ab | 34,660,386,083,338 | c4413c3493cbb85d91a15a69d228d05f1c597d01 | /src/main/java/com/layman/pojo/User.java | 6ac0dec27f7bae9fad864fdbf6a15fc8d09cca86 | []
| no_license | JerryDDDDD/vote-demo | https://github.com/JerryDDDDD/vote-demo | 365a1ce5a8f6b4c1ac7f7b29c98b356e5b0a11cc | f04f28fbc89d5f6681a3fec76040598b9fd829fd | refs/heads/master | 2021-08-28T03:43:35.819000 | 2020-03-01T17:03:44 | 2020-03-01T17:03:44 | 210,742,908 | 0 | 0 | null | false | 2020-03-01T17:03:46 | 2019-09-25T02:56:46 | 2019-09-29T01:06:37 | 2020-03-01T17:03:45 | 137 | 0 | 0 | 0 | Java | false | false | package com.layman.pojo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.io.Serializable;
@JsonIgnoreProperties(ignoreUnknown = true)
public class User implements Serializable {
private String id;
private String openId;
private String nickName;
private Integer gender;
private String country;
private String province;
private String city;
private String avatarUrl;
private static final long serialVersionUID = 1L;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId == null ? null : openId.trim();
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName == null ? null : nickName.trim();
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country == null ? null : country.trim();
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province == null ? null : province.trim();
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city == null ? null : city.trim();
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl == null ? null : avatarUrl.trim();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", openId=").append(openId);
sb.append(", nickName=").append(nickName);
sb.append(", gender=").append(gender);
sb.append(", country=").append(country);
sb.append(", province=").append(province);
sb.append(", city=").append(city);
sb.append(", avatarUrl=").append(avatarUrl);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | UTF-8 | Java | 2,579 | java | User.java | Java | [
{
"context": "(openId);\n sb.append(\", nickName=\").append(nickName);\n sb.append(\", gender=\").append(gender);\n",
"end": 2205,
"score": 0.727565586566925,
"start": 2197,
"tag": "NAME",
"value": "nickName"
}
]
| null | []
| package com.layman.pojo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.io.Serializable;
@JsonIgnoreProperties(ignoreUnknown = true)
public class User implements Serializable {
private String id;
private String openId;
private String nickName;
private Integer gender;
private String country;
private String province;
private String city;
private String avatarUrl;
private static final long serialVersionUID = 1L;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId == null ? null : openId.trim();
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName == null ? null : nickName.trim();
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country == null ? null : country.trim();
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province == null ? null : province.trim();
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city == null ? null : city.trim();
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl == null ? null : avatarUrl.trim();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", openId=").append(openId);
sb.append(", nickName=").append(nickName);
sb.append(", gender=").append(gender);
sb.append(", country=").append(country);
sb.append(", province=").append(province);
sb.append(", city=").append(city);
sb.append(", avatarUrl=").append(avatarUrl);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | 2,579 | 0.602559 | 0.602171 | 109 | 22.669725 | 20.685968 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.477064 | false | false | 3 |
99a6e3fe72f655e590871c3d913b767cb1e9802d | 7,241,314,878,187 | 9ba05b671b1f614c3ebc42d6f34eb6837b957673 | /src/main/java/com/feng/boot/admin/project/system/user/mapper/IUserRoleMapper.java | 43bf9ead0c1096228b4220195c4efb37f69bf314 | [
"MIT"
]
| permissive | Jack165/SaasAdmin | https://github.com/Jack165/SaasAdmin | b07b4454dd3b809b56ec330c5f27b7608464f060 | 2bf5945b0d5299f9f1fe7a3729326220c375a55b | refs/heads/main | 2023-04-21T22:24:47.240000 | 2021-05-08T08:20:58 | 2021-05-08T08:20:58 | 302,864,936 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.feng.boot.admin.project.system.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.feng.boot.admin.project.system.user.model.entity.UserRoleEntity;
/**
* 用户角色 Mapper 接口
*
* @author bing_huang
* @since 3.0.0
*/
public interface IUserRoleMapper extends BaseMapper<UserRoleEntity> {
}
| UTF-8 | Java | 343 | java | IUserRoleMapper.java | Java | [
{
"context": "rRoleEntity;\n\n/**\n * 用户角色 Mapper 接口\n *\n * @author bing_huang\n * @since 3.0.0\n */\npublic interface IUserRoleMap",
"end": 237,
"score": 0.9991661310195923,
"start": 227,
"tag": "USERNAME",
"value": "bing_huang"
}
]
| null | []
| package com.feng.boot.admin.project.system.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.feng.boot.admin.project.system.user.model.entity.UserRoleEntity;
/**
* 用户角色 Mapper 接口
*
* @author bing_huang
* @since 3.0.0
*/
public interface IUserRoleMapper extends BaseMapper<UserRoleEntity> {
}
| 343 | 0.767372 | 0.758308 | 14 | 22.642857 | 27.086124 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.214286 | false | false | 3 |
564529f41855b5529bea0d0620bdb7ef8d7705c2 | 9,543,417,342,164 | 465c9802a8a72c63b575cbd18c5a22e4b89eb904 | /app/src/main/java/libelulati/tripctrl/Categorias/CategoriaListActivity.java | 3bd42527a3a98bb90c7e78a002dbffdf4ff353bf | []
| no_license | elcinho/projetotrip | https://github.com/elcinho/projetotrip | 011213e04b9041b3089a4cb2d7b096d9efedc4d3 | bd005a15638f8588b2152d6890047fa0de7e6cdb | refs/heads/master | 2021-01-24T14:32:58.861000 | 2016-04-01T03:09:29 | 2016-04-01T03:09:29 | 48,512,056 | 0 | 0 | null | true | 2015-12-23T21:34:34 | 2015-12-23T21:34:33 | 2015-12-22T16:06:49 | 2015-12-23T00:48:20 | 0 | 0 | 0 | 0 | null | null | null | package libelulati.tripctrl.Categorias;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import libelulati.tripctrl.Funcoes.Validar;
import libelulati.tripctrl.Inicio.InicioActivity;
import libelulati.tripctrl.R;
public class CategoriaListActivity extends AppCompatActivity {
int id_usuario = InicioActivity.getId_usuario();
Context context;
EditText ed_ca_novo, ed_di_editar;
TextView tx_ca_nome;
ImageView iv_ca_novo;
boolean v_categoria;
Validar validar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categoria_list);
context = CategoriaListActivity.this;
validar = new Validar(context);
ed_ca_novo = (EditText) findViewById(R.id.ed_ca_novo);
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(ed_ca_novo.getWindowToken(), 0);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
iv_ca_novo = (ImageView) findViewById(R.id.iv_ca_novo);
iv_ca_novo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<Categoria> cats = new Categorias_DAO(context).listar(id_usuario);
v_categoria = validar.ValidarCategorias(cats, ed_ca_novo.getText().toString(), ed_ca_novo);
Salvar();
}
});
}
@Override
public void onResume() {
Listar();
super.onResume();
}
public void Salvar(){
Categoria categoria = new Categoria();
categoria.setUs_id(id_usuario);
categoria.setCa_nome(ed_ca_novo.getText().toString());
if(IsValido()){
boolean sucesso = new Categorias_DAO(context).criar(categoria);
if(sucesso){
Toast.makeText(context, context.getResources().getString(R.string.sucesso_criar_categoria), Toast.LENGTH_LONG).show();
ed_ca_novo.setText("");
ed_ca_novo.clearFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(ed_ca_novo.getWindowToken(), 0);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Listar();
}
else{
Toast.makeText(context, context.getResources().getString(R.string.erro_criar_categoria), Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(context,context.getResources().getString(R.string.erro_validar_campos),Toast.LENGTH_LONG).show();
}
}
public void Atualizar(int id){
Categoria categoria = new Categoria();
categoria.setUs_id(id_usuario);
categoria.setCa_nome(ed_di_editar.getText().toString());
if(IsValido()){
boolean sucesso = new Categorias_DAO(context).atualizar(categoria, id);
if(sucesso){
Listar();
}
else {
Toast.makeText(context, context.getResources().getString(R.string.erro_alterar_categoria), Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(context, context.getResources().getString(R.string.erro_validar_campos), Toast.LENGTH_LONG).show();
}
}
public void Listar(){
LinearLayout linearLayout_itens = (LinearLayout)findViewById(R.id.li_ca_lista);
linearLayout_itens.removeAllViews();
List<Categoria> categorias = new Categorias_DAO(context).listar(id_usuario);
View viewItens = null;
if(categorias.size() > 0){
for(final Categoria categoria : categorias){
final int id_ca = categoria.getCa_id();
int id_us = categoria.getUs_id();
final String ca_nome = categoria.getCa_nome();
LayoutInflater inflater = getLayoutInflater();
viewItens = inflater.inflate(R.layout.view_list_textview, null);
tx_ca_nome = (TextView)viewItens.findViewById(R.id.tx_vw_textview);
tx_ca_nome.setText(ca_nome);
tx_ca_nome.requestFocus();
viewItens.setTag(id_ca);
if(id_us == id_usuario){
viewItens.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Editar(id_ca, ca_nome);
}
});
viewItens.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Deletar(id_ca);
return false;
}
});
}
linearLayout_itens.addView(viewItens);
}
}
}
public void Deletar(int id){
final int del_id = id;
AlertDialog confirme;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(context.getResources().getString(R.string.opcao_confirmar));
builder.setMessage(context.getResources().getString(R.string.excluir_registro));
builder.setPositiveButton(context.getResources().getString(R.string.opcao_ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Categorias_DAO categorias_dao = new Categorias_DAO(context);
boolean sucesso = categorias_dao.deletar(del_id);
if (sucesso) {
Toast.makeText(context, context.getResources().getString(R.string.sucesso_excluir_categoria), Toast.LENGTH_LONG).show();
Listar();
} else {
Toast.makeText(context, context.getResources().getString(R.string.erro_excluir_categoria), Toast.LENGTH_LONG).show();
}
dialog.dismiss();
}
});
builder.setNegativeButton(context.getResources().getString(R.string.opcao_cancelar), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
confirme = builder.create();
confirme.show();
}
public void Editar(final int id, String nome) {
AlertDialog editardialog;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(context.getResources().getString(R.string.editar) + " " + nome);
LayoutInflater inflater = getLayoutInflater();
View layoutview = inflater.inflate(R.layout.dialog_editar_edittext, null);
builder.setView(layoutview);
ed_di_editar = (EditText)layoutview.findViewById(R.id.ed_di_editar);
ed_di_editar.setText(nome);
builder.setPositiveButton(context.getResources().getString(R.string.opcao_ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Atualizar(id);
}
});
builder.setNegativeButton(context.getResources().getString(R.string.opcao_cancelar), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
editardialog = builder.create();
editardialog.show();
}
public boolean IsValido(){
if(v_categoria){
return true;
}
else{
return false;
}
}
}
| UTF-8 | Java | 8,440 | java | CategoriaListActivity.java | Java | []
| null | []
| package libelulati.tripctrl.Categorias;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import libelulati.tripctrl.Funcoes.Validar;
import libelulati.tripctrl.Inicio.InicioActivity;
import libelulati.tripctrl.R;
public class CategoriaListActivity extends AppCompatActivity {
int id_usuario = InicioActivity.getId_usuario();
Context context;
EditText ed_ca_novo, ed_di_editar;
TextView tx_ca_nome;
ImageView iv_ca_novo;
boolean v_categoria;
Validar validar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categoria_list);
context = CategoriaListActivity.this;
validar = new Validar(context);
ed_ca_novo = (EditText) findViewById(R.id.ed_ca_novo);
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(ed_ca_novo.getWindowToken(), 0);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
iv_ca_novo = (ImageView) findViewById(R.id.iv_ca_novo);
iv_ca_novo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<Categoria> cats = new Categorias_DAO(context).listar(id_usuario);
v_categoria = validar.ValidarCategorias(cats, ed_ca_novo.getText().toString(), ed_ca_novo);
Salvar();
}
});
}
@Override
public void onResume() {
Listar();
super.onResume();
}
public void Salvar(){
Categoria categoria = new Categoria();
categoria.setUs_id(id_usuario);
categoria.setCa_nome(ed_ca_novo.getText().toString());
if(IsValido()){
boolean sucesso = new Categorias_DAO(context).criar(categoria);
if(sucesso){
Toast.makeText(context, context.getResources().getString(R.string.sucesso_criar_categoria), Toast.LENGTH_LONG).show();
ed_ca_novo.setText("");
ed_ca_novo.clearFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(ed_ca_novo.getWindowToken(), 0);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Listar();
}
else{
Toast.makeText(context, context.getResources().getString(R.string.erro_criar_categoria), Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(context,context.getResources().getString(R.string.erro_validar_campos),Toast.LENGTH_LONG).show();
}
}
public void Atualizar(int id){
Categoria categoria = new Categoria();
categoria.setUs_id(id_usuario);
categoria.setCa_nome(ed_di_editar.getText().toString());
if(IsValido()){
boolean sucesso = new Categorias_DAO(context).atualizar(categoria, id);
if(sucesso){
Listar();
}
else {
Toast.makeText(context, context.getResources().getString(R.string.erro_alterar_categoria), Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(context, context.getResources().getString(R.string.erro_validar_campos), Toast.LENGTH_LONG).show();
}
}
public void Listar(){
LinearLayout linearLayout_itens = (LinearLayout)findViewById(R.id.li_ca_lista);
linearLayout_itens.removeAllViews();
List<Categoria> categorias = new Categorias_DAO(context).listar(id_usuario);
View viewItens = null;
if(categorias.size() > 0){
for(final Categoria categoria : categorias){
final int id_ca = categoria.getCa_id();
int id_us = categoria.getUs_id();
final String ca_nome = categoria.getCa_nome();
LayoutInflater inflater = getLayoutInflater();
viewItens = inflater.inflate(R.layout.view_list_textview, null);
tx_ca_nome = (TextView)viewItens.findViewById(R.id.tx_vw_textview);
tx_ca_nome.setText(ca_nome);
tx_ca_nome.requestFocus();
viewItens.setTag(id_ca);
if(id_us == id_usuario){
viewItens.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Editar(id_ca, ca_nome);
}
});
viewItens.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Deletar(id_ca);
return false;
}
});
}
linearLayout_itens.addView(viewItens);
}
}
}
public void Deletar(int id){
final int del_id = id;
AlertDialog confirme;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(context.getResources().getString(R.string.opcao_confirmar));
builder.setMessage(context.getResources().getString(R.string.excluir_registro));
builder.setPositiveButton(context.getResources().getString(R.string.opcao_ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Categorias_DAO categorias_dao = new Categorias_DAO(context);
boolean sucesso = categorias_dao.deletar(del_id);
if (sucesso) {
Toast.makeText(context, context.getResources().getString(R.string.sucesso_excluir_categoria), Toast.LENGTH_LONG).show();
Listar();
} else {
Toast.makeText(context, context.getResources().getString(R.string.erro_excluir_categoria), Toast.LENGTH_LONG).show();
}
dialog.dismiss();
}
});
builder.setNegativeButton(context.getResources().getString(R.string.opcao_cancelar), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
confirme = builder.create();
confirme.show();
}
public void Editar(final int id, String nome) {
AlertDialog editardialog;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(context.getResources().getString(R.string.editar) + " " + nome);
LayoutInflater inflater = getLayoutInflater();
View layoutview = inflater.inflate(R.layout.dialog_editar_edittext, null);
builder.setView(layoutview);
ed_di_editar = (EditText)layoutview.findViewById(R.id.ed_di_editar);
ed_di_editar.setText(nome);
builder.setPositiveButton(context.getResources().getString(R.string.opcao_ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Atualizar(id);
}
});
builder.setNegativeButton(context.getResources().getString(R.string.opcao_cancelar), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
editardialog = builder.create();
editardialog.show();
}
public boolean IsValido(){
if(v_categoria){
return true;
}
else{
return false;
}
}
}
| 8,440 | 0.605924 | 0.60545 | 229 | 35.855896 | 33.502411 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.633188 | false | false | 3 |
4476782481032ef75c6a77a4757bcc83cfd69b1d | 6,674,379,221,633 | 5e56cdd372dfdd142a5757b56b605bc8c3a729cd | /src/RotatableCore.java | 52f5b2d19d9f47010a623eed733c17411fd66cf4 | []
| no_license | necroTaxonomist/Motor-Diagram | https://github.com/necroTaxonomist/Motor-Diagram | d8d07b16d79bfcc4ca99be1052612352242cf789 | d0d3f14a30d69a02cc34da523ce793e30f560888 | refs/heads/master | 2021-05-09T02:59:40.918000 | 2018-01-28T04:59:06 | 2018-01-28T04:59:06 | 119,226,918 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import javafx.scene.layout.Pane;
import javafx.scene.shape.Polygon;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
public class RotatableCore extends Pane
{
private Polygon mainShape;
private Line[] coil;
public RotatableCore(double radius,
double thickness,
double angle,
double length,
double rotation,
double x,
double y)
{
mainShape = createPoints(radius, thickness, angle, length, rotation, x, y);
mainShape.setStroke(Color.BLACK);
getChildren().add(mainShape);
coil = createCoil(radius, thickness, angle, 3*length/4, rotation, x, y, 5);
for (int i = 0; i < coil.length; ++i)
getChildren().add(coil[i]);
}
public void updateColor(double voltage)
{
if (voltage > 1)
voltage = 1;
else if (voltage < -1)
voltage = -1;
double r = voltage <= 0 ? .85 - 0.15*voltage : .85 - 0.20*voltage;
double g = voltage <= 0 ? .85 + 0.20*voltage : .85 - 0.20*voltage;
double b = voltage <= 0 ? .85 + 0.20*voltage : .85 + 0.15*voltage;
Color c = new Color(r,g,b,1.0);
mainShape.setFill(c);
}
private static Polygon createPoints(double radius,
double thickness,
double angle,
double length,
double rotation,
double xDisp,
double yDisp)
{
System.out.println("PART 0");
double inc = Math.asin((thickness/2) / (radius+thickness));
int amplitude = (int)Math.floor(angle/2/inc);
int numPoints = 4 * amplitude + 3;
System.out.println("amplitude=" + amplitude);
System.out.println("numPoints=" + numPoints);
double[] points = new double[numPoints*2];
int nextIndex= 0;
System.out.println("PART 1");
for (int t = amplitude; t >= 1; --t)
{
double theta = inc * t;
double x = (radius + thickness) * Math.cos(theta);
double y = (radius + thickness) * Math.sin(theta);
points[nextIndex] = x; ++nextIndex;
points[nextIndex] = y; ++nextIndex;
if (t == 1)
{
points[nextIndex] = radius + thickness + length; ++nextIndex;
points[nextIndex] = y; ++nextIndex;
}
}
System.out.println("PART 2");
for (int t = -1; t >= -amplitude; --t)
{
double theta = inc * t;
double x = (radius + thickness) * Math.cos(theta);
double y = (radius + thickness) * Math.sin(theta);
if (t == -1)
{
points[nextIndex] = radius + thickness + length; ++nextIndex;
points[nextIndex] = y; ++nextIndex;
}
points[nextIndex] = x; ++nextIndex;
points[nextIndex] = y; ++nextIndex;
}
System.out.println("PART 3");
for (int t = -amplitude; t <= amplitude; ++t)
{
double theta = inc * t;
double x = (radius) * Math.cos(theta);
double y = (radius) * Math.sin(theta);
points[nextIndex] = x; ++nextIndex;
points[nextIndex] = y; ++nextIndex;
}
System.out.println("PART 4");
for (int i = 0; i < points.length; i += 2)
{
double oldX = points[i];
double oldY = points[i+1];
double newX = oldX * Math.cos(rotation) - oldY * Math.sin(rotation) + xDisp;
double newY = oldX * Math.sin(rotation) + oldY * Math.cos(rotation) + yDisp;
points[i] = newX;
points[i+1] = newY;
}
return new Polygon(points);
}
private static Line[] createCoil(double radius,
double thickness,
double angle,
double length,
double rotation,
double xDisp,
double yDisp,
int number)
{
Line[] lines = new Line[number+1];
double y1 = thickness / 2;
double y2 = thickness / -2;
for (int i = 0; i < number; ++i)
{
double x1 = radius + thickness + i * (length / number);
double x2 = radius + thickness + (i+1) * (length / number);
lines[i] = new Line(x1,
y1,
x2,
y2);
lines[i].setStrokeWidth(2.0);
}
double x = radius + thickness + length;
lines[number] = new Line(x,
y1,
x,
y1 + radius);
lines[number].setStrokeWidth(2.0);
double mirror = 1;
if (rotation == -Math.PI)
mirror = -1;
for (int i = 0; i < lines.length; ++i)
{
double oldX = lines[i].getStartX();
double oldY = lines[i].getStartY() * mirror;
double newX = oldX * Math.cos(rotation) - oldY * Math.sin(rotation) + xDisp;
double newY = oldX * Math.sin(rotation) + oldY * Math.cos(rotation) + yDisp;
lines[i].setStartX(newX);
lines[i].setStartY(newY);
oldX = lines[i].getEndX();
oldY = lines[i].getEndY() * mirror;
newX = oldX * Math.cos(rotation) - oldY * Math.sin(rotation) + xDisp;
newY = oldX * Math.sin(rotation) + oldY * Math.cos(rotation) + yDisp;
lines[i].setEndX(newX);
lines[i].setEndY(newY);
}
return lines;
}
} | UTF-8 | Java | 6,468 | java | RotatableCore.java | Java | []
| null | []
| import javafx.scene.layout.Pane;
import javafx.scene.shape.Polygon;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
public class RotatableCore extends Pane
{
private Polygon mainShape;
private Line[] coil;
public RotatableCore(double radius,
double thickness,
double angle,
double length,
double rotation,
double x,
double y)
{
mainShape = createPoints(radius, thickness, angle, length, rotation, x, y);
mainShape.setStroke(Color.BLACK);
getChildren().add(mainShape);
coil = createCoil(radius, thickness, angle, 3*length/4, rotation, x, y, 5);
for (int i = 0; i < coil.length; ++i)
getChildren().add(coil[i]);
}
public void updateColor(double voltage)
{
if (voltage > 1)
voltage = 1;
else if (voltage < -1)
voltage = -1;
double r = voltage <= 0 ? .85 - 0.15*voltage : .85 - 0.20*voltage;
double g = voltage <= 0 ? .85 + 0.20*voltage : .85 - 0.20*voltage;
double b = voltage <= 0 ? .85 + 0.20*voltage : .85 + 0.15*voltage;
Color c = new Color(r,g,b,1.0);
mainShape.setFill(c);
}
private static Polygon createPoints(double radius,
double thickness,
double angle,
double length,
double rotation,
double xDisp,
double yDisp)
{
System.out.println("PART 0");
double inc = Math.asin((thickness/2) / (radius+thickness));
int amplitude = (int)Math.floor(angle/2/inc);
int numPoints = 4 * amplitude + 3;
System.out.println("amplitude=" + amplitude);
System.out.println("numPoints=" + numPoints);
double[] points = new double[numPoints*2];
int nextIndex= 0;
System.out.println("PART 1");
for (int t = amplitude; t >= 1; --t)
{
double theta = inc * t;
double x = (radius + thickness) * Math.cos(theta);
double y = (radius + thickness) * Math.sin(theta);
points[nextIndex] = x; ++nextIndex;
points[nextIndex] = y; ++nextIndex;
if (t == 1)
{
points[nextIndex] = radius + thickness + length; ++nextIndex;
points[nextIndex] = y; ++nextIndex;
}
}
System.out.println("PART 2");
for (int t = -1; t >= -amplitude; --t)
{
double theta = inc * t;
double x = (radius + thickness) * Math.cos(theta);
double y = (radius + thickness) * Math.sin(theta);
if (t == -1)
{
points[nextIndex] = radius + thickness + length; ++nextIndex;
points[nextIndex] = y; ++nextIndex;
}
points[nextIndex] = x; ++nextIndex;
points[nextIndex] = y; ++nextIndex;
}
System.out.println("PART 3");
for (int t = -amplitude; t <= amplitude; ++t)
{
double theta = inc * t;
double x = (radius) * Math.cos(theta);
double y = (radius) * Math.sin(theta);
points[nextIndex] = x; ++nextIndex;
points[nextIndex] = y; ++nextIndex;
}
System.out.println("PART 4");
for (int i = 0; i < points.length; i += 2)
{
double oldX = points[i];
double oldY = points[i+1];
double newX = oldX * Math.cos(rotation) - oldY * Math.sin(rotation) + xDisp;
double newY = oldX * Math.sin(rotation) + oldY * Math.cos(rotation) + yDisp;
points[i] = newX;
points[i+1] = newY;
}
return new Polygon(points);
}
private static Line[] createCoil(double radius,
double thickness,
double angle,
double length,
double rotation,
double xDisp,
double yDisp,
int number)
{
Line[] lines = new Line[number+1];
double y1 = thickness / 2;
double y2 = thickness / -2;
for (int i = 0; i < number; ++i)
{
double x1 = radius + thickness + i * (length / number);
double x2 = radius + thickness + (i+1) * (length / number);
lines[i] = new Line(x1,
y1,
x2,
y2);
lines[i].setStrokeWidth(2.0);
}
double x = radius + thickness + length;
lines[number] = new Line(x,
y1,
x,
y1 + radius);
lines[number].setStrokeWidth(2.0);
double mirror = 1;
if (rotation == -Math.PI)
mirror = -1;
for (int i = 0; i < lines.length; ++i)
{
double oldX = lines[i].getStartX();
double oldY = lines[i].getStartY() * mirror;
double newX = oldX * Math.cos(rotation) - oldY * Math.sin(rotation) + xDisp;
double newY = oldX * Math.sin(rotation) + oldY * Math.cos(rotation) + yDisp;
lines[i].setStartX(newX);
lines[i].setStartY(newY);
oldX = lines[i].getEndX();
oldY = lines[i].getEndY() * mirror;
newX = oldX * Math.cos(rotation) - oldY * Math.sin(rotation) + xDisp;
newY = oldX * Math.sin(rotation) + oldY * Math.cos(rotation) + yDisp;
lines[i].setEndX(newX);
lines[i].setEndY(newY);
}
return lines;
}
} | 6,468 | 0.42919 | 0.416203 | 195 | 32.174358 | 22.235346 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.748718 | false | false | 0 |
cc50623c113e5d0adef4738df548d1ff66f9dda7 | 11,733,850,703,568 | 861673377628c6090315eebd512bafa96744d7ac | /src/com/biigoh/launch/TwistedRubber.java | b2bbcb40964ef5b4a4443a8ad886939d5738228a | []
| no_license | DeveloperUX/Twisted-Desktop | https://github.com/DeveloperUX/Twisted-Desktop | 5a5ce3603c42ba4e0cb8f1c76e406075e168d502 | dd9ae5834c23ca802646012cb917aa69994f933a | refs/heads/master | 2021-01-13T01:42:06.576000 | 2013-05-07T20:31:31 | 2013-05-07T20:31:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.biigoh.launch;
/*******************************************************************************
*
******************************************************************************/
import java.net.BindException;
import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.FPSLogger;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.input.RemoteInput;
import com.biigoh.screens.BattleScreen;
import com.biigoh.screens.MenuScreen;
import com.biigoh.screens.SplashScreen;
/**
* This class is only in charge of initiating the settings and starting
* the first screen which is the Splash Screen.
*
* @author BiiGo Games
*/
public class TwistedRubber extends Game {
public static final String LOG = TwistedRubber.class.getSimpleName();
public static final boolean ON_PHONE = false;
private FPSLogger fpsLogger;
private InputMultiplexer inputMultiplexer;
// All of our game screens
private MenuScreen menuScreen;
private BattleScreen battleScreen;
private SplashScreen splashScreen;
// private SplitScreen splitScreen;
public static RemoteInput remote_1;
public static RemoteInput remote_2;
/**
* Called when the application is first created.
*/
@SuppressWarnings("unused")
@Override
public void create() {
Gdx.app.log( LOG, "Creating game" );
fpsLogger = new FPSLogger();
// Ignore the whole powers of two warning
Texture.setEnforcePotImages( false );
// Create an object that will process user input but can also
// hold many user input processors, like buttons and such
inputMultiplexer = new InputMultiplexer();
// by default the Mouse and Keyboard input will always be processed
Gdx.input.setInputProcessor( inputMultiplexer );
if( Gdx.app.getType() == ApplicationType.Desktop ) {
for( int attempt = 0; attempt < 5; attempt++ ) {
try {
remote_1 = new RemoteInput( 9997 + attempt );
remote_2 = new RemoteInput( 9988 + attempt );
break;
} catch( Exception bindException ) {
Gdx.app.log( LOG, "Exception Binding Remote at port: " + (9997 + attempt) );
}
}
}
// load our tiled map
// /TiledMap map = TiledLoader.createMap( Gdx.files.internal("data/output") );
// initialize all of our game screens
menuScreen = new MenuScreen( this );
battleScreen = new BattleScreen( this );
splashScreen = new SplashScreen( this );
// splitScreen = new SplitScreen( this );
}
/**
* Get a reference to the MenuScreen, mainly used for
* switching screens.
* @return a Reference to the Game Menu Screen
*/
public MenuScreen getMenuScreen() {
return menuScreen;
}
/**
* Reference to the BattleScreen for screen switching
* @return a Reference to the Game's Battle Screen
*/
public BattleScreen getBattleScreen() {
return battleScreen;
}
/**
* Reference to the SplashScreen for screen switching
* Call this when you want to switch to the Splash Screen
* @return a Reference to the Game's Splash Screen
*/
public SplashScreen getSplashScreen() {
return splashScreen;
}
public void setInputProcessor( InputProcessor input ) {
Gdx.input.setInputProcessor( input );
}
public void disposeInputProcessors() {
if(Gdx.input.getInputProcessor() != null )
Gdx.input.setInputProcessor(null);
if( remote_1 != null && remote_1.getInputProcessor() != null )
remote_1.setInputProcessor(null);
if( remote_2 != null && remote_2.getInputProcessor() != null )
remote_2.setInputProcessor(null);
}
public void setRemoteProcessor( InputProcessor processor ) {
if( remote_1.getInputProcessor() == null ) {
// System.out.println( "SETTING REMOTE 1" );
remote_1.setInputProcessor(processor);
}
else {
// System.out.println( "SETTING REMOTE 2" );
remote_2.setInputProcessor(processor);
}
}
/* (non-Javadoc)
* @see com.badlogic.gdx.Game#render()
*/
@Override
public void render() {
super.render();
// fpsLogger.log(); // Log the current frame rate
}
/* (non-Javadoc)
* @see com.badlogic.gdx.Game#pause()
*/
@Override
public void pause() {
Gdx.app.log( LOG, "Pausing game" );
super.pause();
}
/* (non-Javadoc)
* @see com.badlogic.gdx.Game#resume()
*/
@Override
public void resume() {
Gdx.app.log( LOG, "Resuming game" );
super.resume();
}
/* (non-Javadoc)
* @see com.badlogic.gdx.Game#resize(int, int)
*/
@Override
public void resize(int width, int height) {
super.resize( width, height );
Gdx.app.log( LOG, "Resizing game to: " + width + " x " + height );
// show the splash screen when the game is resized for the first time
if( getScreen() == null ) {
super.setScreen( new SplashScreen( this ) );
}
}
/* (non-Javadoc)
* @see com.badlogic.gdx.Game#dispose()
*/
@Override
public void dispose() {
Gdx.app.log( LOG, "Disposing game" );
super.dispose();
disposeInputProcessors();
}
}
| UTF-8 | Java | 5,180 | java | TwistedRubber.java | Java | [
{
"context": " screen which is the Splash Screen.\n * \n * @author BiiGo Games\n */\npublic class TwistedRubber extends Game {\n\t\n\t",
"end": 818,
"score": 0.9871065020561218,
"start": 807,
"tag": "NAME",
"value": "BiiGo Games"
}
]
| null | []
| package com.biigoh.launch;
/*******************************************************************************
*
******************************************************************************/
import java.net.BindException;
import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.FPSLogger;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.input.RemoteInput;
import com.biigoh.screens.BattleScreen;
import com.biigoh.screens.MenuScreen;
import com.biigoh.screens.SplashScreen;
/**
* This class is only in charge of initiating the settings and starting
* the first screen which is the Splash Screen.
*
* @author <NAME>
*/
public class TwistedRubber extends Game {
public static final String LOG = TwistedRubber.class.getSimpleName();
public static final boolean ON_PHONE = false;
private FPSLogger fpsLogger;
private InputMultiplexer inputMultiplexer;
// All of our game screens
private MenuScreen menuScreen;
private BattleScreen battleScreen;
private SplashScreen splashScreen;
// private SplitScreen splitScreen;
public static RemoteInput remote_1;
public static RemoteInput remote_2;
/**
* Called when the application is first created.
*/
@SuppressWarnings("unused")
@Override
public void create() {
Gdx.app.log( LOG, "Creating game" );
fpsLogger = new FPSLogger();
// Ignore the whole powers of two warning
Texture.setEnforcePotImages( false );
// Create an object that will process user input but can also
// hold many user input processors, like buttons and such
inputMultiplexer = new InputMultiplexer();
// by default the Mouse and Keyboard input will always be processed
Gdx.input.setInputProcessor( inputMultiplexer );
if( Gdx.app.getType() == ApplicationType.Desktop ) {
for( int attempt = 0; attempt < 5; attempt++ ) {
try {
remote_1 = new RemoteInput( 9997 + attempt );
remote_2 = new RemoteInput( 9988 + attempt );
break;
} catch( Exception bindException ) {
Gdx.app.log( LOG, "Exception Binding Remote at port: " + (9997 + attempt) );
}
}
}
// load our tiled map
// /TiledMap map = TiledLoader.createMap( Gdx.files.internal("data/output") );
// initialize all of our game screens
menuScreen = new MenuScreen( this );
battleScreen = new BattleScreen( this );
splashScreen = new SplashScreen( this );
// splitScreen = new SplitScreen( this );
}
/**
* Get a reference to the MenuScreen, mainly used for
* switching screens.
* @return a Reference to the Game Menu Screen
*/
public MenuScreen getMenuScreen() {
return menuScreen;
}
/**
* Reference to the BattleScreen for screen switching
* @return a Reference to the Game's Battle Screen
*/
public BattleScreen getBattleScreen() {
return battleScreen;
}
/**
* Reference to the SplashScreen for screen switching
* Call this when you want to switch to the Splash Screen
* @return a Reference to the Game's Splash Screen
*/
public SplashScreen getSplashScreen() {
return splashScreen;
}
public void setInputProcessor( InputProcessor input ) {
Gdx.input.setInputProcessor( input );
}
public void disposeInputProcessors() {
if(Gdx.input.getInputProcessor() != null )
Gdx.input.setInputProcessor(null);
if( remote_1 != null && remote_1.getInputProcessor() != null )
remote_1.setInputProcessor(null);
if( remote_2 != null && remote_2.getInputProcessor() != null )
remote_2.setInputProcessor(null);
}
public void setRemoteProcessor( InputProcessor processor ) {
if( remote_1.getInputProcessor() == null ) {
// System.out.println( "SETTING REMOTE 1" );
remote_1.setInputProcessor(processor);
}
else {
// System.out.println( "SETTING REMOTE 2" );
remote_2.setInputProcessor(processor);
}
}
/* (non-Javadoc)
* @see com.badlogic.gdx.Game#render()
*/
@Override
public void render() {
super.render();
// fpsLogger.log(); // Log the current frame rate
}
/* (non-Javadoc)
* @see com.badlogic.gdx.Game#pause()
*/
@Override
public void pause() {
Gdx.app.log( LOG, "Pausing game" );
super.pause();
}
/* (non-Javadoc)
* @see com.badlogic.gdx.Game#resume()
*/
@Override
public void resume() {
Gdx.app.log( LOG, "Resuming game" );
super.resume();
}
/* (non-Javadoc)
* @see com.badlogic.gdx.Game#resize(int, int)
*/
@Override
public void resize(int width, int height) {
super.resize( width, height );
Gdx.app.log( LOG, "Resizing game to: " + width + " x " + height );
// show the splash screen when the game is resized for the first time
if( getScreen() == null ) {
super.setScreen( new SplashScreen( this ) );
}
}
/* (non-Javadoc)
* @see com.badlogic.gdx.Game#dispose()
*/
@Override
public void dispose() {
Gdx.app.log( LOG, "Disposing game" );
super.dispose();
disposeInputProcessors();
}
}
| 5,175 | 0.655019 | 0.649421 | 204 | 24.392157 | 22.140663 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.671569 | false | false | 0 |
be7b986b3ba027a186ad5465fc9751207a5dbfb8 | 10,350,871,234,161 | 0d0470285a029d060ff827fb7b29866c46353ad7 | /spring/src/test/java/net/shopin/web/rest/CancelOrderIntegrationTest.java | 16f299026e97f9af47fee4f63d34bbf9dca42d5c | []
| no_license | thushear/shopin-net | https://github.com/thushear/shopin-net | 63979041537e43a66275243601adf19c317b8b62 | 5931f3436acd0ed4e8f7094521890c30c3def423 | refs/heads/master | 2019-11-19T01:08:56.541000 | 2015-07-08T16:27:25 | 2015-07-08T16:27:25 | 38,762,764 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* @Probject Name: spring
* @Path: net.shopin.web.rest.CancelOrderIntegrationTest.java
* @Create By kongm
* @Create In 2013-11-29 下午5:43:10
* TODO
*//*
package net.shopin.web.rest;
import java.util.UUID;
import net.shopin.events.orders.DeleteOrderEvent;
import net.shopin.services.OrderService;
import net.shopin.web.rest.fixture.RestEventFixtures;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
*//**
* @Class Name CancelOrderIntegrationTest
* @Author kongm
* @Create In 2013-11-29
*//*
public class CancelOrderIntegrationTest {
MockMvc mockMvc;
@InjectMocks
OrderCommandsController controller;
@Mock
OrderService orderService;
UUID key = UUID.fromString("f3512d26-72f6-4290-9265-63ad69eccc13");
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = standaloneSetup(controller).setMessageConverters(
new MappingJackson2HttpMessageConverter()).build();
}
// {!begin thatDeleteOrderUsesHttpOkOnSuccess}
@Test
public void thatDeleteOrderUsesHttpOkOnSuccess() throws Exception{
when(orderService.deleteOrder(any(DeleteOrderEvent.class)))
.thenReturn(RestEventFixtures.orderDeleted(key));
this.mockMvc.perform(
delete("/orders/${id}", key.toString())
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk());
}
}
*/ | UTF-8 | Java | 2,145 | java | CancelOrderIntegrationTest.java | Java | [
{
"context": "est.CancelOrderIntegrationTest.java\r\n * @Create By kongm\r\n * @Create In 2013-11-29 下午5:43:10\r\n * TODO\r\n */",
"end": 114,
"score": 0.9993783831596375,
"start": 109,
"tag": "USERNAME",
"value": "kongm"
},
{
"context": "@Class Name CancelOrderIntegrationTest\r\n * @Author kongm\r\n * @Create In 2013-11-29\r\n *//*\r\npublic class Ca",
"end": 1242,
"score": 0.9992809295654297,
"start": 1237,
"tag": "USERNAME",
"value": "kongm"
},
{
"context": "ice orderService;\r\n\r\n\tUUID key = UUID.fromString(\"f3512d26-72f6-4290-9265-63ad69eccc13\");\r\n\r\n\t@Before\r\n\tpublic void setup() {\r\n\t\tMockito",
"end": 1502,
"score": 0.9997565746307373,
"start": 1466,
"tag": "KEY",
"value": "f3512d26-72f6-4290-9265-63ad69eccc13"
}
]
| null | []
| /**
* @Probject Name: spring
* @Path: net.shopin.web.rest.CancelOrderIntegrationTest.java
* @Create By kongm
* @Create In 2013-11-29 下午5:43:10
* TODO
*//*
package net.shopin.web.rest;
import java.util.UUID;
import net.shopin.events.orders.DeleteOrderEvent;
import net.shopin.services.OrderService;
import net.shopin.web.rest.fixture.RestEventFixtures;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
*//**
* @Class Name CancelOrderIntegrationTest
* @Author kongm
* @Create In 2013-11-29
*//*
public class CancelOrderIntegrationTest {
MockMvc mockMvc;
@InjectMocks
OrderCommandsController controller;
@Mock
OrderService orderService;
UUID key = UUID.fromString("f3512d26-72f6-4290-9265-63ad69eccc13");
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = standaloneSetup(controller).setMessageConverters(
new MappingJackson2HttpMessageConverter()).build();
}
// {!begin thatDeleteOrderUsesHttpOkOnSuccess}
@Test
public void thatDeleteOrderUsesHttpOkOnSuccess() throws Exception{
when(orderService.deleteOrder(any(DeleteOrderEvent.class)))
.thenReturn(RestEventFixtures.orderDeleted(key));
this.mockMvc.perform(
delete("/orders/${id}", key.toString())
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk());
}
}
*/ | 2,145 | 0.760392 | 0.738907 | 73 | 27.356165 | 25.516779 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.013699 | false | false | 0 |
18c2f5f884fa707a088f058c123b8942bd84fe2b | 26,036,091,791,268 | d6f043550224113e78c880e1b874cba2665ca63c | /src/niveles/fabricas/FabricaDeTandas.java | 8665e846cfbb406a55effbf9750514c1e40f4660 | []
| no_license | santozzi/Proyecto3-TDP-DrApocalipsis | https://github.com/santozzi/Proyecto3-TDP-DrApocalipsis | 8608bb5a724a3c93ce4b3543377797f3d6d1d37b | 547d2ca88b1d0712c93d7fe64b6c67e0b1f2fe3d | refs/heads/master | 2023-06-01T09:08:43.803000 | 2021-06-27T02:08:58 | 2021-06-27T02:08:58 | 308,643,779 | 6 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package niveles.fabricas;
import java.awt.Point;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import entidades.Entidad;
import entidades.personajes.infectados.Infectado;
import logica.Juego;
import niveles.Nivel;
public abstract class FabricaDeTandas {
protected Juego juego;
protected int cantidadInfectados;
protected Nivel nivel;
protected List<Point> posiciones;
public FabricaDeTandas(Juego j, Nivel nivel, int cantInfectados) {
this.juego = j;
this.cantidadInfectados = cantInfectados;
this.nivel = nivel;
}
/**
* Creo una tanda con los parametros que me mandaron
* -------------------------------------------------
* @param cantidadInfectados : cantidad de infectados que voy a insertar en la nueva tanda
* @param tipoInfectado : tipo de infectado que voy a crear
* @param modulo : velocidad de los infectados que creo
* @param limiteEnY : limite donde voy a definir que tanto espacio en el mapa ocupa la tanda de infactados
*
*/
protected void crearTanda(int cantidadInfectados, Infectado tipoInfectado,int modulo, int limiteEnY) {
Point posicion;
Infectado nuevoInfectado = null;
Random random = new Random();
posiciones = new LinkedList<Point>();
List<Entidad> compositeInfectados = this.nivel.getColeccionDeInfectados().getListaDeInfectados();
for(int i=0 ; i<cantidadInfectados ; i++) {
nuevoInfectado =tipoInfectado.clone();
posicion = asignarPosicion(
posiciones,
nuevoInfectado.getImagen().getIconWidth(),
nuevoInfectado.getImagen().getIconHeight(),
random.nextInt(Juego.ANCHO_DE_COMBATE-nuevoInfectado.getImagen().getIconWidth()),
random.nextInt(limiteEnY),
random,
limiteEnY);
if(posicion!=null) {
posiciones.add(posicion);
if(juego.getLimite().y>=posicion.y)
juego.getLimite().y = posicion.y - nuevoInfectado.getImagen().getIconHeight();
nuevoInfectado.setPosicion(posicion.x, - posicion.y - nuevoInfectado.getImagen().getIconHeight());
nuevoInfectado.getVector().setModulo(modulo);
compositeInfectados.add(nuevoInfectado);
}
}
}
/**
* Busca una posicion libre en el mapa para insertar a un nuevo infectado
* ----------------------------------------------------------------------
* @param posiciones : lista donde guardo todas las posiciones en donde inserte a los infectados
* @param anchoInfectado : ancho que ocupa un infectado en el mapa
* @param altoInfectado : alto que ocupa un infectado en el mapa
* @param x : posicion en x a testear
* @param y : posicion en y a testear
* @param random : Random que voy a utilizar para crear una posicion aleatoria
* @param limiteEnY : limite donde voy a definir que tanto espacio en el mapa ocupa la tanda de infactados
* @return Posicion en el mapa donde voy a insertar al nuevo infectado
*/
private Point asignarPosicion(List<Point> posiciones, int anchoInfectado, int altoInfectado, int x, int y, Random random, int limiteEnY) {
Iterator<Point> itPosiciones;
Point aRetornar =null;
Point elem;
boolean estaInsertado = false;
itPosiciones = posiciones.iterator();
while(itPosiciones.hasNext() && !estaInsertado) {
elem = itPosiciones.next();
estaInsertado = (x <= (elem.x + anchoInfectado) && x >= (elem.x - anchoInfectado))
&& (y <= (elem.y + altoInfectado) && y >= (elem.y - altoInfectado));
}
if(estaInsertado)
aRetornar = asignarPosicion(posiciones, anchoInfectado, altoInfectado, random.nextInt(Juego.ANCHO_DE_COMBATE-anchoInfectado), random.nextInt(limiteEnY), random, limiteEnY);
else
aRetornar = new Point(x, y);
return aRetornar;
}
/**
* Creo la primera tanda
*/
abstract public void primeraTanda();
/**
* Creo la segunda tanda
*/
abstract public void segundaTanda();
/**
* Creo la tanda del jefe
*/
abstract public void elJefe();
}
| UTF-8 | Java | 3,934 | java | FabricaDeTandas.java | Java | []
| null | []
| package niveles.fabricas;
import java.awt.Point;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import entidades.Entidad;
import entidades.personajes.infectados.Infectado;
import logica.Juego;
import niveles.Nivel;
public abstract class FabricaDeTandas {
protected Juego juego;
protected int cantidadInfectados;
protected Nivel nivel;
protected List<Point> posiciones;
public FabricaDeTandas(Juego j, Nivel nivel, int cantInfectados) {
this.juego = j;
this.cantidadInfectados = cantInfectados;
this.nivel = nivel;
}
/**
* Creo una tanda con los parametros que me mandaron
* -------------------------------------------------
* @param cantidadInfectados : cantidad de infectados que voy a insertar en la nueva tanda
* @param tipoInfectado : tipo de infectado que voy a crear
* @param modulo : velocidad de los infectados que creo
* @param limiteEnY : limite donde voy a definir que tanto espacio en el mapa ocupa la tanda de infactados
*
*/
protected void crearTanda(int cantidadInfectados, Infectado tipoInfectado,int modulo, int limiteEnY) {
Point posicion;
Infectado nuevoInfectado = null;
Random random = new Random();
posiciones = new LinkedList<Point>();
List<Entidad> compositeInfectados = this.nivel.getColeccionDeInfectados().getListaDeInfectados();
for(int i=0 ; i<cantidadInfectados ; i++) {
nuevoInfectado =tipoInfectado.clone();
posicion = asignarPosicion(
posiciones,
nuevoInfectado.getImagen().getIconWidth(),
nuevoInfectado.getImagen().getIconHeight(),
random.nextInt(Juego.ANCHO_DE_COMBATE-nuevoInfectado.getImagen().getIconWidth()),
random.nextInt(limiteEnY),
random,
limiteEnY);
if(posicion!=null) {
posiciones.add(posicion);
if(juego.getLimite().y>=posicion.y)
juego.getLimite().y = posicion.y - nuevoInfectado.getImagen().getIconHeight();
nuevoInfectado.setPosicion(posicion.x, - posicion.y - nuevoInfectado.getImagen().getIconHeight());
nuevoInfectado.getVector().setModulo(modulo);
compositeInfectados.add(nuevoInfectado);
}
}
}
/**
* Busca una posicion libre en el mapa para insertar a un nuevo infectado
* ----------------------------------------------------------------------
* @param posiciones : lista donde guardo todas las posiciones en donde inserte a los infectados
* @param anchoInfectado : ancho que ocupa un infectado en el mapa
* @param altoInfectado : alto que ocupa un infectado en el mapa
* @param x : posicion en x a testear
* @param y : posicion en y a testear
* @param random : Random que voy a utilizar para crear una posicion aleatoria
* @param limiteEnY : limite donde voy a definir que tanto espacio en el mapa ocupa la tanda de infactados
* @return Posicion en el mapa donde voy a insertar al nuevo infectado
*/
private Point asignarPosicion(List<Point> posiciones, int anchoInfectado, int altoInfectado, int x, int y, Random random, int limiteEnY) {
Iterator<Point> itPosiciones;
Point aRetornar =null;
Point elem;
boolean estaInsertado = false;
itPosiciones = posiciones.iterator();
while(itPosiciones.hasNext() && !estaInsertado) {
elem = itPosiciones.next();
estaInsertado = (x <= (elem.x + anchoInfectado) && x >= (elem.x - anchoInfectado))
&& (y <= (elem.y + altoInfectado) && y >= (elem.y - altoInfectado));
}
if(estaInsertado)
aRetornar = asignarPosicion(posiciones, anchoInfectado, altoInfectado, random.nextInt(Juego.ANCHO_DE_COMBATE-anchoInfectado), random.nextInt(limiteEnY), random, limiteEnY);
else
aRetornar = new Point(x, y);
return aRetornar;
}
/**
* Creo la primera tanda
*/
abstract public void primeraTanda();
/**
* Creo la segunda tanda
*/
abstract public void segundaTanda();
/**
* Creo la tanda del jefe
*/
abstract public void elJefe();
}
| 3,934 | 0.695984 | 0.69573 | 119 | 32.058823 | 33.186081 | 175 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.319328 | false | false | 0 |
3a22a0775b1f46786f64bad2e130885c444f8dbe | 8,899,172,301,593 | 3a5985651d77a31437cfdac25e594087c27e93d6 | /ojc-core/imsbc/imsbcimpl/src/com/sun/jbi/imsbc/ReplyContext.java | da1d198894df0a4b07cd3d742634feea7d5aaff8 | []
| no_license | vitalif/openesb-components | https://github.com/vitalif/openesb-components | a37d62133d81edb3fdc091abd5c1d72dbe2fc736 | 560910d2a1fdf31879e3d76825edf079f76812c7 | refs/heads/master | 2023-09-04T14:40:55.665000 | 2016-01-25T13:12:22 | 2016-01-25T13:12:33 | 48,222,841 | 0 | 5 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* BEGIN_HEADER - DO NOT EDIT
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the "License"). You may not use this file except
* in compliance with the License.
*
* You can obtain a copy of the license at
* https://open-jbi-components.dev.java.net/public/CDDLv1.0.html.
* See the License for the specific language governing
* permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL
* HEADER in each file and include the License file at
* https://open-jbi-components.dev.java.net/public/CDDLv1.0.html.
* If applicable add the following below this CDDL HEADER,
* with the fields enclosed by brackets "[]" replaced with
* your own identifying information: Portions Copyright
* [year] [name of copyright owner]
*/
package com.sun.jbi.imsbc;
import javax.xml.namespace.QName;
import com.sun.jbi.imsbc.extensions.IMSInput;
import com.sun.jbi.imsbc.extensions.IMSOutput;
import com.sun.jbi.imsbc.extensions.IMSMessage;
import com.sun.jbi.imsbc.extensions.IMSOperation;
/**
* Class to hold message exchange context for IMS message reply
*
* @author Sun Microsystems
*/
public class ReplyContext {
private IMSMessage imsMessage;
private IMSOperation imsOp;
private QName bindingOpQName;
private IMSInput imsIn;
private IMSOutput imsOut;
public ReplyContext(IMSMessage imsMessage, QName bindingOpQName, IMSOperation imsOp, IMSInput imsIn,
IMSOutput imsOut) {
this.imsMessage = imsMessage;
this.bindingOpQName = bindingOpQName;
this.imsOp = imsOp;
this.imsIn = imsIn;
this.imsOut = imsOut;
}
public IMSMessage getIMSMessage() {
return imsMessage;
}
public QName getBindingOperationQName() {
return bindingOpQName;
}
public IMSOperation getIMSOperation() {
return imsOp;
}
public IMSInput getIMSInput() {
return imsIn;
}
public IMSOutput getIMSOutput() {
return imsOut;
}
}
| UTF-8 | Java | 2,075 | java | ReplyContext.java | Java | [
{
"context": "hange context for IMS message reply\n * \n * @author Sun Microsystems\n */\npublic class ReplyContext {\n\n private IMSM",
"end": 1197,
"score": 0.717356264591217,
"start": 1181,
"tag": "NAME",
"value": "Sun Microsystems"
}
]
| null | []
| /*
* BEGIN_HEADER - DO NOT EDIT
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the "License"). You may not use this file except
* in compliance with the License.
*
* You can obtain a copy of the license at
* https://open-jbi-components.dev.java.net/public/CDDLv1.0.html.
* See the License for the specific language governing
* permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL
* HEADER in each file and include the License file at
* https://open-jbi-components.dev.java.net/public/CDDLv1.0.html.
* If applicable add the following below this CDDL HEADER,
* with the fields enclosed by brackets "[]" replaced with
* your own identifying information: Portions Copyright
* [year] [name of copyright owner]
*/
package com.sun.jbi.imsbc;
import javax.xml.namespace.QName;
import com.sun.jbi.imsbc.extensions.IMSInput;
import com.sun.jbi.imsbc.extensions.IMSOutput;
import com.sun.jbi.imsbc.extensions.IMSMessage;
import com.sun.jbi.imsbc.extensions.IMSOperation;
/**
* Class to hold message exchange context for IMS message reply
*
* @author <NAME>
*/
public class ReplyContext {
private IMSMessage imsMessage;
private IMSOperation imsOp;
private QName bindingOpQName;
private IMSInput imsIn;
private IMSOutput imsOut;
public ReplyContext(IMSMessage imsMessage, QName bindingOpQName, IMSOperation imsOp, IMSInput imsIn,
IMSOutput imsOut) {
this.imsMessage = imsMessage;
this.bindingOpQName = bindingOpQName;
this.imsOp = imsOp;
this.imsIn = imsIn;
this.imsOut = imsOut;
}
public IMSMessage getIMSMessage() {
return imsMessage;
}
public QName getBindingOperationQName() {
return bindingOpQName;
}
public IMSOperation getIMSOperation() {
return imsOp;
}
public IMSInput getIMSInput() {
return imsIn;
}
public IMSOutput getIMSOutput() {
return imsOut;
}
}
| 2,065 | 0.706506 | 0.704578 | 78 | 25.602564 | 22.857609 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.346154 | false | false | 0 |
bd82166bae5d4bcf7199cbbb322a357614c33280 | 32,658,931,381,107 | 1e29841b24ed4bf0ce191b8ce4bacd5e5f55beaa | /src/main/java/model/Suit.java | d63d1d369808272ad5799ba5c150694e7b86b076 | []
| no_license | wonhs91/BlackJack | https://github.com/wonhs91/BlackJack | 0599a4e65725a881c8a7d0651fa17ec4d27b2e8c | 2382c31c6e39bd4716590ac5ee5e72ec4f78632c | refs/heads/master | 2021-01-22T12:17:45.741000 | 2017-10-05T02:44:01 | 2017-10-05T02:44:01 | 92,712,995 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package main.java.model;
/**
* Created by stephen on 5/29/17.
*/
public enum Suit {
DIAMOND,
CLUB,
HEART,
SPADE;
}
| UTF-8 | Java | 134 | java | Suit.java | Java | [
{
"context": "package main.java.model;\n\n/**\n * Created by stephen on 5/29/17.\n */\npublic enum Suit {\n DIAMOND,\n ",
"end": 51,
"score": 0.9748800992965698,
"start": 44,
"tag": "USERNAME",
"value": "stephen"
}
]
| null | []
| package main.java.model;
/**
* Created by stephen on 5/29/17.
*/
public enum Suit {
DIAMOND,
CLUB,
HEART,
SPADE;
}
| 134 | 0.58209 | 0.544776 | 11 | 11.181818 | 9.805548 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 0 |
c91f2639adf93f7b1a4aacb0407eec6ebd50273e | 32,152,125,226,468 | f432df303b8ad007a3a73ed9de58fc1273ad22b2 | /app/src/main/java/edu/orangecoastcollege/cs273/vnguyen629/occlostandfound/ItemDetailsActivity.java | f1b41e56828859a20944290328666fea9f464051 | []
| no_license | vhnguyen1/OCCLostandFound | https://github.com/vhnguyen1/OCCLostandFound | 9f001504daa6d47ae60dce90bfaba5d4683f2767 | 8de81c2276c6c9736377013e4802e3e436f6653c | refs/heads/master | 2021-06-09T15:50:12.092000 | 2016-12-13T20:42:12 | 2016-12-13T20:42:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.orangecoastcollege.cs273.vnguyen629.occlostandfound;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Loads intent data from the ItemListActivity, displaying the selected
* item's data more specifically
*
* @author Vu Nguyen
*/
public class ItemDetailsActivity extends AppCompatActivity {
private ImageView itemDetailsImageView;
private TextView itemDetailsNameTextView;
private TextView itemDetailsDateLostTextView;
private TextView itemDetailsLocationTextView;
private TextView itemDetailsDescriptionTextView;
private TextView itemDetailsStatusTextView;
private Sensor accelerometer;
private SensorManager sensorManager;
private ShakeDetector shakeDetector;
/**
* Starts up the activity and loads up the intent data from the ItemListActivity
* that the user selects from the ListView, displaying the data. It also
* prepares the ShakeDetector to monitor any movements that constitute as shakes
* where the ListItemActivity may load up if found.
* @param savedInstanceState The state of the application saved into a bundle.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_details);
final Item ITEM = getIntent().getExtras().getParcelable("Selected");
itemDetailsImageView = (ImageView) findViewById(R.id.itemDetailsImageView);
itemDetailsNameTextView = (TextView) findViewById(R.id.itemDetailsNameTextView);
itemDetailsDateLostTextView = (TextView) findViewById(R.id.itemDetailsDateLostTextView);
itemDetailsLocationTextView = (TextView) findViewById(R.id.itemDetailsLocationTextView);
itemDetailsDescriptionTextView = (TextView) findViewById(R.id.itemDetailsDescriptionTextView);
itemDetailsStatusTextView = (TextView) findViewById(R.id.itemDetailsStatusTextView);
itemDetailsImageView.setImageURI(ITEM.getImageUri());
itemDetailsNameTextView.setText(ITEM.getName());
itemDetailsDescriptionTextView.setText(ITEM.getDescription());
itemDetailsDateLostTextView.setText(ITEM.getDateLost());
itemDetailsLocationTextView.setText(ITEM.getLastLocation());
itemDetailsStatusTextView.setText((ITEM.getStatus())? getString(R.string.found_text)
: getString(R.string.not_found_text));
if (ITEM.getStatus())
itemDetailsStatusTextView.setTextColor(getResources().getColorStateList(R.color.green));
else
itemDetailsStatusTextView.setTextColor(getResources().getColorStateList(R.color.red));
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
shakeDetector = new ShakeDetector(new ShakeDetector.OnShakeListener() {
/**
* When a 3D motion that the sensors constitute as a shake has been detected,
* the ItemListActivity is loaded
*/
@Override
public void onShake() {
startActivity(new Intent(ItemDetailsActivity.this, ItemsListActivity.class));
}
});
}
/**
* When the user re-enters the app, the sensors start back up and begin
* monitoring device movements/g-forces in a 3D (x-y-z) span.
*/
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(shakeDetector, accelerometer,
SensorManager.SENSOR_DELAY_UI);
}
/**
* When the user switches apps or clicks on the home button without closing the app,
* all the sensors that monitor device movements and g-forces are then paused
* to preserve battery life.
*/
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(shakeDetector);
}
} | UTF-8 | Java | 4,187 | java | ItemDetailsActivity.java | Java | [
{
"context": "ted\n * item's data more specifically\n *\n * @author Vu Nguyen\n */\npublic class ItemDetailsActivity extends AppC",
"end": 473,
"score": 0.9998534321784973,
"start": 464,
"tag": "NAME",
"value": "Vu Nguyen"
}
]
| null | []
| package edu.orangecoastcollege.cs273.vnguyen629.occlostandfound;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Loads intent data from the ItemListActivity, displaying the selected
* item's data more specifically
*
* @author <NAME>
*/
public class ItemDetailsActivity extends AppCompatActivity {
private ImageView itemDetailsImageView;
private TextView itemDetailsNameTextView;
private TextView itemDetailsDateLostTextView;
private TextView itemDetailsLocationTextView;
private TextView itemDetailsDescriptionTextView;
private TextView itemDetailsStatusTextView;
private Sensor accelerometer;
private SensorManager sensorManager;
private ShakeDetector shakeDetector;
/**
* Starts up the activity and loads up the intent data from the ItemListActivity
* that the user selects from the ListView, displaying the data. It also
* prepares the ShakeDetector to monitor any movements that constitute as shakes
* where the ListItemActivity may load up if found.
* @param savedInstanceState The state of the application saved into a bundle.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_details);
final Item ITEM = getIntent().getExtras().getParcelable("Selected");
itemDetailsImageView = (ImageView) findViewById(R.id.itemDetailsImageView);
itemDetailsNameTextView = (TextView) findViewById(R.id.itemDetailsNameTextView);
itemDetailsDateLostTextView = (TextView) findViewById(R.id.itemDetailsDateLostTextView);
itemDetailsLocationTextView = (TextView) findViewById(R.id.itemDetailsLocationTextView);
itemDetailsDescriptionTextView = (TextView) findViewById(R.id.itemDetailsDescriptionTextView);
itemDetailsStatusTextView = (TextView) findViewById(R.id.itemDetailsStatusTextView);
itemDetailsImageView.setImageURI(ITEM.getImageUri());
itemDetailsNameTextView.setText(ITEM.getName());
itemDetailsDescriptionTextView.setText(ITEM.getDescription());
itemDetailsDateLostTextView.setText(ITEM.getDateLost());
itemDetailsLocationTextView.setText(ITEM.getLastLocation());
itemDetailsStatusTextView.setText((ITEM.getStatus())? getString(R.string.found_text)
: getString(R.string.not_found_text));
if (ITEM.getStatus())
itemDetailsStatusTextView.setTextColor(getResources().getColorStateList(R.color.green));
else
itemDetailsStatusTextView.setTextColor(getResources().getColorStateList(R.color.red));
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
shakeDetector = new ShakeDetector(new ShakeDetector.OnShakeListener() {
/**
* When a 3D motion that the sensors constitute as a shake has been detected,
* the ItemListActivity is loaded
*/
@Override
public void onShake() {
startActivity(new Intent(ItemDetailsActivity.this, ItemsListActivity.class));
}
});
}
/**
* When the user re-enters the app, the sensors start back up and begin
* monitoring device movements/g-forces in a 3D (x-y-z) span.
*/
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(shakeDetector, accelerometer,
SensorManager.SENSOR_DELAY_UI);
}
/**
* When the user switches apps or clicks on the home button without closing the app,
* all the sensors that monitor device movements and g-forces are then paused
* to preserve battery life.
*/
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(shakeDetector);
}
} | 4,184 | 0.72128 | 0.719131 | 99 | 41.303032 | 31.745342 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.515152 | false | false | 0 |
4f913e62cf89ef4269a34c40f2ef57a85e95f32b | 36,060,545,426,190 | 274e5fcef1659a6c12de0e3a5ddc7d5763fc62cd | /src/main/java/shared/entity/AppDish.java | 6661a685c6c4cec9f35bacd99d00fe377c829415 | []
| no_license | CotletkaMan/Dish | https://github.com/CotletkaMan/Dish | 2ee507920d7def220f0e1285218c2611eea042e6 | dc1c276882f0f45cd8a3c5064cd030a74e950dc6 | refs/heads/master | 2016-08-13T01:36:33.389000 | 2016-02-07T08:48:14 | 2016-02-07T08:48:14 | 51,241,291 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package shared.entity;
import javax.persistence.*;
/**
* Created by cotletkaman on 02.02.16.
*/
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class AppDish extends Statistics{
private Long id;
private Dish dish;
public AppDish(){}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId(){
return id;
}
public void setId(Long id){
this.id = id;
}
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "dish_fk" , nullable = false)
public Dish getDish(){
return dish;
}
public void setDish(Dish dish){
this.dish = dish;
}
}
| UTF-8 | Java | 674 | java | AppDish.java | Java | [
{
"context": "y;\n\nimport javax.persistence.*;\n\n/**\n * Created by cotletkaman on 02.02.16.\n */\n@Entity\n@Inheritance(strategy = ",
"end": 82,
"score": 0.999676525592804,
"start": 71,
"tag": "USERNAME",
"value": "cotletkaman"
}
]
| null | []
| package shared.entity;
import javax.persistence.*;
/**
* Created by cotletkaman on 02.02.16.
*/
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class AppDish extends Statistics{
private Long id;
private Dish dish;
public AppDish(){}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId(){
return id;
}
public void setId(Long id){
this.id = id;
}
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "dish_fk" , nullable = false)
public Dish getDish(){
return dish;
}
public void setDish(Dish dish){
this.dish = dish;
}
}
| 674 | 0.626113 | 0.617211 | 39 | 16.282051 | 16.943268 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.230769 | false | false | 0 |
d30c4be8922e1a25100175f4d99b15d207290447 | 34,668,976,036,755 | 2944ff98721d83c0a11a5cb0ad19d774e9ae0d9f | /src/main/java/com/mateuszmedon/project/jsprestaurant/database/HibernateUtil.java | 42889fe29bc049df6983fff9aa94251e071df8d0 | []
| no_license | Morpheush333/jsprestaurant | https://github.com/Morpheush333/jsprestaurant | e0fd222d12826e949455df838a007a5f144400ad | da543ee4e58e8bd26851725aaebb59cd3224bdef | refs/heads/master | 2022-07-07T06:28:58.836000 | 2019-09-11T18:37:01 | 2019-09-11T18:37:01 | 207,874,518 | 1 | 0 | null | false | 2022-06-21T01:51:20 | 2019-09-11T17:59:50 | 2019-09-11T18:38:41 | 2022-06-21T01:51:19 | 16 | 1 | 0 | 3 | Java | false | false | package com.mateuszmedon.project.jsprestaurant.database;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
// load only once when class is init
// Created object which take config from the hibernate cfg xml
StandardServiceRegistry standardServiceRegistry = // object load to properties only take XML file
new StandardServiceRegistryBuilder()
.configure("hibernate.cfg.xml").build();
// metadata this is info about files. From data load before
// created object metadata
Metadata metadata = new MetadataSources(standardServiceRegistry)
.getMetadataBuilder().build();
// created session with data include hibernate cfg xml file
sessionFactory = metadata.getSessionFactoryBuilder().build();
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
| UTF-8 | Java | 1,274 | java | HibernateUtil.java | Java | []
| null | []
| package com.mateuszmedon.project.jsprestaurant.database;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
// load only once when class is init
// Created object which take config from the hibernate cfg xml
StandardServiceRegistry standardServiceRegistry = // object load to properties only take XML file
new StandardServiceRegistryBuilder()
.configure("hibernate.cfg.xml").build();
// metadata this is info about files. From data load before
// created object metadata
Metadata metadata = new MetadataSources(standardServiceRegistry)
.getMetadataBuilder().build();
// created session with data include hibernate cfg xml file
sessionFactory = metadata.getSessionFactoryBuilder().build();
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
| 1,274 | 0.678179 | 0.678179 | 33 | 37.575756 | 30.036373 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 0 |
b2c671ef8d918d618fac09680b9e1a5e5ede5c14 | 31,756,988,228,970 | 918f64663522d16f222567ed9e0691d357dbe854 | /src/THFrame/StudentModify.java | 28c0a99ace3e470eb281ebef07cca1bb8bb13415 | []
| no_license | buituanson85/JavaSwing | https://github.com/buituanson85/JavaSwing | 4b70c2f1aba47053b579077be6ed2886550a0470 | 7c2cb138433b1b6e2b4124218b04f4ebf320b03e | refs/heads/master | 2023-02-15T12:09:55.742000 | 2021-01-07T20:42:12 | 2021-01-07T20:42:12 | 327,715,169 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 THFrame;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
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;
/**
*
* @author Admin
*/
public class StudentModify {
public static List<Student> findAll(){
// hàm lấy ra tất cả danh sách sinh viên
List<Student> studentList = new ArrayList<>();
Connection connection = null;
Statement statement = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "");
String findSQL = "select * from student";
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(findSQL);
while (resultSet.next()) {
Student student = new Student(
resultSet.getInt("id"),
resultSet.getString("fullName"),
resultSet.getString("gender"),
resultSet.getInt("age"),
resultSet.getString("email"),
resultSet.getString("phone"));
studentList.add(student);
}
} catch (Exception e) {
}finally{
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//keets thucs
return studentList;
}
public static void insert(Student student){
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "");
String insertSQL = "insert into student( fullName, gender, age, email, phone) values( ?, ?, ?, ?, ?)";
preparedStatement = connection.prepareStatement(insertSQL);
preparedStatement.setString(1, student.getFullName());
preparedStatement.setString(2, student.getGender());
preparedStatement.setInt(3, student.getAge());
preparedStatement.setString(4, student.getEmail());
preparedStatement.setString(5, student.getPhoneNumber());
preparedStatement.execute();
System.out.println("Luwu thanh cong");
} catch (Exception e) {
}finally{
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(connection != null){
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static void update(Student student){
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "");
String updateSQL = "update student set fullName = ?, gender = ?, age = ?, email = ?, phone = ? where id = ?";
preparedStatement = connection.prepareStatement(updateSQL);
preparedStatement.setString(1, student.getFullName());
preparedStatement.setString(2, student.getGender());
preparedStatement.setInt(3, student.getAge());
preparedStatement.setString(4, student.getEmail());
preparedStatement.setString(5, student.getPhoneNumber());
preparedStatement.setInt(6, student.getId());
preparedStatement.execute();
System.out.println("update thanh cong");
} catch (Exception e) {
}finally{
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static void delete(int id){
Connection connection = null;
PreparedStatement preparedStatement =null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "");
String deleteSQL = "delete from student where id = ?";
preparedStatement = connection.prepareStatement(deleteSQL);
preparedStatement.setInt(1, id);
preparedStatement.execute();
System.out.println("delete thanh cong");
} catch (Exception e) {
}finally{
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static List<Student> searchByName(String fullName){
List<Student> studentList = new ArrayList<>();
Connection connection = null;
PreparedStatement preparedStatement = null;
//những câu truy vấn nào có dữ liệu đưa từ msql vào thì ta dùng PreparedStatement
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "");
String searchSQL = "select * from student where fullName like ?";
preparedStatement = connection.prepareStatement(searchSQL);
preparedStatement.setString(1, "%" + fullName + "%");
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Student student = new Student(
resultSet.getInt("id"),
resultSet.getString("fullName"),
resultSet.getString("gender"),
resultSet.getInt("age"),
resultSet.getString("email"),
resultSet.getString("phone"));
studentList.add(student);
}
} catch (Exception e) {
}finally{
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return studentList;
}
public static List<Student> saveInfoToTextFile(){
List<Student> studentList = new ArrayList<>();
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("D:\\JavaSwing\\JavaSwing\\src\\THFrame\\student.dat");
oos = new ObjectOutputStream(fos);
oos.writeObject(studentList);
} catch (Exception e) {
}finally{
if (fos != null) {
try {
fos.close();
} catch (IOException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (oos != null) {
try {
oos.close();
} catch (IOException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return studentList;
}
}
| UTF-8 | Java | 9,739 | java | StudentModify.java | Java | [
{
"context": "mport java.util.logging.Logger;\n\n/**\n *\n * @author Admin\n */\npublic class StudentModify {\n \n public ",
"end": 721,
"score": 0.7723916172981262,
"start": 716,
"tag": "USERNAME",
"value": "Admin"
}
]
| null | []
| /*
* 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 THFrame;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
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;
/**
*
* @author Admin
*/
public class StudentModify {
public static List<Student> findAll(){
// hàm lấy ra tất cả danh sách sinh viên
List<Student> studentList = new ArrayList<>();
Connection connection = null;
Statement statement = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "");
String findSQL = "select * from student";
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(findSQL);
while (resultSet.next()) {
Student student = new Student(
resultSet.getInt("id"),
resultSet.getString("fullName"),
resultSet.getString("gender"),
resultSet.getInt("age"),
resultSet.getString("email"),
resultSet.getString("phone"));
studentList.add(student);
}
} catch (Exception e) {
}finally{
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//keets thucs
return studentList;
}
public static void insert(Student student){
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "");
String insertSQL = "insert into student( fullName, gender, age, email, phone) values( ?, ?, ?, ?, ?)";
preparedStatement = connection.prepareStatement(insertSQL);
preparedStatement.setString(1, student.getFullName());
preparedStatement.setString(2, student.getGender());
preparedStatement.setInt(3, student.getAge());
preparedStatement.setString(4, student.getEmail());
preparedStatement.setString(5, student.getPhoneNumber());
preparedStatement.execute();
System.out.println("Luwu thanh cong");
} catch (Exception e) {
}finally{
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(connection != null){
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static void update(Student student){
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "");
String updateSQL = "update student set fullName = ?, gender = ?, age = ?, email = ?, phone = ? where id = ?";
preparedStatement = connection.prepareStatement(updateSQL);
preparedStatement.setString(1, student.getFullName());
preparedStatement.setString(2, student.getGender());
preparedStatement.setInt(3, student.getAge());
preparedStatement.setString(4, student.getEmail());
preparedStatement.setString(5, student.getPhoneNumber());
preparedStatement.setInt(6, student.getId());
preparedStatement.execute();
System.out.println("update thanh cong");
} catch (Exception e) {
}finally{
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static void delete(int id){
Connection connection = null;
PreparedStatement preparedStatement =null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "");
String deleteSQL = "delete from student where id = ?";
preparedStatement = connection.prepareStatement(deleteSQL);
preparedStatement.setInt(1, id);
preparedStatement.execute();
System.out.println("delete thanh cong");
} catch (Exception e) {
}finally{
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static List<Student> searchByName(String fullName){
List<Student> studentList = new ArrayList<>();
Connection connection = null;
PreparedStatement preparedStatement = null;
//những câu truy vấn nào có dữ liệu đưa từ msql vào thì ta dùng PreparedStatement
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "");
String searchSQL = "select * from student where fullName like ?";
preparedStatement = connection.prepareStatement(searchSQL);
preparedStatement.setString(1, "%" + fullName + "%");
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Student student = new Student(
resultSet.getInt("id"),
resultSet.getString("fullName"),
resultSet.getString("gender"),
resultSet.getInt("age"),
resultSet.getString("email"),
resultSet.getString("phone"));
studentList.add(student);
}
} catch (Exception e) {
}finally{
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return studentList;
}
public static List<Student> saveInfoToTextFile(){
List<Student> studentList = new ArrayList<>();
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("D:\\JavaSwing\\JavaSwing\\src\\THFrame\\student.dat");
oos = new ObjectOutputStream(fos);
oos.writeObject(studentList);
} catch (Exception e) {
}finally{
if (fos != null) {
try {
fos.close();
} catch (IOException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (oos != null) {
try {
oos.close();
} catch (IOException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return studentList;
}
}
| 9,739 | 0.521417 | 0.518019 | 259 | 36.49807 | 26.294937 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.671815 | false | false | 0 |
60a5538f644bb1db144b27b460847a67e9d1314d | 30,897,994,752,856 | 57c6268e82a78afd1af360fa5aa61a6d427a0d20 | /src/main/java/com/city/support/dataSet/query/dao/QueryRptDao.java | cd64e4667378c3da07c0a51770845ddeaf415710 | []
| no_license | wanddy/datacity | https://github.com/wanddy/datacity | a1bae75d595b7dfe869cd465433fd9d695129735 | 601db185fc74b44ade3e54950ef1f7913342eb53 | refs/heads/master | 2021-12-09T12:43:13.559000 | 2016-05-20T09:33:21 | 2016-05-20T09:33:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.city.support.dataSet.query.dao;
import com.city.common.dao.BaseDao;
import com.city.support.dataSet.query.pojo.TimePojo;
import com.city.support.regime.collection.entity.ReportData;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by wxl on 2016/3/5.
*/
@Repository
public class QueryRptDao extends BaseDao<ReportData> {
/**
* 根据sql从数据表中查询
*/
public List<ReportData> queryRptData(String sql) {
return queryBySql(sql, ReportData.class);
}
/**
* 根据sql从数据表中查询
*/
public List queryRptTime(String sql) {
return queryBySql(sql);
}
}
| UTF-8 | Java | 680 | java | QueryRptDao.java | Java | [
{
"context": "sitory;\n\nimport java.util.List;\n\n/**\n * Created by wxl on 2016/3/5.\n */\n@Repository\npublic class QueryRp",
"end": 291,
"score": 0.9993951320648193,
"start": 288,
"tag": "USERNAME",
"value": "wxl"
}
]
| null | []
| package com.city.support.dataSet.query.dao;
import com.city.common.dao.BaseDao;
import com.city.support.dataSet.query.pojo.TimePojo;
import com.city.support.regime.collection.entity.ReportData;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by wxl on 2016/3/5.
*/
@Repository
public class QueryRptDao extends BaseDao<ReportData> {
/**
* 根据sql从数据表中查询
*/
public List<ReportData> queryRptData(String sql) {
return queryBySql(sql, ReportData.class);
}
/**
* 根据sql从数据表中查询
*/
public List queryRptTime(String sql) {
return queryBySql(sql);
}
}
| 680 | 0.695652 | 0.686335 | 29 | 21.206896 | 20.499586 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.310345 | false | false | 0 |
f6277ca27c93e62d42c0fb08a6cb36e3830c39d2 | 35,364,760,729,691 | 83e30de5bf200ce5a86603d183b18367e2062dde | /app/src/main/java/com/mrc/appcadernofiado/helper/ClienteHelper.java | 1fa95be1fc68733277cae7635b94294bd5545777 | []
| no_license | fabiosilvaba82/cadernoFiado | https://github.com/fabiosilvaba82/cadernoFiado | 8f3554aeb995b871988a15607167ab7797822fd5 | 4e1c785e7e94866cceabca650f6065b71ea99c5e | refs/heads/master | 2020-09-15T18:46:01.166000 | 2019-11-23T04:58:45 | 2019-11-23T04:58:45 | 223,530,969 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mrc.appcadernofiado.helper;
import android.widget.EditText;
import com.mrc.appcadernofiado.fragments.ClienteFragment;
import com.mrc.appcadernofiado.model.Cliente;
public class ClienteHelper {
private Cliente cliente;
private EditText nome;
private EditText telefone;
public ClienteHelper(ClienteFragment cliente) { ;
this.telefone = telefone;
}
}
| UTF-8 | Java | 393 | java | ClienteHelper.java | Java | []
| null | []
| package com.mrc.appcadernofiado.helper;
import android.widget.EditText;
import com.mrc.appcadernofiado.fragments.ClienteFragment;
import com.mrc.appcadernofiado.model.Cliente;
public class ClienteHelper {
private Cliente cliente;
private EditText nome;
private EditText telefone;
public ClienteHelper(ClienteFragment cliente) { ;
this.telefone = telefone;
}
}
| 393 | 0.760814 | 0.760814 | 17 | 22.117647 | 19.565523 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.529412 | false | false | 0 |
6bf0a50c3c251f830f071c6b0324c3d0c57dbbf5 | 30,305,289,289,979 | c02e7fbe974cffa0677152fa5df1f5fb215d9000 | /myim-server/server-core/src/main/java/com/myim/server/api/dto/resp/UserRegisterRespDto.java | ceca01a5ab252eb834bc582be156f975b8ee9ac4 | [
"MIT"
]
| permissive | lanqiuchenjian/my-im | https://github.com/lanqiuchenjian/my-im | 61c1941086617427c1d2fd69b104fb98c41e72d8 | 8321aa540c362c43f754d05f5f0be9ec3d3e8f2d | refs/heads/master | 2023-04-10T15:43:21.201000 | 2021-04-20T05:57:19 | 2021-04-20T05:57:19 | 346,027,182 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.myim.server.api.dto.resp;
import com.myim.common.basepojo.BaseResponse;
import lombok.Data;
@Data
public class UserRegisterRespDto extends BaseResponse{
private Long registerImUserId;
private Long singleCategoryId;
}
| UTF-8 | Java | 239 | java | UserRegisterRespDto.java | Java | []
| null | []
| package com.myim.server.api.dto.resp;
import com.myim.common.basepojo.BaseResponse;
import lombok.Data;
@Data
public class UserRegisterRespDto extends BaseResponse{
private Long registerImUserId;
private Long singleCategoryId;
}
| 239 | 0.803347 | 0.803347 | 10 | 22.9 | 19.403351 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 0 |
6cfda54fd65a7c22e620399f4af733315c2e2f0a | 26,422,638,820,814 | f731826c7a8e371c77982ab20d1e83a46e88434a | /java/src/main/java/com/techelevator/Drink.java | f2258a05531275e73732e798809b6ac98705a7ff | []
| no_license | paz-mario-j/vending-machine | https://github.com/paz-mario-j/vending-machine | 3bdb1aedb50a5540a1d845aa2ce5b82be60c4fc1 | e67004af5170aae3c93d9f29d74a6a870f876274 | refs/heads/main | 2023-07-29T10:08:41.831000 | 2021-09-13T20:58:14 | 2021-09-13T20:58:14 | 399,220,385 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.techelevator;
import java.math.BigDecimal;
public class Drink extends Product {
public Drink(String slot, String name, BigDecimal price, int quantity) {
super(slot, name, price, quantity);
super.setSound("Glug glug yum!");
}
}
| UTF-8 | Java | 279 | java | Drink.java | Java | []
| null | []
| package com.techelevator;
import java.math.BigDecimal;
public class Drink extends Product {
public Drink(String slot, String name, BigDecimal price, int quantity) {
super(slot, name, price, quantity);
super.setSound("Glug glug yum!");
}
}
| 279 | 0.655914 | 0.655914 | 12 | 22.25 | 24.87343 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false | 0 |
82d50c8af9a9fc6c87bb995f971e21f7a5da1da0 | 23,648,089,935,098 | 4f87e72bae8909568b3e042856ef0f07c202aa32 | /java/test/src/my/test/javaBean/BeanUtilsTest.java | 29d8565b5ef568502ba960a3a457f10e45f56f64 | []
| no_license | soko8/MyWork | https://github.com/soko8/MyWork | 9543e96a9864aa89858d1affea9f66247bc163d4 | 53dd48fd2683d58028dbdbc61a0507b1203175ea | refs/heads/master | 2022-12-05T03:08:29.866000 | 2022-11-17T00:46:49 | 2022-11-17T00:46:49 | 60,009,810 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package my.test.javaBean;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
public class BeanUtilsTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestBean2 bean = new TestBean2();
List l = new ArrayList();
l.add("1");
l.add("2");
String[] arr = new String[]{"a", "b"};
Map m = new HashMap();
m.put("A", "3");
m.put("B", "4");
bean.setBeanUtilsTestArray(arr);
bean.setBeanUtilsTestList(l);
bean.setBeanUtilsTestMap(m);
bean.setItem("iii");
List l2 = new ArrayList();
TestBean subBean1 = new TestBean("s1", "100");
subBean1.setNestedTest("XXXXX");
l2.add(subBean1);
TestBean subBean2 = new TestBean("s2", "222");
l2.add(subBean2);
bean.setBeanUtilsTestIndexedList(l2);
/*************************************/
try {
System.err.println(BeanUtils.getProperty(bean, "item"));
System.err.println(BeanUtils.getNestedProperty(bean, "beanUtilsTestIndexedList[0].nestedTest"));
System.err.println(BeanUtils.getArrayProperty(bean, "beanUtilsTestList")[0]);
System.err.println(BeanUtils.getMappedProperty(bean, "beanUtilsTestMap(B)"));
System.err.println(BeanUtils.getMappedProperty(bean, "beanUtilsTestMap", "A"));
System.err.println(BeanUtils.getIndexedProperty(bean, "beanUtilsTestIndexedList[0]"));
System.err.println(BeanUtils.getIndexedProperty(bean, "beanUtilsTestIndexedList", 0));
} catch (IllegalAccessException | InvocationTargetException
| NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| UTF-8 | Java | 1,787 | java | BeanUtilsTest.java | Java | []
| null | []
| package my.test.javaBean;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
public class BeanUtilsTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestBean2 bean = new TestBean2();
List l = new ArrayList();
l.add("1");
l.add("2");
String[] arr = new String[]{"a", "b"};
Map m = new HashMap();
m.put("A", "3");
m.put("B", "4");
bean.setBeanUtilsTestArray(arr);
bean.setBeanUtilsTestList(l);
bean.setBeanUtilsTestMap(m);
bean.setItem("iii");
List l2 = new ArrayList();
TestBean subBean1 = new TestBean("s1", "100");
subBean1.setNestedTest("XXXXX");
l2.add(subBean1);
TestBean subBean2 = new TestBean("s2", "222");
l2.add(subBean2);
bean.setBeanUtilsTestIndexedList(l2);
/*************************************/
try {
System.err.println(BeanUtils.getProperty(bean, "item"));
System.err.println(BeanUtils.getNestedProperty(bean, "beanUtilsTestIndexedList[0].nestedTest"));
System.err.println(BeanUtils.getArrayProperty(bean, "beanUtilsTestList")[0]);
System.err.println(BeanUtils.getMappedProperty(bean, "beanUtilsTestMap(B)"));
System.err.println(BeanUtils.getMappedProperty(bean, "beanUtilsTestMap", "A"));
System.err.println(BeanUtils.getIndexedProperty(bean, "beanUtilsTestIndexedList[0]"));
System.err.println(BeanUtils.getIndexedProperty(bean, "beanUtilsTestIndexedList", 0));
} catch (IllegalAccessException | InvocationTargetException
| NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 1,787 | 0.677112 | 0.662003 | 73 | 23.479452 | 25.087305 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.438356 | false | false | 0 |
5585ecce68a40b2ca59a93b22c2c7d77bb7ef9ac | 1,022,202,275,257 | 1c04e45e1ebf4c4dcd85edc0bc38a10ccbd00917 | /Lista01/src/main/java/br/edu/ifrs/restinga/daione/lista01/Lista01/Exercicio02.java | d16bb68c71be2ca2588388719d779a9a38422753 | []
| no_license | DCommicsBP/listas-dev01 | https://github.com/DCommicsBP/listas-dev01 | 92074d779779f52e023adb48c7d9e3bd3f7f0d3f | ec36245372ea2b266dd1af498701943c8acd1fa2 | refs/heads/master | 2020-03-28T19:57:27.253000 | 2018-12-06T14:05:08 | 2018-12-06T14:05:08 | 149,025,049 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.edu.ifrs.restinga.daione.lista01.Lista01;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Exercicio02 {
@RequestMapping("/diaDaSemana/{dia}/{mes}/{ano}/")
public String diaDaSemana(@PathVariable int dia, @PathVariable int mes, @PathVariable int ano) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date data = null;
try {
data = sdf.parse(dia+"/"+ mes+"/"+ano);
} catch (ParseException ex) {
Logger.getLogger(Exercicio02.class.getName()).log(Level.SEVERE, null, ex);
}
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(data);
int diaDaSemana = gc.get(GregorianCalendar.DAY_OF_WEEK);
System.out.println("Dia da semana ===>"+ diaDaSemana);
String val = null;
switch(diaDaSemana){
case 1 : val = "Domingo"; break;
case 2 : val = "Segunda"; break;
case 3 : val = "Terça"; break;
case 4 : val = "Quarta"; break;
case 5 : val = "Quinta"; break;
case 6 : val = "Sexta"; break;
case 7 : val = "Sabado"; break;
default: break;
}
return val;
}
}
| UTF-8 | Java | 1,675 | java | Exercicio02.java | Java | []
| null | []
| package br.edu.ifrs.restinga.daione.lista01.Lista01;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Exercicio02 {
@RequestMapping("/diaDaSemana/{dia}/{mes}/{ano}/")
public String diaDaSemana(@PathVariable int dia, @PathVariable int mes, @PathVariable int ano) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date data = null;
try {
data = sdf.parse(dia+"/"+ mes+"/"+ano);
} catch (ParseException ex) {
Logger.getLogger(Exercicio02.class.getName()).log(Level.SEVERE, null, ex);
}
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(data);
int diaDaSemana = gc.get(GregorianCalendar.DAY_OF_WEEK);
System.out.println("Dia da semana ===>"+ diaDaSemana);
String val = null;
switch(diaDaSemana){
case 1 : val = "Domingo"; break;
case 2 : val = "Segunda"; break;
case 3 : val = "Terça"; break;
case 4 : val = "Quarta"; break;
case 5 : val = "Quinta"; break;
case 6 : val = "Sexta"; break;
case 7 : val = "Sabado"; break;
default: break;
}
return val;
}
}
| 1,675 | 0.593787 | 0.584827 | 45 | 36.200001 | 23.616003 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.866667 | false | false | 0 |
7d0580478a9d7368d8b838d83b63d40750b00ca6 | 9,337,258,964,666 | 7d80feabd7851b860b05a2a7a1bfb51379879362 | /etilqs/src/main/java/com/springtrail/etilqs/Builder/ViewModel.java | bf45efe3e48a302c46c6ddcb4be93398f7c38560 | [
"MIT"
]
| permissive | slippers/SqliteEtilqs | https://github.com/slippers/SqliteEtilqs | 9be67f0974d8f093292a3a945d387f510b76c37e | 9e83c5b461ac9c87e139eabff3208dd1241d7652 | refs/heads/master | 2021-01-10T03:21:59.812000 | 2018-02-27T17:51:11 | 2018-02-27T17:51:11 | 44,273,875 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.springtrail.etilqs.Builder;
/**
* Created by kirk on 9/23/15.
*/
public abstract class ViewModel extends Model {
public ViewModel() {
super();
}
@Override
public void configureModel(ModelBuilder builder) {
configureTableModel(((ViewBuilder) builder));
}
public void configureTableModel(ViewBuilder builder) {
}
@Override
public ModelBuilder getBuilder() {
return new ViewBuilder(this);
}
}
| UTF-8 | Java | 477 | java | ViewModel.java | Java | [
{
"context": "com.springtrail.etilqs.Builder;\n\n/**\n * Created by kirk on 9/23/15.\n */\npublic abstract class ViewModel e",
"end": 63,
"score": 0.9989951252937317,
"start": 59,
"tag": "USERNAME",
"value": "kirk"
}
]
| null | []
| package com.springtrail.etilqs.Builder;
/**
* Created by kirk on 9/23/15.
*/
public abstract class ViewModel extends Model {
public ViewModel() {
super();
}
@Override
public void configureModel(ModelBuilder builder) {
configureTableModel(((ViewBuilder) builder));
}
public void configureTableModel(ViewBuilder builder) {
}
@Override
public ModelBuilder getBuilder() {
return new ViewBuilder(this);
}
}
| 477 | 0.647799 | 0.637317 | 28 | 16.035715 | 19.476143 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false | 0 |
d9b5d4b8f65bd30f56ac70fd72cb12f651b13cd7 | 20,306,605,399,106 | 1fd05b32e1858a7a5a19f1804c32cb7f797443f6 | /trunk/netx-job/netx-schedule/src/main/java/com/netx/schedule/jobhandler/ucenter/UserLoginJobHandler.java | 9378096f9ee14a835b01fc7fdf215647eb855b9c | []
| no_license | biantaiwuzui/netx | https://github.com/biantaiwuzui/netx | 089a81cf53768121f99cb54a3daf2f6a1ec3d4c7 | 56c6e07864bd199befe90f8475bf72988c647392 | refs/heads/master | 2020-03-26T22:57:06.970000 | 2018-09-13T02:25:48 | 2018-09-13T02:25:48 | 145,498,445 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.netx.schedule.jobhandler.ucenter;
import com.netx.core.biz.model.ReturnT;
import com.netx.core.handler.IJobHandler;
import com.netx.core.handler.annotation.JobHandler;
import com.netx.core.log.XxlJobLogger;
import com.netx.ucenter.biz.user.UserScoreAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* 每天0点操作
* @author 黎子安 2018-4-10
*/
@JobHandler(value="UserLoginJobHandler")
@Component
public class UserLoginJobHandler extends IJobHandler {
@Autowired
private UserScoreAction userScoreAction;
@Override
public ReturnT<String> execute(String param) throws Exception {
XxlJobLogger.log(new Date()+":"+"定时扣除连续10内没有登录的用户积分启动");
userScoreAction.updateScoreByLoginStatus();
return SUCCESS;
}
}
| UTF-8 | Java | 905 | java | UserLoginJobHandler.java | Java | [
{
"context": "\nimport java.util.Date;\n\n/**\n * 每天0点操作\n * @author 黎子安 2018-4-10\n */\n@JobHandler(value=\"UserLoginJobHand",
"end": 435,
"score": 0.9920851588249207,
"start": 432,
"tag": "NAME",
"value": "黎子安"
}
]
| null | []
| package com.netx.schedule.jobhandler.ucenter;
import com.netx.core.biz.model.ReturnT;
import com.netx.core.handler.IJobHandler;
import com.netx.core.handler.annotation.JobHandler;
import com.netx.core.log.XxlJobLogger;
import com.netx.ucenter.biz.user.UserScoreAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* 每天0点操作
* @author 黎子安 2018-4-10
*/
@JobHandler(value="UserLoginJobHandler")
@Component
public class UserLoginJobHandler extends IJobHandler {
@Autowired
private UserScoreAction userScoreAction;
@Override
public ReturnT<String> execute(String param) throws Exception {
XxlJobLogger.log(new Date()+":"+"定时扣除连续10内没有登录的用户积分启动");
userScoreAction.updateScoreByLoginStatus();
return SUCCESS;
}
}
| 905 | 0.767333 | 0.755582 | 31 | 26.451612 | 22.681297 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.419355 | false | false | 0 |
086b2d43f55aabab32d111f1751f8e3a344a163b | 6,622,839,572,576 | 704093d82f98ba5613f079a4f9404cc1a1aa0571 | /src/main/java/com/qrcode/repository/ProductRepsitory.java | 6d55fe3e3d52fb87e42ee0f0928e602aad309129 | []
| no_license | vhieu-nx/QRCode | https://github.com/vhieu-nx/QRCode | ba758e1065f76ae3a3fdae6bb0ec65c679385315 | 20631fa23f5e36bfb0c351ed35bff7d457def273 | refs/heads/master | 2023-06-06T14:44:29.609000 | 2021-06-23T07:23:51 | 2021-06-23T07:23:51 | 379,515,905 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.qrcode.repository;
import com.qrcode.entity.Product;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepsitory extends CrudRepository<Product, String> {
}
| UTF-8 | Java | 266 | java | ProductRepsitory.java | Java | []
| null | []
| package com.qrcode.repository;
import com.qrcode.entity.Product;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepsitory extends CrudRepository<Product, String> {
}
| 266 | 0.845865 | 0.845865 | 9 | 28.555555 | 26.166607 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 0 |
7d0a5a1912ed6067ef41fad82d70e2380c44d745 | 3,676,492,017,061 | 69e3ff03d6317ec1e8628ae0ef0c8a59334ca9f1 | /src/com/scabhi98/groupE/RollValidationProblem.java | 2b8a6e53b842390de39acdb89df918004be5daa8 | []
| no_license | scabhi98/mca.java.assignment | https://github.com/scabhi98/mca.java.assignment | af0efcba7873e6851a9c68aeb60342b96f41723b | d98bff11d988a6c70617f1f968cce35d76495162 | refs/heads/master | 2023-02-02T00:11:15.421000 | 2020-12-17T17:48:27 | 2020-12-17T17:48:27 | 322,286,576 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.scabhi98.groupE;
import com.scabhi98.ExecutionEnvironment;
import com.scabhi98.Problem;
public class RollValidationProblem implements Problem {
private String roll;
@Override
public String getProblemStatement() {
return "Roll Number Validation";
}
@Override
public void execute() throws Exception {
try{
InvalidRollException.checkRoll(roll);
System.out.println("\nRoll Number is: "+roll);
}catch(InvalidRollException e){
System.out.println("Exception Caught.");
System.out.println(e.getMessage());
}
}
@Override
public void readInputs() throws Exception {
roll = ExecutionEnvironment.readInputFor("Roll");
}
} | UTF-8 | Java | 753 | java | RollValidationProblem.java | Java | []
| null | []
| package com.scabhi98.groupE;
import com.scabhi98.ExecutionEnvironment;
import com.scabhi98.Problem;
public class RollValidationProblem implements Problem {
private String roll;
@Override
public String getProblemStatement() {
return "Roll Number Validation";
}
@Override
public void execute() throws Exception {
try{
InvalidRollException.checkRoll(roll);
System.out.println("\nRoll Number is: "+roll);
}catch(InvalidRollException e){
System.out.println("Exception Caught.");
System.out.println(e.getMessage());
}
}
@Override
public void readInputs() throws Exception {
roll = ExecutionEnvironment.readInputFor("Roll");
}
} | 753 | 0.653386 | 0.645418 | 28 | 25.928572 | 20.448418 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false | 0 |
ffa459ce266fc56ceb92444b19dec71a3859c22d | 19,499,151,548,227 | bea07d2b3b45846b0b89da6e70e8cbaae78bbf37 | /jmbook/Chapter7/BJ1780.java | 1779d69b90dd0c20b613518895486a71e72320a5 | []
| no_license | lee95292/AlgoGaza | https://github.com/lee95292/AlgoGaza | 01fcd8d936673c4027bad1a1238c3e371f2a5251 | 2ff2540fa9a8243c341ad3fb14eef276b2c5840e | refs/heads/master | 2023-08-16T09:51:55.217000 | 2023-08-15T07:26:51 | 2023-08-15T07:26:51 | 210,504,292 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Chapter7;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
public class BJ1780 {
static int minusOne;
static int zero;
static int one;
public static void calculateNumber(Integer[][] paper, int n,int x,int y) {
if(n==1) {
if(paper[y][x]==-1)minusOne++;
if(paper[y][x]==0)zero++;
if(paper[y][x]==1)one++;
return;
}
Integer singleNum=singleNumber(paper, n, x, y);
if(singleNum!=-2) {
if(singleNum==-1)minusOne++;
if(singleNum==0)zero++;
if(singleNum==1)one++;
return;
}
int quoter= n/3;
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
calculateNumber(paper, quoter, x+j*quoter, y+i*quoter);
}
}
}
public static Integer singleNumber(Integer [][] paper, int n,int x,int y) {
Integer prev= paper[y][x];
for(int i=y;i<y+n;i++) {
for(int j=x;j<x+n;j++) {
if(prev!=paper[i][j]) {
return -2;
}
prev=paper[i][j];
}
}
return prev;
}
public static void main(String[] args)throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n =Integer.parseInt(br.readLine());
String[] paperStringType = new String[n];
Integer [][] paper= new Integer[n][n];
for(int i=0;i<n;i++) {
paperStringType=br.readLine().split(" ");
paper[i]=Arrays.stream(paperStringType).map(x->{return Integer.parseInt(x);}).toArray(Integer[]::new);
}
calculateNumber(paper, n, 0, 0);
System.out.println(minusOne);
System.out.println(zero);
System.out.println(one);
}
}
| UTF-8 | Java | 1,551 | java | BJ1780.java | Java | []
| null | []
| package Chapter7;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
public class BJ1780 {
static int minusOne;
static int zero;
static int one;
public static void calculateNumber(Integer[][] paper, int n,int x,int y) {
if(n==1) {
if(paper[y][x]==-1)minusOne++;
if(paper[y][x]==0)zero++;
if(paper[y][x]==1)one++;
return;
}
Integer singleNum=singleNumber(paper, n, x, y);
if(singleNum!=-2) {
if(singleNum==-1)minusOne++;
if(singleNum==0)zero++;
if(singleNum==1)one++;
return;
}
int quoter= n/3;
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
calculateNumber(paper, quoter, x+j*quoter, y+i*quoter);
}
}
}
public static Integer singleNumber(Integer [][] paper, int n,int x,int y) {
Integer prev= paper[y][x];
for(int i=y;i<y+n;i++) {
for(int j=x;j<x+n;j++) {
if(prev!=paper[i][j]) {
return -2;
}
prev=paper[i][j];
}
}
return prev;
}
public static void main(String[] args)throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n =Integer.parseInt(br.readLine());
String[] paperStringType = new String[n];
Integer [][] paper= new Integer[n][n];
for(int i=0;i<n;i++) {
paperStringType=br.readLine().split(" ");
paper[i]=Arrays.stream(paperStringType).map(x->{return Integer.parseInt(x);}).toArray(Integer[]::new);
}
calculateNumber(paper, n, 0, 0);
System.out.println(minusOne);
System.out.println(zero);
System.out.println(one);
}
}
| 1,551 | 0.625403 | 0.611219 | 68 | 21.808823 | 21.483412 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.779412 | false | false | 0 |
237abc97d3380be901d9fdf44a824963c8f80263 | 3,332,894,622,045 | bf8abd70ab8d0bd34fbae80c23192e6814b0e115 | /knowledgeproduction-graph/src/test/java/pl/izertp/knowledgeproduction/hypergraph/HyperGraphTest.java | f835d5071b258545cbad229f2908afe37af9fe83 | []
| no_license | piotrizert/knowledgeproduction | https://github.com/piotrizert/knowledgeproduction | f70773196a1b2b4fdfb0d95b26a48d2c868e60cb | 1f8c65ae53ec1b80b81d2cdf11c155e50120716c | refs/heads/master | 2021-01-23T06:54:17.718000 | 2015-02-03T10:02:57 | 2015-02-03T10:02:57 | 25,458,137 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.izertp.knowledgeproduction.hypergraph;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
public class HyperGraphTest {
private static final int Vfrom1 = 0;
private static final int Vfrom2 = 1;
private static final int Vto1 = 2;
private static final int Vto2 = 3;
private static final int SIZE = 10;
private HyperGraph graph;
@Before
public void setUpGraph() {
graph = new MixedHyperGraph(SIZE);
}
@Test
public void testAddEdge() {
assertFalse("Adding non-existent edge should return false", graph.addEdge(Vfrom1, Vfrom2, Vto1));
assertTrue("Adding existent edge should return true", graph.addEdge(Vfrom1, Vfrom2, Vto1));
}
@Test(expected = IllegalArgumentException.class)
public void testAddEdgeTheSameStart() {
graph.addEdge(Vfrom1, Vfrom1, Vto1);
}
@Test(expected = IllegalArgumentException.class)
public void testSameStartBeginning() {
graph.addEdge(Vfrom1, Vfrom2, Vfrom1);
}
@Test
public void testEdgeSymmetric() {
graph.addEdge(Vfrom1, Vfrom2, Vto1);
assertTrue("Edge should be present", graph.getEdge(Vfrom1, Vfrom2, Vto1));
assertTrue("Edges should be symmetric", graph.getEdge(Vfrom2, Vfrom1, Vto1));
}
@Test
public void testToVertices() {
graph.addEdge(Vfrom1, Vfrom2, Vto1);
graph.addEdge(Vfrom1, Vfrom2, Vto2);
assertArrayEquals("Wrong destination vertices list", graph.toVertices(Vfrom1, Vfrom2).toArray(), new Integer[] { Vto1, Vto2 });
}
}
| UTF-8 | Java | 1,701 | java | HyperGraphTest.java | Java | []
| null | []
| package pl.izertp.knowledgeproduction.hypergraph;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
public class HyperGraphTest {
private static final int Vfrom1 = 0;
private static final int Vfrom2 = 1;
private static final int Vto1 = 2;
private static final int Vto2 = 3;
private static final int SIZE = 10;
private HyperGraph graph;
@Before
public void setUpGraph() {
graph = new MixedHyperGraph(SIZE);
}
@Test
public void testAddEdge() {
assertFalse("Adding non-existent edge should return false", graph.addEdge(Vfrom1, Vfrom2, Vto1));
assertTrue("Adding existent edge should return true", graph.addEdge(Vfrom1, Vfrom2, Vto1));
}
@Test(expected = IllegalArgumentException.class)
public void testAddEdgeTheSameStart() {
graph.addEdge(Vfrom1, Vfrom1, Vto1);
}
@Test(expected = IllegalArgumentException.class)
public void testSameStartBeginning() {
graph.addEdge(Vfrom1, Vfrom2, Vfrom1);
}
@Test
public void testEdgeSymmetric() {
graph.addEdge(Vfrom1, Vfrom2, Vto1);
assertTrue("Edge should be present", graph.getEdge(Vfrom1, Vfrom2, Vto1));
assertTrue("Edges should be symmetric", graph.getEdge(Vfrom2, Vfrom1, Vto1));
}
@Test
public void testToVertices() {
graph.addEdge(Vfrom1, Vfrom2, Vto1);
graph.addEdge(Vfrom1, Vfrom2, Vto2);
assertArrayEquals("Wrong destination vertices list", graph.toVertices(Vfrom1, Vfrom2).toArray(), new Integer[] { Vto1, Vto2 });
}
}
| 1,701 | 0.687243 | 0.663139 | 59 | 27.830509 | 29.577335 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.830508 | false | false | 0 |
df84f971c9e7be65dbd46540fa682471f2724efb | 3,942,780,000,036 | eb1623a335ca6f96a9a0656f874c4bdab1d05655 | /src/main/java/org/efaps/maven/jetty/configuration/ServerDefinition.java | e4757e302ac915b7e78349815c7518b665a083d8 | []
| no_license | eFaps/eFaps-Jetty-Maven-Plugin | https://github.com/eFaps/eFaps-Jetty-Maven-Plugin | 3af5a5656f04220b7ee06477b31ba35114d1ba11 | 4d8deddc84e25ac61372eadcd408e9c05a4fb7bc | refs/heads/master | 2023-03-31T15:53:32.479000 | 2023-03-15T21:52:53 | 2023-03-15T21:52:53 | 32,643,797 | 0 | 0 | null | false | 2023-03-15T21:52:54 | 2015-03-21T18:09:43 | 2021-03-24T05:02:06 | 2023-03-15T21:52:53 | 99 | 0 | 0 | 0 | Java | false | false | /*
* Copyright 2003 - 2023 The eFaps Team
*
* 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.efaps.maven.jetty.configuration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import org.apache.commons.digester3.Digester;
import org.apache.commons.digester3.annotations.rules.SetNext;
import org.apache.commons.digester3.binder.AbstractRulesModule;
import org.apache.commons.digester3.binder.DigesterLoader;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.webapp.WebAppContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author The eFaps Team
*/
public class ServerDefinition
extends AbstractDefinition
{
/**
* Logging instance used to give logging information of this class.
*/
private static final Logger LOG = LoggerFactory.getLogger(ServerDefinition.class);
/**
* List of all Filters used in this server definition.
*/
private final List<FilterDefinition> filters = new ArrayList<>();
/**
* List of all servlets used in this server definition.
*/
private final List<ServletDefinition> servlets = new ArrayList<>();
/**
* Use websocket or not.
*/
private boolean websocket;
/**
* Initializes a new instanc of the server definition a a XML file.
*
* @param _url path to the XML file within the server definition
* @return configured instance from the XML file
*/
public static ServerDefinition read(final String _url)
{
ServerDefinition ret = null;
try {
final DigesterLoader loader = DigesterLoader.newLoader(new AbstractRulesModule()
{
@Override
protected void configure()
{
forPattern("server").createObject().ofType(ServerDefinition.class)
.then().setProperties();
forPattern("server/parameter")
.callMethod("addIniParam").withParamCount(2)
.withParamTypes(String.class, String.class)
.then().callParam().fromAttribute("key").ofIndex(0)
.then().callParam().ofIndex(1);
forPattern("server/filter").createObject().ofType(FilterDefinition.class)
.then().setNext("addFilter");
forPattern("server/filter").setProperties();
forPattern("server/filter/parameter")
.callMethod("addIniParam").withParamCount(2)
.withParamTypes(String.class, String.class)
.then().callParam().fromAttribute("key").ofIndex(0)
.then().callParam().ofIndex(1);
forPattern("server/servlet").createObject().ofType(ServletDefinition.class)
.then().setNext("addServlet");
forPattern("server/servlet").setProperties();
forPattern("server/servlet/parameter")
.callMethod("addIniParam").withParamCount(2)
.withParamTypes(String.class, String.class)
.then().callParam().fromAttribute("key").ofIndex(0)
.then().callParam().ofIndex(1);
}
});
final Digester digester = loader.newDigester();
ret = (ServerDefinition) digester.parse(_url);
} catch (final Exception e) {
ServerDefinition.LOG.error(_url.toString() + " is not readable", e);
}
return ret;
}
/**
* Updates the context handler (defining the server) by appending servlets
* and filters.
*
* @param _handler context handler used to add filters / servlets
* @see FilterDefinition#updateServer(Context)
* @see ServletDefinition#updateServer(Context)
*/
public void updateServer(final ServletContextHandler _handler)
{
for (final Entry<String, String> entry : getIniParams().entrySet()) {
_handler.setInitParameter(entry.getKey(), entry.getValue());
}
for (final FilterDefinition filter : this.filters) {
filter.updateServer(_handler);
}
for (final ServletDefinition servlet : this.servlets) {
servlet.updateServer(_handler);
}
}
/**
* Adds a new filter definition to the list of filter definition.
*
* @param _filter filter to add to the list of filters
* @see #filters
*/
@SetNext
public void addFilter(final FilterDefinition _filter)
{
this.filters.add(_filter);
}
/**
* Adds a new servlet definition to the list of servlet definitions.
*
* @param _servlet servlet to add to the list of servlets
* @see #servlets
*/
@SetNext
public void addServlet(final ServletDefinition _servlet)
{
this.servlets.add(_servlet);
}
/**
* Getter method for the instance variable {@link #websocket}.
*
* @return value of instance variable {@link #websocket}
*/
public boolean isWebsocket()
{
return this.websocket;
}
/**
* Setter method for instance variable {@link #websocket}.
*
* @param _websocket value for instance variable {@link #websocket}
*/
public void setWebsocket(final boolean _websocket)
{
this.websocket = _websocket;
}
/**
* @param _wac context to be updated
*/
public void updateContext(final WebAppContext _wac)
{
for (final Entry<String, String> entry : getIniParams().entrySet()) {
_wac.setInitParameter(entry.getKey(), entry.getValue());
}
}
}
| UTF-8 | Java | 6,300 | java | ServerDefinition.java | Java | []
| null | []
| /*
* Copyright 2003 - 2023 The eFaps Team
*
* 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.efaps.maven.jetty.configuration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import org.apache.commons.digester3.Digester;
import org.apache.commons.digester3.annotations.rules.SetNext;
import org.apache.commons.digester3.binder.AbstractRulesModule;
import org.apache.commons.digester3.binder.DigesterLoader;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.webapp.WebAppContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author The eFaps Team
*/
public class ServerDefinition
extends AbstractDefinition
{
/**
* Logging instance used to give logging information of this class.
*/
private static final Logger LOG = LoggerFactory.getLogger(ServerDefinition.class);
/**
* List of all Filters used in this server definition.
*/
private final List<FilterDefinition> filters = new ArrayList<>();
/**
* List of all servlets used in this server definition.
*/
private final List<ServletDefinition> servlets = new ArrayList<>();
/**
* Use websocket or not.
*/
private boolean websocket;
/**
* Initializes a new instanc of the server definition a a XML file.
*
* @param _url path to the XML file within the server definition
* @return configured instance from the XML file
*/
public static ServerDefinition read(final String _url)
{
ServerDefinition ret = null;
try {
final DigesterLoader loader = DigesterLoader.newLoader(new AbstractRulesModule()
{
@Override
protected void configure()
{
forPattern("server").createObject().ofType(ServerDefinition.class)
.then().setProperties();
forPattern("server/parameter")
.callMethod("addIniParam").withParamCount(2)
.withParamTypes(String.class, String.class)
.then().callParam().fromAttribute("key").ofIndex(0)
.then().callParam().ofIndex(1);
forPattern("server/filter").createObject().ofType(FilterDefinition.class)
.then().setNext("addFilter");
forPattern("server/filter").setProperties();
forPattern("server/filter/parameter")
.callMethod("addIniParam").withParamCount(2)
.withParamTypes(String.class, String.class)
.then().callParam().fromAttribute("key").ofIndex(0)
.then().callParam().ofIndex(1);
forPattern("server/servlet").createObject().ofType(ServletDefinition.class)
.then().setNext("addServlet");
forPattern("server/servlet").setProperties();
forPattern("server/servlet/parameter")
.callMethod("addIniParam").withParamCount(2)
.withParamTypes(String.class, String.class)
.then().callParam().fromAttribute("key").ofIndex(0)
.then().callParam().ofIndex(1);
}
});
final Digester digester = loader.newDigester();
ret = (ServerDefinition) digester.parse(_url);
} catch (final Exception e) {
ServerDefinition.LOG.error(_url.toString() + " is not readable", e);
}
return ret;
}
/**
* Updates the context handler (defining the server) by appending servlets
* and filters.
*
* @param _handler context handler used to add filters / servlets
* @see FilterDefinition#updateServer(Context)
* @see ServletDefinition#updateServer(Context)
*/
public void updateServer(final ServletContextHandler _handler)
{
for (final Entry<String, String> entry : getIniParams().entrySet()) {
_handler.setInitParameter(entry.getKey(), entry.getValue());
}
for (final FilterDefinition filter : this.filters) {
filter.updateServer(_handler);
}
for (final ServletDefinition servlet : this.servlets) {
servlet.updateServer(_handler);
}
}
/**
* Adds a new filter definition to the list of filter definition.
*
* @param _filter filter to add to the list of filters
* @see #filters
*/
@SetNext
public void addFilter(final FilterDefinition _filter)
{
this.filters.add(_filter);
}
/**
* Adds a new servlet definition to the list of servlet definitions.
*
* @param _servlet servlet to add to the list of servlets
* @see #servlets
*/
@SetNext
public void addServlet(final ServletDefinition _servlet)
{
this.servlets.add(_servlet);
}
/**
* Getter method for the instance variable {@link #websocket}.
*
* @return value of instance variable {@link #websocket}
*/
public boolean isWebsocket()
{
return this.websocket;
}
/**
* Setter method for instance variable {@link #websocket}.
*
* @param _websocket value for instance variable {@link #websocket}
*/
public void setWebsocket(final boolean _websocket)
{
this.websocket = _websocket;
}
/**
* @param _wac context to be updated
*/
public void updateContext(final WebAppContext _wac)
{
for (final Entry<String, String> entry : getIniParams().entrySet()) {
_wac.setInitParameter(entry.getKey(), entry.getValue());
}
}
}
| 6,300 | 0.611587 | 0.607302 | 187 | 32.689838 | 28.497679 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false | 0 |
b515c086b9c715ebce6f5c5d9a68e6c98587d34c | 14,602,888,820,265 | ab2f360b8c483edcc4209bb78dd5d322baa18551 | /src/test/java/com/nvankempen/clustering/utils/Vec2Test.java | cc7db00a12106fd5c0dc24545afd76f4b632ba0e | []
| no_license | nicovank/dbscan | https://github.com/nicovank/dbscan | 544785ed57b63354c7db6bd85fc8be3391f4e535 | 2bf2d8b8514e6fcb708e68b86879f74b7dd1ba6e | refs/heads/master | 2020-03-14T13:04:24.947000 | 2018-04-30T17:22:29 | 2018-04-30T17:22:29 | 131,624,857 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nvankempen.clustering.utils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class Vec2Test {
@Test
public void distanceTest() {
Vec2 p1 = new Vec2(0, 0);
Vec2 p2 = new Vec2(3, 4);
assertEquals(5, p1.distance(p2));
assertEquals(5, p2.distance(p1));
}
}
| UTF-8 | Java | 334 | java | Vec2Test.java | Java | []
| null | []
| package com.nvankempen.clustering.utils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class Vec2Test {
@Test
public void distanceTest() {
Vec2 p1 = new Vec2(0, 0);
Vec2 p2 = new Vec2(3, 4);
assertEquals(5, p1.distance(p2));
assertEquals(5, p2.distance(p1));
}
}
| 334 | 0.718563 | 0.667665 | 15 | 21.266666 | 18.057194 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.466667 | false | false | 0 |
1932c4e3753c4340ca35141a39a8a845ac08c873 | 28,595,892,275,340 | 6d82f133295e6c14899ec7b6734361dae9fef300 | /src/BinarySearchTree.java | 446304cde5d3a82c8d08819f9b780670c1923347 | []
| no_license | AaronDSchroeder/Slider_Puzzle_Solver | https://github.com/AaronDSchroeder/Slider_Puzzle_Solver | 8741a0055caca2e64d0c6dc9a42737833d8e5453 | f2acf967ce0b4f2173608c41a831ecc0b47ce17f | refs/heads/master | 2023-04-12T01:47:57.388000 | 2021-04-06T22:48:48 | 2021-04-06T22:48:48 | 355,348,499 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class BinarySearchTree<E> {
private TreeNode root;
public boolean insert(E value){
if(search(value)){
return false;
}
if (root == null) {
root = new TreeNode(value);
}
else {
TreeNode parent = null;
TreeNode node = root;
while (node != null) {
parent = node;
if (node.compareTo(value) < 0) {
node = node.right;
} else {
node = node.left;
}
}
TreeNode newNode = new TreeNode(value);
if(parent.compareTo(value) < 0) {
parent.right = newNode;
} else{
parent.left = newNode;
}
}
return true;
}
public boolean search(E value){
boolean found = false;
TreeNode node = root;
while(!found && node != null){
if(node.compareTo(value) == 0){
found = true;
}
else if(node.compareTo(value) < 0){
node = node.right;
}
else{
node = node.left;
}
}
return found;
}
public class TreeNode implements Comparable<E>{
public E value;
public TreeNode left;
public TreeNode right;
public int compareTo(E value){
String item = value.toString();
return ((this.value.toString()).compareTo(item));
}
public TreeNode(E value){
this.value = value;
}
}
} | UTF-8 | Java | 1,633 | java | BinarySearchTree.java | Java | []
| null | []
| public class BinarySearchTree<E> {
private TreeNode root;
public boolean insert(E value){
if(search(value)){
return false;
}
if (root == null) {
root = new TreeNode(value);
}
else {
TreeNode parent = null;
TreeNode node = root;
while (node != null) {
parent = node;
if (node.compareTo(value) < 0) {
node = node.right;
} else {
node = node.left;
}
}
TreeNode newNode = new TreeNode(value);
if(parent.compareTo(value) < 0) {
parent.right = newNode;
} else{
parent.left = newNode;
}
}
return true;
}
public boolean search(E value){
boolean found = false;
TreeNode node = root;
while(!found && node != null){
if(node.compareTo(value) == 0){
found = true;
}
else if(node.compareTo(value) < 0){
node = node.right;
}
else{
node = node.left;
}
}
return found;
}
public class TreeNode implements Comparable<E>{
public E value;
public TreeNode left;
public TreeNode right;
public int compareTo(E value){
String item = value.toString();
return ((this.value.toString()).compareTo(item));
}
public TreeNode(E value){
this.value = value;
}
}
} | 1,633 | 0.439069 | 0.43662 | 66 | 23.757576 | 15.756731 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 0 |
f59a7fa7cc35b6ef11c378ae81f21b39fd0c1601 | 31,602,369,387,495 | 1e9bc114d1920317e423a54d93a33c558d5e567c | /src/main/java/de/fips/util/tinybinding/weaklistener/WeakListenerHandler.java | 9445ecb2c6774811e15a0f9605b19d8c7df3bef9 | [
"MIT",
"Apache-2.0"
]
| permissive | orb1t/tinybinding | https://github.com/orb1t/tinybinding | fe657c4f7e4beb4581448e8c59575a1496175804 | b5e8f124e8af218249ba187ca35fef05f40f82f1 | refs/heads/master | 2020-03-21T19:46:28.794000 | 2012-06-24T21:56:19 | 2012-06-24T21:56:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright © 2010-2011 Philipp Eichhorn.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.fips.util.tinybinding.weaklistener;
import static org.fest.reflect.core.Reflection.method;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import lombok.Rethrow;
import lombok.core.util.Cast;
import org.fest.reflect.exception.ReflectionError;
/**
*
* @param <LISTENER_TYPE>
* @param <TYPE>
* @author Philipp Eichhorn
*/
class WeakListenerHandler<LISTENER_TYPE, TYPE extends LISTENER_TYPE> implements InvocationHandler {
private static final Method OBJECT_EQUALS = getObjectMethod("equals", Object.class);
private final WeakReference<LISTENER_TYPE> weakListener;
private final Class<LISTENER_TYPE> listenerType;
private final Object target;
private final String propertyName;
private final boolean throwException;
private WeakListenerHandler(final Object target, final Class<LISTENER_TYPE> listenerType, final TYPE listener, final boolean throwException, final String propertyName) {
this.listenerType = listenerType;
this.target = target;
this.throwException = throwException;
this.propertyName = propertyName;
weakListener = new WeakReference<LISTENER_TYPE>(listener);
}
private final void addListener(final Object proxy) {
try {
if (propertyName != null) {
method("add" + listenerType.getSimpleName()).withParameterTypes(String.class, listenerType).in(target).invoke(propertyName, proxy);
} else {
method("add" + listenerType.getSimpleName()).withParameterTypes(listenerType).in(target).invoke(proxy);
}
} catch (ReflectionError e) {
if (throwException) throw new IllegalStateException(String.format("Unable to add weak '%s' to object of type '%s'.", listenerType, target.getClass()), e);
}
}
private final void removeListener(final Object proxy) {
try {
if (propertyName != null) {
method("remove" + listenerType.getSimpleName()).withParameterTypes(String.class, listenerType).in(target).invoke(propertyName, proxy);
} else {
method("remove" + listenerType.getSimpleName()).withParameterTypes(listenerType).in(target).invoke(proxy);
}
} catch (ReflectionError e) {
if (throwException) throw new IllegalStateException(String.format("Unable to remove weak '%s' from object of type '%s'.", listenerType, target.getClass()), e);
}
}
@Override
public final Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
final LISTENER_TYPE listener = weakListener.get();
if (OBJECT_EQUALS.equals(method)) {
final Object other = args[0];
if (other == null) return false;
if (!Proxy.isProxyClass(other.getClass())) return false;
final InvocationHandler handler = Proxy.getInvocationHandler(other);
return (handler instanceof WeakListenerHandler<?, ?>) && (((WeakListenerHandler<?, ?>) handler).weakListener.get() == listener);
}
if (listener == null) {
removeListener(proxy);
return null;
} else {
try {
return method.invoke(listener, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
}
@Rethrow(value = NoSuchMethodException.class, as = IllegalStateException.class)
private static Method getObjectMethod(String name, Class<?>... types) {
return Object.class.getMethod(name, types);
}
static <LISTENER_TYPE, TYPE extends LISTENER_TYPE> LISTENER_TYPE addWeakListener(final Object target, final Class<LISTENER_TYPE> listenerType, final TYPE listener, final boolean throwException, final String propertyName) {
final WeakListenerHandler<LISTENER_TYPE, TYPE> handler = new WeakListenerHandler<LISTENER_TYPE, TYPE>(target, listenerType, listener, throwException, propertyName);
final LISTENER_TYPE proxy = Cast.uncheckedCast(Proxy.newProxyInstance(WeakListenerHandler.class.getClassLoader(), new Class[] { listenerType }, handler));
handler.addListener(proxy);
return proxy;
}
}
| UTF-8 | Java | 5,081 | java | WeakListenerHandler.java | Java | [
{
"context": "/*\n * Copyright © 2010-2011 Philipp Eichhorn.\n * \n * Permission is hereby granted, free of cha",
"end": 44,
"score": 0.9998907446861267,
"start": 28,
"tag": "NAME",
"value": "Philipp Eichhorn"
},
{
"context": "@param <LISTENER_TYPE>\n * @param <TYPE>\n * @author Philipp Eichhorn\n */\nclass WeakListenerHandler<LISTENER_TYPE, TYPE",
"end": 1613,
"score": 0.9998934864997864,
"start": 1597,
"tag": "NAME",
"value": "Philipp Eichhorn"
}
]
| null | []
| /*
* Copyright © 2010-2011 <NAME>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.fips.util.tinybinding.weaklistener;
import static org.fest.reflect.core.Reflection.method;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import lombok.Rethrow;
import lombok.core.util.Cast;
import org.fest.reflect.exception.ReflectionError;
/**
*
* @param <LISTENER_TYPE>
* @param <TYPE>
* @author <NAME>
*/
class WeakListenerHandler<LISTENER_TYPE, TYPE extends LISTENER_TYPE> implements InvocationHandler {
private static final Method OBJECT_EQUALS = getObjectMethod("equals", Object.class);
private final WeakReference<LISTENER_TYPE> weakListener;
private final Class<LISTENER_TYPE> listenerType;
private final Object target;
private final String propertyName;
private final boolean throwException;
private WeakListenerHandler(final Object target, final Class<LISTENER_TYPE> listenerType, final TYPE listener, final boolean throwException, final String propertyName) {
this.listenerType = listenerType;
this.target = target;
this.throwException = throwException;
this.propertyName = propertyName;
weakListener = new WeakReference<LISTENER_TYPE>(listener);
}
private final void addListener(final Object proxy) {
try {
if (propertyName != null) {
method("add" + listenerType.getSimpleName()).withParameterTypes(String.class, listenerType).in(target).invoke(propertyName, proxy);
} else {
method("add" + listenerType.getSimpleName()).withParameterTypes(listenerType).in(target).invoke(proxy);
}
} catch (ReflectionError e) {
if (throwException) throw new IllegalStateException(String.format("Unable to add weak '%s' to object of type '%s'.", listenerType, target.getClass()), e);
}
}
private final void removeListener(final Object proxy) {
try {
if (propertyName != null) {
method("remove" + listenerType.getSimpleName()).withParameterTypes(String.class, listenerType).in(target).invoke(propertyName, proxy);
} else {
method("remove" + listenerType.getSimpleName()).withParameterTypes(listenerType).in(target).invoke(proxy);
}
} catch (ReflectionError e) {
if (throwException) throw new IllegalStateException(String.format("Unable to remove weak '%s' from object of type '%s'.", listenerType, target.getClass()), e);
}
}
@Override
public final Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
final LISTENER_TYPE listener = weakListener.get();
if (OBJECT_EQUALS.equals(method)) {
final Object other = args[0];
if (other == null) return false;
if (!Proxy.isProxyClass(other.getClass())) return false;
final InvocationHandler handler = Proxy.getInvocationHandler(other);
return (handler instanceof WeakListenerHandler<?, ?>) && (((WeakListenerHandler<?, ?>) handler).weakListener.get() == listener);
}
if (listener == null) {
removeListener(proxy);
return null;
} else {
try {
return method.invoke(listener, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
}
@Rethrow(value = NoSuchMethodException.class, as = IllegalStateException.class)
private static Method getObjectMethod(String name, Class<?>... types) {
return Object.class.getMethod(name, types);
}
static <LISTENER_TYPE, TYPE extends LISTENER_TYPE> LISTENER_TYPE addWeakListener(final Object target, final Class<LISTENER_TYPE> listenerType, final TYPE listener, final boolean throwException, final String propertyName) {
final WeakListenerHandler<LISTENER_TYPE, TYPE> handler = new WeakListenerHandler<LISTENER_TYPE, TYPE>(target, listenerType, listener, throwException, propertyName);
final LISTENER_TYPE proxy = Cast.uncheckedCast(Proxy.newProxyInstance(WeakListenerHandler.class.getClassLoader(), new Class[] { listenerType }, handler));
handler.addListener(proxy);
return proxy;
}
}
| 5,061 | 0.755512 | 0.75374 | 117 | 42.418804 | 45.12532 | 223 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.076923 | false | false | 0 |
1c22dbdafef4c9bd7d101c56ef326f74372910fd | 28,664,611,783,048 | 090d359efd7ad7dbe808a32676ce63302c575b9f | /modules/swing/src/test/api/java.injected/javax/swing/plaf/basic/BasicToggleButtonUITest.java | e25bcc7f059c77afdd4f4dbed61314b5acbb97dc | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown",
"SunPro",
"CPL-1.0",
"Bitstream-Vera",
"IJG",
"Libpng",
"MIT",
"LicenseRef-scancode-unicode",
"Zlib",
"EPL-1.0",
"LicenseRef-scancode-mx4j",
"LicenseRef-scancode-ietf-trust",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"ICU",
"LicenseRef-scancode-ietf",
"LicenseRef-scancode-public-domain"
]
| permissive | isabella232/harmony-classlib | https://github.com/isabella232/harmony-classlib | 185aa26ed1f3a1f6529461981fe963142722fc6b | ee663b95e84093405985d9557a925b651a0f69b3 | refs/heads/trunk | 2023-09-01T23:40:42.659000 | 2010-02-12T19:43:01 | 2010-02-12T19:43:01 | 418,124,654 | 0 | 0 | Apache-2.0 | true | 2021-10-17T13:03:44 | 2021-10-17T12:28:28 | 2021-10-17T12:28:30 | 2021-10-17T13:03:44 | 95,760 | 0 | 0 | 1 | null | false | false | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Alexander T. Simbirtsev
* Created on 27.04.2005
*/
package javax.swing.plaf.basic;
import javax.swing.JButton;
import javax.swing.SwingTestCase;
public class BasicToggleButtonUITest extends SwingTestCase {
public class MyBasicToggleButtonUI extends BasicToggleButtonUI {
@Override
public String getPropertyPrefix() {
return super.getPropertyPrefix();
}
@Override
public int getTextShiftOffset() {
return super.getTextShiftOffset();
}
};
public MyBasicToggleButtonUI ui = null;
public static void main(final String[] args) {
junit.textui.TestRunner.run(BasicToggleButtonUITest.class);
}
/*
* @see TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
super.setUp();
ui = new MyBasicToggleButtonUI();
}
public void testCreateUI() {
assertTrue("created UI is not null", null != BasicToggleButtonUI
.createUI(new JButton()));
assertTrue("created UI is of the proper class",
BasicToggleButtonUI.createUI(null) instanceof BasicToggleButtonUI);
assertTrue("created UI is of unique",
BasicToggleButtonUI.createUI(null) == BasicToggleButtonUI.createUI(null));
}
public void testGetPropertyPrefix() {
assertEquals("prefix ", "ToggleButton.", ui.getPropertyPrefix());
}
public void testGetTextShiftOffset() {
assertEquals("offset", 0, ui.getTextShiftOffset());
}
}
| UTF-8 | Java | 2,366 | java | BasicToggleButtonUITest.java | Java | [
{
"context": " limitations under the License.\n */\n/**\n * @author Alexander T. Simbirtsev\n * Created on 27.04.2005\n\n */\npackage javax.swing",
"end": 851,
"score": 0.9998546242713928,
"start": 828,
"tag": "NAME",
"value": "Alexander T. Simbirtsev"
}
]
| null | []
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author <NAME>
* Created on 27.04.2005
*/
package javax.swing.plaf.basic;
import javax.swing.JButton;
import javax.swing.SwingTestCase;
public class BasicToggleButtonUITest extends SwingTestCase {
public class MyBasicToggleButtonUI extends BasicToggleButtonUI {
@Override
public String getPropertyPrefix() {
return super.getPropertyPrefix();
}
@Override
public int getTextShiftOffset() {
return super.getTextShiftOffset();
}
};
public MyBasicToggleButtonUI ui = null;
public static void main(final String[] args) {
junit.textui.TestRunner.run(BasicToggleButtonUITest.class);
}
/*
* @see TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
super.setUp();
ui = new MyBasicToggleButtonUI();
}
public void testCreateUI() {
assertTrue("created UI is not null", null != BasicToggleButtonUI
.createUI(new JButton()));
assertTrue("created UI is of the proper class",
BasicToggleButtonUI.createUI(null) instanceof BasicToggleButtonUI);
assertTrue("created UI is of unique",
BasicToggleButtonUI.createUI(null) == BasicToggleButtonUI.createUI(null));
}
public void testGetPropertyPrefix() {
assertEquals("prefix ", "ToggleButton.", ui.getPropertyPrefix());
}
public void testGetTextShiftOffset() {
assertEquals("offset", 0, ui.getTextShiftOffset());
}
}
| 2,349 | 0.681319 | 0.675824 | 71 | 32.323944 | 27.832382 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.380282 | false | false | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.