blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a4700555e55af2c029f0b9235e407297c7bea367 | ceced64751c092feca544ab3654cf40d4141e012 | /Ext_API_Idempotence/src/main/java/com/pri/entity/UserEntity.java | 8dbc24c35459f7d11d48f98129244ad4b090e029 | [] | no_license | 1163646727/pri_play | 80ec6fc99ca58cf717984db82de7db33ef1e71ca | fbd3644ed780c91bfc535444c54082f4414b8071 | refs/heads/master | 2022-06-30T05:14:02.082236 | 2021-01-05T08:02:40 | 2021-01-05T08:02:40 | 196,859,419 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,128 | java | package com.pri.entity;
/**
* className: UserEntity <BR>
* description: <BR>
* remark: 参考文献:每特教育 <BR>
* author: ChenQi <BR>
* createDate: 2019-10-31 23:57 <BR>
*/
public class UserEntity {
private Long id;
private String userName;
private String password;
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the userName
*/
public String getUserName() {
return userName;
}
/**
* @param userName
* the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password
* the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "UserEntity [id=" + id + ", userName=" + userName + ", password=" + password + "]";
}
}
| [
"[email protected]"
] | |
3290f8d2d16ed61314d54afc6d4c46d0555733aa | 998b09ad651631f0b78051c8c7a160ecc7253591 | /src/mooc/main/tv/codely/mooc/students/application/create/CreateStudentCommand.java | 967f61210cdd1b883485f848f27c4b78463c3c8f | [] | no_license | jlezcanof/java-ddd-skeleton | abedb2ae777c4a0549101f314b9dc452aa474905 | a54d5696e676dbb4cd24c62c5c49b381fee23223 | refs/heads/main | 2022-12-30T13:22:54.274020 | 2022-10-07T12:38:49 | 2022-10-07T12:38:49 | 299,089,221 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 690 | java | package tv.codely.mooc.students.application.create;
import tv.codely.shared.domain.bus.command.Command;
public final class CreateStudentCommand implements Command {
private final String id;
private final String name;
private final String surname;
private final String email;
public CreateStudentCommand(String id, String name, String surname, String email){
this.id = id;
this.name = name;
this.surname = surname;
this.email= email;
}
public String id() {return this.id;}
public String name(){ return this.name;}
public String surname(){ return this.surname;}
public String email(){ return this.email;}
}
| [
"[email protected]"
] | |
3a4ef6f87d9424dbd6e1d755721081dd22de9d63 | be87b3f84f35703690bd3589491430809976a876 | /AdministratorskiModul/src/main/java/adminski/modul/app/repository/KomentarRepository.java | 042f3a8185ce2e7b1d4cbea7d34c78c441f9b925 | [] | no_license | micamat/bezbednost-xml-web-servisi | 77cb619307bf6a255fce10f0a347981a479d4199 | 940d6f79ebadeda5317462de4d56e450860f34f1 | refs/heads/master | 2023-01-10T12:26:59.447565 | 2019-11-05T16:07:00 | 2019-11-05T16:07:00 | 174,142,817 | 0 | 0 | null | 2023-01-07T06:39:32 | 2019-03-06T12:39:56 | Java | UTF-8 | Java | false | false | 286 | java | package adminski.modul.app.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import adminski.modul.app.model.Komentar;
@Repository
public interface KomentarRepository extends JpaRepository<Komentar, Long>{
}
| [
"[email protected]"
] | |
fcd098dedc402a8b27859ac558a7ce0cdede61b9 | 34792bfbccc964de94a48a3fa2bc188e9c0b1a39 | /src/com/crazyprof/util/IndexedModel.java | 559b9c544e9e270261c9bee434db2a5583e1c5d4 | [] | no_license | Reested/ClumsyProf | 132ac966c0b74d611d5d2adb182327614afe3945 | 0951f9b07357ee4e5d9eae2977cde8b4811d1715 | refs/heads/master | 2021-06-13T02:32:04.827428 | 2016-12-19T04:35:29 | 2016-12-19T04:35:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,726 | java | package com.crazyprof.util;
import java.util.ArrayList;
import java.util.List;
import com.crazyprof.util.math.Vector4f;
public class IndexedModel
{
private List<Vector4f> m_positions;
private List<Vector4f> m_texCoords;
private List<Vector4f> m_normals;
private List<Vector4f> m_tangents;
private List<Integer> m_indices;
public IndexedModel()
{
m_positions = new ArrayList<Vector4f>();
m_texCoords = new ArrayList<Vector4f>();
m_normals = new ArrayList<Vector4f>();
m_tangents = new ArrayList<Vector4f>();
m_indices = new ArrayList<Integer>();
}
public void CalcNormals()
{
for(int i = 0; i < m_indices.size(); i += 3)
{
int i0 = m_indices.get(i);
int i1 = m_indices.get(i + 1);
int i2 = m_indices.get(i + 2);
Vector4f v1 = m_positions.get(i1).Sub(m_positions.get(i0));
Vector4f v2 = m_positions.get(i2).Sub(m_positions.get(i0));
Vector4f normal = v1.Cross(v2).Normalized();
m_normals.set(i0, m_normals.get(i0).Add(normal));
m_normals.set(i1, m_normals.get(i1).Add(normal));
m_normals.set(i2, m_normals.get(i2).Add(normal));
}
for(int i = 0; i < m_normals.size(); i++)
m_normals.set(i, m_normals.get(i).Normalized());
}
public void CalcTangents()
{
for(int i = 0; i < m_indices.size(); i += 3)
{
int i0 = m_indices.get(i);
int i1 = m_indices.get(i + 1);
int i2 = m_indices.get(i + 2);
Vector4f edge1 = m_positions.get(i1).Sub(m_positions.get(i0));
Vector4f edge2 = m_positions.get(i2).Sub(m_positions.get(i0));
float deltaU1 = m_texCoords.get(i1).GetX() - m_texCoords.get(i0).GetX();
float deltaV1 = m_texCoords.get(i1).GetY() - m_texCoords.get(i0).GetY();
float deltaU2 = m_texCoords.get(i2).GetX() - m_texCoords.get(i0).GetX();
float deltaV2 = m_texCoords.get(i2).GetY() - m_texCoords.get(i0).GetY();
float dividend = (deltaU1*deltaV2 - deltaU2*deltaV1);
float f = dividend == 0 ? 0.0f : 1.0f/dividend;
Vector4f tangent = new Vector4f(
f * (deltaV2 * edge1.GetX() - deltaV1 * edge2.GetX()),
f * (deltaV2 * edge1.GetY() - deltaV1 * edge2.GetY()),
f * (deltaV2 * edge1.GetZ() - deltaV1 * edge2.GetZ()),
0);
m_tangents.set(i0, m_tangents.get(i0).Add(tangent));
m_tangents.set(i1, m_tangents.get(i1).Add(tangent));
m_tangents.set(i2, m_tangents.get(i2).Add(tangent));
}
for(int i = 0; i < m_tangents.size(); i++)
m_tangents.set(i, m_tangents.get(i).Normalized());
}
public List<Vector4f> GetPositions() { return m_positions; }
public List<Vector4f> GetTexCoords() { return m_texCoords; }
public List<Vector4f> GetNormals() { return m_normals; }
public List<Vector4f> GetTangents() { return m_tangents; }
public List<Integer> GetIndices() { return m_indices; }
}
| [
"[email protected]"
] | |
5cfbd2f82c605d4d7414aec74a6bce721de46480 | 7d9b26311a842c8c312ae5816718e3daadf7ddb1 | /ch01/painter/MyLine.java | bad87606f3290992a4a58889a7e639fcdacfb624 | [] | no_license | austinvernsonger/Java-Homework-Assignments | ebf39a27a5291be8a26350dddd878497a98d0c1d | b301d0eccca204d8e5d3c33e4a99976866cf0948 | refs/heads/master | 2020-07-26T17:28:33.860644 | 2015-07-06T15:43:19 | 2015-07-06T15:43:19 | 38,628,393 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 658 | java | // @Austin Vern Songer
// Robert Morris university
//
import java.awt.Color;
import java.awt.Graphics;
public class MyLine extends MyShape
{
// call default superclass constructor
public MyLine()
{
super();
} // end MyLine no-argument constructor
// call superclass constructor passing parameters
public MyLine(int x1, int y1, int x2, int y2, Color color)
{
super(x1, y1, x2, y2, color);
} // end MyLine constructor
// draw line in specified color
public void draw(Graphics g)
{
g.setColor(getColor());
g.drawLine(getX1(), getY1(), getX2(), getY2());
} // end method draw
} // end class MyLine
| [
"[email protected]"
] | |
04515e7c1ac6b504279f14090d9c6a01083d2697 | 4985302b251b3ef657e30221102ff16f4cf2a0ce | /src/main/java/com/om/calEmotion/customs/Test.java | 57d0a64ead4ab48af853137717dbf5c16a5a4f61 | [] | no_license | poice00/NetworkPublicOpinionMap | 9b065c809a244f69fb03494859d0eff1bf5c5e56 | d343cf554244496dc69f3296082b00c7a11e9dab | refs/heads/master | 2021-01-19T01:02:14.873993 | 2016-08-06T03:50:12 | 2016-08-06T03:50:12 | 65,017,431 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,571 | java | package com.om.calEmotion.customs;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
public static double calEmotion(String str) {
String[] strs = str.split("[ ]+");
for (int i = 0; i < strs.length; i++) {
System.out.println(strs[i]);
}
return 0.0;
}
public static double cal1(List<DataBean> list,
Map<String, Double> intenMap, Map<String, Double> posMap,
List<String> fou) {
double result = 0.0;
//printList(list);
//System.out.println("-----------------------");
for (int i = 0; i < list.size(); i++) {
// System.out.println(result);
DataBean dataBean = list.get(i);
if (posMap.containsKey(dataBean.getFirstWord())
&& dataBean.isState()) {
result += cal2(i, dataBean.getFirstPositon(),
dataBean.getFirstWord(), list, intenMap, posMap, fou);
//System.out.println(dataBean.getFirstWord() + "," + result);
}
if (posMap.containsKey(dataBean.getSecondWord())
&& dataBean.isState()) {
result += cal2(i, dataBean.getSecondPositon(),
dataBean.getSecondWord(), list, intenMap, posMap, fou);
//System.out.println(dataBean.getSecondWord() + "." + result);
}
//printList(list);
//System.out.println("-----------------------");
}
return result;
}
public static double cal2(int j, int pos, String posWord,
List<DataBean> list, Map<String, Double> intenMap,
Map<String, Double> posMap, List<String> fou) {
double result = posMap.get(posWord);
//System.out.println("极性词" + posWord);
result *= cal4(pos, pos, list, intenMap);
/*
* for (int i = pos; i < list.size(); i++) { DataBean dataBean =
* list.get(i); double length = Math.abs(dataBean.getFirstPositon() -
* dataBean.getSecondPositon()); double mul = 0;
*/
/*
* if (posWord.equals(dataBean.getFirstWord()) && dataBean.isState()) {
* result += cal3(i, list, intenMap, posMap, fou);
* System.out.println(dataBean.getFirstWord()+result);
* dataBean.setState(false); } if
* (posWord.equals(dataBean.getSecondWord()) && dataBean.isState()) {
* result += cal3(i, list, intenMap, posMap, fou);
* System.out.println(dataBean.getSecondWord()+result);
* dataBean.setState(false); }
*/
/*
* if (dataBean.isState() && posWord.equals(dataBean.getFirstWord())) {
* if (intenMap.containsKey(dataBean.getSecondWord())) { mul =
* intenMap.get(dataBean.getSecondWord()) > 0 ? intenMap
* .get(dataBean.getSecondWord()) : intenMap
* .get(dataBean.getSecondWord()) / length; } result *= mul;
* dataBean.setState(false); }
*
* if (dataBean.isState() && posWord.equals(dataBean.getSecondWord())) {
* if (intenMap.containsKey(dataBean.getFirstWord())) result *=
* intenMap.get(dataBean.getFirstWord()) > 0 ? intenMap
* .get(dataBean.getFirstWord()) : intenMap
* .get(dataBean.getFirstWord()) / length; dataBean.setState(false); } }
*/
double flag = getPos(j, list, fou);
//System.out.println(flag + "flag");
setStringPos(pos, list);
double intent = getStaticIntent(pos, list, intenMap);
return flag * result * intent;
}
public static double cal3(int xx, List<DataBean> list,
Map<String, Double> intenMap, Map<String, Double> posMap,
List<String> fou) {
DataBean dataBean = list.get(xx);
double x = 0;
double length = Math.abs(dataBean.getFirstPositon()
- dataBean.getSecondPositon());
if (posMap.containsKey(dataBean.getFirstWord()) && dataBean.isState()) {
// System.out.println(dataBean.getFirstWord());
double a = intenMap.containsKey(dataBean.getSecondWord()) ? intenMap
.get(dataBean.getSecondWord()) : posMap
.containsKey(dataBean.getSecondWord()) ? posMap
.get(dataBean.getSecondWord()) : 0;
x = a * posMap.get(dataBean.getFirstWord()) / length;
}
if (posMap.containsKey(dataBean.getSecondWord()) && dataBean.isState()) {
double a = intenMap.containsKey(dataBean.getFirstWord()) ? intenMap
.get(dataBean.getFirstWord()) : posMap.containsKey(dataBean
.getFirstWord()) ? posMap.get(dataBean.getFirstWord()) : 0;
x = a * posMap.get(dataBean.getSecondWord()) / length;
}
return x;
}
public static double cal4(int center, int pos, List<DataBean> list,
Map<String, Double> intenMap) {
double result = 1.0;
double length = 1.0;
for (int i = 0; i < list.size(); i++) {
DataBean dataBean = list.get(i);
if (dataBean.isState()) {
if (dataBean.getFirstPositon() == pos) {
if (intenMap.containsKey(dataBean.getSecondWord())) {
length = Math.abs(dataBean.getSecondPositon() - center) > 1 ? 2
: 1;
result *= intenMap.get(dataBean.getSecondWord()) > 0 ? intenMap
.get(dataBean.getSecondWord()) : intenMap
.get(dataBean.getSecondWord()) / length;
dataBean.setState(false);
result *= cal4(center, dataBean.getSecondPositon(),
list, intenMap);
}
//System.out.println(result + "--");
}
if (dataBean.getSecondPositon() == pos) {
if (intenMap.containsKey(dataBean.getFirstWord())) {
length = Math.abs(dataBean.getFirstPositon() - center) > 1 ? 2
: 1;
//System.out
// .println(intenMap.get(dataBean.getFirstWord()));
result *= intenMap.get(dataBean.getFirstWord()) > 0 ? intenMap
.get(dataBean.getFirstWord()) : intenMap
.get(dataBean.getFirstWord()) / length;
//System.out.println(result + "22" + length);
dataBean.setState(false);
result *= cal4(center, dataBean.getFirstPositon(),
list, intenMap);
}
}
}
}
return result;
}
// 获得未使用的全局极性
public static double getPos(int xx, List<DataBean> list, List<String> fou) {
double flag = 1;
for (int i = 0; i < xx; i++) {
DataBean dataBean = list.get(i);
if (fou.contains(dataBean.getFirstWord()) && dataBean.isState()) {
if (isNotUsed(dataBean.getFirstPositon(), list))
flag = -flag;
// System.out.println(flag+"--");
}
if (fou.contains(dataBean.getSecondWord()) && dataBean.isState()) {
// System.out.println(isNotUsed(dataBean.getSecondPositon(),
// list));
if (isNotUsed(dataBean.getSecondPositon(), list))
flag = -flag;
// System.out.println(flag+"++");
}
}
return flag > 0 ? flag : flag / 2;
}
public static boolean isNotUsed(int pos, List<DataBean> list) {
//System.out.println(pos + ">>>>>>>");
for (int i = 0; i < list.size(); i++) {
DataBean dataBean = list.get(i);
if ((dataBean.getFirstPositon() == pos || dataBean
.getSecondPositon() == pos) && !dataBean.isState())
return false;
}
return true;
}
public static DataBean getDataBean(String str) {
// String s = "我_0 是_1 SBV";
//System.out.println(str+">>>>>>>>>>>>>>>>>>>>>>");
if(str.trim().length()==0){
return null;
}
String[] strs = str.split("[ ]+");
//System.out.println(strs[0]);
String firstWord = strs[0].substring(0, strs[0].lastIndexOf("_"));
// System.out.println(firstWord);
int firstPositon = Integer.valueOf(strs[0].substring(strs[0]
.lastIndexOf("_") + 1));
String secondWord = "";
int secondPosition = 0;
if (strs[1].equals("-1")) {
secondWord = "_";
secondPosition = -1;
} else {
secondWord = strs[1].substring(0, strs[1].lastIndexOf("_"));
secondPosition = Integer.valueOf(strs[1].substring(strs[1]
.lastIndexOf("_") + 1));
}
return new DataBean(firstWord, firstPositon, secondWord,
secondPosition, strs[2], 0, true);
}
public static List<DataBean> getListBeans(String str) {
List<DataBean> dataBeans = new ArrayList<DataBean>();
String[] strs = str.split("[#]{4}");
for (int i = 0; i < strs.length; i++) {
// System.out.println("," + strs[i] + ",");
DataBean dataBean = getDataBean(strs[i]);
// System.out.println(dataBean);
if(dataBean!=null)
dataBeans.add(dataBean);
}
return dataBeans;
}
// 把当前计算过的情感词置为false
public static void setStringPos(int pos, List<DataBean> list) {
for (int i = 0; i < list.size(); i++) {
DataBean dataBean = list.get(i);
if (dataBean.getFirstPositon() == pos
|| dataBean.getSecondPositon() == pos)
dataBean.setState(false);
}
}
// 把剩余的程度副词考虑在内
public static double getStaticIntent(int center, List<DataBean> list,
Map<String, Double> intenMap) {
double result = 1.0;
for (int i = 0; i < list.size(); i++) {
DataBean dataBean = list.get(i);
if (dataBean.isState()) {
if (intenMap.containsKey(dataBean.getFirstWord())
&& dataBean.getFirstPositon() < center)
result *= intenMap.get(dataBean.getFirstWord());
if (intenMap.containsKey(dataBean.getSecondWord())
&& dataBean.getSecondPositon() < center)
result *= intenMap.get(dataBean.getSecondWord());
}
}
return result;
}
public static void printList(List<DataBean> list) {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
public static Map<String, Double> getMapFromText(String src)
throws Exception {
Map<String, Double> map = new HashMap<String, Double>();
BufferedReader bReader = new BufferedReader(new FileReader(
new File(src)));
String s;
String[] strs = new String[2];
while (!(s = bReader.readLine()).equals("$")) {
strs = s.split("[ ]+");
map.put(strs[0].trim(), Double.valueOf(strs[1]));
}
bReader.close();
return map;
}
public static void main(String[] args) throws Exception {
/*
* String str = "我_0 是_1 SBV" + "是_1 -1 HED" + "中国_2 人_3 ATT" +
* "人_3 是_1 VOB"; calEmotion(str);
*/
/*
* System.out.println(getDataBean("我_0 是_1 SBV"));
*
* List<DataBean> list = new ArrayList<DataBean>(); list.add(new
* DataBean("他", 0, "是", 2, "SBV", 0, true)); list.add(new DataBean("不",
* 1, "是", 2, "ADV", 0, true)); list.add(new DataBean("是", 2, "-", -1,
* "HED", 0, true)); list.add(new DataBean("一个", 3, "人", 7, "ATT", 0,
* true)); list.add(new DataBean("很", 4, "骄傲", 5, "ADV", 0, true));
* list.add(new DataBean("骄傲", 5, "人", 7, "ATT", 0, true)); list.add(new
* DataBean("的", 6, "骄傲", 5, "RAD", 0, true)); list.add(new
* DataBean("人", 7, "是", 2, "VOB", 0, true)); list.add(new DataBean(",",
* 8, "是", 2, "WP", 0, true)); System.out.println(cal1(list, mapInten,
* mapPos, fou));
*/
//Map<String, Double> mapPos = getMapFromText("C:\\Users\\Administrator\\Desktop\\dic\\userful.txt");
//mapPos.put("漂亮", 0.8);
//mapPos.put("美丽", 0.7);
//Map<String, Double> mapInten = getMapFromText("C:\\Users\\Administrator\\Desktop\\dic\\intent_userful.txt");
//mapInten.put("很", 1.5);
//mapInten.put("不", -1.0);
//List<String> fou = new ArrayList<String>();
//fou.add("不");
//CustomSegmentation api = new CustomSegmentation();
// api.analyze("file.txt");
//String result = api.analyzeGetResult("不很漂亮");
//List<DataBean> list = getListBeans(result);
//System.out.println(cal1(list, mapInten, mapPos, fou));
System.out.println("http://www.xzlza.gov.cn/qx_show.aspx_0".lastIndexOf('_'));
getDataBean("http://www.xzlza.gov.cn/qx_show.aspx_0 -1 HED");
}
}
| [
"[email protected]"
] | |
15a926e4d99296ea1dcf0b7ec75d668c0f21abbf | 1c99b985fb85a620be89c1425770b732937f0a39 | /LAB_02/src/main/java/com/whynot/zio/Lab02Application.java | c6876cd35350adf56e034c72ba4a616d13ec47e9 | [] | no_license | SideswipeN7/zio | 6a6cfd74af9e44bcb204b1891d16191746d8ac47 | 5ede93e56e604be055a6e69ed17834ba6d9178f0 | refs/heads/master | 2022-03-09T11:01:20.861869 | 2019-12-01T10:28:54 | 2019-12-01T10:28:54 | 213,036,071 | 0 | 0 | null | 2019-12-01T10:28:56 | 2019-10-05T16:50:53 | Java | UTF-8 | Java | false | false | 317 | java | package com.whynot.zio;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Lab02Application {
public static void main(String[] args) {
SpringApplication.run(Lab02Application.class, args);
}
}
| [
"[email protected]"
] | |
f8d3d938bd1852b94eafcc1a1b9e33e2d8d353ca | e36e942033f30b723e69111b85ca308165799c77 | /app/common/util/src/main/java/com/tiny/common/util/MockDataUtil.java | 9668d11caad4086644d4d0e9c47b36439d892a27 | [] | no_license | shenjun134/tiny | eca00ddaa84ea80f3b87bb9949a4de2995eee205 | 216076a79137984738483d75b663d90092192935 | refs/heads/master | 2020-03-22T15:48:45.474060 | 2019-05-10T15:30:59 | 2019-05-10T15:30:59 | 140,280,507 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,560 | java | package com.tiny.common.util;
import com.tiny.common.entity.MockData;
import com.tiny.common.entity.MockHead;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang.StringUtils;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MockDataUtil {
public static MockData parseMockData(String file) {
Reader reader = null;
MockData mockData = new MockData();
try {
URL resource = Thread.currentThread().getContextClassLoader().getResource(file);
reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(resource.toURI()))));
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT);
int index = 0;
for (CSVRecord csvRecord : csvParser) {
int size = csvRecord.size();
index++;
if (index == 1) {
List<MockHead> list = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
String value = csvRecord.get(i);
MockHead mockHead = new MockHead();
mockHead.setName(value);
mockHead.setIndex(i);
list.add(mockHead);
}
mockData.setHeadList(list);
continue;
}
List<String> list = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
String value = csvRecord.get(i);
list.add(value);
}
mockData.getValueList().add(list);
}
} catch (FileNotFoundException e) {
throw new RuntimeException("No " + file + " found", e);
} catch (IOException e) {
throw new RuntimeException("No " + file + " found", e);
} catch (URISyntaxException e) {
throw new RuntimeException("No " + file + " found", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (CollectionUtils.isEmpty(mockData.getHeadList())) {
return mockData;
}
for (int i = 0, len = mockData.getHeadList().size(); i < len; i++) {
MockHead mockHead = mockData.getHeadList().get(i);
int max = getMaxSize(mockData, i);
int headLength = StringUtils.length(mockHead.getName());
if (max < headLength) {
max = headLength;
}
mockData.getHeadList().get(i).setMaxLenght(max);
}
return mockData;
}
private static int getMaxSize(MockData mockData, int colIndex) {
int max = 0;
for (List<String> row : mockData.getValueList()) {
String value = row.get(colIndex);
int length = StringUtils.length(value);
if (length > max) {
max = length;
}
}
return max;
}
public static List<MockHead> copyShuffle(List<MockHead> headList) {
List<MockHead> temp = new ArrayList<>(headList);
Collections.shuffle(temp);
return temp;
}
}
| [
"[email protected]"
] | |
0d0a13f9601e1e31daa5a466cda5ee6d1bde8784 | 6531ce0997f2552f01098d06c34195a5c52a0ea9 | /app/src/main/java/es/ulpgc/miguel/masterdetailrealm/add/AddRouter.java | 6c736362ba8b5d58ba50784f227650f27aa23dd1 | [] | no_license | miguelleonmarti/masterDetailRealm | 0f01821a7aa93a640dcd7b7e5063a18554f6b9a5 | 85ffd3f08763ba6350063831cd54c0e6cb692f42 | refs/heads/master | 2020-11-26T16:30:02.363062 | 2020-01-07T13:59:31 | 2020-01-07T13:59:31 | 229,139,304 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,116 | java | package es.ulpgc.miguel.masterdetailrealm.add;
import android.content.Context;
import android.content.Intent;
import es.ulpgc.miguel.masterdetailrealm.app.AppMediator;
import es.ulpgc.miguel.masterdetailrealm.master.MasterActivity;
public class AddRouter implements AddContract.Router {
public static String TAG = AddRouter.class.getSimpleName();
private AppMediator mediator;
public AddRouter(AppMediator mediator) {
this.mediator = mediator;
}
@Override
public void navigateToNextScreen() {
Context context = mediator.getApplicationContext();
Intent intent = new Intent(context, AddActivity.class);
context.startActivity(intent);
}
@Override
public void passDataToNextScreen(AddState state) {
mediator.setAddState(state);
}
@Override
public AddState getDataFromPreviousScreen() {
AddState state = mediator.getAddState();
return state;
}
@Override
public void navigateToMasterScreen() {
Context context = mediator.getApplicationContext();
Intent intent = new Intent(context, MasterActivity.class);
context.startActivity(intent);
}
}
| [
"[email protected]"
] | |
b84eaf1c9c2215fb119c4600daa84c522359d065 | 80991460cefaf24f3fdd33b99925952d24cc1886 | /hw0/Max2.java | 2484351db46e7afc3fbd20060df611ecc9596103 | [] | no_license | elinsky/CS61B | 79609334b19cb46825e905c8a29463252b01487f | 0ae302b0ca46f9f7b15cdef0818d5f9c9cd3fc23 | refs/heads/master | 2023-01-13T14:28:32.312126 | 2020-11-18T13:40:46 | 2020-11-18T13:40:46 | 253,020,719 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 244 | java | public class Max2 {
public static void main (String[] args) {
int max = 0;
int i = 0;
for (; i < args.length; i += 1) {
if (Integer.parseInt (args[i]) > max)
max = Integer.parseInt (args[i]);
}
System.out.println (max);
}
}
| [
"[email protected]"
] | |
1d209e87cb15d64eddef29943b5c975f41ffae79 | 59bc292fe0fdac3ef78dfa2ec1b0342d623815a6 | /src/main/java/com/sbdc/sbdcweb/member/domain/request/DeleteForm.java | e53da25e61ccf5b4024408ba3219b1e2297c4d56 | [] | no_license | sirleeone31/sbdcweb | 58927e4567e06f10459fcecf06c64aeb1e7945e5 | e232c6840404f26239fc7276b54a4dd86193ca7a | refs/heads/master | 2023-05-15T08:01:58.769378 | 2021-06-17T07:48:31 | 2021-06-17T07:48:31 | 297,354,190 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 268 | java | package com.sbdc.sbdcweb.member.domain.request;
import lombok.Data;
/**
* ChangeForm Domain
* 회원탈퇴
*
* @author : 이승희
* @version : 1.0
* @since : 1.0
* @date : 2019-06-10
*/
@Data
public class DeleteForm {
private String retireComment;
} | [
"[email protected]"
] | |
191cc75f2bc6d81d7c42b19d239b89980a52d734 | 937536c416263ad7c54e6de1c5d0097ae895aa9b | /src/test/java/racinggame/domain/car/PositionTest.java | e2f142d248a29a711b6bdf6263f0c38c91bcf21a | [] | no_license | include42/java-racingcar | 112f72def3c833d762c55f8016960592ffc07db0 | 04f63f4ccdf7da51fca5c363eb44de22d2d3cd70 | refs/heads/master | 2021-01-02T14:26:14.167675 | 2020-02-18T14:40:48 | 2020-02-18T14:40:48 | 239,661,032 | 0 | 0 | null | 2020-02-11T02:43:57 | 2020-02-11T02:43:56 | null | UTF-8 | Java | false | false | 1,838 | java | package racinggame.domain.car;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
public class PositionTest {
@ParameterizedTest
@ValueSource(strings = {"10", "5", "0"})
void 위치값_생성_테스트(int value) {
Position position = new Position(value);
Assertions.assertThat(position.match(value)).isTrue();
}
@ParameterizedTest
@ValueSource(strings = {"-1", "-214"})
void 위치값_오류_테스트(int value) {
Assertions.assertThatThrownBy(() -> {
Position position = new Position(value);
}).isInstanceOf(IllegalArgumentException.class)
.hasMessageMatching("위치값은 0 이상이어야 합니다.");
}
@Test
void 위치값_가속메서드_호출_테스트() {
Position position1 = new Position(0);
position1.accelerate();
Assertions.assertThat(position1.match(1)).isTrue();
Position position2 = new Position(0);
position2.accelerate(3);
Assertions.assertThat(position2.match(3)).isTrue();
}
@Test
void 위치값_가속메서드_에러_테스트() {
Position position1 = new Position(0);
Assertions.assertThatThrownBy(() -> position1.accelerate(-1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageMatching("잘못된 요청이 가속 메서드에 전달되었습니다");
Position position2 = new Position(100000);
Assertions.assertThatThrownBy(() -> position2.accelerate(2147483647))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageMatching("잘못된 요청이 가속 메서드에 전달되었습니다");
}
}
| [
"[email protected]"
] | |
af8bed06b48caaa5f6637150c0340d771af90d40 | f0da222a17b179ab407565d42914882cf629939d | /app/src/main/java/com/ekattorit/tishunote/apapters/NotesAdapterListener.java | 8dfb36b5c420baf62b8981ba9a851f3298a500a1 | [] | no_license | smensulaiman/Tishu-Note | 2e38bf25c238a58f3e9fcb9acdccf19f3be3758d | c4c2460b812a0d34b452ac1d5927540a025181eb | refs/heads/master | 2022-06-30T10:23:16.173500 | 2020-05-14T09:46:26 | 2020-05-14T09:46:26 | 263,261,681 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 174 | java | package com.ekattorit.tishunote.apapters;
public interface NotesAdapterListener {
public void onItemClick(int position);
public void onItemDelete(int position);
}
| [
"[email protected]"
] | |
3f71c5936fdfefdc58681311958574fd8cb3c35a | 8af1164bac943cef64e41bae312223c3c0e38114 | /results-java/spring-projects--spring-framework/d554229981381979d63c3228ae0195a376fa3b18/before/TransportHandlingSockJsService.java | 70fc96a1c8635819a5a690518a883ccf4f5c35f9 | [] | no_license | fracz/refactor-extractor | 3ae45c97cc63f26d5cb8b92003b12f74cc9973a9 | dd5e82bfcc376e74a99e18c2bf54c95676914272 | refs/heads/master | 2021-01-19T06:50:08.211003 | 2018-11-30T13:00:57 | 2018-11-30T13:00:57 | 87,353,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,836 | java | /*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.socket.sockjs.transport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import org.springframework.context.Lifecycle;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeFailureException;
import org.springframework.web.socket.server.HandshakeHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.socket.server.support.HandshakeInterceptorChain;
import org.springframework.web.socket.sockjs.SockJsException;
import org.springframework.web.socket.sockjs.frame.Jackson2SockJsMessageCodec;
import org.springframework.web.socket.sockjs.frame.SockJsMessageCodec;
import org.springframework.web.socket.sockjs.support.AbstractSockJsService;
/**
* A basic implementation of {@link org.springframework.web.socket.sockjs.SockJsService}
* with support for SPI-based transport handling and session management.
*
* <p>Based on the {@link TransportHandler} SPI. {@link TransportHandler}s may additionally
* implement the {@link SockJsSessionFactory} and {@link HandshakeHandler} interfaces.
*
* <p>See the {@link AbstractSockJsService} base class for important details on request mapping.
*
* @author Rossen Stoyanchev
* @author Juergen Hoeller
* @author Sebastien Deleuze
* @since 4.0
*/
public class TransportHandlingSockJsService extends AbstractSockJsService implements SockJsServiceConfig, Lifecycle {
private static final boolean jackson2Present = ClassUtils.isPresent(
"com.fasterxml.jackson.databind.ObjectMapper", TransportHandlingSockJsService.class.getClassLoader());
private final Map<TransportType, TransportHandler> handlers = new HashMap<TransportType, TransportHandler>();
private SockJsMessageCodec messageCodec;
private final List<HandshakeInterceptor> interceptors = new ArrayList<HandshakeInterceptor>();
private final Map<String, SockJsSession> sessions = new ConcurrentHashMap<String, SockJsSession>();
private ScheduledFuture<?> sessionCleanupTask;
private boolean running;
/**
* Create a TransportHandlingSockJsService with given {@link TransportHandler handler} types.
* @param scheduler a task scheduler for heart-beat messages and removing timed-out sessions;
* the provided TaskScheduler should be declared as a Spring bean to ensure it gets
* initialized at start-up and shuts down when the application stops
* @param handlers one or more {@link TransportHandler} implementations to use
*/
public TransportHandlingSockJsService(TaskScheduler scheduler, TransportHandler... handlers) {
this(scheduler, Arrays.asList(handlers));
}
/**
* Create a TransportHandlingSockJsService with given {@link TransportHandler handler} types.
* @param scheduler a task scheduler for heart-beat messages and removing timed-out sessions;
* the provided TaskScheduler should be declared as a Spring bean to ensure it gets
* initialized at start-up and shuts down when the application stops
* @param handlers one or more {@link TransportHandler} implementations to use
*/
public TransportHandlingSockJsService(TaskScheduler scheduler, Collection<TransportHandler> handlers) {
super(scheduler);
if (CollectionUtils.isEmpty(handlers)) {
logger.warn("No transport handlers specified for TransportHandlingSockJsService");
}
else {
for (TransportHandler handler : handlers) {
handler.initialize(this);
this.handlers.put(handler.getTransportType(), handler);
}
}
if (jackson2Present) {
this.messageCodec = new Jackson2SockJsMessageCodec();
}
}
/**
* Return the registered handlers per transport type.
*/
public Map<TransportType, TransportHandler> getTransportHandlers() {
return Collections.unmodifiableMap(this.handlers);
}
/**
* The codec to use for encoding and decoding SockJS messages.
*/
public void setMessageCodec(SockJsMessageCodec messageCodec) {
this.messageCodec = messageCodec;
}
public SockJsMessageCodec getMessageCodec() {
Assert.state(this.messageCodec != null, "A SockJsMessageCodec is required but not available: " +
"Add Jackson 2 to the classpath, or configure a custom SockJsMessageCodec.");
return this.messageCodec;
}
/**
* Configure one or more WebSocket handshake request interceptors.
*/
public void setHandshakeInterceptors(List<HandshakeInterceptor> interceptors) {
this.interceptors.clear();
if (interceptors != null) {
this.interceptors.addAll(interceptors);
}
}
/**
* Return the configured WebSocket handshake request interceptors.
*/
public List<HandshakeInterceptor> getHandshakeInterceptors() {
return this.interceptors;
}
@Override
public void start() {
if (!isRunning()) {
this.running = true;
for (TransportHandler handler : this.handlers.values()) {
if (handler instanceof Lifecycle) {
((Lifecycle) handler).start();
}
}
}
}
@Override
public void stop() {
if (isRunning()) {
this.running = false;
for (TransportHandler handler : this.handlers.values()) {
if (handler instanceof Lifecycle) {
((Lifecycle) handler).stop();
}
}
}
}
@Override
public boolean isRunning() {
return this.running;
}
@Override
protected void handleRawWebSocketRequest(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler handler) throws IOException {
TransportHandler transportHandler = this.handlers.get(TransportType.WEBSOCKET);
if (!(transportHandler instanceof HandshakeHandler)) {
logger.error("No handler configured for raw WebSocket messages");
response.setStatusCode(HttpStatus.NOT_FOUND);
return;
}
HandshakeInterceptorChain chain = new HandshakeInterceptorChain(this.interceptors, handler);
HandshakeFailureException failure = null;
try {
Map<String, Object> attributes = new HashMap<String, Object>();
if (!chain.applyBeforeHandshake(request, response, attributes)) {
return;
}
((HandshakeHandler) transportHandler).doHandshake(request, response, handler, attributes);
chain.applyAfterHandshake(request, response, null);
}
catch (HandshakeFailureException ex) {
failure = ex;
}
catch (Throwable ex) {
failure = new HandshakeFailureException("Uncaught failure for request " + request.getURI(), ex);
}
finally {
if (failure != null) {
chain.applyAfterHandshake(request, response, failure);
throw failure;
}
}
}
@Override
protected void handleTransportRequest(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler handler, String sessionId, String transport) throws SockJsException {
TransportType transportType = TransportType.fromValue(transport);
if (transportType == null) {
if (logger.isWarnEnabled()) {
logger.warn("Unknown transport type for " + request.getURI());
}
response.setStatusCode(HttpStatus.NOT_FOUND);
return;
}
TransportHandler transportHandler = this.handlers.get(transportType);
if (transportHandler == null) {
if (logger.isWarnEnabled()) {
logger.warn("No TransportHandler for " + request.getURI());
}
response.setStatusCode(HttpStatus.NOT_FOUND);
return;
}
SockJsException failure = null;
HandshakeInterceptorChain chain = new HandshakeInterceptorChain(this.interceptors, handler);
try {
HttpMethod supportedMethod = transportType.getHttpMethod();
if (supportedMethod != request.getMethod()) {
if (HttpMethod.OPTIONS == request.getMethod() && transportType.supportsCors()) {
if (checkOrigin(request, response, HttpMethod.OPTIONS, supportedMethod)) {
response.setStatusCode(HttpStatus.NO_CONTENT);
addCacheHeaders(response);
}
}
else if (transportType.supportsCors()) {
sendMethodNotAllowed(response, supportedMethod, HttpMethod.OPTIONS);
}
else {
sendMethodNotAllowed(response, supportedMethod);
}
return;
}
SockJsSession session = this.sessions.get(sessionId);
if (session == null) {
if (transportHandler instanceof SockJsSessionFactory) {
Map<String, Object> attributes = new HashMap<String, Object>();
if (!chain.applyBeforeHandshake(request, response, attributes)) {
return;
}
SockJsSessionFactory sessionFactory = (SockJsSessionFactory) transportHandler;
session = createSockJsSession(sessionId, sessionFactory, handler, attributes);
}
else {
response.setStatusCode(HttpStatus.NOT_FOUND);
if (logger.isDebugEnabled()) {
logger.debug("Session not found, sessionId=" + sessionId +
". The session may have been closed " +
"(e.g. missed heart-beat) while a message was coming in.");
}
return;
}
}
else {
if (session.getPrincipal() != null) {
if (!session.getPrincipal().equals(request.getPrincipal())) {
logger.debug("The user for the session does not match the user for the request.");
response.setStatusCode(HttpStatus.NOT_FOUND);
return;
}
}
}
if (transportType.sendsNoCacheInstruction()) {
addNoCacheHeaders(response);
}
if (transportType.supportsCors()) {
if (!checkOrigin(request, response)) {
return;
}
}
transportHandler.handleRequest(request, response, handler, session);
chain.applyAfterHandshake(request, response, null);
}
catch (SockJsException ex) {
failure = ex;
}
catch (Throwable ex) {
failure = new SockJsException("Uncaught failure for request " + request.getURI(), sessionId, ex);
}
finally {
if (failure != null) {
chain.applyAfterHandshake(request, response, failure);
throw failure;
}
}
}
@Override
protected boolean validateRequest(String serverId, String sessionId, String transport) {
if (!super.validateRequest(serverId, sessionId, transport)) {
return false;
}
if (!this.allowedOrigins.contains("*")) {
TransportType transportType = TransportType.fromValue(transport);
if (transportType == null || !transportType.supportsOrigin()) {
if (logger.isWarnEnabled()) {
logger.warn("Origin check enabled but transport '" + transport + "' does not support it.");
}
return false;
}
}
return true;
}
private SockJsSession createSockJsSession(String sessionId, SockJsSessionFactory sessionFactory,
WebSocketHandler handler, Map<String, Object> attributes) {
SockJsSession session = this.sessions.get(sessionId);
if (session != null) {
return session;
}
if (this.sessionCleanupTask == null) {
scheduleSessionTask();
}
session = sessionFactory.createSession(sessionId, handler, attributes);
this.sessions.put(sessionId, session);
return session;
}
private void scheduleSessionTask() {
synchronized (this.sessions) {
if (this.sessionCleanupTask != null) {
return;
}
final List<String> removedSessionIds = new ArrayList<String>();
this.sessionCleanupTask = getTaskScheduler().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
for (SockJsSession session : sessions.values()) {
try {
if (session.getTimeSinceLastActive() > getDisconnectDelay()) {
sessions.remove(session.getId());
session.close();
}
}
catch (Throwable ex) {
// Could be part of normal workflow (e.g. browser tab closed)
logger.debug("Failed to close " + session, ex);
}
}
if (logger.isDebugEnabled() && !removedSessionIds.isEmpty()) {
logger.debug("Closed " + removedSessionIds.size() + " sessions " + removedSessionIds);
removedSessionIds.clear();
}
}
}, getDisconnectDelay());
}
}
} | [
"[email protected]"
] | |
07c6a677c160a34794c1694f9cd21cf62fdb1287 | 055e74dcede3b54d2c4156da29e160d7b3f6024c | /Pacman/src/frontend/End.java | 58f8709748552f2ab050c9f856493eb0eba3649f | [] | no_license | JDaniloC/GAME-Ferias-2019.2 | fc2d54b7eb3760a3cd61ce4aa57cd24b309fe502 | 113b80d399ea1c9a99b26041dbd37a882f5447e8 | refs/heads/master | 2021-06-26T21:59:51.335622 | 2020-09-28T20:18:20 | 2020-09-28T20:18:20 | 214,432,514 | 0 | 3 | null | 2021-06-14T23:37:46 | 2019-10-11T12:36:56 | Java | UTF-8 | Java | false | false | 1,192 | java | package frontend;
import javax.swing.*;
import java.awt.*;
public class End extends JFrame {
public End(int pontos, boolean venceu) {
setSize(717, 730);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
ImageIcon imagem;
if (venceu) {
imagem = new ImageIcon(new ImageIcon("./src/Imagens/Misc/Win.gif").getImage().getScaledInstance(717, 600, Image.SCALE_DEFAULT));
this.getContentPane().setBackground(Color.BLACK);
} else {
imagem = new ImageIcon("./src/Imagens/Misc/GameOver.jpg");
this.getContentPane().setBackground(Color.decode("#000000"));
}
JLabel label = new JLabel(imagem);
this.getContentPane().add(label, BorderLayout.PAGE_START);
Font fonte = new Font(Font.SANS_SERIF, Font.BOLD, 70);
JLabel texto = new JLabel("Pontuação", SwingConstants.CENTER);
texto.setFont(fonte);
texto.setForeground(Color.WHITE);
texto.setText("Pontuação: " + pontos);
add(texto, BorderLayout.PAGE_END);
setVisible(true);
}
}
| [
"[email protected]"
] | |
774ac6345c31d980aade2e09b3a20573415462a1 | c6963e5f989a3a120fd21014a2e75f1f561d669a | /src/DSA2/Graphs/Algos/BellmanFord.java | 38d8c4412331fba409d44c9573cafecb55dd60c6 | [] | no_license | ayushman999/CN_DSA | 6274540ad3e4ee0460997d935a755f2918fb5f5d | eb16e1e3c81880bd11723485e9add64531947faa | refs/heads/main | 2023-07-21T03:45:24.514948 | 2021-09-08T13:20:07 | 2021-09-08T13:20:07 | 395,240,116 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,704 | java | package DSA2.Graphs.Algos;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class BellmanFord {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
ArrayList<ArrayList<ArrayList<Integer>>> adj=new ArrayList<>();
int v=sc.nextInt();
int e=sc.nextInt();
ArrayList<Edge> edge=new ArrayList<>();
for(int i=0;i<v;i++)
{
adj.add(new ArrayList<>());
}
for(int i=0;i<e;i++)
{
int sv=sc.nextInt();
int ev=sc.nextInt();
int wv=sc.nextInt();
ArrayList<Integer> list=new ArrayList<>();
list.add(ev);
list.add(wv);
ArrayList<Integer> list1=new ArrayList<>();
list1.add(sv);
list1.add(wv);
adj.get(ev).add(list1);
adj.get(sv).add(list);
edge.add(new Edge(sv,ev,wv));
}
check(v,edge);
}
private static void check( int v,ArrayList<Edge> edge) {
int[] distance=new int[v];
Arrays.fill(distance,Integer.MAX_VALUE);
distance[0]=0;
for(int i=1;i<v;i++)
{
for(int j=0;j<edge.size();j++)
{
Edge p=edge.get(j);
int sv=p.sv;
int ev=p.ev;
int d= distance[sv]+p.weight;
if(d<distance[ev])
{
distance[ev]=d;
}
}
}
}
}
class Edge{
int sv,ev,weight;
public Edge(int sv, int ev, int weight) {
this.sv = sv;
this.ev = ev;
this.weight = weight;
}
}
| [
"[email protected]"
] | |
87cb866e3c5fd7a1c78d27d24472d5333a86d251 | 13200e547eec0d67ff9da9204c72ab26a93f393d | /src/com/google/android/gms/awareness/snapshot/internal/NetworkStateImpl.java | fb9490996e2cadd7b0aca04c7eb37a7a11675924 | [] | no_license | emtee40/DecompiledPixelLauncher | d72d107eaafb42896aa903b9f0f34f5f09f5a15c | fb954b108a7bf3377da5c28fd9a2f22e1b6990ea | refs/heads/master | 2020-04-03T03:18:06.239632 | 2018-01-19T08:49:36 | 2018-01-19T08:49:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,097 | java | //
// Decompiled by Procyon v0.5.30
//
package com.google.android.gms.awareness.snapshot.internal;
import android.os.Parcel;
import android.os.Parcelable$Creator;
import com.google.android.gms.common.internal.safeparcel.AbstractSafeParcelable;
public class NetworkStateImpl extends AbstractSafeParcelable
{
public static final Parcelable$Creator CREATOR;
private final int fS;
private final int fT;
private final int fU;
static {
CREATOR = (Parcelable$Creator)new l();
}
NetworkStateImpl(final int ft, final int fs, final int fu) {
this.fT = ft;
this.fS = fs;
this.fU = fu;
}
public static String eu(final int n) {
switch (n) {
default: {
return new StringBuilder(37).append("unknown connection state: ").append(n).toString();
}
case 1: {
return "DISCONNECTED";
}
case 2: {
return "ON_WIFI";
}
case 3: {
return "ON_CELLULAR";
}
}
}
public static String ew(final int n) {
switch (n) {
default: {
return new StringBuilder(32).append("unknown meter state: ").append(n).toString();
}
case 1: {
return "METERED";
}
case 2: {
return "UNMETERED";
}
}
}
int ev() {
return this.fU;
}
public int ex() {
return this.fS;
}
int ey() {
return this.fT;
}
public String toString() {
final String value = String.valueOf(eu(this.fS));
final String value2 = String.valueOf(ew(this.fU));
return new StringBuilder(String.valueOf(value).length() + 41 + String.valueOf(value2).length()).append("ConnectionState = ").append(value).append(" NetworkMeteredState = ").append(value2).toString();
}
public void writeToParcel(final Parcel parcel, final int n) {
l.gc(this, parcel, n);
}
}
| [
"[email protected]"
] | |
e3a14bc9e3a349d6a6a11396e000aa2fd9f8201f | e13ccce89488fc448e72958a952a4c196b97657a | /Space_Invaders/src/screens/GameOver.java | f38afac12b517abae7ed00bba87e2760db3ee109 | [] | no_license | danielkag2000/Space_Invaders | f21694a56c9fdf89bbd31773e5e6ec5583889be1 | 54fc8e619308cd654fcac48c1738cd55272fe5f8 | refs/heads/master | 2020-05-03T04:59:48.331541 | 2019-03-29T16:11:04 | 2019-03-29T16:11:04 | 178,437,353 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,145 | java | package screens;
import java.awt.Color;
import biuoop.DrawSurface;
import interfaces.Animation;
/**
* the game over screen.
*
* @author Daniel Kaganovich
* @version 1.0
* @since 2018-05-20
*/
public class GameOver implements Animation {
private int score;
private boolean stop;
/**
* create new end game animation.
*
* @param score the score of the player
*/
public GameOver(int score) {
this.score = score;
this.stop = false;
}
@Override
public void doOneFrame(DrawSurface d, double dt) {
d.setColor(Color.LIGHT_GRAY);
d.fillRectangle(0, 0, 800, 800);
d.setColor(Color.YELLOW.darker());
d.drawText(d.getWidth() / 2 - 250, 100, "Game Over, Your score is " + this.score, 40);
d.setColor(Color.ORANGE.darker());
d.drawText(d.getWidth() / 2 - 170, d.getHeight() / 2, "try to do better next time", 35);
d.setColor(Color.BLACK);
d.drawText(d.getWidth() / 2 - 150, d.getHeight() - 50, "press space to continue", 30);
}
@Override
public boolean shouldStop() {
return this.stop;
}
}
| [
"[email protected]"
] | |
b2520d63cae94217cd41688b78d1100d8c6438f9 | cbd09f8591b1597c3aedebb0961d9d4a811319b3 | /main/java/Collections/_2_iterator/_1_adapter/Test_1.java | a5b29dca78bac3a2ed533264f84672a62c26a187 | [] | no_license | olaaa/sg | 1ca82b342e0c06b7368eae5879d64f081bc6d731 | 2a51f7b959fb3275b71fe7d49e5031aa27ba9214 | refs/heads/master | 2021-01-16T21:03:45.563287 | 2016-04-11T12:44:31 | 2016-04-11T12:44:31 | 62,746,715 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,100 | java | package Collections._2_iterator._1_adapter;
import java.io.ByteArrayInputStream;
import java.util.Iterator;
public class Test_1 {
public static void main(String[] args) {
test(new byte[] {1});
System.out.print("OK");
}
private static void test(byte[] array) {
testNextWithoutHasNext(array);
testNextWithManyHasNext(array);
}
private static void testNextWithoutHasNext(byte[] expected) {
Iterator<Byte> iter
= new ISToIteratorAdapter(new ByteArrayInputStream(expected));
Utils.checkEquals(1, iter.next());
Utils.checkHasNextFalse(iter, 3);
Utils.checkNextThrow(iter);
Utils.checkRemoveThrow(iter);
}
private static void testNextWithManyHasNext(byte[] expected) {
Iterator<Byte> iter
= new ISToIteratorAdapter(new ByteArrayInputStream(expected));
Utils.checkHasNextTrue(iter, 3);
Utils.checkEquals(1, iter.next());
Utils.checkHasNextFalse(iter, 3);
Utils.checkNextThrow(iter);
Utils.checkRemoveThrow(iter);
}
}
| [
"[email protected]"
] | |
04a6cfd21b4d2e9b621ab06af75bb16e04d3f1a7 | 8df9eee318f544640ae0996d00bf32f6af38aa1b | /old/thirdparty/src/main/java/com/sleepycat/je/latch/Latch.java | 667d89b480fa13d726323ce7b7e99c94ee86b8e2 | [] | no_license | jpercent/syndeticlogic | 1e6b4ba5167ddfbd4bc147a4544972abc556774c | 0a102049a369f7a82ebd104ece1e90934c2bd9af | refs/heads/master | 2020-03-26T15:28:01.906430 | 2015-02-12T23:20:55 | 2015-02-12T23:20:55 | 10,148,918 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,747 | java | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002,2008 Oracle. All rights reserved.
*
* $Id: Latch.java,v 1.92 2008/06/10 02:52:11 cwl Exp $
*/
package com.sleepycat.je.latch;
import java.util.concurrent.locks.ReentrantLock;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.RunRecoveryException;
import com.sleepycat.je.dbi.EnvironmentImpl;
public class Latch {
/*
* Required because getOwner() is protected (for unknown reasons) and can't
* be accessed except by a subclass of ReentrantLock.
*/
@SuppressWarnings("serial")
private static class JEReentrantLock extends ReentrantLock {
JEReentrantLock(boolean fair) {
super(fair);
}
@Override
protected Thread getOwner() {
return super.getOwner();
}
}
private JEReentrantLock lock;
private String name;
private LatchStats stats = new LatchStats();
public Latch(String name) {
lock = new JEReentrantLock(EnvironmentImpl.getFairLatches());
this.name = name;
}
/**
* Set the latch name, used for latches in objects instantiated from
* the log.
*/
public void setName(String name) {
this.name = name;
}
/**
* Acquire a latch for exclusive/write access.
*
* <p>Wait for the latch if some other thread is holding it. If there are
* threads waiting for access, they will be granted the latch on a FIFO
* basis. When the method returns, the latch is held for exclusive
* access.</p>
*
* @throws LatchException if the latch is already held by the calling
* thread.
*
* @throws RunRecoveryException if an InterruptedException exception
* occurs.
*/
public void acquire()
throws DatabaseException {
try {
if (lock.isHeldByCurrentThread()) {
stats.nAcquiresSelfOwned++;
throw new LatchException(name + " already held");
}
if (lock.isLocked()) {
stats.nAcquiresWithContention++;
} else {
stats.nAcquiresNoWaiters++;
}
lock.lock();
assert noteLatch(); // intentional side effect;
} finally {
assert EnvironmentImpl.maybeForceYield();
}
}
/**
* Acquire a latch for exclusive/write access, but do not block if it's not
* available.
*
* @return true if the latch was acquired, false if it is not available.
*
* @throws LatchException if the latch is already held by the calling
* thread.
*/
public boolean acquireNoWait()
throws LatchException {
try {
if (lock.isHeldByCurrentThread()) {
stats.nAcquiresSelfOwned++;
throw new LatchException(name + " already held");
}
boolean ret = lock.tryLock();
if (ret) {
assert noteLatch();
stats.nAcquireNoWaitSuccessful++;
} else {
stats.nAcquireNoWaitUnsuccessful++;
}
return ret;
} finally {
assert EnvironmentImpl.maybeForceYield();
}
}
/**
* Release the latch. If there are other thread(s) waiting for the latch,
* one is woken up and granted the latch. If the latch was not owned by
* the caller, just return;
*/
public void releaseIfOwner() {
doRelease(false);
}
/**
* Release the latch. If there are other thread(s) waiting for the latch,
* they are woken up and granted the latch.
*
* @throws LatchNotHeldException if the latch is not currently held.
*/
public void release()
throws LatchNotHeldException {
if (doRelease(true)) {
throw new LatchNotHeldException(name + " not held");
}
}
/**
* Do the work of releasing the latch. Wake up any waiters.
*
* @returns true if this latch was not owned by the caller.
*/
private boolean doRelease(boolean checkHeld) {
try {
if (!lock.isHeldByCurrentThread()) {
return true;
}
lock.unlock();
stats.nReleases++;
assert unNoteLatch(checkHeld); // intentional side effect.
} catch (IllegalMonitorStateException IMSE) {
return true;
}
return false;
}
/**
* Return true if the current thread holds this latch.
*
* @return true if we hold this latch. False otherwise.
*/
public boolean isOwner() {
return lock.isHeldByCurrentThread();
}
/**
* Used only for unit tests.
*
* @return the thread that currently holds the latch for exclusive access.
*/
public Thread owner() {
return lock.getOwner();
}
/**
* Return the number of threads waiting.
*
* @return the number of threads waiting for the latch.
*/
public int nWaiters() {
return lock.getQueueLength();
}
/**
* @return a LatchStats object with information about this latch.
*/
public LatchStats getLatchStats() {
LatchStats s = null;
try {
s = (LatchStats) stats.clone();
} catch (CloneNotSupportedException e) {
/* Klockwork - ok */
}
return s;
}
/**
* Formats a latch owner and waiters.
*/
@Override
public String toString() {
return lock.toString();
}
/**
* Only call under the assert system. This records latching by thread.
*/
private boolean noteLatch()
throws LatchException {
return LatchSupport.latchTable.noteLatch(this);
}
/**
* Only call under the assert system. This records latching by thread.
*/
private boolean unNoteLatch(boolean checkHeld) {
/* Only return a false status if we are checking for latch ownership.*/
if (checkHeld) {
return LatchSupport.latchTable.unNoteLatch(this, name);
} else {
LatchSupport.latchTable.unNoteLatch(this, name);
return true;
}
}
}
| [
"[email protected]"
] | |
0e95e1b51e07f65f4bba33a65bc7da9e6846692f | 11ac7f84a48358b4dc1c70de658627dd1af3cd4c | /Mobile Android/Exam25.01.2018/app/src/main/java/com/example/andreeagritco/exam25/utils/GameListAdapter.java | 869d22c8b132ff2a38e8e6c37285cfe29a8e0cf5 | [] | no_license | gritcoandreea/Year3-Semester1 | e308f0574fc6df25a2dc43f8e9147a7732b4a578 | d97119fb4518d6e92d8e9e6e17cb012777eb5c95 | refs/heads/master | 2021-05-09T02:09:18.382383 | 2018-02-03T09:44:30 | 2018-02-03T09:44:30 | 119,199,461 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,927 | java | package com.example.andreeagritco.exam25.utils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.andreeagritco.exam25.R;
import com.example.andreeagritco.exam25.model.Game;
import java.util.List;
/**
* Created by Andreea Gritco on 01-Feb-18.
*/
public class GameListAdapter extends BaseAdapter {
private List<Game> gamesList;
private LayoutInflater inflater;
private boolean isClient;
public GameListAdapter(List<Game> gamesList, LayoutInflater inflater, boolean isClient) {
this.gamesList = gamesList;
this.inflater = inflater;
this.isClient = isClient;
}
@Override
public int getCount() {
return gamesList.size();
}
@Override
public Object getItem(int position) {
return gamesList.get(position);
}
@Override
public long getItemId(int position) {
return gamesList.get(position).getId();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.game_layout, null);
TextView nameText = convertView.findViewById(R.id.gameNameText);
TextView quantityText = convertView.findViewById(R.id.gameQuantityText);
TextView typeText = convertView.findViewById(R.id.gameTypeText);
TextView statusText = convertView.findViewById(R.id.gameStatusText);
nameText.setText(gamesList.get(position).getName());
quantityText.setText(gamesList.get(position).getQuantity() + "");
typeText.setText(gamesList.get(position).getType().toString());
if (isClient) {
statusText.setVisibility(View.GONE);
} else {
statusText.setText(gamesList.get(position).getStatus().toString());
}
return convertView;
}
}
| [
"[email protected]"
] | |
d4bd76e611a2c909848a988e8739c7bc67d80a0b | 3d4e777ef3bebd9b4fa87a8eaaa89a8a126cf6e5 | /Kuwangamelib/src/com/kuwan/sdk/utils/SIMCardUtil.java | b5033d5e48be521ed7dd60bd99667ddf84ffad5d | [] | no_license | zhangjiafan8652/kuwansdkcore | fd9bd23592bf5cbc67974236b5668cfa19425bce | 90bf791cd85900aa74eeee8ecb96f656e759a60b | refs/heads/master | 2020-06-01T09:18:51.540104 | 2019-06-10T01:38:22 | 2019-06-10T01:38:22 | 190,728,429 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,366 | java | package com.kuwan.sdk.utils;
import android.content.Context;
import android.telephony.TelephonyManager;
public class SIMCardUtil {
/**
* TelephonyManager提供设备上获取通讯服务信息的入口。 应用程序可以使用这个类方法确定的电信服务商和国家 以及某些类型的用户访问信息。
* 应用程序也可以注册一个监听器到电话收状态的变化。不需要直接实例化这个类
* 使用Context.getSystemService(Context.TELEPHONY_SERVICE)来获取这个类的实例。
*/
private static TelephonyManager telephonyManager;
/**
* 国际移动用户识别码
*/
private static String IMSI;
/**
* Role:获取当前设置的电话号码 <BR>
*
* @author wjy
*/
public static String getNativePhoneNumber(Context context) {
if (telephonyManager == null) {
telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
}
String NativePhoneNumber = null;
NativePhoneNumber = telephonyManager.getSubscriberId();
return NativePhoneNumber;
}
/**
* Role:Telecom service providers获取手机服务商信息 <BR>
* 需要加入权限<uses-permission
* android:name="android.permission.READ_PHONE_STATE"/> <BR>
*
* @author wjy
*/
public static String getProvidersName(Context context) {
if (telephonyManager == null) {
telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
}
String ProvidersName = null;
// 返回唯一的用户ID;就是这张卡的编号神马的
IMSI = telephonyManager.getSubscriberId();
// IMSI号前面3位460是国家,紧接着后面2位00 02是中国移动,01是中国联通,03是中国电信。
if (IMSI.startsWith("46000") || IMSI.startsWith("46002") || IMSI.startsWith("46007")) {
ProvidersName = "CMCC";
} else if (IMSI.startsWith("46001") || IMSI.startsWith("46006")) {
ProvidersName = "UNICOM";
} else if (IMSI.startsWith("46003") || IMSI.startsWith("46005")) {
ProvidersName = "TELECOM";
}else {
ProvidersName = "OTHER";
}
return ProvidersName;
}
}
| [
"[email protected]"
] | |
b9145735138864b5e87ba80ee221766df9219e7c | 60e3e994b7ead89d9ea4155f657e3cab884772f1 | /src/main/java/com/github/jarviskim/algorithm/boj/a1157_WordStudy/WordStudy.java | e806aacebbb3ce5e176fadd7a1abfa997799027d | [] | no_license | jarvis-kim/algorithm | ad921b6c2f0799f8b0397cac9f989888b7ff76ee | 9d24454e14684908cb22e312ce67f6593649d563 | refs/heads/master | 2020-03-29T09:37:15.001772 | 2019-08-26T04:08:50 | 2019-08-26T04:08:50 | 149,766,347 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,301 | java | package com.github.jarviskim.algorithm.boj.a1157_WordStudy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;
public class WordStudy {
public static char solve(String word) {
word = word.toUpperCase().trim();
char[] chars = word.toCharArray();
Map<Character, Integer> map = new HashMap<>();
for ( char c : chars ) {
Integer count = map.get(c);
if ( count == null ) {
count = new Integer(0);
}
map.put(c, count.intValue() + 1);
}
List<Map.Entry<Character, Integer>> collect = map.entrySet().stream().sorted((o1, o2) -> Integer.compare(o2.getValue(), o1.getValue())).collect(Collectors.toList());
if ( collect.size() == 1 ) {
return collect.get(0).getKey();
}
Map.Entry<Character, Integer> max = collect.get(0);
Map.Entry<Character, Integer> max2 = collect.get(1);
if ( max.getValue().equals(max2.getValue()) ) {
return '?';
}
return max.getKey();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println(solve(scanner.nextLine()));
}
}
| [
"[email protected]"
] | |
596ec548d4b3b270282a773ae284c5a7fa78d3d9 | c3d386b1a08ef0e1fb2d667cfc34f8dead2b487e | /app/src/main/java/com/app/alldemo/effect/TuneWheelActivity.java | 67b4dd9864339712fdf710e27cdef614eb344172 | [] | no_license | wbsguo/StudioAlldemo | ef1b7ae131752ad8f90c76ccfbda0deb961dcc75 | 7e8b42eeb6c19f109f3e3ec57826b40c7a9a6c1c | refs/heads/master | 2021-01-17T12:52:11.158909 | 2016-08-04T07:08:55 | 2016-08-04T07:08:55 | 58,708,516 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,714 | java | package com.app.alldemo.effect;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import com.app.alldemo.R;
import com.app.alldemo.courview.TuneWheel;
import com.app.alldemo.courview.TuneWheel2;
public class TuneWheelActivity extends Activity {
private TuneWheel tuneWheel;
private TuneWheel2 tuneWheel2;
private TextView textview,textview2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tunewheel);
findUI();
}
private void findUI(){
tuneWheel();
tuneWheel2();
}
private void tuneWheel(){
tuneWheel=(TuneWheel)findViewById(R.id.tuneWheel);
tuneWheel.setmMaxValue(100);
tuneWheel.setValue(50);
textview=(TextView)findViewById(R.id.textview);
textview.setText("50");
tuneWheel.setValueChangeListener(new TuneWheel.OnValueChangeListener() {
@Override
public void onValueChange(float value) {
textview.setText(String.valueOf(value));
}
});
}
private void tuneWheel2(){
tuneWheel2=(TuneWheel2)findViewById(R.id.tuneWheel2);
tuneWheel2.setmMaxValue(2000);
tuneWheel2.setValue(500);
textview2=(TextView)findViewById(R.id.textview2);
textview2.setText("50");
tuneWheel2.setValueChangeListener(new TuneWheel2.OnValueChangeListener() {
@Override
public void onValueChange(float value) {
textview2.setText(String.valueOf(value/10));
}
});
}
}
| [
"[email protected]"
] | |
9e9f8c4bdb1833bb38cb69d05f24e9e2a30155bb | 36c76b1767b224e84fafcc81e8c79995dc3dfb5d | /src/main/java/com/design_pattern/proxy/static_proxy/RealSubject.java | 3c5df6932752d0ed3f5e461d115e5b2c66ade706 | [] | no_license | huangxiaowei08/myproject | aae63504467c600c82238baa8bfd0678ca39050f | fa9503579bc4c395d0b163c6fe542c360ca71477 | refs/heads/master | 2021-09-11T20:56:29.479501 | 2018-04-12T08:52:02 | 2018-04-12T08:52:02 | 125,138,008 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 207 | java | package com.design_pattern.proxy.static_proxy;
public class RealSubject implements Subject{
private String name = "tom";
@Override
public void visit() {
System.out.println("this is " + name);
}
}
| [
"[email protected]"
] | |
3103e0dd0ecb810d671a030bac8355a0b28dcf59 | 526997758b12f1ad7114bf6187019989aa21c4f1 | /dolphin-core/src/main/java/fr/bmqt/dolphin/network/packets/play/server/SEntityStatusPacket.java | 16846ae2705265f6e844632254c50b354db1774e | [
"MIT"
] | permissive | baptmqt/dolphin | b77b03441d62ed9b344cdc5f066fecced8d30b5d | a2421650bf2acfa43f0d9a93bc8f606682a170d8 | refs/heads/main | 2023-02-03T13:58:13.591711 | 2020-12-19T20:30:48 | 2020-12-19T20:30:48 | 312,092,176 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,191 | java | /*
* MIT License
*
* Copyright (c) 2020. Baptiste MAQUET
*
* 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 fr.bmqt.dolphin.network.packets.play.server;
import fr.bmqt.dolphin.network.packets.Packet;
import fr.bmqt.dolphin.network.packets.PacketBuffer;
import fr.bmqt.dolphin.network.packets.play.INetHandlerPlayClient;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.io.IOException;
/**
* @author Baptiste MAQUET on 11/11/2020
* @project dolphin-parent
*/
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class SEntityStatusPacket implements Packet<INetHandlerPlayClient> {
protected int entityId;
protected byte logicOpcode;
@Override
public void readPacketData(PacketBuffer buf) throws IOException {
entityId = buf.readInt();
logicOpcode = buf.readByte();
}
@Override
public void writePacketData(PacketBuffer buf) throws IOException {
buf.writeInt(entityId);
buf.writeByte(logicOpcode);
}
@Override
public void processPacket(INetHandlerPlayClient handler) {
handler.handleEntityStatus(this);
}
}
| [
"[email protected]"
] | |
78b3ce9dd1273b0432b4c5d1d0bd87ef371d688e | 87e12e17fa3a51e9ddfea542ae67476b799b2eab | /Project/ChartView_Demo/ChartView/src/com/qskobe24/chartview/MainActivity.java | 2ae6f1d3ec80f404466357d644c563ec827fc276 | [] | no_license | QSKOBE24/PageAndRefreshLibrary | 22466999c0a3dd5662f57f488d90a59c8182aef9 | c937dd3b61373e737a34d9e6e1d559ad6d97d2cc | refs/heads/master | 2021-01-22T02:40:09.706016 | 2015-09-01T13:48:22 | 2015-09-01T13:48:22 | 41,740,854 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,841 | java | package com.qskobe24.chartview;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import com.guosen.chartview.animation.Easing;
import com.guosen.chartview.charts.LineChart;
import com.guosen.chartview.charts.PieChart;
import com.guosen.chartview.data.Approximator;
import com.guosen.chartview.data.Approximator.ApproximatorType;
import com.guosen.chartview.data.DataSet;
import com.guosen.chartview.data.Entry;
import com.guosen.chartview.data.LineData;
import com.guosen.chartview.data.LineDataSet;
import com.guosen.chartview.data.PieData;
import com.guosen.chartview.data.PieDataSet;
import com.guosen.chartview.util.ColorTemplate;
@SuppressLint("SimpleDateFormat")
public class MainActivity extends DemoBase {
private LineChart mChart;
private Button getDataButton,skipButton;
private PieChart pieChart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
getDataButton = (Button)findViewById(R.id.setdata);
getDataButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
GetDataFromNetOrDisk(7);
}
});
skipButton = (Button)findViewById(R.id.skip);
skipButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
});
mChart = (LineChart) findViewById(R.id.chart1);
pieChart = (PieChart)findViewById(R.id.piechart);
pieChart.setTouchEnabled(true);
pieChart.animateY(1500, Easing.EasingOption.EaseInOutQuad);
setPieData(3);
}
private void setPieData(int count) {
float mult = 10;
ArrayList<Entry> yVals1 = new ArrayList<Entry>();
for (int i = 0; i < count + 1; i++) {
yVals1.add(new Entry((float) (Math.random() * mult) + mult / 5, i));
}
ArrayList<String> xVals = new ArrayList<String>();
for (int i = 0; i < count + 1; i++)
xVals.add(Companies[i % Companies.length]);
PieDataSet dataSet = new PieDataSet(yVals1, "手机销量占比");
ArrayList<Integer> colors = new ArrayList<Integer>();
for (int c : ColorTemplate.PASTEL_COLORS)
colors.add(c);
dataSet.setColors(colors);
PieData data = new PieData(xVals, dataSet);
pieChart.setData(data);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.line, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.actionToggleValues: {
for (DataSet<?> set : mChart.getData().getDataSets())
set.setDrawValues(!set.isDrawValuesEnabled());
mChart.invalidate();
break;
}
case R.id.actionToggleHighlight: {
if (mChart.isHighlightEnabled())
mChart.setHighlightEnabled(false);
else
mChart.setHighlightEnabled(true);
mChart.invalidate();
break;
}
case R.id.actionToggleFilled: {
ArrayList<LineDataSet> sets = (ArrayList<LineDataSet>) mChart.getData()
.getDataSets();
for (LineDataSet set : sets) {
if (set.isDrawFilledEnabled())
set.setDrawFilled(false);
else
set.setDrawFilled(true);
}
mChart.invalidate();
break;
}
case R.id.actionToggleCircles: {
ArrayList<LineDataSet> sets = (ArrayList<LineDataSet>) mChart.getData()
.getDataSets();
for (LineDataSet set : sets) {
if (set.isDrawCirclesEnabled())
set.setDrawCircles(false);
else
set.setDrawCircles(true);
}
mChart.invalidate();
break;
}
case R.id.actionToggleCubic: {
ArrayList<LineDataSet> sets = (ArrayList<LineDataSet>) mChart.getData()
.getDataSets();
for (LineDataSet set : sets) {
if (set.isDrawCubicEnabled())
set.setDrawCubic(false);
else
set.setDrawCubic(true);
}
mChart.invalidate();
break;
}
case R.id.actionToggleStartzero: {
mChart.getAxisLeft().setStartAtZero(!mChart.getAxisLeft().isStartAtZeroEnabled());
// mChart.getAxisRight().setStartAtZero(!mChart.getAxisRight().isStartAtZeroEnabled());
mChart.invalidate();
break;
}
case R.id.actionTogglePinch: {
if (mChart.isPinchZoomEnabled())
mChart.setPinchZoom(false);
else
mChart.setPinchZoom(true);
mChart.invalidate();
break;
}
case R.id.actionToggleAutoScaleMinMax: {
mChart.setAutoScaleMinMaxEnabled(!mChart.isAutoScaleMinMaxEnabled());
mChart.notifyDataSetChanged();
break;
}
case R.id.animateX: {
mChart.animateX(3000);
break;
}
case R.id.animateY: {
mChart.animateY(3000, Easing.EasingOption.EaseInCubic);
break;
}
case R.id.animateXY: {
mChart.animateXY(3000, 3000);
break;
}
case R.id.actionToggleFilter: {
// the angle of filtering is 35°
Approximator a = new Approximator(ApproximatorType.DOUGLAS_PEUCKER, 35);
if (!mChart.isFilteringEnabled()) {
mChart.enableFiltering(a);
} else {
mChart.disableFiltering();
}
mChart.invalidate();
break;
}
case R.id.actionSave: {
if (mChart.saveToPath("title" + System.currentTimeMillis(), "")) {
Toast.makeText(getApplicationContext(), "Saving SUCCESSFUL!",
Toast.LENGTH_SHORT).show();
} else
Toast.makeText(getApplicationContext(), "Saving FAILED!", Toast.LENGTH_SHORT)
.show();
// mChart.saveToGallery("title"+System.currentTimeMillis())
break;
}
case R.id.pieactionToggleValues: {
for (DataSet<?> set : mChart.getData().getDataSets())
set.setDrawValues(!set.isDrawValuesEnabled());
mChart.invalidate();
break;
}
case R.id.pieactionToggleHole: {
if (pieChart.isDrawHoleEnabled())
pieChart.setDrawHoleEnabled(false);
else
pieChart.setDrawHoleEnabled(true);
mChart.invalidate();
break;
}
case R.id.pieactionDrawCenter: {
if (pieChart.isDrawCenterTextEnabled())
pieChart.setDrawCenterText(false);
else
pieChart.setDrawCenterText(true);
pieChart.invalidate();
break;
}
case R.id.pieactionToggleXVals: {
pieChart.setDrawSliceText(!pieChart.isDrawSliceTextEnabled());
pieChart.invalidate();
break;
}
case R.id.pieactionSave: {
// mChart.saveToGallery("title"+System.currentTimeMillis());
pieChart.saveToPath("title" + System.currentTimeMillis(), "");
break;
}
case R.id.pieactionTogglePercent:
pieChart.setUsePercentValues(!pieChart.isUsePercentValuesEnabled());
pieChart.invalidate();
break;
case R.id.pieanimateX: {
pieChart.animateX(1800);
break;
}
case R.id.pieanimateY: {
pieChart.animateY(1800);
break;
}
case R.id.pieanimateXY: {
pieChart.animateXY(1800, 1800);
break;
}
}
return true;
}
public void GetDataFromNetOrDisk(int count) {
ArrayList<String> xVals = new ArrayList<String>();
Calendar now = Calendar.getInstance();
String today = new SimpleDateFormat("MM-dd").format(now.getTime());
String []result = new String[count];
result [count-1] = today;
//result[count-2] = today;
for (int i = 0; i< count-1; i++) {
now.add(Calendar.DATE, -1);
String yesterday = new SimpleDateFormat( "MM-dd").format(now.getTime());
result[count-2-i] = yesterday;
}
for (int i = 0; i < result.length; i++) {
xVals.add(result[i]);
}
ArrayList<Entry> yVals = new ArrayList<Entry>();
yVals.add(new Entry((float) 0.001, 0));
yVals.add(new Entry((float) 0.001, 1));
yVals.add(new Entry((float) 0.001, 2));
yVals.add(new Entry((float) 0.001, 3));
yVals.add(new Entry((float) 0.001, 4));
yVals.add(new Entry((float) 0.001, 5));
yVals.add(new Entry((float) 0.001, 6));
//通过计算求得七日年化利率,然后再将其设置好
yVals.get(yVals.size()-1).setExtra("2.00");
// create a dataset and give it a type
LineDataSet set1 = new LineDataSet(yVals, "");
ArrayList<LineDataSet> dataSets = new ArrayList<LineDataSet>();
dataSets.add(set1); // add the datasets
// create a data object with the datasets
LineData data = new LineData(xVals, dataSets);
//准备好了数据以后,一定要设置这句话
mChart.setShowDefaultData(false);
//以下2句话一定要在setData()之前调用,不然绘制图会出错
//其中的最大值和最小值是得到数据之后进行计算以后得出的,其中MaxValue为最大值4/3*(数据集中最大Y值)-1/3*(数据集中的最小值)
//MinValue为4/3*(数据集中最小Y值)-1/3*(数据集中的最大值)
// mChart.getAxisLeft().setAxisMaxValue((float) (6.028f));
// mChart.getAxisLeft().setAxisMinValue((float) (-1.10f));
setMaxMin(data);
mChart.setData(data);
mChart.invalidate();
}
public void setMaxMin(LineData data){
float max = 0.0f;
float min = 0.0f;
int num = 0;
double range = 0.0f;
double rawInterval= 0.0f;
for (int j = 0; j < data.getDataSetCount(); j++) {
LineDataSet lineDataSet = data.getDataSets().get(j);
num = lineDataSet.getYVals().size();
max = lineDataSet.getYMax();
min = lineDataSet.getYMin();
range = Math.abs(max - min);
rawInterval = range / num;
}
if(max == min){
mChart.getAxisLeft().setAxisMaxValue((float) (max + 1.0f));
mChart.getAxisLeft().setAxisMinValue((float) (min - 1.0f));
}else {
mChart.getAxisLeft().setAxisMaxValue((float) (max + rawInterval));
mChart.getAxisLeft().setAxisMinValue((float) (min-rawInterval));
}
}
}
| [
"[email protected]"
] | |
de97f70e7deb243db856bab45bd58c17f0c729df | 4acd456f975bb1f3c2655bc98e910f9e424e3763 | /src/main/java/com/b1soft/e_learning/service/LeccionesService.java | 6ec10803a9d1481a8f608bc867bf9e7a448da1a2 | [] | no_license | herbri/E_learning | b2858c904fd4796870c161c281646f7e2b8dbfd4 | ba3dc3493883effbb094fb92e6ce6e3f9402d87c | refs/heads/main | 2023-06-10T20:41:32.806466 | 2021-06-24T21:59:48 | 2021-06-24T21:59:48 | 372,951,261 | 1 | 0 | null | 2021-06-23T22:47:23 | 2021-06-01T20:16:36 | CSS | UTF-8 | Java | false | false | 291 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.b1soft.e_learning.service;
/**
*
* @author Jose
*/
public class LeccionesService {
}
| [
"[email protected]"
] | |
ec20bc90debee8ca7b7504c6185704e1a8dc7830 | 16ed5a853a921fdf53363db658750d52b95cb538 | /library_work/src/com/luoy/library/common/util/TestMain.java | 65a826daaeba4e1769ac32756990f97b43e2e0fc | [] | no_license | GoneLuo/mygit | b8b36e64ee9a14cb666048eba2df86d57f4e6da1 | e37c35f6645913eae39909621eb3f365181241b1 | refs/heads/master | 2020-03-26T05:12:40.461096 | 2018-08-13T09:17:36 | 2018-08-13T09:17:36 | 144,544,196 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,588 | java | package com.luoy.library.common.util;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class TestMain {
public static void main(String[] args) {
subStr();
}
//格式化double数据,小数点位数
public static double parseDouble(double d) {
d = Double.parseDouble(new DecimalFormat("#.0").format(d));
System.out.println(d);
return d;
}
/**
* 计算date1-date2的天数
* @createUser ying luo
* @createDate 2018年4月16日
*
* @param date1
* @param date2
* @return
*/
public Long diffDays(Date date1, Date date2) {
long nd = 1000 * 24 * 60 * 60;
long diff = date2.getTime() - date1.getTime();
// 计算差多少天
long day = diff / nd;
return day;
}
public static void subStr() {
String fileName = "123";
String[] strs = fileName.split("\\.");
for (String str: strs) {
System.out.println(str);
}
StringBuffer s = new StringBuffer("1");
String ss = s.substring(0, s.length() - 1);
System.out.println(ss);
}
/**
* 去掉from前的字符
*/
public static String hqlSubStr(String hql) {
int fisrt = hql.indexOf("from");
String res = hql.substring(fisrt);
return res;
}
public static void CalendarTest(){
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.set(Calendar.MONTH, c.get(Calendar.MONTH) + 1);
Date d = c.getTime();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(format.format(d));
}
}
| [
"[email protected]"
] | |
bff70a7e21dfaf720716cb480991a4f502cb1725 | d28b06a3067a8eef89e6d0f0884f1607b00364ec | /leetcode/src/leetcode/Q048.java | f25fc3d9937d54962e374298042af43af94effe5 | [] | no_license | cakmaky/My_Leetcode_solutions | 8ee9e403f2801152a8fe93c76a5e440c734e9aae | d36553716e6037fb32848dfb009be9a0d8cac785 | refs/heads/master | 2021-01-12T09:03:21.351937 | 2017-12-13T05:58:45 | 2017-12-13T05:58:45 | 76,747,445 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,131 | java | package leetcode;
public class Q048 {
public static void rotate_(int[][] matrix) {
// ayri bir matrix tanimlayip en son ordaki degeri matrix e attim
int[][] matrix2 = new int[matrix.length][matrix.length];
for(int i=0;i<matrix.length;i++){
for(int j=0; j<matrix[0].length; j++){
matrix2[j][matrix.length-1-i] = matrix[i][j];
}
}
for(int i=0;i<matrix.length;i++){
for(int j=0; j<matrix[0].length; j++){
matrix[i][j] = matrix2[i][j];
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
public static void rotate(int[][] matrix) {
for(int i=0;i<matrix.length / 2;i++){
for(int j=0; j<matrix[0].length; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[matrix.length-1-i][j];
matrix[matrix.length-1-i][j] = temp;
}
}
for(int i=0;i<matrix.length;i++){
for(int j=i+1; j<matrix[0].length; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
public static void main(String[] args) {
int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
rotate(matrix);
}
}
| [
"[email protected]"
] | |
4027c853921fbd206099f18142e559b6106b3b74 | 60ee99fcdb808e7c3f96848961bdbfe7f5851d92 | /app/src/androidTest/java/com/friends/chat/ExampleInstrumentedTest.java | 8c95f3d759c3a3a527f0aa01e7dfb8486ad0c920 | [] | no_license | abhuraj/ChatApp | 2c7e75c043f7243627eacfb9212cb242fabfc66b | 1b12d770fbe45869b885be2d9fbac967bef0e9c8 | refs/heads/master | 2022-12-08T22:45:35.599311 | 2020-09-12T11:31:31 | 2020-09-12T11:31:31 | 294,930,442 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 727 | java | package com.friends.chat;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.friends.sales_assistant", appContext.getPackageName());
}
}
| [
"[email protected]"
] | |
2ecc4e074a2eb095c77d7859240dd08cda639905 | a2d0e880e07d036e9225cc3a2adad8aed7a8d75a | /src/com/gss/rcp/examples/gef5/geometry/AbstractExample.java | 6ef324523c303ac2cb54ac81f6bd916ccfd461ab | [] | no_license | sxrCode/gssrcp-gef5 | a787fb7cb7a722d0ccf86484fc698f5d7fc64f10 | 906c4b4d40728285f01db1a933da338b39ba04ea | refs/heads/master | 2020-12-02T21:12:03.280156 | 2017-07-21T09:37:42 | 2017-07-21T09:37:42 | 96,270,577 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,619 | java | /*******************************************************************************
* Copyright (c) 2012, 2016 itemis AG and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Matthias Wienand (itemis AG) - initial API and implementation
*
*******************************************************************************/
package com.gss.rcp.examples.gef5.geometry;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
abstract public class AbstractExample implements PaintListener {
public ControllableShapeViewer viewer;
public Shell shell;
public AbstractExample(String title, String... infos) {
Display display = new Display();
shell = new Shell(display, SWT.SHELL_TRIM | SWT.DOUBLE_BUFFERED);
shell.setText(title);
shell.setBounds(0, 0, 640, 480);
shell.setLayout(new FormLayout());
if (infos.length > 0) {
Label infoLabel = new Label(shell, SWT.NONE);
FormData infoLabelFormData = new FormData();
infoLabelFormData.right = new FormAttachment(100, -10);
infoLabelFormData.bottom = new FormAttachment(100, -10);
infoLabel.setLayoutData(infoLabelFormData);
String infoText = "You can...";
for (int i = 0; i < infos.length; i++) {
infoText += "\n..." + infos[i];
}
infoLabel.setText(infoText);
}
// open the shell before creating the controllable shapes so that their
// default coordinates are not changed due to the resize of their canvas
shell.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
shell.open();
viewer = new ControllableShapeViewer(shell);
for (ControllableShape cs : getControllableShapes()) {
viewer.addShape(cs);
}
onInit();
shell.addPaintListener(this);
shell.redraw(); // triggers a PaintEvent platform independently
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
abstract protected ControllableShape[] getControllableShapes();
public void onInit() {
}
@Override
public void paintControl(PaintEvent e) {
}
}
| [
"[email protected]"
] | |
ed1905d0cd3bbd0feaaad34fe583d90dbd973a3a | 66a8e82c99f0499e1c019452da30e3a5d8c870ea | /src/lab6/zad2/WykresWielomianTest.java | 9607d0482788fee80d35faccfb54f04314a3345b | [] | no_license | camisalo/JAVA-AGH | 75857217551ff9add8c87dad8b937ae7d068d4ee | ea2c2aea321f24de7497f315da7a6a20a719e804 | refs/heads/master | 2021-05-15T13:50:30.547350 | 2018-01-05T20:37:16 | 2018-01-05T20:37:16 | 107,236,804 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 262 | java | package lab6.zad2;
import javax.swing.*;
import java.awt.*;
public class WykresWielomianTest {
public static void main(String[] args) {
EventQueue.invokeLater(() ->
{
ButtonFrame frame = new ButtonFrame();
});
}
}
| [
"[email protected]"
] | |
9d11dae88a135f442b1d77a688caebb071d535df | 0e4968f97fcd9e66ae22a7f6e8354b366f05ff8c | /Acacia360CASA_POC/services/SecurityFacade/src/com/etel/facade/SecurityFacade.java | 6d3fd1b4823cff9e3ba3360cce4a0d310ab366f4 | [
"Apache-2.0"
] | permissive | etelced/casa-project | 0e272c306d65a25a695138edf100b5b420d4899c | d29da70fdd3efb13d69d8a2ec6c7db7122fe03c1 | refs/heads/master | 2020-03-30T19:17:05.911561 | 2018-10-12T05:21:40 | 2018-10-12T05:21:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,602 | java |
package com.etel.facade;
import java.util.ArrayList;
import java.util.List;
import com.etel.forms.FormValidation;
import com.etel.forms.UserForm;
import com.etel.security.forms.TBRoleForm;
import com.etel.utils.UserUtil;
import com.smslai_eoddb.data.Tbsecurityparams;
import com.smslai_eoddb.data.Tbunituser;
import com.smslai_eoddb.data.Tbuser;
import com.wavemaker.runtime.RuntimeAccess;
import com.wavemaker.runtime.javaservice.JavaServiceSuperClass;
import com.wavemaker.runtime.service.annotations.ExposeToClient;
/**
* This is a client-facing service class. All
* public methods will be exposed to the client. Their return
* values and parameters will be passed to the client or taken
* from the client, respectively. This will be a singleton
* instance, shared between all requests.
*
* To log, call the superclass method log(LOG_LEVEL, String) or log(LOG_LEVEL, String, Exception).
* LOG_LEVEL is one of FATAL, ERROR, WARN, INFO and DEBUG to modify your log level.
* For info on these levels, look for tomcat/log4j documentation
*/
@ExposeToClient
public class SecurityFacade extends JavaServiceSuperClass {
/* Pass in one of FATAL, ERROR, WARN, INFO and DEBUG to modify your log level;
* recommend changing this to FATAL or ERROR before deploying. For info on these levels, look for tomcat/log4j documentation
*/
public SecurityFacade() {
super(FATAL);
}
//User Account Inquiry (MMM)
public List<Tbuser> getListofUsersPerUsernameOrRole(String username, String rolecode, String groupcode) {
List<Tbuser> userlist = new ArrayList<Tbuser>();
SecurityService secsrvc = new SecurityServiceImpl();
userlist = secsrvc.getListofUsersPerUsernameOrRole(username, rolecode, groupcode);
return userlist;
}
//get Roles
public List<TBRoleForm> getListofRoles() {
SecurityService secsrvc = new SecurityServiceImpl();
return secsrvc.getListofRoles();
}
public Boolean checkUsername(String username) {
SecurityService secsrvc = new SecurityServiceImpl();
return secsrvc.checkUsername(username);
}
public UserForm getUserAccount(String username) {
UserForm useraccount = new UserForm();
SecurityService secsrvc = new SecurityServiceImpl();
useraccount = secsrvc.getUserAccount(username);
return useraccount;
}
public String saveUserAccount(Tbuser useracct, List<TBRoleForm> roles) {
String result = "Failed";
SecurityService secsrvc = new SecurityServiceImpl();
result = secsrvc.saveUserAccount(useracct, roles);
return result;
}
public FormValidation validate(Tbunituser useracct, TBRoleForm role, String newOrEdited) {
SecurityService secsrvc = new SecurityServiceImpl();
return secsrvc.validate(useracct,role,newOrEdited);
}
public FormValidation validatePassword(String password, String username) {
SecurityService secsrvc = new SecurityServiceImpl();
return secsrvc.validatePassword(password, username);
}
public String validateOldPassword(String password, String username) {
SecurityService secsrvc = new SecurityServiceImpl();
return secsrvc.validateOldPassword(password, username);
}
public String changePassword(String username, String password) {
SecurityService secsrvc = new SecurityServiceImpl();
return secsrvc.changePassword(username, password);
}
public String datetimerecord() {
SecurityService secsrvc = new SecurityServiceImpl();
return secsrvc.datetimerecord();
}
public String saveSecurityParams(Tbsecurityparams params) {
SecurityService secsrvc = new SecurityServiceImpl();
return secsrvc.saveSecurityParams(params);
}
public Tbsecurityparams getSecurityParams() {
SecurityService secsrvc = new SecurityServiceImpl();
return secsrvc.getSecurityParams();
}
public String resetUserSession() {
SecurityService secsrvc = new SecurityServiceImpl();
return secsrvc.resetUserSession();
}
public List<Tbuser> filterDeletedAcct(String search) {
SecurityService secsrvc = new SecurityServiceImpl();
return secsrvc.filterDeletedAcct(search);
}
public String enableUserAcct(String username) {
SecurityService secsrvc = new SecurityServiceImpl();
return secsrvc.enableUserAcct(username);
}
public String getUserFirstname() throws Exception{
String name = null;
name = UserUtil.getUserByUsername(RuntimeAccess.getInstance().getRequest().getUserPrincipal().getName())
.getFirstname();
if (name == null) {
name = "";
}
return name;
}
public String getUserAgreementMessage() {
SecurityService secsrvc = new SecurityServiceImpl();
return secsrvc.getUserAgreementMessage();
}
public FormValidation resetPassword(String username) {
SecurityService secsrvc = new SecurityServiceImpl();
return secsrvc.resetPassword(username);
}
public boolean userSessionCheck(){
return UserUtil.userSessionCheck();
}
public boolean validateMaxNoOfUser(){
return UserUtil.isMaxNumberOfUserReached();
}
// public String resendEmail(String username, String changepass, String type){
// SecurityService secsrvc = new SecurityServiceImpl();
// return secsrvc.resendEmail(username, changepass, type);
// }
public List<Tbunituser> getListOfUser(){
SecurityService service = new SecurityServiceImpl();
List<Tbunituser> list = new ArrayList<Tbunituser>();
list = service.getListOfUser();
return list;
}
}
| [
"[email protected]"
] | |
11d824f1f674b6670269055da0ad456896eb6b54 | cf6620a9cddfff1b7a32e3f46c031aba76fd1241 | /src/parser/SkipStatement.java | 901495db1f5fc8142497785a947161a05772ac18 | [] | no_license | AshwathVS/mc-jacc | c618df092ded015e6f00dade070baef9c384cfcb | 90bc083849c4fcaf6c21d28dc9343b1978b0f850 | refs/heads/master | 2022-11-14T09:08:47.042564 | 2020-06-26T21:18:32 | 2020-06-26T21:18:32 | 268,644,951 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 516 | java | package parser;
public class SkipStatement implements BaseStatement {
private SkipStatementType skipStatementType;
public SkipStatement(SkipStatementType skipStatementType) {
this.skipStatementType = skipStatementType;
}
@Override
public BaseStatementType getStatementType() {
switch (skipStatementType) {
case BREAK: return BaseStatementType.BREAK;
case CONTINUE: return BaseStatementType.CONTINUE;
default: return null;
}
}
}
| [
"[email protected]"
] | |
24f7fc8c044c2adcc1ad65d18aa5f066364b3d07 | ab187ccedd471c653c8128828327aba77f3f6946 | /src/main/java/com/robertx22/age_of_exile/event_hooks/ontick/OnClientTick.java | f80b1d675746fcd0e3bc714bccc75730fa702175 | [] | no_license | evstarMC/Age-of-Exile | bdd04cf73058fe48fb0be8b16db7f12cb661fb7a | 9a8b9d0d44e4860216e25e769fd9a46e046d86bb | refs/heads/master | 2023-08-27T19:15:50.846198 | 2021-09-17T12:08:10 | 2021-09-17T12:08:10 | 357,961,872 | 0 | 0 | null | 2021-04-29T22:40:43 | 2021-04-14T15:54:42 | Java | UTF-8 | Java | false | false | 2,325 | java | package com.robertx22.age_of_exile.event_hooks.ontick;
import com.robertx22.age_of_exile.capability.player.EntitySpellCap;
import com.robertx22.age_of_exile.uncommon.datasaving.Load;
import com.robertx22.age_of_exile.uncommon.utilityclasses.ChatUtils;
import com.robertx22.age_of_exile.uncommon.utilityclasses.ClientOnly;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.minecraft.client.MinecraftClient;
import net.minecraft.entity.player.PlayerEntity;
import java.util.HashMap;
import java.util.List;
public class OnClientTick implements ClientTickEvents.EndTick {
public static HashMap<String, Integer> COOLDOWN_READY_MAP = new HashMap<>();
static int TICKS_TO_SHOW = 50;
private static int NO_MANA_SOUND_COOLDOWN = 0;
public static boolean canSoundNoMana() {
return NO_MANA_SOUND_COOLDOWN <= 0;
}
public static void setNoManaSoundCooldown() {
NO_MANA_SOUND_COOLDOWN = 30;
}
@Override
public void onEndTick(MinecraftClient mc) {
PlayerEntity player = MinecraftClient.getInstance().player;
if (player == null) {
return;
}
if (ChatUtils.isChatOpen()) {
ClientOnly.ticksSinceChatWasOpened = 0;
} else {
ClientOnly.ticksSinceChatWasOpened--;
}
if (player.isPartOf(player)) {
Load.Unit(player)
.getResources()
.onTickBlock(player);
NO_MANA_SOUND_COOLDOWN--;
EntitySpellCap.ISpellsCap spells = Load.spells(player);
List<String> onCooldown = spells.getCastingData()
.getSpellsOnCooldown(player);
Load.Unit(player)
.getCooldowns()
.onTicksPass(1);
spells.getCastingData()
.onTimePass(player, spells, 1); // ticks spells on client
List<String> onCooldownAfter = spells.getCastingData()
.getSpellsOnCooldown(player);
onCooldown.removeAll(onCooldownAfter);
COOLDOWN_READY_MAP.entrySet()
.forEach(x -> x.setValue(x.getValue() - 1));
onCooldown.forEach(x -> {
COOLDOWN_READY_MAP.put(x, TICKS_TO_SHOW);
x.isEmpty();
});
}
}
} | [
"[email protected]"
] | |
944f77ff609479566ba74011811f3bf6d61d31bc | 9fa259262305cd0b3756bd4382760081525800d4 | /backend/src/main/java/ch/fhnw/server/exception/JwtAuthenticationException.java | f82f990fac4ea471a00c677744c0092dbfcb7b1f | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | fhnw-imvs/fhnw-remotepa | 5567ca7d57f91afcf68f42992f4973e208a537d2 | 337f3f55abca1149b0fe564881a03b39911529d6 | refs/heads/master | 2022-12-11T13:46:30.300087 | 2020-09-11T17:55:17 | 2020-09-11T17:55:17 | 290,732,012 | 1 | 2 | MIT | 2020-09-11T17:55:18 | 2020-08-27T09:21:13 | HTML | UTF-8 | Java | false | false | 620 | java | // Copyright (c) 2020 FHNW, Switzerland. All rights reserved.
// Licensed under MIT License. Initiated by HB9RYZ and HB9CQK.
package ch.fhnw.server.exception;
import org.springframework.security.core.AuthenticationException;
/**
* The type Jwt authentication exception.
*/
// Based on https://ertan-toker.de/spring-boot-spring-security-jwt-token/
public class JwtAuthenticationException extends AuthenticationException {
/**
* Instantiates a new Jwt authentication exception.
*
* @param msg the msg as String
*/
public JwtAuthenticationException(String msg) {
super(msg);
}
}
| [
"[email protected]"
] | |
053f3cbf01bae22d49b95b95834d5414eabe6679 | ac30aa43eb3116d7c98895d0b01d7012a85726b5 | /src/test/java/tests/TestCases9_12.java | be4a9bff98fc8ce193d80a10140094ad5bbdf624 | [] | no_license | samilAkkus/BasicNavigationTests | 77134f8801f75d434fec793077caf15a77b0a9d9 | 1e5c85d51f8dc9f14af5fc32da305172c5520560 | refs/heads/master | 2023-05-11T03:51:30.833025 | 2020-03-23T09:48:52 | 2020-03-23T09:48:52 | 246,678,939 | 0 | 0 | null | 2023-05-09T18:22:37 | 2020-03-11T21:00:09 | Java | UTF-8 | Java | false | false | 2,442 | java | package tests;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import utilities.BrowserFactory;
import utilities.BrowserUtils;
public class TestCases9_12 {
WebDriver driver;
@Test
public void testCase9(){
driver.findElement(By.xpath("//div[@id='content']//a[text()='200']")).click();
BrowserUtils.wait(3);
String expected = "This page returned a 200 status code";
String actual = driver.findElement(By.cssSelector("div[class='example'] > p")).getText();
Assert.assertTrue(actual.contains(expected));
}
@Test
public void testCase10(){
driver.findElement(By.xpath("//div[@id='content']//a[text()='301']")).click();
BrowserUtils.wait(3);
String expected = "This page returned a 301 status code";
String actual = driver.findElement(By.cssSelector("div[class='example'] > p")).getText();
Assert.assertTrue(actual.contains(expected));
}
@Test
public void testCase11(){
driver.findElement(By.xpath("//div[@id='content']//a[text()='404']")).click();
BrowserUtils.wait(3);
String expected = "This page returned a 404 status code";
String actual = driver.findElement(By.cssSelector("div[class='example'] > p")).getText();
Assert.assertTrue(actual.contains(expected));
}
@Test
public void testCase12(){
driver.findElement(By.xpath("//div[@id='content']//a[text()='500']")).click();
BrowserUtils.wait(3);
String expected = "This page returned a 500 status code";
String actual = driver.findElement(By.cssSelector("div[class='example'] > p")).getText();
Assert.assertTrue(actual.contains(expected));
}
@AfterMethod
public void teardown(){
driver.quit();
}
@BeforeMethod
public void setup(){
driver = BrowserFactory.createADriver("chrome");
driver.get("https://practice-cybertekschool.herokuapp.com");
driver.manage().window().maximize();
BrowserUtils.wait(3);
driver.findElement(By.linkText("Status Codes")).click();
BrowserUtils.wait(4);
}
}
| [
"[email protected]"
] | |
3a845b14cf080f40c6f5e53f29c93cd5a244c9e1 | ba62745effaea4c48b7292c943dd0916d756b577 | /src004_diSetterObject/com/luv2code/spring/_004_di_Setter_Object/BaseballCoach.java | 5bf1f26a4b58cb9a075d60dde32e57b4f7fd8abf | [] | no_license | harshilgupta93/SpringCore | 47561d64de0f258304b2600be9a0a1c7a9f815c0 | a665eab67601be6a42df8c9812a75075efca7908 | refs/heads/master | 2021-06-19T17:09:16.257974 | 2017-07-24T16:42:30 | 2017-07-24T16:42:30 | 95,001,749 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 609 | java | package com.luv2code.spring._004_di_Setter_Object;
public class BaseballCoach implements Coach{
private FortuneService fortuneService;
public BaseballCoach() {
System.out.println("in no-arg Constructor: BaseballCoach()");
}
public void setFortuneService(FortuneService fortuneService) {
System.out.println("in Setter Method: setFortuneService()");
this.fortuneService = fortuneService;
}
@Override
public String getDailyWorkout() {
return "BaseballCoach: Workout";
}
@Override
public String getDailyFortune() {
return "From BaseballCoach: " + fortuneService.getFortune();
}
}
| [
"[email protected]"
] | |
9955504688e0a9d218f9abe1506e5046f74e63b0 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/17/17_a1438752da389ff29c2d1cde155daab8a5b880e5/DefaultArtifact/17_a1438752da389ff29c2d1cde155daab8a5b880e5_DefaultArtifact_t.java | 3c4cf5ddf7809989fdaf4a5dbf2da0ac37a08a79 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 15,589 | java | package org.apache.maven.artifact;
/*
* 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.
*/
import java.io.File;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import org.apache.maven.artifact.handler.ArtifactHandler;
import org.apache.maven.artifact.metadata.ArtifactMetadata;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.apache.maven.artifact.versioning.OverConstrainedVersionException;
import org.apache.maven.artifact.versioning.VersionRange;
import org.codehaus.plexus.util.StringUtils;
/**
* @author Jason van Zyl
*/
public class DefaultArtifact
implements Artifact
{
private String groupId;
private String artifactId;
private String baseVersion;
private final String type;
private final String classifier;
private String scope;
private volatile File file;
private ArtifactRepository repository;
private String downloadUrl;
private ArtifactFilter dependencyFilter;
private ArtifactHandler artifactHandler;
private List<String> dependencyTrail;
private String version;
private VersionRange versionRange;
private volatile boolean resolved;
private boolean release;
private List<ArtifactVersion> availableVersions;
private Map<Object,ArtifactMetadata> metadataMap;
private boolean optional;
public DefaultArtifact( String groupId, String artifactId, String version, String scope, String type, String classifier, ArtifactHandler artifactHandler )
{
this( groupId, artifactId, VersionRange.createFromVersion( version ), scope, type, classifier, artifactHandler, false );
}
public DefaultArtifact( String groupId, String artifactId, VersionRange versionRange, String scope, String type, String classifier, ArtifactHandler artifactHandler )
{
this( groupId, artifactId, versionRange, scope, type, classifier, artifactHandler, false );
}
public DefaultArtifact( String groupId, String artifactId, VersionRange versionRange, String scope, String type, String classifier, ArtifactHandler artifactHandler, boolean optional )
{
this.groupId = groupId;
this.artifactId = artifactId;
this.versionRange = versionRange;
selectVersionFromNewRangeIfAvailable();
this.artifactHandler = artifactHandler;
this.scope = scope;
this.type = type;
if ( classifier == null )
{
classifier = artifactHandler.getClassifier();
}
this.classifier = classifier;
this.optional = optional;
validateIdentity();
}
private void validateIdentity()
{
if ( empty( groupId ) )
{
throw new InvalidArtifactRTException( groupId, artifactId, getVersion(), type,
"The groupId cannot be empty." );
}
if ( artifactId == null )
{
throw new InvalidArtifactRTException( groupId, artifactId, getVersion(), type,
"The artifactId cannot be empty." );
}
if ( type == null )
{
throw new InvalidArtifactRTException( groupId, artifactId, getVersion(), type,
"The type cannot be empty." );
}
if ( ( version == null ) && ( versionRange == null ) )
{
throw new InvalidArtifactRTException( groupId, artifactId, getVersion(), type,
"The version cannot be empty." );
}
}
private boolean empty( String value )
{
return ( value == null ) || ( value.trim().length() < 1 );
}
public String getClassifier()
{
return classifier;
}
public boolean hasClassifier()
{
return StringUtils.isNotEmpty( classifier );
}
public String getScope()
{
return scope;
}
public String getGroupId()
{
return groupId;
}
public String getArtifactId()
{
return artifactId;
}
public String getVersion()
{
return version;
}
public void setVersion( String version )
{
this.version = version;
setBaseVersionInternal( version );
versionRange = null;
}
public String getType()
{
return type;
}
public void setFile( File file )
{
this.file = file;
}
public File getFile()
{
return file;
}
public ArtifactRepository getRepository()
{
return repository;
}
public void setRepository( ArtifactRepository repository )
{
this.repository = repository;
}
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
public String getId()
{
return getDependencyConflictId() + ":" + getBaseVersion();
}
public String getDependencyConflictId()
{
StringBuilder sb = new StringBuilder( 128 );
sb.append( getGroupId() );
sb.append( ":" );
appendArtifactTypeClassifierString( sb );
return sb.toString();
}
private void appendArtifactTypeClassifierString( StringBuilder sb )
{
sb.append( getArtifactId() );
sb.append( ":" );
sb.append( getType() );
if ( hasClassifier() )
{
sb.append( ":" );
sb.append( getClassifier() );
}
}
public void addMetadata( ArtifactMetadata metadata )
{
if ( metadataMap == null )
{
metadataMap = new HashMap<Object,ArtifactMetadata>();
}
ArtifactMetadata m = metadataMap.get( metadata.getKey() );
if ( m != null )
{
m.merge( metadata );
}
else
{
metadataMap.put( metadata.getKey(), metadata );
}
}
public Collection<ArtifactMetadata> getMetadataList()
{
if ( metadataMap == null )
{
return Collections.emptyList();
}
return metadataMap.values();
}
// ----------------------------------------------------------------------
// Object overrides
// ----------------------------------------------------------------------
public String toString()
{
StringBuilder sb = new StringBuilder();
if ( getGroupId() != null )
{
sb.append( getGroupId() );
sb.append( ":" );
}
appendArtifactTypeClassifierString( sb );
sb.append( ":" );
if ( getBaseVersionInternal() != null )
{
sb.append( getBaseVersionInternal() );
}
else
{
sb.append( versionRange.toString() );
}
if ( scope != null )
{
sb.append( ":" );
sb.append( scope );
}
return sb.toString();
}
public int hashCode()
{
int result = 17;
result = 37 * result + groupId.hashCode();
result = 37 * result + artifactId.hashCode();
result = 37 * result + type.hashCode();
if ( version != null )
{
result = 37 * result + version.hashCode();
}
result = 37 * result + ( classifier != null ? classifier.hashCode() : 0 );
return result;
}
public boolean equals( Object o )
{
if ( o == this )
{
return true;
}
if ( !( o instanceof Artifact ) )
{
return false;
}
Artifact a = (Artifact) o;
if ( !a.getGroupId().equals( groupId ) )
{
return false;
}
else if ( !a.getArtifactId().equals( artifactId ) )
{
return false;
}
else if ( !a.getVersion().equals( version ) )
{
return false;
}
else if ( !a.getType().equals( type ) )
{
return false;
}
else if ( a.getClassifier() == null ? classifier != null : !a.getClassifier().equals( classifier ) )
{
return false;
}
// We don't consider the version range in the comparison, just the resolved version
return true;
}
public String getBaseVersion()
{
if ( baseVersion == null && version != null )
{
setBaseVersionInternal( version );
}
return baseVersion;
}
protected String getBaseVersionInternal()
{
if ( ( baseVersion == null ) && ( version != null ) )
{
setBaseVersionInternal( version );
}
return baseVersion;
}
public void setBaseVersion( String baseVersion )
{
setBaseVersionInternal( baseVersion );
}
protected void setBaseVersionInternal( String baseVersion )
{
Matcher m = VERSION_FILE_PATTERN.matcher( baseVersion );
if ( m.matches() )
{
this.baseVersion = m.group( 1 ) + "-" + SNAPSHOT_VERSION;
}
else
{
this.baseVersion = baseVersion;
}
}
public int compareTo( Artifact a )
{
int result = groupId.compareTo( a.getGroupId() );
if ( result == 0 )
{
result = artifactId.compareTo( a.getArtifactId() );
if ( result == 0 )
{
result = type.compareTo( a.getType() );
if ( result == 0 )
{
if ( classifier == null )
{
if ( a.getClassifier() != null )
{
result = 1;
}
}
else
{
if ( a.getClassifier() != null )
{
result = classifier.compareTo( a.getClassifier() );
}
else
{
result = -1;
}
}
if ( result == 0 )
{
// We don't consider the version range in the comparison, just the resolved version
result = new DefaultArtifactVersion( version ).compareTo(
new DefaultArtifactVersion( a.getVersion() ) );
}
}
}
}
return result;
}
public void updateVersion( String version, ArtifactRepository localRepository )
{
setResolvedVersion( version );
setFile( new File( localRepository.getBasedir(), localRepository.pathOf( this ) ) );
}
public String getDownloadUrl()
{
return downloadUrl;
}
public void setDownloadUrl( String downloadUrl )
{
this.downloadUrl = downloadUrl;
}
public ArtifactFilter getDependencyFilter()
{
return dependencyFilter;
}
public void setDependencyFilter( ArtifactFilter artifactFilter )
{
dependencyFilter = artifactFilter;
}
public ArtifactHandler getArtifactHandler()
{
return artifactHandler;
}
public List<String> getDependencyTrail()
{
return dependencyTrail;
}
public void setDependencyTrail( List<String> dependencyTrail )
{
this.dependencyTrail = dependencyTrail;
}
public void setScope( String scope )
{
this.scope = scope;
}
public VersionRange getVersionRange()
{
return versionRange;
}
public void setVersionRange( VersionRange versionRange )
{
this.versionRange = versionRange;
selectVersionFromNewRangeIfAvailable();
}
private void selectVersionFromNewRangeIfAvailable()
{
if ( ( versionRange != null ) && ( versionRange.getRecommendedVersion() != null ) )
{
selectVersion( versionRange.getRecommendedVersion().toString() );
}
else
{
version = null;
baseVersion = null;
}
}
public void selectVersion( String version )
{
this.version = version;
setBaseVersionInternal( version );
}
public void setGroupId( String groupId )
{
this.groupId = groupId;
}
public void setArtifactId( String artifactId )
{
this.artifactId = artifactId;
}
public boolean isSnapshot()
{
return getBaseVersion() != null
&& ( getBaseVersion().endsWith( SNAPSHOT_VERSION ) || getBaseVersion().equals( LATEST_VERSION ) );
}
public void setResolved( boolean resolved )
{
this.resolved = resolved;
}
public boolean isResolved()
{
return resolved;
}
public void setResolvedVersion( String version )
{
this.version = version;
// retain baseVersion
}
public void setArtifactHandler( ArtifactHandler artifactHandler )
{
this.artifactHandler = artifactHandler;
}
public void setRelease( boolean release )
{
this.release = release;
}
public boolean isRelease()
{
return release;
}
public List<ArtifactVersion> getAvailableVersions()
{
return availableVersions;
}
public void setAvailableVersions( List<ArtifactVersion> availableVersions )
{
this.availableVersions = availableVersions;
}
public boolean isOptional()
{
return optional;
}
public ArtifactVersion getSelectedVersion()
throws OverConstrainedVersionException
{
return versionRange.getSelectedVersion( this );
}
public boolean isSelectedVersionKnown()
throws OverConstrainedVersionException
{
return versionRange.isSelectedVersionKnown( this );
}
public void setOptional( boolean optional )
{
this.optional = optional;
}
}
| [
"[email protected]"
] | |
686c344e7fbc1d0dadaf4e12813bc9ce27d701ee | 94912777a3218b543c6c06feb6e1cfcd72a7d925 | /src/main/test/java/com/vaadin/toolkit/common/TestData.java | 50502363383910369208ea4ff4f639fc7627ed70 | [] | no_license | richardk123/vaadin-toolkit | ef82b0b076f1f77a0cca0fd4050753535643072b | 543a118da88ef25cc74d5a5842761ac443e50b91 | refs/heads/master | 2021-07-22T07:30:21.887715 | 2017-10-13T08:42:26 | 2017-10-13T08:42:26 | 105,689,759 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 871 | java | package com.vaadin.toolkit.common;
import com.vaadin.toolkit.MyUI;
import java.util.ArrayList;
import java.util.List;
public class TestData
{
private String name;
private TestData test;
private List<TestData> testList = new ArrayList<>();
public TestData(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public TestData getTest()
{
return test;
}
public void setTest(TestData test)
{
this.test = test;
}
public List<TestData> getTestList()
{
return testList;
}
public void setTestList(List<TestData> testList)
{
this.testList = testList;
}
public void addTest(TestData test)
{
this.testList.add(test);
}
}
| [
"[email protected]"
] | |
e4707f4e6f829323619c8ac927bf32969ad8475b | 8671a87fc1586b25796c4f415927a0674ec1d5ec | /GCD-Sistema/src/br/edu/ifpb/tsi/gcd/dao/GenericDAO.java | 6c72b70927c0c2efb79ec13fefb68805cc16536e | [] | no_license | GCD-Sistema/GCD-RELEASE02 | 865c240d590c897db97cc3bcfae1e18a107e0b44 | 04c302770478629213355807cbd0d383b35323f7 | refs/heads/master | 2020-04-06T06:58:17.697375 | 2016-08-23T15:11:37 | 2016-08-23T15:11:37 | 64,080,903 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 285 | java | package br.edu.ifpb.tsi.gcd.dao;
import java.io.Serializable;
public interface GenericDAO<T, PK extends Serializable> {
T insert(T t);
T find(PK id);
T update(T t);
void delete(T t);
void beginTransaction();
void commit();
void rollback();
}
| [
"[email protected]"
] | |
6d4ae12889fc4f93d17c7e405684d6e61d86b0d5 | 468c3f3a50201b6ed3cb5715de7e1a96946b1594 | /MODULE_04/casestudy04/src/main/java/com/codegym/casestudy04/controller/CustomerTypeController.java | ad5305f2ce8cf0d9ffda88ba16edbffb326b1f16 | [] | no_license | phapnguyen539/A0920I1-NguyenTanPhap | 066acd49f4883a2736c244f4e25f6be8db1118f7 | 614b86ea208bea19a8c3efb28bbbe573ba75cd21 | refs/heads/master | 2023-07-07T19:57:44.185829 | 2021-08-31T02:05:36 | 2021-08-31T02:05:36 | 297,361,783 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,284 | java | package com.codegym.casestudy04.controller;
import com.codegym.casestudy04.model.Customer;
import com.codegym.casestudy04.model.CustomerType;
import com.codegym.casestudy04.service.CustomerService;
import com.codegym.casestudy04.service.CustomerTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
public class CustomerTypeController {
@Autowired
CustomerTypeService customerTypeService;
@Autowired
CustomerService customerService;
@GetMapping("/customerType")
public ModelAndView listType(){
List<CustomerType> customerTypes= customerTypeService.findAll();
return new ModelAndView("/customerType/list","customerTypes", customerTypes);
}
@GetMapping("/create-type")
public ModelAndView createType(){
return new ModelAndView("/customerType/create","customerTypes",new CustomerType());
}
@PostMapping("/create-type")
public String saveType(@ModelAttribute("customerTypes") CustomerType customerType){
customerTypeService.save(customerType);
return "/redirect:/customerType";
}
}
| [
"[email protected]"
] | |
2cb1573ea022d82018443ec9ac990c76ba3931a7 | 0e67aa55ca974e020decbade51f343c20d15a2aa | /nycity_taxi_ad_api_java/src/main/java/com/springml/nyc/taxi/ad/api/model/Prediction.java | fa13a93688c9269228edc69fe289967242edf0d8 | [] | no_license | kaarthikraajpt/nycity_taxi_ad_api | e2f00ac0f1df9ca860d75f7cdcb62ecc90914f4d | 547804559db40f0f2d3c3c3811958783acd418e2 | refs/heads/master | 2021-01-20T07:38:19.005923 | 2017-05-02T10:18:20 | 2017-05-02T10:18:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 950 | java | package com.springml.nyc.taxi.ad.api.model;
import java.util.List;
public class Prediction {
private List<Double> probabilities = null;
private List<Double> logits = null;
private Integer classes;
public List<Double> getProbabilities() {
return probabilities;
}
public void setProbabilities(List<Double> probabilities) {
this.probabilities = probabilities;
}
public List<Double> getLogits() {
return logits;
}
public void setLogits(List<Double> logits) {
this.logits = logits;
}
public Integer getClasses() {
return classes;
}
public void setClasses(Integer classes) {
this.classes = classes;
}
@Override
public String toString() {
return "Prediction{" +
"probabilities=" + probabilities +
", logits=" + logits +
", classes=" + classes +
'}';
}
}
| [
"[email protected]"
] | |
e30a5f082fdb5bbd3aa37e3a3a0e53713f1db4d2 | 14bea85e8bf24d7650bfa6b70531a81e5d337609 | /src/main/java/com/wonders/core/filter/XssFilter.java | 521b33ab222917e901722a47e4972e5df47b4cd6 | [] | no_license | liqingdong/STU | db7bf0b7186d893918e8bf0fc9c108db86379320 | 9b7079e16602d5598400b4b58cd57ec468bff1f1 | refs/heads/master | 2021-01-19T22:39:57.730716 | 2018-03-28T06:16:25 | 2018-03-28T06:16:25 | 101,032,472 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 616 | java | package com.wonders.core.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class XssFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("XssFilter初始化");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
chain.doFilter(new XssHttpServletRequestWrapper(
(HttpServletRequest) request), response);
}
@Override
public void destroy() {
}
}
| [
"[email protected]"
] | |
2de923f6bbc7a5298dc41c1c15c5a56545d238c3 | d52e3d5a4802f083ab1832e946bac390937635a6 | /jackylib/src/main/java/com/example/jacky/recycler/adapter/base/entity/MultiItemEntity.java | 2093493c63e6099d0e3532aed1e1363c2662f117 | [] | no_license | p-jie/MilestoneProjects | 128154cf3485166f7f9f53b180bb20eb6be594d8 | 0b5da2fbce07149ea7573ab1a216ccdae4e22730 | refs/heads/master | 2020-03-31T12:28:52.707420 | 2018-10-09T08:26:05 | 2018-10-09T08:26:05 | 152,217,474 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 118 | java | package com.example.jacky.recycler.adapter.base.entity;
public interface MultiItemEntity {
int getItemType();
}
| [
"[email protected]"
] | |
11b7f8b9598b5061722e73960f99ccb4a81272ba | 81d4b9d6eb7d26a6729c340e5bd20edf5179d7cc | /app/src/main/java/com/codepath/apps/restclienttemplate/models/Tweet.java | fee6f9bdd4fba06039f01eae0c81c3c29c8c1dda | [
"MIT",
"Apache-2.0"
] | permissive | krishnakhadka200416/SimpleTweet | 4e1b2660ae94cf52bbac928cbea365c3fbbf875c | 9b9d3352663a8fab8377f3fabc9e22e0fe2e83a8 | refs/heads/master | 2023-03-09T16:51:34.286443 | 2021-02-25T23:07:37 | 2021-02-25T23:07:37 | 337,848,801 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,158 | java | package com.codepath.apps.restclienttemplate.models;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.parceler.Parcel;
import java.util.ArrayList;
import java.util.List;
@Parcel
public class Tweet {
public String body;
public String createdAt;
public long id;
public User user;
public Tweet(){}
public static Tweet fromJson(JSONObject jsonObject) throws JSONException {
Tweet tweet = new Tweet();
tweet.body = jsonObject.getString("text");
tweet.createdAt = jsonObject.getString("created_at");
tweet.id = jsonObject.getLong("id");
tweet.user = User.fromJson(jsonObject.getJSONObject("user"));
return tweet;
}
public static List<Tweet> fromJsonArray(JSONArray jsonArray) throws JSONException {
List<Tweet> tweets = new ArrayList<>();
for(int i = 0 ; i <jsonArray.length(); i++){
tweets.add(fromJson(jsonArray.getJSONObject(i)));
}
return tweets;
}
public static String getFormattedTimestamp(String createdat){
return TimeFormatter.getTimeDifference(createdat);
}
}
| [
"[email protected]"
] | |
da83f0125680263d3d94b9607856102677f20a0b | 846fcec86cdb4865460fadbf08c62799bb840747 | /src/ui/Authentification.java | 0af0a18bf9a5c196ab617cfb346a809b31a8f12c | [] | no_license | jospin2017/GestionEtudiant | 4761eddeb8a06f2b5292d87d9d48e659e2ee25bc | 90d85fe77d5cd41792d62364be9c1231ef2d6e8b | refs/heads/master | 2021-06-29T16:38:35.609051 | 2020-10-31T10:49:28 | 2020-10-31T10:49:28 | 182,456,955 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 4,227 | java | package ui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import dao.ConnexionMysql;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Authentification extends JFrame {
private JFrame frame;
private JTextField usernameField;
private JTextField passwordField;
Connection cnx = null;
PreparedStatement prepared = null;
ResultSet resultat = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Authentification window = new Authentification();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Authentification() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 1000, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
cnx = ConnexionMysql.ConnectToDb();
usernameField = new JTextField();
usernameField.setBounds(286, 91, 255, 31);
frame.getContentPane().add(usernameField);
usernameField.setColumns(10);
passwordField = new JTextField();
passwordField.setBounds(286, 146, 255, 31);
frame.getContentPane().add(passwordField);
passwordField.setColumns(10);
JLabel lblUsername = new JLabel("Username :");
lblUsername.setBounds(128, 98, 84, 16);
frame.getContentPane().add(lblUsername);
JButton btnNewButton = new JButton("Se connecter");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
/*String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
if(!username.equals("") || !password.equals("")){
if(username.equals("admin") && password.equals("admin")){
JOptionPane.showMessageDialog(null, "you are welcome");
Accueil accueil = new Accueil();
accueil.setVisible(true);
}else{
JOptionPane.showMessageDialog(null, "Paramètres incorrectes !");
}
}else{
JOptionPane.showMessageDialog(null, "Entrez vos parametres !");
}*/
String sql = "select username,password from utilisateurs";
try {
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
prepared = cnx.prepareStatement(sql);
resultat = prepared.executeQuery();
int i = 0;
if(username.equals("") || password.equals("")){
JOptionPane.showMessageDialog(null, "Veuillez remplir les champs vide");
}else{
while(resultat.next()){
String username1 = resultat.getString("username");
String password1 = resultat.getString("password");
if(username1.equals(username) && password1.equals(password1)){
JOptionPane.showMessageDialog(null, "you are welcome");
i = 1;
}
}
if(i==0){
JOptionPane.showMessageDialog(null, "Paramètres érronés !");
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnNewButton.setBounds(286, 208, 256, 37);
frame.getContentPane().add(btnNewButton);
JLabel lblPassword = new JLabel("Password :");
lblPassword.setBounds(128, 153, 84, 16);
frame.getContentPane().add(lblPassword);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setIcon(new ImageIcon("C:\\Users\\Speedy\\Desktop\\back.png"));
lblNewLabel.setBounds(0, 0, 982, 453);
frame.getContentPane().add(lblNewLabel);
}
}
| [
"[email protected]"
] | |
ddc413e01131da13eb1e6bab219178ca36a69735 | 343e2c10f88f069d8af785375b44a42ed7909366 | /Citibank/src/test/java/SearchOnElementTest.java | dfeb8083b53828a3caaa7f6b67cb60e04c5498b5 | [] | no_license | Mozahar-Ahmed/MultiDomainTest | bfb1fa9a1fa0d6134530a401603bcc1561ea7177 | f83f36aabf8c686374eac529bcc2e24281676802 | refs/heads/master | 2022-02-25T03:47:22.122796 | 2019-10-28T21:37:36 | 2019-10-28T21:37:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 185 | java | import org.testng.annotations.Test;
public class SearchOnElementTest extends SearchOnElement {
@Test
public void searchFunctionalityTest() {
validateSearch();
}
}
| [
"[email protected]"
] | |
70d1c4fd596a495eb9f99424be520f0c16930dd6 | 6db6eca7443c22213faf8c01445231ee3e7984de | /src/test/java/com/test/one/SanityTest.java | 6e49c19b2e9cb7a294e0a716ef949b73de35b307 | [] | no_license | tangintabassum/TestNG | f9a93c6c32c5f144abfa273e240e4b1cff942264 | 0944ccdeba388fc9b68edf3a40034ea7ac7134e2 | refs/heads/master | 2023-02-04T20:32:50.388934 | 2020-12-16T20:28:58 | 2020-12-16T20:28:58 | 321,780,935 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 664 | java | package com.test.one;
import org.testng.annotations.Test;
public class SanityTest {
@Test (groups = "aGroup")
public void TestOne() {
System.out.println("Test one");
}
@Test (groups = "bGroup")
public void TestTwo() {
System.out.println("Test two");
}
@Test ( groups = "aGroup")
public void TestThree() {
System.out.println("Test Three");
}
@Test (groups = "bGroup")
public void TestFour() {
System.out.println("Test four");
}
@Test (dependsOnGroups = "aGroup")
public void TestFive() {
System.out.println("Test five");
}
@Test (dependsOnMethods = "TestOne")
public void TestSix() {
System.out.println("Test six");
}
}
| [
"[email protected]"
] | |
70098b0e5ab00a841857bb2c20a0494347867baf | d49dcc3df76120003776e1ec944a8fd1fb99795d | /PullRecycler/app/src/main/java/com/stay4it/sample/WelcomeActivity.java | ce8b70013f13d561854da94f88e8e3829093f6b7 | [
"MIT"
] | permissive | chefish/RecycleView | 5f719f4e3f110e7508c6d58e094fa25c0ca6bb58 | 289f43f13b361bcbe22c8b579dcc7c19119adfd5 | refs/heads/master | 2020-04-29T17:00:28.140578 | 2019-03-18T12:42:34 | 2019-03-18T12:42:34 | 176,282,915 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,107 | java | package com.stay4it.sample;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import com.stay4it.R;
import com.stay4it.core.BaseActivity;
/**
* Created by Stay on 2/2/16.
* Powered by www.stay4it.com
*/
public class WelcomeActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void setUpContentView() {
setContentView(R.layout.activity_welcome, -1, MODE_NONE);
}
@Override
protected void setUpView() {
}
@Override
protected void setUpData() {
handler.sendEmptyMessageDelayed(0, 100);
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
startActivity(new Intent(WelcomeActivity.this, HomeActivity.class));
finish();
}
};
@Override
protected void onPause() {
super.onPause();
handler.removeMessages(0);
}
}
| [
"[email protected]"
] | |
ff30bb840299276ec4eea395cca947502ad38e3f | 3c30127ec3d2a5dd5bc9b98cb86d35319daca019 | /app/src/main/java/com/example/phetandroidprototype/data/source/local/PhetDatabase.java | 46d4a3c5fc6858e6da8945aaf0f162952147b9bd | [] | no_license | mbarlow12/PhetAndroidPrototype | 9516fbf60af82a8eb7519bc4382b93ace08faf4a | 093cf3121f5463be81631de96ac1b1c3ab0be958 | refs/heads/master | 2020-04-23T00:24:04.616107 | 2019-03-01T23:59:07 | 2019-03-01T23:59:07 | 170,778,340 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,231 | java | package com.example.phetandroidprototype.data.source.local;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import com.example.phetandroidprototype.data.source.local.dao.CategoryDao;
import com.example.phetandroidprototype.data.source.local.dao.JoinSimulationCategoryDao;
import com.example.phetandroidprototype.data.source.local.dao.SimulationDao;
import com.example.phetandroidprototype.data.source.local.entity.Category;
import com.example.phetandroidprototype.data.source.local.entity.JoinSimulationCategory;
import com.example.phetandroidprototype.data.source.local.entity.Simulation;
@Database( entities = {Category.class, JoinSimulationCategory.class, Simulation.class }, exportSchema = false, version = 1 )
public abstract class PhetDatabase extends RoomDatabase {
// data access objects
public abstract SimulationDao simulationDao();
public abstract CategoryDao categoryDao();
public abstract JoinSimulationCategoryDao simCategoryRelationDao();
private static final String DB_NAME = "phetsims.db";
// singleton pattern
private static volatile PhetDatabase INSTANCE = null;
synchronized public static PhetDatabase getDatabase( Context ctx ) {
if ( INSTANCE == null ) {
INSTANCE = create( ctx, false );
}
return INSTANCE;
}
static PhetDatabase create( Context context, boolean memoryOnly ) {
RoomDatabase.Builder<PhetDatabase> b;
if ( memoryOnly ) {
b = Room.inMemoryDatabaseBuilder( context.getApplicationContext(), PhetDatabase.class );
}
else {
b = Room.databaseBuilder( context.getApplicationContext(), PhetDatabase.class, DB_NAME );
}
return ( b.build() );
}
// private static class PopulateDbAsync extends AsyncTask<Void, Void, Void> {
//
// private final SimulationDao simulationDao;
//
// PopulateDbAsync( PhetDatabase db ) {
// simulationDao = db.simulationDao();
// }
//
// @Override
// protected Void doInBackground(Void... voids) {
// simulationDao.deleteAll();
// return null;
// }
// }
}
| [
"[email protected]"
] | |
7f89acf6bfd8adabf148fdc82e810a9b229165cb | e204e5409d0c2c17583a3b8b68360ea22312d8d8 | /src/java/com/sium/dao/component/UsuarioDAO.java | 19e97529ceb60db84220da4cf7697052e9f90d26 | [] | no_license | rimegaray/proyectodsw | 8112ebe8010faf31ffd0830f9cb1efeeed506d4d | 9f257f8ae2b47615c6239d852c4e368f87164af9 | refs/heads/master | 2021-05-07T07:43:32.565320 | 2017-11-22T20:48:29 | 2017-11-22T20:48:29 | 109,152,812 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,561 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sium.dao.component;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Filters.eq;
import com.sium.dao.design.IUsuarioDAO;
import com.sium.dao.to.UsuarioTO;
import com.sium.mongo.AccesoMongoDB;
import org.bson.Document;
/**
*
* @author Aisac
*/
public class UsuarioDAO implements IUsuarioDAO {
private final MongoClient db;
private MongoDatabase database;
private MongoCollection<Document> collection;
public UsuarioDAO() {
this.db = AccesoMongoDB.getAccesoSingleton();
database = db.getDatabase("sium");
}
@Override
public boolean validarUsuario(UsuarioTO usuario) {
try {
collection = database.getCollection("usuario");
FindIterable<Document> findIterable = collection.find(
and(
eq("usuario", usuario.getUsuario()),
eq("password", usuario.getPassword())
)
);
return findIterable.first() != null;
} catch (MongoException e) {
System.out.println(e.getMessage());
return false;
}
}
}
| [
"[email protected]"
] | |
8429083691ec67855660e8040aa455b4090031eb | 42d9bfece1999c12abdea00f6006f8ba375d4ad6 | /app/src/main/java/www/coders/org/qr_fintech_client/ProductObject.java | 621f34f4b28542a298ed4142ffdd082fbc947e39 | [] | no_license | hendel95/QR_FinTech_Client | 7f7cf0b11b877a649353171d9d9b696f9e262171 | f1c10a39550c13066d0bd8579138c63226db7b96 | refs/heads/master | 2020-03-18T21:31:15.217884 | 2018-05-29T11:53:25 | 2018-05-29T11:53:25 | 135,285,011 | 0 | 0 | null | 2018-05-29T11:18:27 | 2018-05-29T11:18:26 | null | UTF-8 | Java | false | false | 1,914 | java | package www.coders.org.qr_fintech_client;
import org.json.JSONException;
import org.json.JSONObject;
public class ProductObject {
private String num, name, price, img, init_date, del_date, owner_id, owner_shop, isDelete;
//??
@Override
public String toString() {
return name + "\t\t" + price + "\\";
}
public ProductObject(JSONObject jsonObject) throws JSONException {
this.num = jsonObject.getString("num");
this.name = jsonObject.getString("name");
this.price = jsonObject.getString("price");
//// 정보없는거넘어오면 안됨
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getInit_date() {
return init_date;
}
public void setInit_date(String init_date) {
this.init_date = init_date;
}
public String getDel_date() {
return del_date;
}
public void setDel_date(String del_date) {
this.del_date = del_date;
}
public String getOwner_id() {
return owner_id;
}
public void setOwner_id(String owner_id) {
this.owner_id = owner_id;
}
public String getOwner_shop() {
return owner_shop;
}
public void setOwner_shop(String owner_shop) {
this.owner_shop = owner_shop;
}
public String getIsDelete() {
return isDelete;
}
public void setIsDelete(String isDelete) {
this.isDelete = isDelete;
}
}
| [
"[email protected]"
] | |
6124dcf23a50252a7e7fefdcbb816595d8012f43 | 43a59b3b36d5a35d5fa1747e25d9194e1ffcd1b4 | /src/main/java/org/geotools/data/kml/KMLFeatureSource.java | 19b0652988fd178ee68ab895f4ac89aeb2bd2753 | [
"MIT"
] | permissive | FirokOtaku/GeodataTransformSpring | 2f9816b24e2a61f96ead36b249a86d21b9cc4dba | 77f0073cd5e7bc9d52ca098a2699211d751acfdc | refs/heads/main | 2023-08-29T01:10:23.634434 | 2021-10-15T01:29:42 | 2021-10-15T01:29:42 | 417,329,208 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,298 | java | /*
* The MIT License
*
* Copyright 2020 Emre Demir.
*
* 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 org.geotools.data.kml;
import java.io.IOException;
import javax.xml.namespace.QName;
import org.geotools.data.FeatureReader;
import org.geotools.data.Query;
import org.geotools.data.QueryCapabilities;
import org.geotools.data.store.ContentEntry;
import org.geotools.data.store.ContentFeatureSource;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
/** @author Niels Charlier, Scitus Development */
public class KMLFeatureSource extends ContentFeatureSource {
public KMLFeatureSource(ContentEntry entry, Query query) {
super(entry, query);
}
@Override
protected QueryCapabilities buildQueryCapabilities() {
return new QueryCapabilities() {
public boolean isUseProvidedFIDSupported() {
return true;
}
};
}
@Override
protected ReferencedEnvelope getBoundsInternal(Query query) throws IOException {
ReferencedEnvelope bounds =
new ReferencedEnvelope(getSchema().getCoordinateReferenceSystem());
FeatureReader<SimpleFeatureType, SimpleFeature> featureReader = getReaderInternal(query);
try {
while (featureReader.hasNext()) {
SimpleFeature feature = featureReader.next();
bounds.include(feature.getBounds());
}
} finally {
featureReader.close();
}
return bounds;
}
@Override
protected int getCountInternal(Query query) throws IOException {
int count = 0;
FeatureReader<SimpleFeatureType, SimpleFeature> featureReader = getReaderInternal(query);
try {
while (featureReader.hasNext()) {
featureReader.next();
count++;
}
} finally {
featureReader.close();
}
return count;
}
@Override
protected SimpleFeatureType buildFeatureType() throws IOException {
String typeName = getEntry().getTypeName();
String namespace = getEntry().getName().getNamespaceURI();
SimpleFeatureType type;
FeatureReader<SimpleFeatureType, SimpleFeature> featureReader = getReaderInternal(query);
try {
type = featureReader.getFeatureType();
} finally {
featureReader.close();
}
// rename
SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
if (type != null) {
b.init(type);
}
b.setName(typeName);
b.setNamespaceURI(namespace);
return b.buildFeatureType();
}
@Override
protected FeatureReader<SimpleFeatureType, SimpleFeature> getReaderInternal(Query query)
throws IOException {
KMLDataStore dataStore = (KMLDataStore) getEntry().getDataStore();
return new KMLFeatureReader(
dataStore.getNamespaceURI(),
dataStore.file,
new QName(getEntry().getName().getNamespaceURI(), getEntry().getTypeName()));
}
} | [
"[email protected]"
] | |
b754a1ab5b3ec448aa0f225e93d1dc274bafbfaa | 326c7f9e6e2bd047c660a0182e44387a2a36df9b | /wflow-consoleweb/src/main/java/org/kecak/webapi/soap/endpoint/SoapAssignmentEndpoint.java | e8b87b3f1ae8ad295ddd099336ff4883937f0250 | [] | no_license | kinnara-digital-studio/kecak-workflow | ff2f76dc8c209358a0ef54199a67137e81bd6a16 | 0d54090b0bf159c81e25c80e05785a1efa2eff9b | refs/heads/master | 2023-06-23T12:22:15.567088 | 2023-06-08T07:29:09 | 2023-06-08T07:29:09 | 96,003,163 | 3 | 2 | null | 2023-02-22T04:30:42 | 2017-07-02T04:54:57 | Java | UTF-8 | Java | false | false | 33,904 | java | package org.kecak.webapi.soap.endpoint;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jdom2.filter.Filters;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
import org.joget.apps.app.service.AppService;
import org.joget.apps.app.service.AppUtil;
import org.joget.commons.util.LogUtil;
import org.joget.commons.util.PagedList;
import org.joget.commons.util.TimeZoneUtil;
import org.joget.workflow.model.WorkflowAssignment;
import org.joget.workflow.model.WorkflowProcess;
import org.joget.workflow.model.WorkflowVariable;
import org.joget.workflow.model.service.WorkflowManager;
import org.joget.workflow.util.WorkflowUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import javax.annotation.Nonnull;
import java.util.*;
@Endpoint
public class SoapAssignmentEndpoint {
private static final String NAMESPACE_URI = "http://kecak.org/soap/process/schemas";
private final Namespace namespace = Namespace.getNamespace("xps", NAMESPACE_URI);
private XPathExpression<Element> packageIdExpresssion;
private XPathExpression<Element> processIdExpression;
private XPathExpression<Element> activityIdExpression;
private XPathExpression<Element> processDefIdExpression;
private XPathExpression<Element> variablesExpression;
private XPathExpression<Element> variableExpression;
private XPathExpression<Element> valueExpression;
private XPathExpression<Element> sortExpression;
private XPathExpression<Element> descExpression;
private XPathExpression<Element> startExpression;
private XPathExpression<Element> rowsExpression;
private XPathExpression<Element> checkWhiteListExpression;
@Autowired
private AppService appService;
@Autowired
private WorkflowManager workflowManager;
public SoapAssignmentEndpoint() {
XPathFactory xpathFactory = XPathFactory.instance();
try {
packageIdExpresssion = xpathFactory.compile("//xps:packageId", Filters.element(), null, namespace);
} catch (NullPointerException e) {
packageIdExpresssion = null;
}
try {
processIdExpression = xpathFactory.compile("//xps:processId", Filters.element(), null, namespace);
} catch (NullPointerException e) {
processIdExpression = null;
}
try {
activityIdExpression = xpathFactory.compile("//xps:activityId", Filters.element(), null, namespace);
} catch (NullPointerException e) {
activityIdExpression = null;
}
try {
processDefIdExpression = xpathFactory.compile("//xps:processDefId", Filters.element(), null, namespace);
} catch (NullPointerException e) {
processDefIdExpression = null;
}
try {
sortExpression = xpathFactory.compile("//xps:sort", Filters.element(), null, namespace);
} catch (NullPointerException e) {
sortExpression = null;
}
try {
descExpression = xpathFactory.compile("//xps:desc", Filters.element(), null, namespace);
} catch (NullPointerException e) {
descExpression = null;
}
try {
startExpression = xpathFactory.compile("//xps:start", Filters.element(), null, namespace);
} catch (NullPointerException e) {
startExpression = null;
}
try {
rowsExpression = xpathFactory.compile("//xps:rows", Filters.element(), null, namespace);
} catch (NullPointerException e) {
rowsExpression = null;
}
try {
variablesExpression = xpathFactory.compile("//xps:variables", Filters.element(), null, namespace);
} catch (NullPointerException e) {
variablesExpression = null;
}
try {
variableExpression = xpathFactory.compile("//xps:variable", Filters.element(), null, namespace);
} catch (NullPointerException e) {
variableExpression = null;
}
try {
valueExpression = xpathFactory.compile("//xps:value", Filters.element(), null, namespace);
} catch (NullPointerException e) {
valueExpression = null;
}
try {
checkWhiteListExpression = xpathFactory.compile("//xps:checkWhiteList", Filters.element(), null, namespace);
} catch (NullPointerException e) {
checkWhiteListExpression = null;
}
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "AssignmentAcceptRequest")
public @ResponsePayload Element handleAssignmentAccept(@RequestPayload Element assignmentAcceptElement) {
final String activityId = activityIdExpression.evaluate(assignmentAcceptElement).get(0).getValue();
Element response = new Element("AssignmentAcceptResponse",namespace);
appService.getAppDefinitionForWorkflowActivity(activityId);
workflowManager.assignmentAccept(activityId);
WorkflowAssignment assignment = workflowManager.getAssignment(activityId);
LogUtil.info(getClass().getName(), "Assignment " + activityId + " accepted");
response.addContent(new Element("assignment",namespace).setText(assignment.getActivityId()));
response.addContent(new Element("status",namespace).setText("accepted"));
return response;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "AssignmentCompleteRequest")
public @ResponsePayload Element handleAssignmentComplete(@RequestPayload Element assignmentCompleteElement) {
final String activityId = activityIdExpression.evaluate(assignmentCompleteElement).get(0).getValue();
Element response = new Element("AssignmentCompleteResponse",namespace);
appService.getAppDefinitionForWorkflowActivity(activityId);
WorkflowAssignment assignment = workflowManager.getAssignment(activityId);
String processId = (assignment != null) ? assignment.getProcessId() : "";
if (assignment != null && !assignment.isAccepted()) {
workflowManager.assignmentAccept(activityId);
}
workflowManager.assignmentComplete(activityId);
LogUtil.info(getClass().getName(), "Assignment " + activityId + " completed");
response.addContent(new Element("status",namespace).setText("completed"));
response.addContent(new Element("processId",namespace).setText(processId));
response.addContent(new Element("activityId",namespace).setText(activityId));
// check for auto continuation
String processDefId = assignment.getProcessDefId();
String activityDefId = assignment.getActivityDefId();
String packageId = WorkflowUtil.getProcessDefPackageId(processDefId);
String packageVersion = WorkflowUtil.getProcessDefVersion(processDefId);
boolean continueNextAssignment = appService.isActivityAutoContinue(packageId, packageVersion, processDefId, activityDefId);
if (continueNextAssignment) {
WorkflowAssignment nextAssignment = workflowManager.getAssignmentByProcess(processId);
if (nextAssignment != null) {
response.addContent(new Element("nextActivityId",namespace).setText(nextAssignment.getActivityId()));
}
}
return response;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "AssignmentCompleteWithVariableRequest")
public @ResponsePayload Element handleAssignmentCompleteWithVariable(@RequestPayload Element assignmentCompleteWithVariableElement) {
final String activityId = activityIdExpression.evaluate(assignmentCompleteWithVariableElement).get(0).getValue();
@Nonnull final Map<String, String> variables = variablesExpression.evaluate(assignmentCompleteWithVariableElement).stream()
.flatMap(elementFields -> elementFields.getChildren("map", namespace).stream())
.flatMap(elementMap -> elementMap.getChildren("item", namespace).stream())
.collect(HashMap::new, (m, e) -> {
String key = e.getChildText("key", namespace);
String value = e.getChildText("value", namespace);
if(key == null || value == null)
return;
m.merge(key, value, (v1, v2) -> String.join(";", v1, v2));
}, Map::putAll);
Element response = new Element("AssignmentCompleteWithVariableResponse",namespace);
appService.getAppDefinitionForWorkflowActivity(activityId);
WorkflowAssignment assignment = workflowManager.getAssignment(activityId);
String processId = (assignment != null) ? assignment.getProcessId() : "";
if (assignment != null && !assignment.isAccepted()) {
workflowManager.assignmentAccept(activityId);
}
workflowManager.assignmentComplete(activityId, variables);
LogUtil.info(getClass().getName(), "Assignment " + activityId + " completed");
response.addContent(new Element("assignment",namespace).setText(assignment.getAssigneeId()));
response.addContent(new Element("status",namespace).setText("completed"));
response.addContent(new Element("processId",namespace).setText(processId));
response.addContent(new Element("activityId",namespace).setText(activityId));
// check for automatic continuation
String processDefId = assignment.getProcessDefId();
String activityDefId = assignment.getActivityDefId();
String packageId = WorkflowUtil.getProcessDefPackageId(processDefId);
String packageVersion = WorkflowUtil.getProcessDefVersion(processDefId);
boolean continueNextAssignment = appService.isActivityAutoContinue(packageId, packageVersion, processDefId, activityDefId);
if (continueNextAssignment) {
WorkflowAssignment nextAssignment = workflowManager.getAssignmentByProcess(processId);
if (nextAssignment != null) {
response.addContent(new Element("nextActivityId",namespace).setText(nextAssignment.getActivityId()));
}
}
return response;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "AssignmentListRequest")
public @ResponsePayload Element handleAssignmentList(@RequestPayload Element assignmentListElement) {
final String packageId = packageIdExpresssion.evaluate(assignmentListElement).get(0).getValue();
final String processDefId = processDefIdExpression.evaluate(assignmentListElement).get(0).getValue();
final String processId = processIdExpression.evaluate(assignmentListElement).get(0).getValue();
final String sort = sortExpression.evaluate(assignmentListElement).get(0).getValue();
final String descString = descExpression.evaluate(assignmentListElement).get(0).getValue();
final boolean desc = (descString == null)?null:Boolean.parseBoolean(descString);
final String startString = startExpression.evaluate(assignmentListElement).get(0).getValue();
final int start = (startString == null)?null:Integer.parseInt(startString);
final String rowsString = rowsExpression.evaluate(assignmentListElement).get(0).getValue();
final int rows = (rowsString == null)?null:Integer.parseInt(rowsString);
Element response = new Element("AssignmentListResponse",namespace);
PagedList<WorkflowAssignment> assignmentList = workflowManager.getAssignmentPendingAndAcceptedList(packageId, processDefId, processId, sort, desc, start, rows);
Integer total = assignmentList.getTotal();
Element data = new Element("data",namespace);
String format = AppUtil.getAppDateFormat();
for (WorkflowAssignment assignment : assignmentList) {
Element item = new Element("item",namespace);
item.addContent(new Element("processId",namespace).setText(assignment.getProcessId()));
item.addContent(new Element("activityId",namespace).setText(assignment.getActivityId()));
item.addContent(new Element("processName",namespace).setText(assignment.getProcessName()));
item.addContent(new Element("activityName",namespace).setText(assignment.getActivityName()));
item.addContent(new Element("processVersion",namespace).setText(assignment.getProcessVersion()));
item.addContent(new Element("dateCreated",namespace).setText(TimeZoneUtil.convertToTimeZone(assignment.getDateCreated(), null, format)));
item.addContent(new Element("acceptedStatus",namespace).setText(String.valueOf(assignment.isAccepted())));
item.addContent(new Element("due",namespace).setText(assignment.getDueDate() != null ? TimeZoneUtil.convertToTimeZone(assignment.getDueDate(), null, format) : "-"));
double serviceLevelMonitor = workflowManager.getServiceLevelMonitorForRunningActivity(assignment.getActivityId());
item.addContent(new Element("serviceLevelMonitor",namespace).setText( WorkflowUtil.getServiceLevelIndicator(serviceLevelMonitor)));
item.addContent(new Element("id",namespace).setText(assignment.getActivityId()));
item.addContent(new Element("label",namespace).setText(assignment.getActivityName()));
item.addContent(new Element("description",namespace).setText(assignment.getDescription()));
data.addContent(item);
}
response.addContent(data);
response.addContent(new Element("total",namespace).setText(total.toString()));
response.addContent(new Element("start",namespace).setText(startString));
response.addContent(new Element("sort",namespace).setText(sort));
response.addContent(new Element("desc",namespace).setText(descString));
return response;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "AssignmentListCountRequest")
public @ResponsePayload Element handleAssignmentListCount(@RequestPayload Element assignmentListCountElement) {
final String packageId = packageIdExpresssion.evaluate(assignmentListCountElement).get(0).getValue();
final String processDefId = processDefIdExpression.evaluate(assignmentListCountElement).get(0).getValue();
final String processId = processIdExpression.evaluate(assignmentListCountElement).get(0).getValue();
Element response = new Element("AssignmentListCountResponse",namespace);
Integer total = new Integer(workflowManager.getAssignmentSize(packageId, processDefId, processId));
response.addContent(new Element("total",namespace).setText(total.toString()));
return response;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "AssignmentListAcceptedRequest")
public @ResponsePayload Element handleAssignmentListAccepted(@RequestPayload Element assignmentListAcceptedElement) {
final String processId = processIdExpression.evaluate(assignmentListAcceptedElement).get(0).getValue();
final String sort = sortExpression.evaluate(assignmentListAcceptedElement).get(0).getValue();
final String descString = descExpression.evaluate(assignmentListAcceptedElement).get(0).getValue();
final boolean desc = (descString == null)?null:Boolean.parseBoolean(descString);
final String startString = startExpression.evaluate(assignmentListAcceptedElement).get(0).getValue();
final int start = (startString == null)?null:Integer.parseInt(startString);
final String rowsString = rowsExpression.evaluate(assignmentListAcceptedElement).get(0).getValue();
final int rows = (rowsString == null)?null:Integer.parseInt(rowsString);
Element response = new Element("AssignmentListAcceptedResponse",namespace);
PagedList<WorkflowAssignment> assignmentList = workflowManager.getAssignmentAcceptedList(processId, sort, desc, start, rows);
Integer total = assignmentList.getTotal();
Element data = new Element("data",namespace);
String format = AppUtil.getAppDateFormat();
for (WorkflowAssignment assignment : assignmentList) {
Element item = new Element("item",namespace);
item.addContent(new Element("processId",namespace).setText(assignment.getProcessId()));
item.addContent(new Element("activityId",namespace).setText(assignment.getActivityId()));
item.addContent(new Element("processName",namespace).setText(assignment.getProcessName()));
item.addContent(new Element("activityName",namespace).setText(assignment.getActivityName()));
item.addContent(new Element("processVersion",namespace).setText(assignment.getProcessVersion()));
item.addContent(new Element("dateCreated",namespace).setText(TimeZoneUtil.convertToTimeZone(assignment.getDateCreated(), null, format)));
item.addContent(new Element("due",namespace).setText(assignment.getDueDate() != null ? TimeZoneUtil.convertToTimeZone(assignment.getDueDate(), null, format) : "-"));
double serviceLevelMonitor = workflowManager.getServiceLevelMonitorForRunningActivity(assignment.getActivityId());
item.addContent(new Element("serviceLevelMonitor",namespace).setText( WorkflowUtil.getServiceLevelIndicator(serviceLevelMonitor)));
item.addContent(new Element("id",namespace).setText(assignment.getActivityId()));
item.addContent(new Element("label",namespace).setText(assignment.getActivityName()));
item.addContent(new Element("description",namespace).setText(assignment.getDescription()));
data.addContent(item);
}
response.addContent(data);
response.addContent(new Element("total",namespace).setText(total.toString()));
response.addContent(new Element("start",namespace).setText(startString));
response.addContent(new Element("sort",namespace).setText(sort));
response.addContent(new Element("desc",namespace).setText(descString));
return response;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "AssignmentListAcceptedCountRequest")
public @ResponsePayload Element handleAssignmentListAcceptedCount() {
Element response = new Element("AssignmentListAcceptedCountResponse",namespace);
Integer total = new Integer(workflowManager.getAssignmentSize(Boolean.TRUE, null));
response.addContent(new Element("total",namespace).setText(total.toString()));
return response;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "AssignmentListAcceptedProcessRequest")
public @ResponsePayload Element handleAssignmentListAcceptedProcess(@RequestPayload Element assignmentListAcceptedProcessElement) {
final String checkWhiteListString = checkWhiteListExpression.evaluate(assignmentListAcceptedProcessElement).get(0).getValue();
final boolean checkWhiteList = (checkWhiteListString == null)?null:Boolean.parseBoolean(checkWhiteListString);
Element response = new Element("AssignmentListAcceptedProcessResponse",namespace);
Collection<WorkflowProcess> processList = workflowManager.getProcessList(null, null, null, null, null, true, checkWhiteList);
Element dataElement = new Element("data",namespace);
for (WorkflowProcess process : processList) {
int size = workflowManager.getAssignmentSize(Boolean.TRUE, process.getId());
if (size > 0) {
String label = process.getName() + " ver " + process.getVersion() + " (" + size + ")";
Element item = new Element("item",namespace);
item.addContent(new Element("processDefId",namespace).setText(process.getId()));
item.addContent(new Element("processName",namespace).setText(process.getName()));
item.addContent(new Element("processVersion",namespace).setText(process.getVersion()));
item.addContent(new Element("label",namespace).setText(label));
String url = "/json/workflow/assignment/list/accepted?processId=" + process.getEncodedId();
item.addContent(new Element("url",namespace).setText(url));
item.addContent(new Element("count",namespace).setText(new Integer(size).toString()));
dataElement.addContent(item);
}
}
response.addContent(dataElement);
return response;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "AssignmentListPendingRequest")
public @ResponsePayload Element handleAssignmentListPending(@RequestPayload Element assignmentListPendingElement) {
final String processId = processIdExpression.evaluate(assignmentListPendingElement).get(0).getValue();
final String sort = sortExpression.evaluate(assignmentListPendingElement).get(0).getValue();
final String descString = descExpression.evaluate(assignmentListPendingElement).get(0).getValue();
final boolean desc = (descString == null)?null:Boolean.parseBoolean(descString);
final String startString = startExpression.evaluate(assignmentListPendingElement).get(0).getValue();
final int start = (startString == null)?null:Integer.parseInt(startString);
final String rowsString = rowsExpression.evaluate(assignmentListPendingElement).get(0).getValue();
final int rows = (rowsString == null)?null:Integer.parseInt(rowsString);
Element response = new Element("AssignmentListPendingResponse",namespace);
PagedList<WorkflowAssignment> assignmentList = workflowManager.getAssignmentPendingList(processId, sort, desc, start, rows);
Integer total = assignmentList.getTotal();
Element data = new Element("data",namespace);
String format = AppUtil.getAppDateFormat();
for (WorkflowAssignment assignment : assignmentList) {
Element item = new Element("item",namespace);
item.addContent(new Element("processId",namespace).setText(assignment.getProcessId()));
item.addContent(new Element("activityId",namespace).setText(assignment.getActivityId()));
item.addContent(new Element("processName",namespace).setText(assignment.getProcessName()));
item.addContent(new Element("activityName",namespace).setText(assignment.getActivityName()));
item.addContent(new Element("processVersion",namespace).setText(assignment.getProcessVersion()));
item.addContent(new Element("dateCreated",namespace).setText(TimeZoneUtil.convertToTimeZone(assignment.getDateCreated(), null, format)));
item.addContent(new Element("due",namespace).setText(assignment.getDueDate() != null ? TimeZoneUtil.convertToTimeZone(assignment.getDueDate(), null, format) : "-"));
double serviceLevelMonitor = workflowManager.getServiceLevelMonitorForRunningActivity(assignment.getActivityId());
item.addContent(new Element("serviceLevelMonitor",namespace).setText( WorkflowUtil.getServiceLevelIndicator(serviceLevelMonitor)));
item.addContent(new Element("id",namespace).setText(assignment.getActivityId()));
item.addContent(new Element("label",namespace).setText(assignment.getActivityName()));
item.addContent(new Element("description",namespace).setText(assignment.getDescription()));
data.addContent(item);
}
response.addContent(data);
response.addContent(new Element("total",namespace).setText(total.toString()));
response.addContent(new Element("start",namespace).setText(startString));
response.addContent(new Element("sort",namespace).setText(sort));
response.addContent(new Element("desc",namespace).setText(descString));
return response;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "AssignmentListPendingCountRequest")
public @ResponsePayload Element handleAssignmentListPendingCount() {
Element response = new Element("AssignmentListPendingCountResponse",namespace);
Integer total = new Integer(workflowManager.getAssignmentSize(Boolean.FALSE, null));
response.addContent(new Element("total",namespace).setText(total.toString()));
return response;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "AssignmentListPendingProcessRequest")
public @ResponsePayload Element handleAssignmentListPendingProcess(@RequestPayload Element assignmentListAcceptedProcessElement) {
final String checkWhiteListString = checkWhiteListExpression.evaluate(assignmentListAcceptedProcessElement).get(0).getValue();
final boolean checkWhiteList = (checkWhiteListString == null)?null:Boolean.parseBoolean(checkWhiteListString);
Element response = new Element("AssignmentListPendingProcessResponse",namespace);
Collection<WorkflowProcess> processList = workflowManager.getProcessList(null, null, null, null, null, true, checkWhiteList);
Element dataElement = new Element("data",namespace);
for (WorkflowProcess process : processList) {
int size = workflowManager.getAssignmentSize(Boolean.FALSE, process.getId());
if (size > 0) {
String label = process.getName() + " ver " + process.getVersion() + " (" + size + ")";
Element item = new Element("item",namespace);
item.addContent(new Element("processDefId",namespace).setText(process.getId()));
item.addContent(new Element("processName",namespace).setText(process.getName()));
item.addContent(new Element("processVersion",namespace).setText(process.getVersion()));
item.addContent(new Element("label",namespace).setText(label));
String url = "/json/workflow/assignment/list/pending?processId=" + process.getEncodedId();
item.addContent(new Element("url",namespace).setText(url));
item.addContent(new Element("count",namespace).setText(new Integer(size).toString()));
dataElement.addContent(item);
}
}
response.addContent(dataElement);
return response;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "AssignmentProcessViewRequest")
public @ResponsePayload Element handleAssignmentProcessView(@RequestPayload Element assignmentProcessViewElement) {
final String processId = processIdExpression.evaluate(assignmentProcessViewElement).get(0).getValue();
Element response = new Element("AssignmentProcessViewResponse",namespace);
WorkflowAssignment assignment = workflowManager.getAssignmentByProcess(processId);
if (assignment == null) {
return response.addContent(new Element("error","Assignment not found"));
}
response.addContent(new Element("activityId",namespace).setText(assignment.getActivityId()));
response.addContent(new Element("activityDefId",namespace).setText(assignment.getActivityDefId()));
response.addContent(new Element("processId",namespace).setText(assignment.getProcessId()));
response.addContent(new Element("processDefId",namespace).setText(assignment.getProcessDefId()));
response.addContent(new Element("processVersion",namespace).setText(assignment.getProcessVersion()));
response.addContent(new Element("processName",namespace).setText(assignment.getProcessName()));
response.addContent(new Element("activityName",namespace).setText(assignment.getActivityName()));
response.addContent(new Element("description",namespace).setText(assignment.getDescription()));
response.addContent(new Element("participant",namespace).setText(assignment.getParticipant()));
response.addContent(new Element("assigneeId",namespace).setText(assignment.getAssigneeId()));
response.addContent(new Element("assigneeName",namespace).setText(assignment.getAssigneeName()));
String format = AppUtil.getAppDateFormat();
response.addContent(new Element("dateCreated",namespace).setText(TimeZoneUtil.convertToTimeZone(assignment.getDateCreated(), null, format)));
if (assignment.getDueDate() != null) {
response.addContent(new Element("dueDate",namespace).setText(TimeZoneUtil.convertToTimeZone(assignment.getDueDate(), null, format)));
}
Collection<WorkflowVariable> variableList = workflowManager.getActivityVariableList(assignment.getActivityId());
Element var = new Element("variable",namespace);
for (WorkflowVariable variable : variableList) {
var.addContent(new Element(variable.getId(),namespace).setText(variable.getVal().toString()));
}
response.addContent(var);
return response;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "AssignmentWithdrawRequest")
public @ResponsePayload Element handleAssignmentWithdraw(@RequestPayload Element assignmentWithdrawElement) {
final String activityId = activityIdExpression.evaluate(assignmentWithdrawElement).get(0).getValue();
Element response = new Element("AssignmentWithdrawResponse",namespace);
appService.getAppDefinitionForWorkflowActivity(activityId);
workflowManager.assignmentWithdraw(activityId);
WorkflowAssignment assignment = workflowManager.getAssignment(activityId);
LogUtil.info(getClass().getName(), "Assignment " + activityId + " withdrawn");
response.addContent(new Element("assignment",namespace).setText(assignment.getActivityId()));
response.addContent(new Element("status",namespace).setText("withdrawn"));
return response;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "AssignmentVariableRequest")
public @ResponsePayload Element handleAssignmentVariable(@RequestPayload Element assignmentVariableElement) {
final String activityId = activityIdExpression.evaluate(assignmentVariableElement).get(0).getValue();
final String variable = variableExpression.evaluate(assignmentVariableElement).get(0).getValue();
final String value = valueExpression.evaluate(assignmentVariableElement).get(0).getValue();
Element response = new Element("AssignmentVariableResponse",namespace);
appService.getAppDefinitionForWorkflowActivity(activityId);
workflowManager.assignmentVariable(activityId, variable, value);
LogUtil.info(getClass().getName(), "Assignment variable " + variable + " set to " + value);
response.addContent(new Element("status",namespace).setText("variableSet"));
return response;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "AssignmentViewRequest")
public @ResponsePayload Element handleAssignmentView(@RequestPayload Element assignmentViewElement) {
final String activityId = activityIdExpression.evaluate(assignmentViewElement).get(0).getValue();
Element response = new Element("AssignmentViewResponse",namespace);
WorkflowAssignment assignment = workflowManager.getAssignment(activityId);
if (assignment == null) {
response.addContent(new Element("error",namespace).setText("Assignment not found"));
}
response.addContent(new Element("activityId",namespace).setText(assignment.getActivityId()));
response.addContent(new Element("activityDefId",namespace).setText(assignment.getActivityDefId()));
response.addContent(new Element("processId",namespace).setText(assignment.getProcessId()));
response.addContent(new Element("processDefId",namespace).setText(assignment.getProcessDefId()));
response.addContent(new Element("processVersion",namespace).setText(assignment.getProcessVersion()));
response.addContent(new Element("processName",namespace).setText(assignment.getProcessName()));
response.addContent(new Element("activityName",namespace).setText(assignment.getActivityName()));
response.addContent(new Element("description",namespace).setText(assignment.getDescription()));
response.addContent(new Element("participant",namespace).setText(assignment.getParticipant()));
response.addContent(new Element("assigneeId",namespace).setText(assignment.getAssigneeId()));
response.addContent(new Element("assigneeName",namespace).setText(assignment.getAssigneeName()));
String format = AppUtil.getAppDateFormat();
response.addContent(new Element("dateCreated",namespace).setText(TimeZoneUtil.convertToTimeZone(assignment.getDateCreated(), null, format)));
if (assignment.getDueDate() != null) {
response.addContent(new Element("dueDate", namespace).setText(TimeZoneUtil.convertToTimeZone(assignment.getDueDate(), null, format)));
}
Element var = new Element("variable",namespace);
Collection<WorkflowVariable> variableList = workflowManager.getActivityVariableList(activityId);
for (WorkflowVariable variable : variableList) {
var.addContent(new Element(variable.getId(),namespace).setText(variable.getVal().toString()));
}
return response;
}
}
| [
"[email protected]"
] | |
7d746ea15ef5d3dfad92f5b62af2656e69cc5480 | b30480c73b52e97c531a9f486cc5d03201dae873 | /Tests/src/class_tests/Card.java | 82b0bc26c0ebe881e6d8ab98e1cbf190c59d6f56 | [] | no_license | lin432/High-School-work | 062e63d27d97ff3820d034230cb1a0bcc6acddf4 | a3a58bb96736430af38e46821140d1c2fbed9cd6 | refs/heads/master | 2021-01-17T21:06:21.767773 | 2016-07-10T15:08:18 | 2016-07-10T15:08:18 | 63,003,152 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 379 | java | package class_tests;
public class Card {
private int G3D;
private double price;
private String name;
public Card(int performance,double price,String title)
{
G3D = performance;
this.price = price;
name = title;
}
public int getG3D()
{return G3D;}
public double getPrice()
{return price;}
public String getTitle()
{return name;}
}
| [
"[email protected]"
] | |
fffc1ad3123731e77e3fef37e5585451005e1317 | 8af1164bac943cef64e41bae312223c3c0e38114 | /results-java/google--closure-compiler/b783533aac33c06fc34ed4c3f284aa8411ea0c54/after/InlineFunctions.java | 7972c31435ff27c4d3677437b151c98f406339d2 | [] | no_license | fracz/refactor-extractor | 3ae45c97cc63f26d5cb8b92003b12f74cc9973a9 | dd5e82bfcc376e74a99e18c2bf54c95676914272 | refs/heads/master | 2021-01-19T06:50:08.211003 | 2018-11-30T13:00:57 | 2018-11-30T13:00:57 | 87,353,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 34,779 | java | /*
* Copyright 2005 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.javascript.jscomp.FunctionInjector.CanInlineResult;
import com.google.javascript.jscomp.FunctionInjector.InliningMode;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.jscomp.NodeTraversal.Callback;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Inlines functions that are divided into two types: "direct call node
* replacement" (aka "direct") and as a block of statements (aka block).
* Function that can be inlined "directly" functions consist of a single
* return statement, everything else is must be inlined as a "block". These
* functions must meet these general requirements:
* - it is not recursive
* - the function does not contain another function -- these may be
* intentional to to limit the scope of closures.
* - function is called only once OR the size of the inline function is smaller
* than the call itself.
* - the function name is not referenced in any other manner
*
* "directly" inlined functions must meet these additional requirements:
* - consists of a single return statement
*
*/
class InlineFunctions implements SpecializationAwareCompilerPass {
// TODO(nicksantos): This needs to be completely rewritten to use scopes
// to do variable lookups. Right now, it assumes that all functions are
// uniquely named variables. There's currently a stopgap scope-check
// to ensure that this doesn't produce invalid code. But in the long run,
// this needs a major refactor.
private final Map<String, FunctionState> fns = Maps.newHashMap();
private final Map<Node, String> anonFns = Maps.newHashMap();
private final AbstractCompiler compiler;
private final FunctionInjector injector;
private final boolean blockFunctionInliningEnabled;
private final boolean inlineGlobalFunctions;
private final boolean inlineLocalFunctions;
private SpecializeModule.SpecializationState specializationState;
InlineFunctions(AbstractCompiler compiler,
Supplier<String> safeNameIdSupplier,
boolean inlineGlobalFunctions,
boolean inlineLocalFunctions,
boolean blockFunctionInliningEnabled) {
Preconditions.checkArgument(compiler != null);
Preconditions.checkArgument(safeNameIdSupplier != null);
this.compiler = compiler;
this.inlineGlobalFunctions = inlineGlobalFunctions;
this.inlineLocalFunctions = inlineLocalFunctions;
this.blockFunctionInliningEnabled = blockFunctionInliningEnabled;
this.injector = new FunctionInjector(compiler, safeNameIdSupplier, true);
}
FunctionState getOrCreateFunctionState(String fnName) {
FunctionState fs = fns.get(fnName);
if (fs == null) {
fs = new FunctionState();
fns.put(fnName, fs);
}
return fs;
}
public void enableSpecialization(SpecializeModule.SpecializationState
specializationState) {
this.specializationState = specializationState;
}
@Override
public void process(Node externs, Node root) {
Preconditions.checkState(compiler.getLifeCycleStage().isNormalized());
NodeTraversal.traverse(compiler, root, new FindCandidateFunctions());
if (fns.isEmpty()) {
return; // Nothing left to do.
}
NodeTraversal.traverse(compiler, root,
new FindCandidatesReferences(fns, anonFns));
trimCanidatesNotMeetingMinimumRequirements();
if (fns.isEmpty()) {
return; // Nothing left to do.
}
// Store the set of function names eligible for inlining and use this to
// prevent function names from being moved into temporaries during
// expression decomposition. If this movement were allowed it would prevent
// the Inline callback from finding the function calls.
//
// This pass already assumes these are constants, so this is safe for anyone
// using function inlining.
//
Set<String> fnNames = Sets.newHashSet(fns.keySet());
injector.setKnownConstants(fnNames);
trimCanidatesUsingOnCost();
if (fns.isEmpty()) {
return; // Nothing left to do.
}
resolveInlineConflicts();
decomposeExpressions(fnNames);
NodeTraversal.traverse(compiler, root,
new CallVisitor(
fns, anonFns, new Inline(injector, specializationState)));
removeInlinedFunctions();
}
/**
* Find functions that might be inlined.
*/
private class FindCandidateFunctions implements Callback {
private int callsSeen = 0;
@Override
public boolean shouldTraverse(
NodeTraversal nodeTraversal, Node n, Node parent) {
// Don't traverse into function bodies
// if we aren't inlining local functions.
return inlineLocalFunctions || nodeTraversal.inGlobalScope();
}
public void visit(NodeTraversal t, Node n, Node parent) {
if ((t.inGlobalScope() && inlineGlobalFunctions)
|| (!t.inGlobalScope() && inlineLocalFunctions)) {
findNamedFunctions(t, n, parent);
findFunctionExpressions(t, n);
}
}
public void findNamedFunctions(NodeTraversal t, Node n, Node parent) {
if (!NodeUtil.isStatement(n)) {
// There aren't any interesting functions here.
return;
}
switch (n.getType()) {
// Functions expressions in the form of:
// var fooFn = function(x) { return ... }
case Token.VAR:
Preconditions.checkState(n.hasOneChild());
Node nameNode = n.getFirstChild();
if (nameNode.getType() == Token.NAME && nameNode.hasChildren()
&& nameNode.getFirstChild().getType() == Token.FUNCTION) {
maybeAddFunction(new FunctionVar(n), t.getModule());
}
break;
// Named functions
// function Foo(x) { return ... }
case Token.FUNCTION:
Preconditions.checkState(NodeUtil.isStatementBlock(parent)
|| parent.getType() == Token.LABEL);
if (!NodeUtil.isFunctionExpression(n)) {
Function fn = new NamedFunction(n);
maybeAddFunction(fn, t.getModule());
}
break;
}
}
/**
* Find function expressions that are called directly in the form of
* (function(a,b,...){...})(a,b,...)
* or
* (function(a,b,...){...}).call(this,a,b, ...)
*/
public void findFunctionExpressions(NodeTraversal t, Node n) {
switch (n.getType()) {
// Functions expressions in the form of:
// (function(){})();
case Token.CALL:
Node fnNode = null;
if (n.getFirstChild().getType() == Token.FUNCTION) {
fnNode = n.getFirstChild();
} else if (NodeUtil.isFunctionObjectCall(n)) {
Node fnIdentifingNode = n.getFirstChild().getFirstChild();
if (fnIdentifingNode.getType() == Token.FUNCTION) {
fnNode = fnIdentifingNode;
}
}
// If a interesting function was discovered, add it.
if (fnNode != null) {
Function fn = new FunctionExpression(fnNode, callsSeen++);
maybeAddFunction(fn, t.getModule());
anonFns.put(fnNode, fn.getName());
}
break;
}
}
}
/**
* Updates the FunctionState object for the given function. Checks if the
* given function matches the criteria for an inlinable function.
*/
private void maybeAddFunction(Function fn, JSModule module) {
String name = fn.getName();
FunctionState fs = getOrCreateFunctionState(name);
// TODO(johnlenz): Maybe "smarten" FunctionState by adding this logic
// to it?
// If the function has multiple definitions, don't inline it.
if (fs.hasExistingFunctionDefinition()) {
fs.setInline(false);
} else {
// verify the function hasn't already been marked as "don't inline"
if (fs.canInline()) {
// store it for use when inlining.
fs.setFn(fn);
if (injector.isDirectCallNodeReplacementPossible(
fn.getFunctionNode())) {
fs.inlineDirectly(true);
}
// verify the function meets all the requirements.
// TODO(johnlenz): Minimum requirement checks are about 5% of the
// runtime cost of this pass.
if (!isCandidateFunction(fn)) {
// It doesn't meet the requirements.
fs.setInline(false);
}
// Set the module and gather names that need temporaries.
if (fs.canInline()) {
fs.setModule(module);
Node fnNode = fn.getFunctionNode();
Set<String> namesToAlias =
FunctionArgumentInjector.findModifiedParameters(fnNode);
if (!namesToAlias.isEmpty()) {
fs.inlineDirectly(false);
fs.setNamesToAlias(namesToAlias);
}
Node block = NodeUtil.getFunctionBody(fnNode);
if (NodeUtil.referencesThis(block)) {
fs.setReferencesThis(true);
}
if (NodeUtil.containsFunction(block)) {
fs.setHasInnerFunctions(true);
// If there are inner functions, we can inline into global scope
// if there are no local vars or named functions.
// TODO(johnlenz): this can be improved by looking at the possible
// values for locals. If there are simple values, or constants
// we could still inline.
if (hasLocalNames(fnNode)) {
fs.setInline(false);
}
}
}
// Check if block inlining is allowed.
if (fs.canInline() && !fs.canInlineDirectly()) {
if (!blockFunctionInliningEnabled) {
fs.setInline(false);
}
}
}
}
}
/**
* @param fnNode The function to inspect.
* @return Whether the function has parameters, var, or function declarations.
*/
private boolean hasLocalNames(Node fnNode) {
Node block = NodeUtil.getFunctionBody(fnNode);
return NodeUtil.getFunctionParameters(fnNode).hasChildren()
|| NodeUtil.has(
block,
new NodeUtil.MatchDeclaration(),
new NodeUtil.MatchShallowStatement());
}
/**
* Returns the function the traversal is currently traversing, or null
* if in the global scope.
*/
private static Node getContainingFunction(NodeTraversal t) {
return (t.inGlobalScope()) ? null : t.getScopeRoot();
}
/**
* Checks if the given function matches the criteria for an inlinable
* function.
*/
private boolean isCandidateFunction(Function fn) {
// Don't inline exported functions.
String fnName = fn.getName();
if (compiler.getCodingConvention().isExported(fnName)) {
// TODO(johnlenz): Should we allow internal references to be inlined?
// An exported name can be replaced externally, any inlined instance
// would not reflect this change.
// To allow inlining we need to be able to distinguish between exports
// that are used in a read-only fashion and those that can be replaced
// by external definitions.
return false;
}
// Don't inline this special function
if (RenameProperties.RENAME_PROPERTY_FUNCTION_NAME.equals(fnName)) {
return false;
}
// Don't inline if we are specializing and the function can't be fixed up
if (specializationState != null &&
!specializationState.canFixupFunction(fn.getFunctionNode())) {
return false;
}
Node fnNode = fn.getFunctionNode();
return injector.doesFunctionMeetMinimumRequirements(fnName, fnNode);
}
/**
* @see CallVisitor
*/
private interface CallVisitorCallback {
public void visitCallSite(
NodeTraversal t, Node callNode, Node parent, FunctionState fs);
}
/**
* Visit call sites for functions in functionMap.
*/
private static class CallVisitor extends AbstractPostOrderCallback {
protected CallVisitorCallback callback;
private Map<String, FunctionState> functionMap;
private Map<Node, String> anonFunctionMap;
CallVisitor(Map<String, FunctionState> fns,
Map<Node, String> anonFns,
CallVisitorCallback callback) {
this.functionMap = fns;
this.anonFunctionMap = anonFns;
this.callback = callback;
}
public void visit(NodeTraversal t, Node n, Node parent) {
switch (n.getType()) {
// Function calls
case Token.CALL:
Node child = n.getFirstChild();
String name = null;
// NOTE: The normalization pass insures that local names do not
// collide with global names.
if (child.getType() == Token.NAME) {
name = child.getString();
} else if (child.getType() == Token.FUNCTION) {
name = anonFunctionMap.get(child);
} else if (NodeUtil.isFunctionObjectCall(n)) {
Preconditions.checkState(NodeUtil.isGet(child));
Node fnIdentifingNode = child.getFirstChild();
if (fnIdentifingNode.getType() == Token.NAME) {
name = fnIdentifingNode.getString();
} else if (fnIdentifingNode.getType() == Token.FUNCTION) {
name = anonFunctionMap.get(fnIdentifingNode);
}
}
if (name != null) {
FunctionState fs = functionMap.get(name);
// Only visit call-sites for functions that can be inlined.
if (fs != null) {
callback.visitCallSite(t, n, parent, fs);
}
}
break;
}
}
}
/**
* @return Whether the name is used in a way that might be a candidate
* for inlining.
*/
static boolean isCandidateUsage(Node name) {
Node parent = name.getParent();
Preconditions.checkState(name.getType() == Token.NAME);
if (parent.getType() == Token.VAR || parent.getType() == Token.FUNCTION) {
// This is a declaration. Duplicate declarations are handle during
// function candidate gathering.
return true;
}
if (parent.getType() == Token.CALL && parent.getFirstChild() == name) {
// This is a normal reference to the function.
return true;
}
// Check for a ".call" to the named function:
// CALL
// GETPROP/GETELEM
// NAME
// STRING == "call"
// This-Value
// Function-parameter-1
// ...
if (NodeUtil.isGet(parent)
&& name == parent.getFirstChild()
&& name.getNext().getType() == Token.STRING
&& name.getNext().getString().equals("call")) {
Node gramps = name.getAncestor(2);
if (gramps.getType() == Token.CALL
&& gramps.getFirstChild() == parent) {
// Yep, a ".call".
return true;
}
}
return false;
}
/**
* Find references to functions that are inlinable.
*/
private class FindCandidatesReferences
extends CallVisitor
implements CallVisitorCallback {
FindCandidatesReferences(
Map<String, FunctionState> fns,
Map<Node, String> anonFns) {
super(fns, anonFns, null);
this.callback = this;
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
super.visit(t, n, parent);
if (n.getType() == Token.NAME) {
checkNameUsage(t, n, parent);
}
}
public void visitCallSite(
NodeTraversal t, Node callNode, Node parent, FunctionState fs) {
maybeAddReference(t, fs, callNode, t.getModule());
}
void maybeAddReference(NodeTraversal t, FunctionState fs,
Node callNode, JSModule module) {
if (!fs.canInline()) {
return;
}
boolean referenceAdded = false;
InliningMode mode = fs.canInlineDirectly()
? InliningMode.DIRECT : InliningMode.BLOCK;
referenceAdded = maybeAddReferenceUsingMode(
t, fs, callNode, module, mode);
if (!referenceAdded &&
mode == InliningMode.DIRECT && blockFunctionInliningEnabled) {
// This reference can not be directly inlined, see if
// block replacement inlining is possible.
mode = InliningMode.BLOCK;
referenceAdded = maybeAddReferenceUsingMode(
t, fs, callNode, module, mode);
}
if (!referenceAdded) {
// Don't try to remove a function if we can't inline all
// the references.
fs.setRemove(false);
}
}
private boolean maybeAddReferenceUsingMode(
NodeTraversal t, FunctionState fs, Node callNode,
JSModule module, InliningMode mode) {
if (specializationState != null) {
// If we're specializing, make sure we can fixup
// the containing function before inlining
Node containingFunction = getContainingFunction(t);
if (containingFunction != null && !specializationState.canFixupFunction(
containingFunction)) {
return false;
}
}
CanInlineResult result = injector.canInlineReferenceToFunction(
t, callNode, fs.getFn().getFunctionNode(),
fs.getNamesToAlias(), mode, fs.getReferencesThis(),
fs.hasInnerFunctions());
if (result != CanInlineResult.NO) {
// Yeah!
boolean decompose =
(result == CanInlineResult.AFTER_DECOMPOSITION);
fs.addReference(new Reference(callNode, module, mode, decompose));
return true;
}
return false;
}
/**
* Find functions that can be inlined.
*/
private void checkNameUsage(NodeTraversal t, Node n, Node parent) {
Preconditions.checkState(n.getType() == Token.NAME);
if (isCandidateUsage(n)) {
return;
}
// Other refs to a function name remove its candidacy for inlining
String name = n.getString();
FunctionState fs = fns.get(name);
if (fs == null) {
return;
}
// Unlike normal call/new parameters, references passed to
// JSCompiler_ObjectPropertyString are not aliases of a value, but
// a reference to the name itself, as such the value of the name is
// unknown and can not be inlined.
if (parent.getType() == Token.NEW) {
Node target = parent.getFirstChild();
if (target.getType() == Token.NAME && target.getString().equals(
ObjectPropertyStringPreprocess.EXTERN_OBJECT_PROPERTY_STRING)) {
// This method is going to be replaced so don't inline it anywhere.
fs.setInline(false);
}
}
// If the name is being assigned to it can not be inlined.
if (parent.getType() == Token.ASSIGN && parent.getFirstChild() == n) {
// e.g. bar = something; <== we can't inline "bar"
// so mark the function as uninlinable.
// TODO(johnlenz): Should we just remove it from fns here?
fs.setInline(false);
} else {
// e.g. var fn = bar; <== we can't inline "bar"
// As this reference can't be inlined mark the function as
// unremovable.
fs.setRemove(false);
}
}
}
/**
* Inline functions at the call sites.
*/
private static class Inline implements CallVisitorCallback {
private final FunctionInjector injector;
private final SpecializeModule.SpecializationState specializationState;
Inline(FunctionInjector injector,
SpecializeModule.SpecializationState specializationState) {
this.injector = injector;
this.specializationState = specializationState;
}
public void visitCallSite(
NodeTraversal t, Node callNode, Node parent, FunctionState fs) {
Preconditions.checkState(fs.hasExistingFunctionDefinition());
if (fs.canInline()) {
Reference ref = fs.getReference(callNode);
// There are two cases ref can be null: if the call site was introduce
// because it was part of a function that was inlined during this pass
// or if the call site was trimmed from the list of references because
// the function couldn't be inlined at this location.
if (ref != null) {
if (specializationState != null) {
Node containingFunction = getContainingFunction(t);
if (containingFunction != null) {
// Report that the function was specialized so that
// {@link SpecializeModule} can fix it up.
specializationState.reportSpecializedFunction(containingFunction);
}
}
inlineFunction(t, callNode, fs, ref.mode);
// Keep track of references that have been inlined so that
// we can verify that none have been missed.
ref.inlined = true;
}
}
}
/**
* Inline a function into the call site.
*/
private void inlineFunction(
NodeTraversal t, Node callNode, FunctionState fs, InliningMode mode) {
Function fn = fs.getFn();
String fnName = fn.getName();
Node fnNode = fs.getSafeFnNode();
Node newCode = injector.inline(t, callNode, fnName, fnNode, mode);
t.getCompiler().reportCodeChange();
t.getCompiler().addToDebugLog("Inlined function: " + fn.getName());
}
}
/**
* Remove entries that aren't a valid inline candidates, from the list of
* encountered names.
*/
private void trimCanidatesNotMeetingMinimumRequirements() {
Iterator<Entry<String, FunctionState>> i;
for (i = fns.entrySet().iterator(); i.hasNext();) {
FunctionState fs = i.next().getValue();
if (!fs.hasExistingFunctionDefinition() || !fs.canInline()) {
i.remove();
}
}
}
/**
* Remove entries from the list of candidates that can't be inlined.
*/
void trimCanidatesUsingOnCost() {
Iterator<Entry<String, FunctionState>> i;
for (i = fns.entrySet().iterator(); i.hasNext();) {
FunctionState fs = i.next().getValue();
if (fs.hasReferences()) {
// Only inline function if it decreases the code size.
boolean lowersCost = mimimizeCost(fs);
if (!lowersCost) {
// It shouldn't be inlined; remove it from the list.
i.remove();
}
} else if (!fs.canRemove()) {
// Don't bother tracking functions without references that can't be
// removed.
i.remove();
}
}
}
/**
* Determines if the function is worth inlining and potentially
* trims references that increase the cost.
* @return Whether inlining the references lowers the overall cost.
*/
private boolean mimimizeCost(FunctionState fs) {
if (!inliningLowersCost(fs)) {
// Try again without Block inlining references
if (fs.hasBlockInliningReferences()) {
fs.setRemove(false);
fs.removeBlockInliningReferences();
if (!fs.hasReferences() || !inliningLowersCost(fs)) {
return false;
}
} else {
return false;
}
}
return true;
}
/**
* @return Whether inlining the function reduces code size.
*/
private boolean inliningLowersCost(FunctionState fs) {
return injector.inliningLowersCost(
fs.getModule(),
fs.getFn().getFunctionNode(),
fs.getReferences(),
fs.getNamesToAlias(),
fs.canRemove(),
fs.getReferencesThis());
}
/**
* Size base inlining calculations are thrown off when a function that is
* being inlined also contains calls to functions that are slated for
* inlining.
*
* Specifically, a clone of the FUNCTION node tree is used when the function
* is inlined. Calls in this new tree are not included in the list of function
* references so they won't be inlined (which is what we want). Here we mark
* those functions as non-removable (as they will have new references in the
* cloned node trees).
*
* This prevents a function that would only be inlined because it is
* referenced once from being inlined into multiple call sites because
* the calling function has been inlined in multiple locations or the
* function being removed while there are still references.
*/
private void resolveInlineConflicts() {
for (FunctionState fs : fns.values()) {
resolveInlineConflictsForFunction(fs);
}
}
/**
* @see #resolveInlineConflicts
*/
private void resolveInlineConflictsForFunction(FunctionState fs) {
// Functions that aren't referenced don't cause conflicts.
if (!fs.hasReferences()) {
return;
}
Node fnNode = fs.getFn().getFunctionNode();
Set<String> names = findCalledFunctions(fnNode);
if (!names.isEmpty()) {
// Prevent the removal of the referenced functions.
for (String name : names) {
FunctionState fsCalled = fns.get(name);
if (fsCalled != null && fsCalled.canRemove()) {
fsCalled.setRemove(false);
// For functions that can no longer be removed, check if they should
// still be inlined.
if (!mimimizeCost(fsCalled)) {
// It can't be inlined remove it from the list.
fsCalled.setInline(false);
}
}
}
// Make a copy of the Node, so it isn't changed by other inlines.
fs.setSafeFnNode(fs.getFn().getFunctionNode().cloneTree());
}
}
/**
* This functions that may be called directly.
*/
private Set<String> findCalledFunctions(Node node) {
Set<String> changed = Sets.newHashSet();
findCalledFunctions(NodeUtil.getFunctionBody(node), changed);
return changed;
}
/**
* @see #findCalledFunctions(Node)
*/
private void findCalledFunctions(
Node node, Set<String> changed) {
Preconditions.checkArgument(changed != null);
// For each referenced function, add a new reference
if (node.getType() == Token.NAME) {
if (isCandidateUsage(node)) {
changed.add(node.getString());
}
}
for (Node c = node.getFirstChild(); c != null; c = c.getNext()) {
findCalledFunctions(c, changed);
}
}
/**
* For any call-site that needs it, prepare the call-site for inlining
* by rewriting the containing expression.
*/
private void decomposeExpressions(Set<String> fnNames) {
ExpressionDecomposer decomposer = new ExpressionDecomposer(
compiler, compiler.getUniqueNameIdSupplier(), fnNames);
for (FunctionState fs : fns.values()) {
if (fs.canInline()) {
for (Reference ref : fs.getReferences()) {
if (ref.requiresDecomposition) {
decomposer.maybeDecomposeExpression(ref.callNode);
}
}
}
}
}
/**
* Removed inlined functions that no longer have any references.
*/
void removeInlinedFunctions() {
for (FunctionState fs : fns.values()) {
if (fs.canRemove()) {
Function fn = fs.getFn();
Preconditions.checkState(fs.canInline());
Preconditions.checkState(fn != null);
verifyAllReferencesInlined(fs);
if (specializationState != null) {
specializationState.reportRemovedFunction(
fn.getFunctionNode(), fn.getDeclaringBlock());
}
fn.remove();
compiler.reportCodeChange();
}
}
}
/**
* Sanity check to verify, that expression rewriting didn't
* make a call inaccessible.
*/
void verifyAllReferencesInlined(FunctionState fs) {
for (Reference ref : fs.getReferences()) {
if (!ref.inlined) {
throw new IllegalStateException("Call site missed.\n call: "
+ ref.callNode.toStringTree() + "\n parent: "
+ ref.callNode.getParent().toStringTree());
}
}
}
/**
* Use to track the decisions that have been make about a function.
*/
private static class FunctionState {
private Function fn = null;
private Node safeFnNode = null;
private boolean inline = true;
private boolean remove = true;
private boolean inlineDirectly = false;
private boolean referencesThis = false;
private boolean hasInnerFunctions = false;
private Map<Node, Reference> references = null;
private JSModule module = null;
private Set<String> namesToAlias = null;
boolean hasExistingFunctionDefinition() {
return (fn != null);
}
public void setReferencesThis(boolean referencesThis) {
this.referencesThis = referencesThis;
}
public boolean getReferencesThis() {
return this.referencesThis;
}
public void setHasInnerFunctions(boolean hasInnerFunctions) {
this.hasInnerFunctions = hasInnerFunctions;
}
public boolean hasInnerFunctions() {
return hasInnerFunctions;
}
void removeBlockInliningReferences() {
Iterator<Entry<Node, Reference>> i;
for (i = getReferencesInternal().entrySet().iterator(); i.hasNext();) {
Entry<Node, Reference> entry = i.next();
if (entry.getValue().mode == InliningMode.BLOCK) {
i.remove();
}
}
}
public boolean hasBlockInliningReferences() {
for (Reference r : getReferencesInternal().values()) {
if (r.mode == InliningMode.BLOCK) {
return true;
}
}
return false;
}
public Function getFn() {
return fn;
}
public void setFn(Function fn) {
Preconditions.checkState(this.fn == null);
this.fn = fn;
}
public Node getSafeFnNode() {
return (safeFnNode != null) ? safeFnNode : fn.getFunctionNode();
}
public void setSafeFnNode(Node safeFnNode) {
this.safeFnNode = safeFnNode;
}
public boolean canInline() {
return inline;
}
public void setInline(boolean inline) {
this.inline = inline;
if (inline == false) {
// No need to keep references to function that can't be inlined.
references = null;
// Don't remove functions that we aren't inlining.
remove = false;
}
}
public boolean canRemove() {
return remove;
}
public void setRemove(boolean remove) {
this.remove = remove;
}
public boolean canInlineDirectly() {
return inlineDirectly;
}
public void inlineDirectly(boolean directReplacement) {
this.inlineDirectly = directReplacement;
}
public boolean hasReferences() {
return (references != null && !references.isEmpty());
}
private Map<Node, Reference> getReferencesInternal() {
if (references == null) {
return Collections.emptyMap();
}
return references;
}
public void addReference(Reference ref) {
if (references == null) {
references = Maps.newHashMap();
}
references.put(ref.callNode, ref);
}
public Collection<Reference> getReferences() {
return getReferencesInternal().values();
}
public Reference getReference(Node n) {
return getReferencesInternal().get(n);
}
public Set<String> getNamesToAlias() {
if (namesToAlias == null) {
return Collections.emptySet();
}
return Collections.unmodifiableSet(namesToAlias);
}
public void setNamesToAlias(Set<String> names) {
namesToAlias = names;
}
public void setModule(JSModule module) {
this.module = module;
}
public JSModule getModule() {
return module;
}
}
/**
* Interface for dealing with function declarations and function
* expressions equally
*/
private static interface Function {
/** Gets the name of the function */
public String getName();
/** Gets the function node */
public Node getFunctionNode();
/** Removes itself from the javascript */
public void remove();
public Node getDeclaringBlock();
}
/** NamedFunction implementation of the Function interface */
private static class NamedFunction implements Function {
private final Node fn;
public NamedFunction(Node fn) {
this.fn = fn;
}
public String getName() {
return fn.getFirstChild().getString();
}
public Node getFunctionNode() {
return fn;
}
public void remove() {
NodeUtil.removeChild(fn.getParent(), fn);
}
@Override
public Node getDeclaringBlock() {
return fn.getParent();
}
}
/** FunctionVar implementation of the Function interface */
private static class FunctionVar implements Function {
private final Node var;
public FunctionVar(Node var) {
this.var = var;
}
public String getName() {
return var.getFirstChild().getString();
}
public Node getFunctionNode() {
return var.getFirstChild().getFirstChild();
}
public void remove() {
NodeUtil.removeChild(var.getParent(), var);
}
@Override
public Node getDeclaringBlock() {
return var.getParent();
}
}
/** FunctionExpression implementation of the Function interface */
private static class FunctionExpression implements Function {
private final Node fn;
private final String fakeName;
public FunctionExpression(Node fn, int index) {
this.fn = fn;
// A number is not a valid function javascript indentifier
// so we don't need to worry about collisions.
this.fakeName = String.valueOf(index);
}
public String getName() {
return fakeName;
}
public Node getFunctionNode() {
return fn;
}
public void remove() {
// Nothing to do. The function is removed with the call.
}
@Override
public Node getDeclaringBlock() {
return null;
}
}
class Reference extends FunctionInjector.Reference {
final boolean requiresDecomposition;
boolean inlined = false;
Reference(
Node callNode, JSModule module, InliningMode mode, boolean decompose) {
super(callNode, module, mode);
this.requiresDecomposition = decompose;
}
}
} | [
"[email protected]"
] | |
d741a9f4ac4a9966fddbd3c71a3448afdd57d3f1 | bc6881aaddd9cf265f56cc95350ddf14322b246a | /hapi-fhir-client-okhttp/src/main/java/ca/uhn/fhir/okhttp/client/OkHttpRestfulClientFactory.java | a036aa748dfb759f6e69c13128ecdf49561b82a1 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | circa138/hapi-fhir | 7fd648d1016f4173cc47a7ecb3906458b6be1440 | af32c4b7e9c27b0a48a2fb42047b8d0d2007b720 | refs/heads/master | 2021-01-11T21:19:51.885486 | 2017-01-12T13:59:51 | 2017-01-12T13:59:51 | 78,763,334 | 1 | 0 | null | 2017-01-12T16:16:40 | 2017-01-12T16:16:40 | null | UTF-8 | Java | false | false | 3,048 | java | package ca.uhn.fhir.okhttp.client;
/*
* #%L
* HAPI FHIR OkHttp Client
* %%
* Copyright (C) 2014 - 2016 University Health Network
* %%
* 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.
* #L%
*/
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.rest.api.RequestTypeEnum;
import ca.uhn.fhir.rest.client.RestfulClientFactory;
import ca.uhn.fhir.rest.client.api.Header;
import ca.uhn.fhir.rest.client.api.IHttpClient;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.List;
import java.util.Map;
/**
* A Restful client factory based on OkHttp.
*
* @author Matthew Clarke | [email protected] | Orion Health
*/
public class OkHttpRestfulClientFactory extends RestfulClientFactory {
private Call.Factory myNativeClient;
public OkHttpRestfulClientFactory() {
super();
}
public OkHttpRestfulClientFactory(FhirContext theFhirContext) {
super(theFhirContext);
}
@Override
protected IHttpClient getHttpClient(String theServerBase) {
return new OkHttpRestfulClient(getNativeClient(), new StringBuilder(theServerBase), null, null, null, null);
}
@Override
protected void resetHttpClient() {
myNativeClient = null;
}
public synchronized Call.Factory getNativeClient() {
if (myNativeClient == null) {
myNativeClient = new OkHttpClient();
}
return myNativeClient;
}
@Override
public IHttpClient getHttpClient(StringBuilder theUrl,
Map<String, List<String>> theIfNoneExistParams,
String theIfNoneExistString,
RequestTypeEnum theRequestType,
List<Header> theHeaders) {
return new OkHttpRestfulClient(getNativeClient(), theUrl, theIfNoneExistParams, theIfNoneExistString, theRequestType, theHeaders);
}
/**
* Only accepts clients of type {@link OkHttpClient}
*
* @param okHttpClient
*/
@Override
public void setHttpClient(Object okHttpClient) {
myNativeClient = (Call.Factory) okHttpClient;
}
@Override
public void setProxy(String theHost, Integer thePort) {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(theHost, thePort));
OkHttpClient.Builder builder = ((OkHttpClient)getNativeClient()).newBuilder().proxy(proxy);
setHttpClient(builder.build());
}
}
| [
"[email protected]"
] | |
cf6e651a4e6b81646f35178433b2316221faff72 | 19f420ee0efe7f77944eaa31a86b6627dd33d557 | /MyApplication2/app/src/main/java/com/example/myapplication/present/DoiMatKhauGVFragment.java | aa18046881282574021627e1c4f4bd424fb2b36e | [] | no_license | HaseNguyen/GDU-Management-App | c1cf3b4a87ff84d81904f8c79daadd70fdb2a574 | bad5f51bb86162ba9e1520125cf042eb2cdd958f | refs/heads/master | 2022-12-13T16:43:37.918256 | 2020-09-25T13:43:50 | 2020-09-25T13:43:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,938 | java | package com.example.myapplication.present;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.myapplication.R;
import com.example.myapplication.model.DoiMatKhauGVViewModel;
import com.example.myapplication.model.SERVER;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class DoiMatKhauGVFragment extends Fragment {
String email,mkcu, mkmoi,mknmoi;
private DoiMatKhauGVViewModel doiMatKhauGVViewModel;
private EditText txtMKcu,txtMKmoi,txtNMKmoi;
private Button btnXacNhanGV;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate( R.layout.fragment_doimkgv, container, false);
txtMKcu = view.findViewById( R.id.txtMKcugv );
txtMKmoi = view.findViewById( R.id.txtMKmoigv );
txtNMKmoi = view.findViewById( R.id.txtNMKmoigv );
btnXacNhanGV = view.findViewById( R.id.btnxacnhangv );
//Lay du lieu
Bundle bundle = getArguments();
email = bundle.getString( "Email" );
mkcu = bundle.getString( "Password" );
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated( view, savedInstanceState );
btnXacNhanGV.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View view) {
String matkhaucu = txtMKcu.getText().toString();
String matkhaumoi = txtMKmoi.getText().toString();
Log.e( "GT: ", matkhaumoi );
String matkhaunhaplaimoi = txtNMKmoi.getText().toString();
try {
Connection con = SERVER.Connect();
if (con == null) {
} else {
String query = "Update GiangVien set Password = '" + matkhaunhaplaimoi + "' where Email ='" +
email + "' and '" + matkhaumoi + "' = '" + matkhaunhaplaimoi + "' " +
"and '" + matkhaucu + "' = '" + mkcu + "'";
Log.e( "onClick: ", matkhaunhaplaimoi );
PreparedStatement preStmt = con.prepareStatement( query );
preStmt.executeUpdate();
Toast.makeText( getActivity(), "Password Đổi Thành Công!", Toast.LENGTH_SHORT ).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
} );
}
} | [
"[email protected]"
] | |
db080d10abb5a1a80414164d962787effed6551f | f62e39c558e26e768e3cb4666fd890f7f6eaa562 | /src/main/java/com/example/thymeLeaf20200208/service/UserService.java | 706b96fd061500b0c333a1856df49b05ed90e30c | [] | no_license | Mrumian89/thymeLeaf20200208 | c5fa54fc91481d8efccf6a86ef8ac2a187025114 | 0baeb5f2777afbc77eb54d12854112b5925cf445 | refs/heads/master | 2021-01-01T03:00:44.094141 | 2020-02-09T16:01:30 | 2020-02-09T16:01:30 | 239,153,101 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,887 | java | /*
package com.example.thymeLeaf20200208.service;
import com.example.thymeLeaf20200208.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@Component
public class UserService {
private Map<Integer, User> userMap = new HashMap<>();
public User createUser(String name, String nazwisko, int wiek){
int id = new Random().nextInt();
User user = new User(id, name, nazwisko, wiek);
userMap.put(id, user);
return user;
}
public void deleteUser(int id){
userMap.remove(id);
}
public Collection<User> listUsers(){
return userMap.values();
}
public User getUser(int id) {
return userMap.get(id);
}
@Controller
public static class NewTestController {
public class NotFoundException extends RuntimeException {
}
public class NumberFormatException extends RuntimeException {
}
@Autowired
UserService userService;
@GetMapping("/listPacjents")
public String listPacjents(Model model) {
List<User> users = new ArrayList<>();
users.add(new User(1, "Anna", "Kowalska", 22));
users.add(new User(2, "Anna", "Kowalska", 32));
users.add(new User(3, "Anna", "Kowalska", 45));
users.add(new User(4, "Anna", "Kowalska", 10));
users.add(new User(5, "Anna", "Kowalska", 29));
model.addAttribute("Pacjents", userService.listUsers());
return "list-Pacjents-view";
}
@GetMapping("/addPacjent")
public String addUser(Model model) {
model.addAttribute("Pacjent", new User());
return "addPacjent";
}
@GetMapping("/getPacjent/{id}")
public String getUser(@PathVariable String id, Model model) {
int i = Integer.parseInt(id);
User user = userService.getUser(i);
if (user == null) {
throw new TestController.NotFoundException();
}
model.addAttribute("user", user);
return "pacjent-details";
}
@PostMapping("/addPacjent")
public String createUser(@ModelAttribute User user, BindingResult bindingResult, Model model) {
validate(user, bindingResult);
if (bindingResult.hasErrors()) {
model.addAttribute("user", user);
return "redirect:/addPacjent";
}
userService.createUser(user.getName(), user.getNazwisko(), user.getWiek());
return "redirect:/listPacjents";
}
@ExceptionHandler(TestController.NotFoundException.class)
public String notFound() {
return "exception404";
}
public void validate(User user, BindingResult bindingResult) {
if (listPacjents().getName() == null || user.getName().isEmpty()) {
bindingResult.addError(new ObjectError("pacjent", "Musisz podać imię"));
}
if (user.getNazwisko() == null || user.getNazwisko().isEmpty()) {
bindingResult.addError(new ObjectError("lekarz", "Musisz podać nazwisko"));
}
if (user.getWiek() < 0) {
bindingResult.addError(new ObjectError("termin", "Wiek nie może być ujemny"));
}
}
}
}
*/
| [
"[email protected]"
] | |
db03fbda0435cf4902deac0d4366a9a47ff75ea1 | c7a811acae842627d5483dced7282e6ce4a2d8b9 | /Seminar12/src/ro/ase/cts/seminar12/observer/BankAccount.java | 77faeafabc86ea727adcde0f3e1f4de0b642da6e | [] | no_license | wannawdo/cts_lab | d5accfd8900d04e850880f4636e7d0ba45eb7afa | ae8656293288b8ddc199f7fb8e8300f2702b2aba | refs/heads/main | 2023-05-13T17:00:56.510797 | 2021-06-03T06:28:51 | 2021-06-03T06:28:51 | 342,136,885 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 883 | java | package ro.ase.cts.seminar12.observer;
import java.util.ArrayList;
public abstract class BankAccount extends Account {
// entitate Observabil
// colectie de observatori
protected ArrayList<NotificationInterface> observers;
protected double balance;
protected String iban;
public BankAccount() {
this.observers = new ArrayList<NotificationInterface>();
this.balance = 0;
this.iban = "N/A";
}
public BankAccount(double b, String i) {
this.observers = new ArrayList<NotificationInterface>();
this.balance = b;
this.iban = i;
}
public double getBalance() {
return this.balance;
}
public void setBalance(double newBalance) {
this.balance = newBalance;
}
public void addObserver(NotificationInterface observer) {
this.observers.add(observer);
}
public void removeObserver(NotificationInterface observer) {
this.observers.remove(observer);
}
}
| [
"[email protected]"
] | |
31601d126107d08660b0ff877a49750c0a636d02 | 5652e2d0f050b9b2b9caa95eb856e7fc81f9234d | /src/BodyMassIndex.java | 818967b1ba5d1e88b39aecbb2bf4a9bca01305a1 | [] | no_license | Nikolai-vyalkov/body-Mass-Index | 9eba3eb8a216316b9a96a19e980f5795c73276dc | df217491b42c438bbb03f12e509b3c30405e1a7d | refs/heads/master | 2022-11-25T05:27:09.991224 | 2020-07-30T19:03:55 | 2020-07-30T19:03:55 | 283,855,892 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 163 | java | public class BodyMassIndex {
public double calculate(double weight,double height){
double IMT = weight/(height*height);
return IMT;
}
}
| [
"[email protected]"
] | |
6f79657ec93d165cac0a6e594f5ff2e8dc088782 | bf2966abae57885c29e70852243a22abc8ba8eb0 | /aws-java-sdk-mediaconnect/src/main/java/com/amazonaws/services/mediaconnect/model/transform/RevokeFlowEntitlementRequestProtocolMarshaller.java | 95a176070ee537423e5237d9cef306a2b1a054c3 | [
"Apache-2.0"
] | permissive | kmbotts/aws-sdk-java | ae20b3244131d52b9687eb026b9c620da8b49935 | 388f6427e00fb1c2f211abda5bad3a75d29eef62 | refs/heads/master | 2021-12-23T14:39:26.369661 | 2021-07-26T20:09:07 | 2021-07-26T20:09:07 | 246,296,939 | 0 | 0 | Apache-2.0 | 2020-03-10T12:37:34 | 2020-03-10T12:37:33 | null | UTF-8 | Java | false | false | 2,782 | java | /*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.mediaconnect.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.mediaconnect.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* RevokeFlowEntitlementRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class RevokeFlowEntitlementRequestProtocolMarshaller implements Marshaller<Request<RevokeFlowEntitlementRequest>, RevokeFlowEntitlementRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON)
.requestUri("/v1/flows/{flowArn}/entitlements/{entitlementArn}").httpMethodName(HttpMethodName.DELETE).hasExplicitPayloadMember(false)
.hasPayloadMembers(false).serviceName("AWSMediaConnect").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public RevokeFlowEntitlementRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<RevokeFlowEntitlementRequest> marshall(RevokeFlowEntitlementRequest revokeFlowEntitlementRequest) {
if (revokeFlowEntitlementRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<RevokeFlowEntitlementRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
revokeFlowEntitlementRequest);
protocolMarshaller.startMarshalling();
RevokeFlowEntitlementRequestMarshaller.getInstance().marshall(revokeFlowEntitlementRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| [
""
] | |
2259b5a66c7883661331bcee9935d797154a52d5 | e6ee845cfcc072cc178e1e3f29c2218dda421ac7 | /Comp_Facebook/reverse_linked_list/Solution.java | abf265b88b62482c37b8844fb67318f9128c971b | [] | no_license | river06/leetcode2 | 184643124944bcd35d6ba6bbab1199eeee043136 | ad6d69ae3968b049f1b17f1b465533a24183e885 | refs/heads/master | 2021-01-21T02:11:13.199135 | 2018-02-02T05:21:40 | 2018-02-02T05:21:40 | 30,609,007 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 248 | java | class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
| [
"[email protected]"
] | |
83879c32225ac09781d631488ade80a85bcdc841 | a207945f5350d89cb15b412fcddaf08b1ad2b208 | /src/main/java/com/hacker/framework/pipeline/Dataview.java | 7d571d497e66e68662dffb69c31e432d89041aa1 | [] | no_license | HackerFight/xdatafront-framework-parent | 1dbee5769fdc70f487b8c354fe22b901088085d3 | 0c8d7bf65dbf1937fbc88329c88313b0573da8a4 | refs/heads/master | 2020-05-02T06:35:52.957647 | 2019-05-11T07:09:29 | 2019-05-11T07:09:29 | 177,799,169 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,505 | java | package com.hacker.framework.pipeline;
import java.util.List;
/**
* Created by hacker on 2019/3/30 0030.
*/
public class Dataview {
/**
* 试图编码
*/
private String dataviewCode;
/**
* 请求组建的集合,比如缓存读
*/
private List<String> requestComList;
/**
* 响应组件的集合,比如缓存写
*/
private List<String> responseComList;
/**
* 连接渠道的组件标识
*/
private String channelDispatchCom;
private boolean available;
public String getDataviewCode() {
return dataviewCode;
}
public void setDataviewCode(String dataviewCode) {
this.dataviewCode = dataviewCode;
}
public List<String> getRequestComList() {
return requestComList;
}
public void setRequestComList(List<String> requestComList) {
this.requestComList = requestComList;
}
public List<String> getResponseComList() {
return responseComList;
}
public void setResponseComList(List<String> responseComList) {
this.responseComList = responseComList;
}
public String getChannelDispatchCom() {
return channelDispatchCom;
}
public void setChannelDispatchCom(String channelDispatchCom) {
this.channelDispatchCom = channelDispatchCom;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
}
| [
"[email protected]"
] | |
3ac7d1e99157cebb24eccc488528cdd7d5cb7908 | 74bb9c6488cc14ec1b94eb4dacc9982a0ea864ef | /app/src/main/java/com/example/WAStickerApp/StickerPackInfoActivity.java | 6a0ab1fe0325f2e184289b27c214d614be73d612 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | fokkahontas/custom-sticker-app | 0594cbd87f96c96aa20f31cc730e5df8954bbbb4 | 818e2149a14942559917d809d7c5115d481217ed | refs/heads/master | 2020-04-08T13:43:35.261836 | 2018-11-27T22:29:14 | 2018-11-27T22:29:14 | 159,403,850 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,826 | java | /*
* Copyright (c) WhatsApp Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.example.WAStickerApp;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class StickerPackInfoActivity extends BaseActivity {
private static final String TAG = "StickerPackInfoActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sticker_pack_info);
final String trayIconUriString = getIntent().getStringExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_TRAY_ICON);
final String website = getIntent().getStringExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_WEBSITE);
final String email = getIntent().getStringExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_EMAIL);
final String privacyPolicy = getIntent().getStringExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_PRIVACY_POLICY);
final TextView trayIcon = findViewById(R.id.tray_icon);
try {
final InputStream inputStream = getContentResolver().openInputStream(Uri.parse(trayIconUriString));
final BitmapDrawable trayDrawable = new BitmapDrawable(getResources(), inputStream);
final Drawable emailDrawable = getDrawableForAllAPIs(R.drawable.sticker_3rdparty_email);
trayDrawable.setBounds(new Rect(0, 0, emailDrawable.getIntrinsicWidth(), emailDrawable.getIntrinsicHeight()));
trayIcon.setCompoundDrawables(trayDrawable, null, null, null);
} catch (FileNotFoundException e) {
Log.e(TAG, "could not find the uri for the tray image:" + trayIconUriString);
}
final TextView viewWebpage = findViewById(R.id.view_webpage);
if (TextUtils.isEmpty(website)) {
viewWebpage.setVisibility(View.GONE);
} else {
viewWebpage.setOnClickListener(v -> launchWebpage(website));
}
final TextView sendEmail = findViewById(R.id.send_email);
if (TextUtils.isEmpty(email)) {
sendEmail.setVisibility(View.GONE);
} else {
sendEmail.setOnClickListener(v -> launchEmailClient(email));
}
final TextView viewPrivacyPolicy = findViewById(R.id.privacy_policy);
if (TextUtils.isEmpty(privacyPolicy)) {
viewPrivacyPolicy.setVisibility(View.GONE);
} else {
viewPrivacyPolicy.setOnClickListener(v -> launchWebpage(privacyPolicy));
}
}
private void launchEmailClient(String email) {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", email, null));
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{email});
startActivity(Intent.createChooser(emailIntent, getResources().getString(R.string.info_send_email_to_prompt)));
}
private void launchWebpage(String website) {
Uri uri = Uri.parse(website);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
private Drawable getDrawableForAllAPIs(@DrawableRes int id) {
if (Build.VERSION.SDK_INT >= 21) {
return getDrawable(id);
} else {
return getResources().getDrawable(id);
}
}
}
| [
"[email protected]"
] | |
9b54ca1486b0c83d65f36c84bd8c75e7b7f1c1e4 | d1a6d1e511df6db8d8dd0912526e3875c7e1797d | /genny_JavaWithoutLambdas/applicationModule/src/main/java/applicationModulepackageJava9/Foo575.java | 923e458f313a2decc048fa3e4e1eb28366e1c07f | [] | no_license | NikitaKozlov/generated-project-for-desugaring | 0bc1443ab3ddc84cd289331c726761585766aea7 | 81506b3711004185070ca4bb9a93482b70011d36 | refs/heads/master | 2020-03-20T00:35:06.996525 | 2018-06-12T09:30:37 | 2018-06-12T09:30:37 | 137,049,317 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 346 | java | package applicationModulepackageJava9;
public class Foo575 {
public void foo0() {
new applicationModulepackageJava9.Foo574().foo5();
}
public void foo1() {
foo0();
}
public void foo2() {
foo1();
}
public void foo3() {
foo2();
}
public void foo4() {
foo3();
}
public void foo5() {
foo4();
}
}
| [
"[email protected]"
] | |
58206d1b807b2e81c0f0602af2dc60b060014754 | 3e20a358fb2ca39e84cf800b0f821f7898cc1e6a | /task14/LocationShareServer/src/com/jikexueyuan/locationshareserver/LocationShareHandler.java | ecc8b1092e219d009291818041d7eeb97b4c7420 | [] | no_license | dej-software/Android-Practice | 3f430a8cef9f7e28bba903d5f1a035780ac8f26b | 3ab4cd57f06b3866c5aeb41271e51fd326aef386 | refs/heads/master | 2021-01-12T09:08:16.199771 | 2016-12-18T06:56:33 | 2016-12-18T06:56:33 | 76,772,019 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,639 | java | package com.jikexueyuan.locationshareserver;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
/**
* Created by dej on 2016/11/6.
*/
public class LocationShareHandler extends IoHandlerAdapter {
// flag对应的JSON值说明:
// 0 - 服务器发给客户端连接信息
// 1 - 服务器发给客户端用户名信息
// 1 - 用户发给服务器用户名信息
// 2 - 用户共享的位置信息
private static final int DATA_FLAG_CONNECT = 0;
private static final int DATA_FLAG_USER = 1;
private static final int DATA_FLAG_MAP = 2;
private static final String JSON_FLAG = "flag";
private static final String JSON_NAME = "name";
private static final String JSON_MSG = "message";
// private List<IoSession> userSessions = new ArrayList<>();
private Map<String, IoSession> usersMap = new HashMap<>();
private JSONObject makeMessage(int flag, String msg) {
JSONObject root = new JSONObject();
try {
root.put(JSON_FLAG, flag);
root.put(JSON_MSG, msg);
} catch (JSONException e) {
e.printStackTrace();
}
return root;
}
@Override
public void sessionCreated(IoSession session) throws Exception {
super.sessionCreated(session);
System.out.println(session.toString());
session.write(makeMessage(DATA_FLAG_CONNECT, "@success").toString());
}
@Override
public void sessionClosed(IoSession session) throws Exception {
super.sessionClosed(session);
System.out.println(session.toString());
// 从map中去掉 并发送 {"flag":2,"name":"user1","latitude":-1,"longitude":-1}
String name = "";
Iterator iterator = usersMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
if (session.equals(entry.getValue())) {
name = (String) entry.getKey();
iterator.remove();
}
}
// 此客户端用户存在 把断开连接的数据发送给客户端
if (!"".equals(name)) {
for (IoSession ioSession : usersMap.values()) {
ioSession.write(String.format("{\"flag\":2,\"name\":\"%s\",\"latitude\":-1,\"longitude\":-1}", name));
}
}
}
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
super.messageReceived(session, message);
System.out.println("message:" + message);
// 使用JSON格式解析数据
JSONObject root = null;
try {
root = new JSONObject((String) message);
} catch (JSONException e) {
e.printStackTrace();
return;
}
// 处理用户名情况
int flag = root.getInt(JSON_FLAG);
if (flag == DATA_FLAG_USER) {
String name = root.getString(JSON_NAME);
if (usersMap.containsKey(name)) {
session.write(makeMessage(DATA_FLAG_USER, "@user_error").toString());
return;
} else {
usersMap.put(name, session);
session.write(makeMessage(DATA_FLAG_USER, "@user_success").toString());
}
}
// 处理定位数据 发送给每一个客户端
if (flag == DATA_FLAG_MAP) {
for (IoSession ioSession : usersMap.values()) {
ioSession.write(message);
}
}
}
}
| [
"[email protected]"
] | |
634744b1c82775f5953d525ffb7cdf6f0333eaba | 3eb04851b0eef88e9175ff5a524d0c0ce820d136 | /app/src/main/java/com/arabic/app/model/Tain_Sath/JomlehSahih.java | 05119a74686a97f146cb8bc2ed99509d982085e9 | [] | no_license | sobhan-zp/Arabic_app | d8a023700ca1d550e283b7d511936d6832f28d37 | 905539f3eba4bbcbb43eaa32eaf6714c31cceb5a | refs/heads/master | 2020-03-08T03:40:50.105424 | 2018-04-26T08:43:09 | 2018-04-26T08:43:09 | 122,808,427 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,030 | java | package com.arabic.app.model.Tain_Sath;
/**
* Created by zp on 15/12/2017.
*/
public class JomlehSahih {
private int id;
private String title;
private String btn_1;
private String btn_2;
private String btn_3;
private String btn_4;
private String btn_5;
private String tv_1;
private String tv_2;
private String tv_3;
private String tv_4;
private String tv_5;
public JomlehSahih() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBtn_1() {
return btn_1;
}
public void setBtn_1(String btn_1) {
this.btn_1 = btn_1;
}
public String getBtn_2() {
return btn_2;
}
public void setBtn_2(String btn_2) {
this.btn_2 = btn_2;
}
public String getBtn_3() {
return btn_3;
}
public void setBtn_3(String btn_3) {
this.btn_3 = btn_3;
}
public String getBtn_4() {
return btn_4;
}
public void setBtn_4(String btn_4) {
this.btn_4 = btn_4;
}
public String getBtn_5() {
return btn_5;
}
public void setBtn_5(String btn_5) {
this.btn_5 = btn_5;
}
public String getTv_1() {
return tv_1;
}
public void setTv_1(String tv_1) {
this.tv_1 = tv_1;
}
public String getTv_2() {
return tv_2;
}
public void setTv_2(String tv_2) {
this.tv_2 = tv_2;
}
public String getTv_3() {
return tv_3;
}
public void setTv_3(String tv_3) {
this.tv_3 = tv_3;
}
public String getTv_4() {
return tv_4;
}
public void setTv_4(String tv_4) {
this.tv_4 = tv_4;
}
public String getTv_5() {
return tv_5;
}
public void setTv_5(String tv_5) {
this.tv_5 = tv_5;
}
}
| [
"[email protected]"
] | |
e5515ce0b4967ac93d7e8a26c79455b559b1c8c9 | 38a6795a6a384e43b8d1ae8c7fd8c6a40671f83f | /mall-pms/pms-boot/src/main/java/com/youlai/mall/pms/mapper/PmsCategoryBrandMapper.java | 4f5482979b050613ceb2040071454e4da04e6303 | [
"Apache-2.0"
] | permissive | zhlog1024/youlai-mall | 43a53c7591ddc1cf1fbc6a644f06e5f42ea3b830 | 7cd5ebe9f48e2c87e3cb0f15356f1ff95f81e7ea | refs/heads/master | 2023-07-11T00:31:20.174578 | 2021-08-14T12:20:25 | 2021-08-14T12:20:25 | 394,536,585 | 0 | 0 | Apache-2.0 | 2021-08-14T12:20:26 | 2021-08-10T05:33:36 | null | UTF-8 | Java | false | false | 338 | java | package com.youlai.mall.pms.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.youlai.mall.pms.pojo.entity.PmsCategory;
import com.youlai.mall.pms.pojo.entity.PmsCategoryBrand;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface PmsCategoryBrandMapper extends BaseMapper<PmsCategoryBrand> {
}
| [
"[email protected]"
] | |
655409e8b0b1008d6c842bb54c668cbc0435e503 | c04934fe0020c8d79153e92eea92d42f6f580831 | /inOrderEqualLogic.java | cb7277f6b0028891c43a0ed28eb90368ac248136 | [] | no_license | taymosier/Java-Practice | d6d092bfb63259297720556858aaa816e5e116b6 | 770c601b9bf58c745c59fe24a297dbe336490e9c | refs/heads/master | 2021-01-19T21:32:47.924449 | 2017-04-19T03:01:02 | 2017-04-19T03:01:02 | 88,663,788 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 536 | java | /*
Given three ints, a b c, return true if they are in
strict increasing order, such as 2 5 11, or 5 6 7, but
not 6 5 7 or 5 5 7. However, with the exception that if "equalOk"
is true, equality is allowed, such as 5 5 7 or 5 5 5.
*/
public class inOrderEqualLogic {
public boolean inOrderEqual(int a, int b, int c, boolean equalOk) {
if (b > a && c > b) {
return true;
} else if (equalOk && ((a == b && c > b) || (b == c && b > a) || (a == b && b == c))) {
return true;
}
return false;
}
}
| [
"[email protected]"
] | |
8a296d817581cb75a3c0624b3a0861dd97b90189 | 1499772a52e699ef192993c54cc186f2050d155b | /ex1/src/com/banixc/study/j2ee/lesson/ex1/ShowDarkServlet.java | 979f00a20c8eb209d5f0095120e0655ac0e633af | [] | no_license | banixc/J2EE-Study | 3eea4043036e748551908bd4782e02cc74c08283 | 6cfea722c25b81d066a070dc89838fefddbe78a4 | refs/heads/master | 2021-01-10T18:12:03.226148 | 2016-11-06T06:43:48 | 2016-11-06T06:43:48 | 69,155,291 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 884 | java | package com.banixc.study.j2ee.lesson.ex1;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "ShowDarkServlet", urlPatterns={"/dark"})
public class ShowDarkServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("This is dark! method: POST");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("This is dark! method: GET");
}
}
| [
"[email protected]"
] | |
9cb9907e22f3c1754e88eeaf47b020d7414d2d22 | 3eae5674144d86c3316ba30de564a80914dc4a41 | /src/siddhant/hindi/wordsense/PreProcess.java | db6ba34ed04947bd6ab1f26c368f7a959c6e15b1 | [] | no_license | Praggie/Hindi-NLP | 69b84e776b629e060b5f68d3fc6352ab72d7dd57 | 5a42031235088c29b21ea775416ad349782ce753 | refs/heads/master | 2020-04-23T01:35:29.967344 | 2017-07-20T07:39:20 | 2017-07-20T07:39:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,860 | java | package siddhant.hindi.wordsense;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class PreProcess {
String address;
String inputfilename;
String stopwordfile;
String targetWordFile;
String sensefilename;
BufferedReader inputWordsFile = null;
PreProcess(String addr,String inpFN,String targWF,String SWF,String senseFN){
address = addr;
inputfilename=inpFN;
targetWordFile=targWF;
stopwordfile=SWF;
sensefilename=senseFN;
}
ArrayList<String> run(){
ArrayList<String> cleanWords;
cleanWords=readAndFilter(address+inputfilename);
ArrayList<String> stopWordRemoved;
stopWordRemoved=stopWordRemoval(cleanWords);
//return cleanWords;
return stopWordRemoved;
}
public Long readSense(){
try {
BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(address+sensefilename)));
String ans = input.readLine().trim();
Long sen = Long.valueOf(ans);
input.close();
return sen;
} catch ( FileNotFoundException e) {
System.err.println("sense.txt not found");
e.printStackTrace();
System.exit(-1);
return null;
} catch (UnsupportedEncodingException e){
System.err.println("sense.txt : unicode not supported");
e.printStackTrace();
System.exit(-1);
return null;
} catch (IOException e){
System.err.println("sense.txt : can't read");
e.printStackTrace();
System.exit(-1);
return null;
}
}
/* Gets target word from a file */
public String getTargetWord()
{
File inFiletargetword = new File(address+targetWordFile);
String targetword1 = "";
try
{
BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(inFiletargetword), "unicode"));
while (true)
{
String TTline1 = input.readLine();
if (TTline1 == null)
{
break;
}
targetword1 = targetword1 +TTline1+"\n";
}
input.close();
}
catch (IOException except)
{
except.printStackTrace();
}
String targetword = targetword1.trim();
return(targetword);
}
/* Reads the input file, removes characters like ,/;' etc. and then writes to a output file
* and puts all the words into an array list.
* This method calls another clean method in the class as well
*/
public ArrayList<String> readAndFilter(String inp)
{
File inFile = new File(inp);
File outFile = new File(inp+"filterprocess.txt");
String text = "";
BufferedReader input=null;
try
{
input = new BufferedReader(new InputStreamReader (new FileInputStream(inFile), "unicode"));
while (true)
{
String TTline = input.readLine();
if (TTline == null)
{
break;
}
text+=TTline+"\n";
}
String text1 = text.replace(","," ");
String text2 = text1.replace("-"," ");
String text3 = text2.replace("."," ");
String text4 = text3.replace("?"," ");
String text5 = text4.replace("[", " ");
String text6 = text5.replace("]", " ");
String text7 = text6.replace("|"," ");
String text8 = text7.replace(";"," ");
String text9 = text8.replace("\"", " ");
String text10 = text9.replaceAll("REABaBoGKKaKoMMaMlNSTTe", " ");
String text11 = text10.replace("।", " ");
String text12 = text11.replace("'"," ");
String text13 = text12.replace("/", " ");
String text14 = text13.replace("(", " ");
String text15 = text14.replace(")", " ");
String text16 = text15.replace(".", " ");
String text17 = text16.replace("*", " ");
String text18 = text17.replace("`", " ");
String text19 = text18.replace("?", " ");
String text20 = text19.replace("=", " ");
String text21 = text20.replace("+", " ");
String text22 = text21.replace("‘", " ");
String text23 = text22.replace("’", " ");
String text24 = text23.replace("!", " ");
String text25 = text24.replace("“", " ");
String text26 = text25.replace("”", " ");
String text27 = text26.replace("।"," ");
String text28 = text27.replace("–", " ");
String text29 = text28.replace(":", " ");
String text30 = text29.replace("<"," ");
String text31 = text30.replace(">"," ");
String text32 = text31.replace("I"," ");
String text33 = text32.replace("0"," ");
String text34 = text33.replace("1"," ");
String text35 = text34.replace("2"," ");
String text36 = text35.replace("3"," ");
String text37 = text36.replace("4"," ");
String text38 = text37.replace("5"," ");
String text39 = text38.replace("6"," ");
String text40 = text39.replace("7"," ");
String text41 = text40.replace("8"," ");
String text42 = text41.replace("9"," ");
String text43 = text42.replace("०"," ");
String text44 = text43.replace("१"," ");
String text45 = text44.replace("२"," ");
String text46 = text45.replace("३"," ");
String text47 = text46.replace("४"," ");
String text48 = text47.replace("५"," ");
String text49 = text48.replace("६"," ");
String text50 = text49.replace("७"," ");
String text51 = text50.replace("८"," ");
String text52 = text51.replace("९"," ");
String text53 = text52.replace("%"," ");
String text54 = text53.trim();
String word;
ArrayList<String> inputWords = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(text54);
while(st.hasMoreTokens()){
word = st.nextToken();
String word1 = clean(word);
inputWords.add(word1.trim());
}
input.close();
Writer output = null;
output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "unicode"));
output.write(inputWords.toString());
output.close();
return(inputWords);
}
catch( FileNotFoundException e){
System.err.println("Error opening input words file.");
System.exit(-1);
return null;
}
catch (UnsupportedEncodingException e){
System.err.println("Unicode encoding is not supported: Can't Open File");
System.exit(-1);
return null;
}
catch (IOException except){
except.printStackTrace();
return null;
}
}
/* Further removal of useless characters
* Gets called by CreateVector */
public String clean (String x){
String word;
word = x;
if ((word.startsWith(" , "))|| (word.endsWith(" , ")))
word.replace(" , ", " ");
if ((word.startsWith(" - "))|| (word.endsWith(" - ")))
word.replace(" - ", " ");
if ((word.startsWith(" . "))|| (word.endsWith(" . ")))
word.replace(" . ", " ");
if ((word.startsWith(" ? "))|| (word.endsWith(" ? ")))
word.replace(" ? ", " ");
if ((word.startsWith(" [ "))|| (word.endsWith(" [ ")))
word.replace(" [ ", " ");
if ((word.startsWith(" ] "))|| (word.endsWith(" ] ")))
word.replace(" ] ", " ");
if ((word.startsWith(" | "))|| (word.endsWith(" | ")))
word.replace(" | ", " ");
if ((word.startsWith(" ; "))|| (word.endsWith(" ; ")))
word.replace(" ; ", " ");
if ((word.startsWith(" \" "))|| (word.endsWith(" \" ")))
word.replace(" \" ", " ");
if ((word.startsWith(" : "))|| (word.endsWith(" : ")))
word.replace(" : ", " ");
if ((word.startsWith(" – "))|| (word.endsWith(" – ")))
word.replace(" – ", " ");
if ((word.startsWith(" । "))|| (word.endsWith(" । ")))
word.replace(" । ", " ");
if ((word.startsWith(" ” "))|| (word.endsWith(" ” ")))
word.replace(" ” ", " ");
if ((word.startsWith(" “ "))|| (word.endsWith(" “ ")))
word.replace(" “ ", " ");
if ((word.startsWith(" ! "))|| (word.endsWith(" ! ")))
word.replace(" ! ", " ");
if ((word.startsWith(" ’ "))|| (word.endsWith(" ’ ")))
word.replace(" ’ ", " ");
if ((word.startsWith(" ‘ "))|| (word.endsWith(" ‘ ")))
word.replace(" ‘ ", " ");
if ((word.startsWith(" + "))|| (word.endsWith(" + ")))
word.replace(" + ", " ");
if ((word.startsWith(" = "))|| (word.endsWith(" = ")))
word.replace(" = ", " ");
if ((word.startsWith(" ? "))|| (word.endsWith(" ? ")))
word.replace(" ? ", " ");
if ((word.startsWith(" ` "))|| (word.endsWith(" ` ")))
word.replace(" ` ", " ");
if ((word.startsWith(" * "))|| (word.endsWith(" * ")))
word.replace(" * ", " ");
if ((word.startsWith(" ) "))|| (word.endsWith(" ) ")))
word.replace(" ) ", " ");
if ((word.startsWith(" ( "))|| (word.endsWith(" ( ")))
word.replace(" ( ", " ");
if ((word.startsWith(" ' "))|| (word.endsWith(" ' ")))
word.replace(" ' ", " ");
if ((word.startsWith(" । "))|| (word.endsWith(" । ")))
word.replace(" । ", " ");
word.trim();
return word;
}
/* Reads stop words from a file and removes them */
public ArrayList<String> stopWordRemoval(ArrayList<String> x ){
ArrayList<String> stopword = new ArrayList<String>();
ArrayList<String> fil = x;
stopword = readAndFilter(stopwordfile);
String[] arraystopword = new String [stopword.size()];
String[] astopword = stopword.toArray(arraystopword);
String[] arrayfil = new String [fil.size()];
String[] file = fil.toArray(arrayfil);
ArrayList<String> stopWordsRemoved = new ArrayList<String>();
for(int i =0; i < file.length; i++){
Boolean isStopWord = false;
for(int j = 0 ; j < astopword.length; j++){
if (file[i].equalsIgnoreCase(astopword[j])==true) {
isStopWord = true;
}
}
if (isStopWord == false){
stopWordsRemoved.add(file[i]);
}
}
return stopWordsRemoved;
}
}
| [
"[email protected]"
] | |
78eb5955c015662e668442526b151a7eefc4d7b6 | 9f10e58b66b1b36cbd62d59ed47b826d1c10139b | /src/java/main/level_2/CompressString.java | 8d3b722a4565f5ea58387bd3ed200d6e6734e6a8 | [] | no_license | Gor-Ren/firecode.io | 4b4a3a3c04da1c0bee3b8739fa0beb72ca0faa6b | 314aae53eb4fa7350bcac49fc82ec39572bf9e72 | refs/heads/master | 2021-01-22T01:34:25.893456 | 2019-09-30T17:18:00 | 2019-09-30T17:18:00 | 102,221,455 | 2 | 0 | null | 2017-09-13T21:33:37 | 2017-09-02T20:22:08 | Python | UTF-8 | Java | false | false | 2,279 | java | /**
* Compress a sorted String by replacing instances of repeated characters with
* the character followed by the count of the character.
*
* compressString("aaabbbbbcccc") --> a3b5c4
* compressString("aabbbbccc") --> a2b4c3
* compressString("abc") --> abc
*/
public class CompressString {
public static String compressString(String text) {
if (text.isEmpty() || text.length() == 1) {
return text;
}
StringBuilder result = new StringBuilder();
char current = text.charAt(0);
char next;
int repetitions = 1;
for (char c : text.substring(1).toCharArray()) {
next = c;
if (current == next) {
repetitions++;
} else {
// compress repeated char
appendCompressed(result, current, repetitions);
current = next;
repetitions = 1;
}
}
// append last character(s)
appendCompressed(result, current, repetitions);
return result.toString();
}
/**
* Appends the input character to the builder, "compressing" it if it was repeated multiple times.
*
* <p>If the character only occurred once ({@code times = 1}) then the char is simply appended. If
* it occurred {@code n} times in sequence, then the character followed by the number {@code n}
* is appended.
*
* @param builder the string builder to which the compressed character(s) will be appended
* @param character the character to append
* @param times the number of times the character was repeated
* @return the input builder, with the character appended, possibly with compression
* @throws IllegalArgumentException if {@code times} is zero or negative
*/
private static StringBuilder appendCompressed(StringBuilder builder, char character, int times) {
if (times == 1) {
return builder.append(character);
} else if (times > 1) { // compress
return builder.append(character).append(times);
} else {
throw new IllegalArgumentException(String.format(
"Cannot append char %s negative times [%s]", character, times)
);
}
}
}
| [
"[email protected]"
] | |
49b24e3bdaf31a35451d223ab34b98430698813f | 039fb5a76e2ffca265bc15203ca3277264e9e488 | /src/main/java/cz/educanet/tranformations/Dimensions.java | b6d30c7decbb316fd55f65ad37bc846e3ccce7a1 | [
"MIT"
] | permissive | j-forgac/Rasterization | 5049d14148bf00a0997803b5222fcb977fbc9885 | d9c5ca5d9646ac4aafedb411215c33396323d809 | refs/heads/main | 2023-03-08T04:58:00.697397 | 2021-02-19T10:47:19 | 2021-02-19T10:47:19 | 338,265,299 | 0 | 0 | MIT | 2021-02-12T08:47:59 | 2021-02-12T08:47:59 | null | UTF-8 | Java | false | false | 192 | java | package cz.educanet.tranformations;
public class Dimensions {
int width = 36;
int height = 27;
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
}
| [
"[email protected]"
] | |
373e5e8ead5181a11ca1eda6312a47932e167c1c | 15b7df666a25d7cfcb14211444897c70759983bd | /soyatec_java_SDK/org.soyatec.windows.azure.java/src/org/soyatec/windowsazure/blob/internal/SharedAccessUrl.java | 2a178ac7e15323c62d3a0d12a2c4a5d21352442f | [] | no_license | movence/PRODDL-C | e06f867bb5ce9f9907c81d4d241947841f651cb0 | 394fec5f798ba33d5dabcec1d09614719964a7d9 | refs/heads/master | 2016-09-02T05:04:35.400589 | 2014-02-03T18:05:11 | 2014-02-03T18:05:11 | 15,555,355 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 7,310 | java | /**
* Copyright 2006-2010 Soyatec
*
* 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.
*
* $Id$
*/
package org.soyatec.windowsazure.blob.internal;
import org.soyatec.windowsazure.blob.ISharedAccessUrl;
public class SharedAccessUrl implements ISharedAccessUrl {
private String accountName;
private String blobName;
private String containerName;
private String signedResource;
private String signedStart;
private String signedExpiry;
private String signedPermissions;
private String signedIdentifier;
private String signature;
private String restUrl;
private String signedString;
public static ISharedAccessUrl parse(String url) {
SharedAccessUrl share = new SharedAccessUrl();
String[] parts = url.split("\\?");
share.restUrl = parts[0];
share.signedString = parts[1];
int pos = url.indexOf(".blob.core.windows.net");
if (pos > -1) {
share.accountName = url.substring("http://".length(), pos);
url = url.substring(pos + ".blob.core.windows.net/".length(), url
.indexOf('?'));
} else {
pos = url.indexOf("blob.core.windows.net/")
+ "blob.core.windows.net/".length();
share.accountName = url.substring(pos, url.indexOf('/', pos));
url = url.substring(url.indexOf('/', pos) + 1, url
.indexOf('?', pos));
}
parts = url.split("/");
share.containerName = parts[0];
if (parts.length > 1)
share.blobName = parts[1];
String[] params = share.signedString.split("&");
for (String param : params) {
if (param.indexOf("st=") > -1)
share.signedStart = param.substring(3);
else if (param.indexOf("sr=") > -1)
share.signedResource = param.substring(3);
else if (param.indexOf("se=") > -1)
share.signedExpiry = param.substring(3);
else if (param.indexOf("sp=") > -1)
share.signedPermissions = param.substring(3);
else if (param.indexOf("si=") > -1)
share.signedIdentifier = param.substring(3);
else if (param.indexOf("sig=") > -1)
share.signature = param.substring(4);
}
return share;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#getAccountName()
*/
public String getAccountName() {
return accountName;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#setAccountName(java.lang.String)
*/
public void setAccountName(String accountName) {
this.accountName = accountName;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#getBlobName()
*/
public String getBlobName() {
return blobName;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#setBlobName(java.lang.String)
*/
public void setBlobName(String blobName) {
this.blobName = blobName;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#getContainerName()
*/
public String getContainerName() {
return containerName;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#setContainerName(java.lang.String)
*/
public void setContainerName(String containerName) {
this.containerName = containerName;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#getSignedResource()
*/
public String getSignedResource() {
return signedResource;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#setSignedResource(java.lang.String)
*/
public void setSignedResource(String signedResource) {
this.signedResource = signedResource;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#getSignedStart()
*/
public String getSignedStart() {
return signedStart;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#setSignedStart(java.lang.String)
*/
public void setSignedStart(String signedStart) {
this.signedStart = signedStart;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#getSignedExpiry()
*/
public String getSignedExpiry() {
return signedExpiry;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#setSignedExpiry(java.lang.String)
*/
public void setSignedExpiry(String signedExpiry) {
this.signedExpiry = signedExpiry;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#getSignedPermissions()
*/
public String getSignedPermissions() {
return signedPermissions;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#setSignedPermissions(java.lang.String)
*/
public void setSignedPermissions(String signedPermissions) {
this.signedPermissions = signedPermissions;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#getSignedIdentifier()
*/
public String getSignedIdentifier() {
return signedIdentifier;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#setSignedIdentifier(java.lang.String)
*/
public void setSignedIdentifier(String signedIdentifier) {
this.signedIdentifier = signedIdentifier;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#getSignature()
*/
public String getSignature() {
return signature;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#setSignature(java.lang.String)
*/
public void setSignature(String signature) {
this.signature = signature;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#getRestUrl()
*/
public String getRestUrl() {
return restUrl;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#setRestUrl(java.lang.String)
*/
public void setRestUrl(String restUrl) {
this.restUrl = restUrl;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#getSignedString()
*/
public String getSignedString() {
return signedString;
}
/* (non-Javadoc)
* @see org.soyatec.windowsazure.blob.ISharedAccessUrl#setSignedString(java.lang.String)
*/
public void setSignedString(String signedString) {
this.signedString = signedString;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "ShareAccessUrl [accountName=" + accountName + ", blobName="
+ blobName + ", containerName=" + containerName + ", restUrl="
+ restUrl + ", signature=" + signature + ", signedExpiry="
+ signedExpiry + ", signedIdentifier=" + signedIdentifier
+ ", signedPermissions=" + signedPermissions
+ ", signedResource=" + signedResource + ", signedStart="
+ signedStart + ", signedString=" + signedString + "]";
}
}
| [
"devnull@localhost"
] | devnull@localhost |
90cfc4d92b4e9d82d972fcd9af22fdeba1dd8369 | f3218116a1facfdbe88394e9baa85bf134a04dd0 | /app/http/org/apache/http/impl/conn/SystemDefaultRoutePlanner.java | 6b872b9eb4516f0f1297c489ae02c2557c699d31 | [
"Apache-2.0"
] | permissive | xxonehjh/remote-files-sync | 422b45c031bd3aba30dd4402ab1614551509e6b5 | a4ee7952f6da3b931d70af075ae9ab5c88f32d0d | refs/heads/master | 2021-01-09T20:31:55.287970 | 2016-08-07T01:27:45 | 2016-08-07T01:27:45 | 62,180,893 | 8 | 3 | null | null | null | null | UTF-8 | Java | false | false | 4,826 | java | /*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.conn;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.annotation.Immutable;
import org.apache.http.conn.SchemePortResolver;
import org.apache.http.protocol.HttpContext;
/**
* {@link org.apache.http.conn.routing.HttpRoutePlanner} implementation
* based on {@link ProxySelector}. By default, this class will pick up
* the proxy settings of the JVM, either from system properties
* or from the browser running the application.
*
* @since 4.3
*/
@Immutable
public class SystemDefaultRoutePlanner extends DefaultRoutePlanner {
private final ProxySelector proxySelector;
public SystemDefaultRoutePlanner(
final SchemePortResolver schemePortResolver,
final ProxySelector proxySelector) {
super(schemePortResolver);
this.proxySelector = proxySelector != null ? proxySelector : ProxySelector.getDefault();
}
public SystemDefaultRoutePlanner(final ProxySelector proxySelector) {
this(null, proxySelector);
}
@Override
protected HttpHost determineProxy(
final HttpHost target,
final HttpRequest request,
final HttpContext context) throws HttpException {
final URI targetURI;
try {
targetURI = new URI(target.toURI());
} catch (final URISyntaxException ex) {
throw new HttpException("Cannot convert host to URI: " + target, ex);
}
final List<Proxy> proxies = this.proxySelector.select(targetURI);
final Proxy p = chooseProxy(proxies);
HttpHost result = null;
if (p.type() == Proxy.Type.HTTP) {
// convert the socket address to an HttpHost
if (!(p.address() instanceof InetSocketAddress)) {
throw new HttpException("Unable to handle non-Inet proxy address: " + p.address());
}
final InetSocketAddress isa = (InetSocketAddress) p.address();
// assume default scheme (http)
result = new HttpHost(getHost(isa), isa.getPort());
}
return result;
}
private String getHost(final InetSocketAddress isa) {
//@@@ Will this work with literal IPv6 addresses, or do we
//@@@ need to wrap these in [] for the string representation?
//@@@ Having it in this method at least allows for easy workarounds.
return isa.isUnresolved() ?
isa.getHostName() : isa.getAddress().getHostAddress();
}
private Proxy chooseProxy(final List<Proxy> proxies) {
Proxy result = null;
// check the list for one we can use
for (int i=0; (result == null) && (i < proxies.size()); i++) {
final Proxy p = proxies.get(i);
switch (p.type()) {
case DIRECT:
case HTTP:
result = p;
break;
case SOCKS:
// SOCKS hosts are not handled on the route level.
// The socket may make use of the SOCKS host though.
break;
}
}
if (result == null) {
//@@@ log as warning or info that only a socks proxy is available?
// result can only be null if all proxies are socks proxies
// socks proxies are not handled on the route planning level
result = Proxy.NO_PROXY;
}
return result;
}
}
| [
"[email protected]"
] | |
698cb5f6c0efedc04c5938fb852292f5adedf9f2 | ee19aed8e7c6518a4e2632c99a7477f76d84805c | /Phimy/app/src/main/java/com/phimy/view/adapter/MovieAdapter.java | bee309f2f7b07518d022af4ed8b5a2293a322246 | [] | no_license | avyavasthe/cautious-garbanzo | 1826cf5f43d95746f70f89a42f0c9ea522bfd5b9 | 712191da984686e31a9cd604af9ea7e55876aa0e | refs/heads/master | 2021-10-08T23:00:30.054060 | 2018-12-18T20:27:46 | 2018-12-18T20:27:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,205 | java | package com.phimy.view.adapter;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.phimy.R;
import com.phimy.controller.ControllerMovieDB;
import com.phimy.dao.ServiceMoviesDB;
import com.phimy.helper.ItemTouchHelperAdapter;
import com.phimy.model.MovieDB;
import com.phimy.model.MovieDBContainer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import Utils.ResultListener;
import retrofit2.Call;
import retrofit2.Response;
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> implements ItemTouchHelperAdapter, Filterable {
private Context context;
private List<MovieDB> movieList;
private Integer resources;
private Drawable imageFavorito;
private Drawable imageNoFavorito;
private ControllerMovieDB controllerMovieDB;
private Receptor receptor;
final static public Integer KEY_TAG_FAVORITO = 0;
final static public Integer KEY_TAG_NOFAVORITO = 1;
public MovieAdapter(Context context, Receptor receptor, List<MovieDB> movieList, Integer resources, Drawable imageFavorito, Drawable imageNoFavorito) {
this.movieList = movieList;
this.resources = resources;
this.imageFavorito=imageFavorito;
this.imageNoFavorito=imageNoFavorito;
this.receptor=receptor;
this.context=context;
}
@NonNull
@Override
public MovieViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int position) {
View view = LayoutInflater.from(parent.getContext()).inflate(resources, parent, false);
return new MovieViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final MovieViewHolder movieViewHolder, int position) {
final MovieDB movieDB = movieList.get(position);
movieViewHolder.load(movieDB);
movieViewHolder.controlFavoritos(movieDB);
movieViewHolder.favoriteImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Integer icon= (Integer) movieViewHolder.favoriteImage.getTag();
if (icon == KEY_TAG_FAVORITO){
Toast.makeText(view.getContext(), "eliminar favoritos " + movieDB.getTitle() , Toast.LENGTH_SHORT).show();
movieViewHolder.favoriteImage.setCompoundDrawablesWithIntrinsicBounds(imageNoFavorito,
null, null, null );
movieViewHolder.favoriteImage.setTag(KEY_TAG_NOFAVORITO);
controllerMovieDB.getInstance().removeFavoritos(context, movieDB);
notifyDataSetChanged();
} else {
Toast.makeText(view.getContext(), "agregar favoritos " + movieDB.getTitle() , Toast.LENGTH_SHORT).show();
movieViewHolder.favoriteImage.setCompoundDrawablesWithIntrinsicBounds(imageFavorito,
null, null, null );
movieViewHolder.favoriteImage.setTag(KEY_TAG_FAVORITO);
controllerMovieDB.getInstance().addFavoritos(context, movieDB);
notifyDataSetChanged();
}
}
});
}
@Override
public int getItemCount() {
return movieList.size();
}
@Override
public Boolean onItemMove(int fromPosition, int toPosition) {
return null;
}
@Override
public void onItemDismiss(int position) {
}
public class MovieViewHolder extends RecyclerView.ViewHolder {
private ImageView movieImage;
private Button favoriteImage;
private TextView artistaName;
public MovieViewHolder(@NonNull View itemView) {
super(itemView);
movieImage = itemView.findViewById(R.id.moviePoster);
artistaName = itemView.findViewById(R.id.artista);
favoriteImage= itemView.findViewById(R.id.butonFavoritos);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MovieDB movieDB = movieList.get(getAdapterPosition());
receptor.recibir(movieDB, getAdapterPosition(), movieList, "MovieFragment");
}
});
}
public void load(MovieDB movie) {
String path = movie.getPoster_path();
//TODO sacar la URL de las imagenes a una variable o values
Glide.with(itemView.getContext()).load("http://image.tmdb.org/t/p/w500/"+movie.getPoster_path()).into(movieImage);
artistaName.setText(movie.getTitle());
}
public void controlFavoritos(MovieDB movieDB){
//TODO controlar si la peli está o no en favoritos
if (controllerMovieDB.getInstance().isFavorito(movieDB, context)) {
//Asigno a todos los no favoritos
favoriteImage.setCompoundDrawablesWithIntrinsicBounds(imageFavorito,
null, null, null);
favoriteImage.setTag(KEY_TAG_FAVORITO);
} else{
favoriteImage.setCompoundDrawablesWithIntrinsicBounds(imageNoFavorito,
null, null, null);
favoriteImage.setTag(KEY_TAG_NOFAVORITO);
}
}
}
public List<MovieDB> getMovieList() {
return movieList;
}
public void setMovieList(List<MovieDB> movieList) {
this.movieList = movieList;
notifyDataSetChanged();
}
public interface Receptor{
void recibir(MovieDB movieDB, Integer pos, List<MovieDB> list, String nameFrag);
}
@Override
public Filter getFilter() {
final Context cont= this.context;
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<MovieDB> filterList = new ArrayList<>();
final FilterResults results = new FilterResults();
if (constraint == null || constraint.length() == 0) {
filterList.addAll(movieList);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
filterList= ControllerMovieDB.getInstance().getSearchMovies(filterPattern);
}
results.values = filterList;
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
movieList.clear();
movieList.addAll((Collection<? extends MovieDB>) results.values);
notifyDataSetChanged();
}
};
}
} | [
"[email protected]"
] | |
3979b10844857f5e73c51c9192d15b0179887150 | ce791608be642d04c0f5272dd11a34504b1b189a | /p_volley/src/main/java/com/volley/libirary/http/request/RequestCallBack2.java | 1e0a23cdc646ee950d851395d9166b1fd50f6eea | [] | no_license | wincentytg/MBApplication | 7c30790a4404bee1f09942210b4f6744140bd869 | 2a7f33541f3071336cbb1ea5850756e8406671bf | refs/heads/master | 2020-03-22T17:16:33.449824 | 2018-09-11T06:42:50 | 2018-09-11T06:42:50 | 140,385,262 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 253 | java | package com.volley.libirary.http.request;
import com.android.volley.VolleyError;
/**
*
* @author 于堂刚
*/
public interface RequestCallBack2<T> {
public abstract void onResult(T response);
public abstract void onError(VolleyError error);
}
| [
"[email protected]"
] | |
af84469e524ed4cce0c3990feb57e771f91697d0 | d950704f993a38c5f7c632d0322eb6df5877ff49 | /framework/src/main/java/com/wch/jdbc/SessionImpl.java | 0302a5de8ff19e940ba41b2fdd310b2212a4e6b3 | [] | no_license | gdnwxf/framework | 025fef9c1e60d6673c16aed88fc969da810c44ba | dee9604c004a28c7fc40a1d16b96dec8a4852cd1 | refs/heads/master | 2020-04-15T12:44:02.039374 | 2017-05-12T02:52:12 | 2017-05-12T02:52:12 | 61,381,968 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 28,064 | java | package com.wch.jdbc;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.wch.utils.BeanUtils;
import com.wch.utils.string.StringUtils;
/**
* The Class SessionImpl.
*
* @author gdnwxf
* @version 1.0
* @since 2014
* @email [email protected]
* @date 2015-1-22 18:42:39
*/
public class SessionImpl implements Session {
/** 数据库链接. */
private Connection connection = null;
/** 数据库的预编译. */
private PreparedStatement ps = null;
/** 查询数据库的结果集. */
private ResultSet rs = null;
/** 数据库中的BIGDECIMAL数据类型. */
private final Class<?> BIGDECIMAL_CLASS_NAME = java.math.BigDecimal.class;
/** The transaction. */
private Transaction transaction = null;
/** The is show sql. */
private boolean isShowSql = false;
/** The factory. */
private SessionFactory factory = null;
/** The Constant pattern. */
private final static Pattern pattern = Pattern.compile(":[\\w\\W]+?\\b");
/** The transaction flag. */
private boolean transactionFlag = true;
/** 确认返回的值是list map Entity. */
private String returnType = Session.ALIAS_TO_ENTITY_MAP;
/** 当查询出来的东西给实体赋值. */
private Class<?> entity = null;
/**
* 单次事务.
*
* @throws SQLException the SQL exception
*/
public SessionImpl() throws SQLException {
connection = SessionFactory.getInstance().getConnection();
connection.setAutoCommit(false);// 让其事务手动提交
isShowSql = SessionFactory.getInstance().isShowSql();
transactionFlag = false;
}
/**
* 多次事务.
*
* @param transaction the transaction
* @throws SQLException the SQL exception
*/
public SessionImpl(Transaction transaction) throws SQLException {
this.transaction = transaction;
this.factory = transaction == null ? SessionFactory.getInstance() : transaction.getFactory();
this.isShowSql = factory.isShowSql();
}
/**
* 由sessionFactory 创建session.
*
* @param connection the connection
* @throws SQLException the SQL exception
*/
public SessionImpl(Connection connection) throws SQLException {
this.connection = connection;
this.connection.setAutoCommit(false);// 让其事务手动提交
isShowSql = SessionFactory.getInstance().isShowSql();
transactionFlag = false; // 表示不进行事务的处理
}
/**
* 获取链接.
*
* @return the connection
* @throws SQLException the SQL exception
*/
public Connection getConnection() throws SQLException {
if (!transactionFlag) {
return connection;
}
if (transaction != null && transaction.isBegin()) {
return transaction.getConnection();
} else {
return factory.getConnection();
}
}
/**
* 开启事务.
*
* @return the transaction
* @throws SQLException the SQL exception
*/
public Transaction beginTransaction() throws SQLException {
if (getConnection().getAutoCommit()) {
getConnection().setAutoCommit(false);
}
// 如果不是事务类型的时候
if (!transactionFlag) {
transaction = Transaction.getTransaction(getConnection());
}
return transaction;
}
/**
* 获取事务.
*
* @return the transaction
* @throws SQLException the SQL exception
*/
public Transaction getTransaction() throws SQLException {
if (transaction == null) {
return Transaction.getTransaction(getConnection());
} else {
return transaction;
}
}
/**
* 打印sql语句.
*
* @param sql the sql
*/
private void printSql(String sql) {
if (isShowSql) {
System.out.println(sql);
}
}
/**
* 关闭session.
*
* @throws SQLException the SQL exception
*/
public void close() throws SQLException {
if (getConnection() != null && !getConnection().isClosed()) {
getConnection().close();
}
}
/**
* 关闭结果集和预编译块.
*/
public void simpleClose() {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("未能成功关闭的原因" + e);
}
}
/**
* Gets the result transformer.
*
* @return the result transformer
*/
private String getResultTransformer() {
return returnType;
}
/**
* Sets the result transformer.
*
* @param returnType the new result transformer
*/
public void setResultTransformer(String returnType) {
this.returnType = returnType;
}
/* (non-Javadoc)
* @see com.wch.jdbc.Session#addEntity(java.lang.Class)
*/
public Session addEntity(Class<?> clazz) {
this.entity = clazz;
return this;
}
/**
* Gets the entity.
*
* @return the entity
*/
private Class<?> getEntity() {
Class<?> temp = entity;
entity = null;
return temp;
}
/**
* 更新数据库.
*
* @param sql the sql
* @param params 以Object可变参数的形式传值
* @throws SQLException the SQL exception
*/
public void executeUpdate(String sql, Object... params) throws SQLException {
try {
if (getConnection().getAutoCommit()) {
getConnection().isClosed();
throw new SQLException("请手动开启事务");
}
createSessionQuery(sql, params);
ps.executeUpdate();
} finally {
simpleClose();
}
}
/**
* 更新数据库.
*
* @param sql the sql
* @param params the params
* @throws SQLException the SQL exception
*/
public void executeUpdate(String sql, Map<String, Object> params) throws SQLException {
try {
if (getConnection().getAutoCommit()) {
getConnection().isClosed();
throw new SQLException("请手动开启事务");
}
createSessionQuery(sql, params);
ps.executeUpdate();
} finally {
simpleClose();
}
}
/**
* 获取该实体类的有参或无参的构造方法.
*
* @param clazz the clazz
* @param fields the fields
* @return the constructor
* @throws SQLException the SQL exception
*/
@SuppressWarnings("unused")
private Constructor<?> getConstructor(Class<?> clazz, Field... fields) throws SQLException {
Constructor<?> construtor = null;
try {
Class<?>[] cla = null;
if (fields != null) {
Integer fieldLen = fields.length;
cla = new Class[fieldLen];
for (int i = 0; i < fieldLen; i++) {
cla[i] = fields[i].getType();
}
// 得到的有参的构造函数
construtor = clazz.getConstructor(cla);
} else {
construtor = clazz.getConstructor();
}
return construtor;
} catch (NoSuchMethodException e) {
throw new SQLException("无法通过反射技术获取该实体类的构造函数" + e);
}
}
/**
* 返回查询到的结果集.
*
* @return the result set
* @throws SQLException the SQL exception
*/
public ResultSet getResultSet() throws SQLException {
if (ps == null) {
throw new SQLException("没有预编译sql");
} else if (rs == null || rs.isClosed()) {
rs = ps.executeQuery();
}
return rs;
}
/**
* 查出的列的String 数组转成大写.
*
* @return the alias upper
* @throws SQLException the SQL exception
*/
public String[] getAliasUpper() throws SQLException {
getResultSet();
int rs_col = getColsNo();
String[] paramName = new String[rs_col];
for (int i = 0; i < rs_col; i++) {
// 是选择的字段另取得名称
paramName[i] = rs.getMetaData().getColumnLabel(i + 1).toUpperCase();
}
return paramName;
}
/**
* 返回结果集中查出的列的String 数组.
*
* @return the alias
* @throws SQLException the SQL exception
*/
public String[] getAlias() throws SQLException {
getResultSet();
int rs_col = getColsNo();
String[] paramName = new String[rs_col];
for (int i = 0; i < rs_col; i++) {
// 是选择的字段另取得名称
paramName[i] = rs.getMetaData().getColumnLabel(i + 1);
}
return paramName;
}
/**
* Gets the cols no.
*
* @return 返回查询出的结果列的数量
* @throws SQLException the SQL exception
*/
private int getColsNo() throws SQLException {
ResultSetMetaData rsmd = getResultSet().getMetaData();
return rsmd.getColumnCount();
}
/**
* 以对象数组的形式返回.
*
* @return the values
* @throws SQLException the SQL exception
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public List getValues() throws SQLException {
getResultSet();
List valueList = new ArrayList();
while (rs.next()) {
Object[] objects = new Object[getColsNo()];
for (int j = 0; j < getColsNo(); j++) {
objects[j] = rs.getObject(j + 1);
}
if (getColsNo() == 1) {
valueList.add(objects[0]);
} else {
valueList.add(objects);
}
}
simpleClose();
return valueList;
}
/**
* 以list<Map<String,Object>> 返回从数据库中查出的东西.
*
* @return the list
* @throws SQLException the SQL exception
*/
public List<?> list() throws SQLException {
getResultSet();
String sReturnType = getResultTransformer();
if (sReturnType.equals(Session.ALIAS_TO_LIST)) {
return getValues();
}
List<Map<String, Object>> valueList = new ArrayList<Map<String, Object>>();
List<Object> entityList = new ArrayList<Object>();
int iColNo = getColsNo();
String[] alias = getAlias();
Class<?> entityClass = getEntity();
while (rs.next()) {
Map<String, Object> map = new HashMap<String, Object>();
for (int j = 0; j < iColNo; j++) {
map.put(alias[j], rs.getObject(alias[j]));
}
if (entityClass != null) {
try {
entityList.add(BeanUtils.mapToBean(map, entityClass));
} catch (InstantiationException e) {
throw new SQLException(e.getMessage());
} catch (IllegalAccessException e) {
throw new SQLException(e.getMessage());
} catch (IllegalArgumentException e) {
throw new SQLException(e.getMessage());
} catch (InvocationTargetException e1) {
throw new SQLException(e1.getMessage());
}
} else if (entityClass == null) {
if (sReturnType.equals(Session.ALIAS_TO_ENTITY_MAP)) {
valueList.add(map);
}
}
}
// simpleClose();
rs.close();
if (entityClass != null) {
return entityList;
} else if (sReturnType.equals(Session.ALIAS_TO_ENTITY_MAP)) {
return valueList;
}
return null;
}
/**
* 以Object[]返回唯一的行值.
*
* @return the unique row
* @throws SQLException the SQL exception
*/
public Object[] getUniqueRow() throws SQLException {
getResultSet();
Object[] objects = new Object[getColsNo()];
if (rs.next()) {
for (int j = 0; j < getColsNo(); j++) {
objects[j] = rs.getObject(j + 1);
}
}
simpleClose();
return objects;
}
/**
* Map<String,Object> 的形式返回一行值.
*
* @return the unique map row
* @throws SQLException the SQL exception
*/
public Map<String, Object> getUniqueMapRow() throws SQLException {
getResultSet();
Map<String, Object> map = new HashMap<String, Object>();
if (rs.next()) {
for (int j = 0; j < getColsNo(); j++) {
map.put(getAlias()[j], rs.getObject(getAlias()[j]));
}
}
simpleClose();
return map;
}
/**
* 返回唯一的单值.
*
* @param <T> the generic type
* @return the unique object
* @throws SQLException the SQL exception
*/
public <T> T getUniqueObject() throws SQLException {
getResultSet();
@SuppressWarnings("unchecked")
T t = (T) rs.getObject(1);
simpleClose();
return t;
}
/**
* 当从数据库获取的值为BIGDECIMAL时进行转换.
*
* @param value the value
* @return the obj
*/
private Object getObj(Object value) {
if (value != null && BIGDECIMAL_CLASS_NAME.equals(value.getClass())) {
BigDecimal bigDecimal = (BigDecimal) value;
long longValue = bigDecimal.longValue();
value = longValue;
}
return value;
}
/**
* 将Map 实例化成 bean.
*
* @param <T> the generic type
* @param map the map
* @param t the t
* @return the t
* @throws InstantiationException the instantiation exception
* @throws IllegalAccessException the illegal access exception
* @throws IllegalArgumentException the illegal argument exception
* @throws InvocationTargetException the invocation target exception
*/
public static <T> T mapToBean(Map<String, Object> map, Class<T> t) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
T object = t.newInstance();
Method[] methods = object.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
String methodName = methods[i].getName();
if (methodName.indexOf("set") == 0) {
String fieldName = methodName.substring(3);// 下标从0开始的
System.out.println(fieldName);
methods[i].invoke(object, map.get(StringUtils.char2Lower(fieldName, 0)));
}
}
return object;
}
/**
* Instance object.
*
* @param <T> the generic type
* @param num 为0时为 无参构造方法 为1时是有参构造方法
* @param t the t
* @param map the map
* @return the t
* @throws SQLException the SQL exception
*/
@SuppressWarnings("unused")
@Deprecated
private <T> T instanceObject(Integer num, Class<T> t, Map<String, Object> map) throws SQLException {
T object = null;
Field[] fields = null;
// Constructor<?> cons = null;
// 无参构造函数的赋值
try {
// cons = getConstructor(t, fields);
fields = t.getDeclaredFields();
if (num == 0) {
object = t.newInstance();
for (int i = 0; i < fields.length; i++) {
String fieldName = fields[i].getName();// .toUpperCase();
fields[i].setAccessible(true);
fields[i].set(object, getObj(map.get(fieldName)));
}
} else if (num == 1) {
// 有参构造函数的赋值
// object = cons.newInstance(params);
}
return object;
} catch (Exception e) {
e.printStackTrace();
throw new SQLException("为对象赋值时发生错误");
}
}
/**
* Instance object.
*
* @param <T> the generic type
* @param t the t
* @param map the map
* @return the t
* @throws SQLException the SQL exception
*/
private <T> T instanceObject(Class<T> t, Map<String, Object> map) throws SQLException {
T object = null;
Field[] fields = null;
try {
fields = t.getDeclaredFields();
object = t.newInstance();
for (int i = 0; i < fields.length; i++) {
String fieldName = fields[i].getName();
fields[i].setAccessible(true);
fields[i].set(object, getObj(map.get(fieldName), fields[i].getType()));
}
} catch (Exception e) {
throw new SQLException("为对象赋值时发生错误" + e.getMessage());
}
return object;
}
/**
* Gets the obj.
*
* @param value the value
* @param type the type
* @return the obj
*/
private Object getObj(Object value, Class<?> type) {
if (value != null && BIGDECIMAL_CLASS_NAME.equals(value.getClass())) {
BigDecimal bigDecimal = (BigDecimal) value;
if (type == byte.class) {
return bigDecimal.byteValue();
} else if (type == Byte.class) {
return bigDecimal.byteValue();
} else if (type == short.class) {
return bigDecimal.shortValue();
} else if (type == Short.class) {
return bigDecimal.shortValue();
} else if (type == int.class) {
return bigDecimal.intValue();
} else if (type == Integer.class) {
return bigDecimal.intValue();
} else if (type == long.class) {
return bigDecimal.longValue();
} else if (type == Long.class) {
return bigDecimal.longValue();
} else if (type == float.class) {
return bigDecimal.floatValue();
} else if (type == Float.class) {
return bigDecimal.floatValue();
} else if (type == double.class) {
return bigDecimal.doubleValue();
} else if (type == Double.class) {
return bigDecimal.doubleValue();
}
}
return value;
}
/**
* 获取查询的结果集以List<?>形式返回.
*
* @param <T> the generic type
* @param t the t
* @param sql the sql
* @param params the params
* @return List<?> 查询结果集
* @throws SQLException the SQL exception
*/
public <T> List<T> queryList(Class<T> t, String sql, Object... params) throws SQLException {
// new 一个List
List<T> list = new ArrayList<T>();
// 查询数据库中的数据然后封装成
try {
createSessionQuery(sql, params);
@SuppressWarnings("unchecked")
List<Map<String, Object>> list2 = (List<Map<String, Object>>) list();
for (Map<String, Object> map : list2) {
list.add(this.instanceObject(t, map));
}
} finally {
this.simpleClose();
}
return list;
}
/**
* 获取查询的结果集以List<?>形式返回.
*
* @param clazz 要映射的实体类的Class类
* @param sql the sql
* @param params the params
* @return List<?> 查询结果集
* @throws SQLException the SQL exception
*/
public List<?> queryList(Class<?> clazz, String sql, Map<String, Object> params) throws SQLException {
// new 一个List
List<Object> list = new ArrayList<Object>();
// 查询数据库中的数据然后封装成
try {
createSessionQuery(sql, params);
Integer rs_col = rs.getMetaData().getColumnCount();
String[] paramName = new String[rs_col];
for (int i = 0; i < rs_col; i++) {
// 是选择的字段另取得名称
paramName[i] = rs.getMetaData().getColumnLabel(i + 1);
}
while (rs.next()) {
Map<String, Object> map = new HashMap<String, Object>();
for (int i = 0; i < paramName.length; i++) {
map.put(paramName[i].toUpperCase().replace("_", ""), rs.getObject(paramName[i]));
}
Object objentity = this.instanceObject(clazz, map);
list.add(objentity);
}
} finally {
this.simpleClose();
}
return list;
}
/**
* 获取查询的结果集以List<?>形式返回.
*
* @param sql the sql
* @param translate 通过自定义的赋值方式
* @param params the params
* @return List<?> 查询结果集
* @throws SQLException the SQL exception
*/
public List<?> queryList(String sql, ResultTranslate translate, Object... params) throws SQLException {
// new 一个List
List<Object> list = new ArrayList<Object>();
// 查询数据库中的数据然后封装成
try {
createSessionQuery(sql, params);
while (rs.next()) {
list.add(translate.getObject(rs));
}
} finally {
this.simpleClose();
}
return list;
}
/**
* 获取查询的结果集以List<?>形式返回.
*
* @param sql the sql
* @param translate 通过自定义的赋值方式
* @param params the params
* @return List<?> 查询结果集
* @throws SQLException the SQL exception
*/
public List<?> queryList(String sql, ResultTranslate translate, Map<String, Object> params) throws SQLException {
// new 一个List
List<Object> list = new ArrayList<Object>();
// 查询数据库中的数据然后封装成
try {
createSessionQuery(sql, params);
while (rs.next()) {
list.add(translate.getObject(rs));
}
} finally {
this.simpleClose();
}
return list;
}
/**
* 获取查询的结果集以List<Map<String,Object>>形式返回.
*
* @param sql the sql
* @param params the params
* @return List<Map<String,Object>> 查询结果集
* @throws SQLException the SQL exception
*/
public List<Map<String, Object>> queryList(String sql, Object... params) throws SQLException {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
try {
createSessionQuery(sql, params);
String[] paramName = new String[getColsNo()];
for (int i = 0; i < getColsNo(); i++) {
// 是选择的字段另取得名称
paramName[i] = rs.getMetaData().getColumnLabel(i + 1);
}
/**
* String [] fieldsName = new String[rs_col]; for (int i = 0; i < rs_col; i++) { //是 字段的名称 fieldsName[i] = rs.getMetaData().getColumnName(i+1); }
*/
while (rs.next()) {
Map<String, Object> map = new HashMap<String, Object>();
for (int i = 0; i < getColsNo(); i++) {
map.put(paramName[i], rs.getObject(paramName[i]));
}
list.add(map);
}
} finally {
this.simpleClose();
}
return list;
}
/**
* 获取查询的结果集以List<Map<String,Object>>形式返回.
*
* @param sql the sql
* @param params the params
* @return List<Map<String,Object>> 查询结果集
* @throws SQLException the SQL exception
*/
public List<Map<String, Object>> queryList(String sql, Map<String, Object> params) throws SQLException {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
try {
createSessionQuery(sql, params);
getResultSet();
Integer rs_col = rs.getMetaData().getColumnCount();
String[] paramName = new String[rs_col];
for (int i = 0; i < rs_col; i++) {
// 是选择的字段另取得名称
paramName[i] = rs.getMetaData().getColumnLabel(i + 1);
}
/**
* String [] fieldsName = new String[rs_col]; for (int i = 0; i < rs_col; i++) { //是 字段的名称 fieldsName[i] = rs.getMetaData().getColumnName(i+1); }
*/
while (rs.next()) {
Map<String, Object> map = new HashMap<String, Object>();
for (int i = 0; i < rs_col; i++) {
map.put(paramName[i], rs.getObject(paramName[i]));
}
list.add(map);
}
} finally {
this.simpleClose();
}
return list;
}
/**
* 通过反射技术获取单个对象的数据记录以对象的形式返回.
*
* @param clazz the clazz
* @param sql the sql
* @param params the params
* @return 单个对象
* @throws SQLException the SQL exception
*/
public Object querySingal(Class<?> clazz, String sql, Object... params) throws SQLException {
Object object = null;
try {
createSessionQuery(sql, params);
Integer rs_col = rs.getMetaData().getColumnCount();
String[] paramName = new String[rs_col];
for (int i = 0; i < rs_col; i++) {
// 是选择的字段另取得名称
paramName[i] = rs.getMetaData().getColumnLabel(i + 1);
}
if (rs.next()) {
Map<String, Object> map = new HashMap<String, Object>();
for (int i = 0; i < rs_col; i++) {
map.put(paramName[i].toUpperCase().replace("_", ""), rs.getObject(paramName[i]));
}
return this.instanceObject(clazz, map);
}
} finally {
this.simpleClose();
}
return object;
}
/**
* 通过反射技术获取单个对象的数据记录以对象的形式返回.
*
* @param clazz the clazz
* @param sql the sql
* @param params the params
* @return 单个对象
* @throws SQLException the SQL exception
*/
public Object querySingal(Class<?> clazz, String sql, Map<String, Object> params) throws SQLException {
Object object = null;
try {
createSessionQuery(sql, params);
Integer rs_col = rs.getMetaData().getColumnCount();
String[] paramName = new String[rs_col];
for (int i = 0; i < rs_col; i++) {
// 是选择的字段另取得名称
paramName[i] = rs.getMetaData().getColumnLabel(i + 1);
}
if (rs.next()) {
Map<String, Object> map = new HashMap<String, Object>();
for (int i = 0; i < rs_col; i++) {
map.put(paramName[i].toUpperCase().replace("_", ""), rs.getObject(paramName[i]));
}
return this.instanceObject(clazz, map);
}
} finally {
this.simpleClose();
}
return object;
}
/**
* 获取单个对象的数据记录以对象的形式返回.
*
* @param sql the sql
* @param translate 自定义赋值
* @param params the params
* @return 单个对象
* @throws SQLException the SQL exception
*/
public Object querySingal(String sql, ResultTranslate translate, Object... params) throws SQLException {
Object object = null;
try {
createSessionQuery(sql, params);
if (rs.next()) {
return translate.getObject(rs);
}
} finally {
this.simpleClose();
}
return object;
}
/**
* 获取单个对象的数据记录以对象的形式返回.
*
* @param sql the sql
* @param translate 自定义赋值
* @param params the params
* @return 单个对象
* @throws SQLException the SQL exception
*/
public Object querySingal(String sql, ResultTranslate translate, Map<String, Object> params) throws SQLException {
Object object = null;
try {
createSessionQuery(sql, params);
if (rs.next()) {
return translate.getObject(rs);
}
} finally {
this.simpleClose();
}
return object;
}
/**
* 获取单条数据记录一Map的形式返回.
*
* @param sql the sql
* @param params the params
* @return 单条数据记录
* @throws SQLException the SQL exception
*/
public Map<String, Object> querySingal(String sql, Object... params) throws SQLException {
Map<String, Object> map = new HashMap<String, Object>();
try {
createSessionQuery(sql, params);
Integer rs_col = rs.getMetaData().getColumnCount();
String[] paramName = new String[rs_col];
for (int i = 0; i < rs_col; i++) {
// 是选择的字段另取得名称
paramName[i] = rs.getMetaData().getColumnLabel(i + 1);
}
if (rs.next()) {
Object[] orm = new Object[rs_col];
for (int i = 0; i < orm.length; i++) {
map.put(paramName[i], rs.getObject(paramName[i]));
}
return map;
}
} finally {
this.simpleClose();
}
return map;
}
/**
* 获取单条数据记录一Map的形式返回.
*
* @param sql the sql
* @param params the params
* @return 单条数据记录
* @throws SQLException the SQL exception
*/
public Map<String, Object> querySingal(String sql, Map<String, Object> params) throws SQLException {
Map<String, Object> map = new HashMap<String, Object>();
try {
createSessionQuery(sql, params);
String[] paramName = getAlias();
int rs_col = paramName.length;
if (rs.next()) {
Object[] orm = new Object[rs_col];
for (int i = 0; i < orm.length; i++) {
map.put(paramName[i], rs.getObject(paramName[i]));
}
return map;
}
} finally {
if (rs != null)
rs.close();
}
return map;
}
/* (non-Javadoc)
* @see com.wch.jdbc.Session#createSessionQuery(java.lang.String, java.lang.Object[])
*/
public Session createSessionQuery(String sql, Object... params) throws SQLException {
ps = getStatement(sql, params);
return this;
}
/**
* @param sql
* @param params
* @throws SQLException
*/
private PreparedStatement getStatement(String sql, Object... params) throws SQLException {
PreparedStatement preparedStatement = null;
if (getConnection().isClosed()) {
throw new SQLException("connection is closed");
}
if (params.length == 0) {
preparedStatement = getConnection().prepareStatement(sql);
} else if (params[0] instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) params[0];
Matcher matcher = pattern.matcher(sql);
List<Object> list = new ArrayList<Object>();
while (matcher.find()) {
String temp = matcher.group();
Object value = map.get(temp.substring(1));
sql = sql.replace(temp, "?");
if (value == null) {
throw new SQLException("你还没有设置 " + temp.substring(1) + " 的值!");
}
list.add(value);
}
preparedStatement = getConnection().prepareStatement(sql);
Object[] mapObjects = list.toArray(new Object[1]);
for (int i = 0; i < mapObjects.length; i++) {
preparedStatement.setObject(i + 1, mapObjects[i]);
}
} else if (params instanceof Object[]) {
ps = getConnection().prepareStatement(sql);
Object[] objects = (Object[]) params;
for (int i = 0; i < objects.length; i++) {
ps.setObject(i + 1, objects[i]);
}
} else {
throw new SQLException("不支持此类型的参数!");
}
return preparedStatement;
}
/**
* 创建一个查询的Query.
*
* @param sql the sql
* @param params the params
* @return the query
* @throws SQLException the SQL exception
*/
public Query createQuery(String sql, Object... params) throws SQLException {
printSql(sql);
return new SQLQuery(getStatement(sql, params), sql);
}
}
| [
"[email protected]"
] | |
eed6ead4ba4419b851bea143794f7b7c92e6fb13 | 937ae320ee4474b49da921c31ac9ca91a83c8b73 | /Networking./app/src/test/java/com/example/adwitiyasingh/networking/ExampleUnitTest.java | f5f86d09521711a9ddae93f19d1bed146176508f | [] | no_license | Adwitiya-Singh/Android | f5767ec41629c11faa778d8ed54a8309a65bc06a | 7163b469279d001bad52c3b88b103de2f57bd021 | refs/heads/master | 2021-08-10T22:10:57.486824 | 2017-11-13T01:26:49 | 2017-11-13T01:26:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 414 | java | package com.example.adwitiyasingh.networking;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
afed8fd3fee39d472c77028dc4f6af19ee747f61 | 15cb86c70c12beedccb7cf2f185ee5a25b316ce4 | /src/main/java/com/cr/rental/customer/Customer.java | 5e441708af75a2aef707c40af289467dff29732b | [] | no_license | shekharDivyanshu/cr-car-rental-system | 2ef83e4e263afad246294f049c5ba5a164648408 | 7f378e9763ef42aa9e0032fdc88a329fbd7746c9 | refs/heads/master | 2020-03-28T23:19:02.678851 | 2018-09-18T13:06:40 | 2018-09-18T13:06:40 | 149,285,979 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 934 | java | /**
*
*/
package com.cr.rental.customer;
/**
*
* @author dshekhar
*
*/
public class Customer {
private String firstName;
private String lastName;
private String dateOfBirth;
public Customer(String firstName, String lastName, String dateOfBirth) {
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
@Override
public String toString() {
return "Customer [firstName=" + firstName + ", lastName=" + lastName + ", dateOfBirth=" + dateOfBirth + "]";
}
}
| [
"[email protected]"
] | |
4bd7cce77e8eef558f75da6673d3dc3a7260c2dd | 37a35ef17577a5bb92b6e45d8d70fda74a9f99b9 | /LoginPractice/src/main/java/mx/utng/practice/model/UserPorfile.java | 113fab8c5b143e109ab268288924329b8b41fe12 | [] | no_license | maribelmmc/Unidad-5 | a3082f14550816f0a76dafa70ede4e6d93ba8ed3 | c4d0bc68805841d17a2f806837a18d60589525b0 | refs/heads/master | 2021-01-12T00:14:26.387397 | 2017-01-12T00:54:24 | 2017-01-12T00:54:24 | 78,693,857 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,086 | java | package mx.utng.practice.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity @Table (name="userPorfile")
public class UserPorfile {
@Id @GeneratedValue
private Long porfileId;
private String userId;
private String propertyDefinitionId;
private String propertyValue;
private String propertyText;
private String visivility;
private String lastUpdateDate;
public UserPorfile(String userId, String propertyDefinitionId, String propertyValue, String propertyText, String visivility, String lastUpdateDate) {
super();
this.userId = userId;
this.propertyDefinitionId = propertyDefinitionId;
this.propertyValue= propertyValue;
this.propertyText= propertyText;
this.visivility= visivility;
this.lastUpdateDate= lastUpdateDate;
}
public UserPorfile() {
this("","","","","","");
}
public Long getPorfileId() {
return porfileId;
}
public void setPorfileId(Long porfileId) {
this.porfileId = porfileId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPropertyDefinitionId() {
return propertyDefinitionId;
}
public void setPropertyDefinitionId(String propertyDefinitionId) {
this.propertyDefinitionId = propertyDefinitionId;
}
public String getPropertyValue() {
return propertyValue;
}
public void setPropertyValue(String propertyValue) {
this.propertyValue = propertyValue;
}
public String getPropertyText() {
return propertyText;
}
public void setPropertyText(String propertyText) {
this.propertyText = propertyText;
}
public String getVisivility() {
return visivility;
}
public void setVisivility(String visivility) {
this.visivility = visivility;
}
public String getLastUpdateDate() {
return lastUpdateDate;
}
public void setLastUpdateDate(String lastUpdateDate) {
this.lastUpdateDate = lastUpdateDate;
}
}
| [
"[email protected]"
] | |
9eab0f53b6b2526fe7bddbb9e0d32fac50db9539 | 726a28dcac2f8f7aceb5927497ac03a251ebe3d2 | /Builder/OrderBuilder.java | 9c86fdf3b1807172859fd3ee04c34134e5b11ce2 | [] | no_license | manjirimanikrao/collect | ce86611d317725843f41dcbfc6b225d4c1b38de0 | adf356130c766b9bf3d56de5cfb28c0be0a9c0a2 | refs/heads/master | 2020-06-14T15:51:18.529464 | 2019-08-09T09:19:30 | 2019-08-09T09:19:30 | 195,047,189 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,552 | java |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
* @author Ashwani
*/
public class OrderBuilder {
public OrderedItems preparePizza() throws IOException{
OrderedItems itemsOrder=new OrderedItems();
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
System.out.println(" Enter the choice of Pizza ");
System.out.println("============================");
System.out.println(" 1. Veg-Pizza ");
System.out.println(" 2. Non-Veg Pizza ");
System.out.println(" 3. Exit ");
System.out.println("============================");
int pizzaandcolddrinkchoice=Integer.parseInt(br.readLine());
switch(pizzaandcolddrinkchoice)
{
case 1:{
System.out.println("You ordered Veg Pizza");
System.out.println("\n\n");
System.out.println(" Enter the types of Veg-Pizza ");
System.out.println("------------------------------");
System.out.println(" 1.Cheeze Pizza ");
System.out.println(" 2.Onion Pizza ");
System.out.println(" 3.Masala Pizza ");
System.out.println(" 4.Exit ");
System.out.println("------------------------------");
int vegpizzachoice=Integer.parseInt(br.readLine());
switch(vegpizzachoice)
{
case 1:
{
System.out.println("You ordered Cheeze Pizza");
System.out.println("Enter the cheeze pizza size");
System.out.println("------------------------------------");
System.out.println(" 1. Small Cheeze Pizza ");
System.out.println(" 2. Medium Cheeze Pizza ");
System.out.println(" 3. Large Cheeze Pizza ");
System.out.println(" 4. Extra-Large Cheeze Pizza ");
System.out.println("------------------------------------");
int cheezepizzasize=Integer.parseInt(br.readLine());
switch(cheezepizzasize)
{
case 1:
itemsOrder.addItems(new SmallCheezePizza());
break;
case 2:
itemsOrder.addItems(new MediumCheezePizza());
break;
case 3:
itemsOrder.addItems(new LargeCheezePizza());
break;
case 4:
itemsOrder.addItems(new ExtraLargeCheezePizza());
break;
}
}
break;
case 2:
{
System.out.println("You ordered Onion Pizza");
System.out.println("Enter the Onion pizza size");
System.out.println("----------------------------------");
System.out.println(" 1. Small Onion Pizza ");
System.out.println(" 2. Medium Onion Pizza ");
System.out.println(" 3. Large Onion Pizza ");
System.out.println(" 4. Extra-Large Onion Pizza ");
System.out.println("----------------------------------");
int onionpizzasize=Integer.parseInt(br.readLine());
switch(onionpizzasize)
{
case 1:
itemsOrder.addItems(new SmallOnionPizza());
break;
case 2:
itemsOrder.addItems(new MediumOnionPizza());
break;
case 3:
itemsOrder.addItems(new LargeOnionPizza());
break;
case 4:
itemsOrder.addItems(new ExtraLargeOnionPizza());
break;
}
}
break;
case 3:
{
System.out.println("You ordered Masala Pizza");
System.out.println("Enter the Masala pizza size");
System.out.println("------------------------------------");
System.out.println(" 1. Small Masala Pizza ");
System.out.println(" 2. Medium Masala Pizza ");
System.out.println(" 3. Large Masala Pizza ");
System.out.println(" 4. Extra-Large Masala Pizza ");
System.out.println("------------------------------------");
int masalapizzasize=Integer.parseInt(br.readLine());
switch(masalapizzasize)
{
case 1:
itemsOrder.addItems(new SmallMasalaPizza());
break;
case 2:
itemsOrder.addItems(new MediumMasalaPizza());
break;
case 3:
itemsOrder.addItems(new LargeMasalaPizza());
break;
case 4:
itemsOrder.addItems(new ExtraLargeMasalaPizza());
break;
}
}
break;
}
}
break;// Veg- pizza choice completed.
case 2:
{
System.out.println("You ordered Non-Veg Pizza");
System.out.println("\n\n");
System.out.println("Enter the Non-Veg pizza size");
System.out.println("------------------------------------");
System.out.println(" 1. Small Non-Veg Pizza ");
System.out.println(" 2. Medium Non-Veg Pizza ");
System.out.println(" 3. Large Non-Veg Pizza ");
System.out.println(" 4. Extra-Large Non-Veg Pizza ");
System.out.println("------------------------------------");
int nonvegpizzasize=Integer.parseInt(br.readLine());
switch(nonvegpizzasize)
{
case 1:
itemsOrder.addItems(new SmallNonVegPizza());
break;
case 2:
itemsOrder.addItems(new MediumNonVegPizza());
break;
case 3:
itemsOrder.addItems(new LargeNonVegPizza());
break;
case 4:
itemsOrder.addItems(new ExtraLargeNonVegPizza());
break;
}
}
break;
default:
{
break;
}
}//end of main Switch
System.out.println(" Enter the choice of ColdDrink ");
System.out.println("============================");
System.out.println(" 1. Pepsi ");
System.out.println(" 2. Coke ");
System.out.println(" 3. Exit ");
System.out.println("============================");
int coldDrink=Integer.parseInt(br.readLine());
switch (coldDrink)
{
case 1:
{
System.out.println("You ordered Pepsi ");
System.out.println("Enter the Pepsi Size ");
System.out.println("------------------------");
System.out.println(" 1. Small Pepsi ");
System.out.println(" 2. Medium Pepsi ");
System.out.println(" 3. Large Pepsi ");
System.out.println("------------------------");
int pepsisize=Integer.parseInt(br.readLine());
switch(pepsisize)
{
case 1:
itemsOrder.addItems(new SmallPepsi());
break;
case 2:
itemsOrder.addItems(new MediumPepsi());
break;
case 3:
itemsOrder.addItems(new LargePepsi());
break;
}
}
break;
case 2:
{
System.out.println("You ordered Coke");
System.out.println("Enter the Coke Size");
System.out.println("------------------------");
System.out.println(" 1. Small Coke ");
System.out.println(" 2. Medium Coke ");
System.out.println(" 3. Large Coke ");
System.out.println(" 4. Extra-Large Coke ");
System.out.println("------------------------");
int cokesize=Integer.parseInt(br.readLine());
switch(cokesize)
{
case 1:
itemsOrder.addItems(new SmallCoke());
break;
case 2:
itemsOrder.addItems(new MediumCoke());
break;
case 3:
itemsOrder.addItems(new LargeCoke());
break;
}
}
break;
default:
{
break;
}
}//End of the Cold-Drink switch
return itemsOrder;
} //End of the preparePizza() method
}//End of the OrderBuilder class.
| [
"[email protected]"
] | |
d825747e5ee7af385a0d92818509ef4855c27c0d | ee4cfa2130e2c6e5ae9e16fae7ef26855ebe3e16 | /src/main/java/web/ManterIngredientes.java | a9422b42c495c7e6473fb6bba04ddb478d1a692b | [] | no_license | zecarlosalmeida/sce | d3633ca62a2d280e00d14f3f674f1169d931deb5 | 9a9a1d159e85f6a7d4faca27163041a0c462d597 | refs/heads/master | 2021-07-07T06:55:13.569680 | 2017-10-04T16:22:00 | 2017-10-04T16:22:00 | 105,790,043 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 951 | java | package web;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dominio.Ingrediente;
import servico.IngredienteServico;
@WebServlet("/ingrediente/listar")
public class ManterIngredientes extends HttpServlet {
private static final long serialVersionUID = 1L;
private static String DESTINO = "/ingrediente/listar.jsp";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
IngredienteServico in = new IngredienteServico();
List<Ingrediente> ingrediente = in.buscarTodosOrdenadosPorNome();
request.setAttribute("ingrediente", ingrediente);
request.getRequestDispatcher(DESTINO).forward(request,response);
}
} | [
"[email protected]"
] | |
b0fe2c67dddd98c5e61ab33018455e3db21d0b1b | b1516ff1890edab3f4f7db376d9cbdf4e9f9d74e | /hgs3896/Prototype/app/src/test/java/hgs/app/prototype/ExampleUnitTest.java | 0fd6ecf3f0d9515b32c33c2c998123f8e6bfb7b7 | [] | no_license | hgs3896/EventPlanner | ca37625118820e5ebbd3f5b6cbf581751e58d35e | c48f9a11554ea8d8891677bc12ed3d0149b29a85 | refs/heads/master | 2020-06-10T19:17:33.020197 | 2019-07-06T12:28:12 | 2019-07-06T12:28:12 | 193,719,204 | 0 | 0 | null | 2019-06-25T14:02:57 | 2019-06-25T14:02:57 | null | UTF-8 | Java | false | false | 378 | java | package hgs.app.prototype;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
d6ff07b7904e804b0cfe01966694445d62fdbbb9 | 4bda683297b9722a66dea07806339c335c143a85 | /app/src/main/java/net/lzzy/practicesonline/activities/activities/QuestionActivity.java | 7f0416f56f98e6396269c522f7721ef1a944b078 | [] | no_license | zhuoxiaofei/PracticesOnline | 712da97b3cea96a5f5c17f85855f674a67673724 | 4062ad4c88c8bad1b271233c5fcb23dd616e247a | refs/heads/master | 2020-05-07T11:43:05.365635 | 2019-05-22T04:08:07 | 2019-05-22T04:08:07 | 180,472,975 | 0 | 0 | null | 2019-04-10T00:55:20 | 2019-04-10T00:55:19 | null | UTF-8 | Java | false | false | 12,178 | java | package net.lzzy.practicesonline.activities.activities;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.os.Parcelable;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;
import net.lzzy.practicesonline.R;
import net.lzzy.practicesonline.activities.fragments.QuestionFragment;
import net.lzzy.practicesonline.activities.models.FavoriteFactory;
import net.lzzy.practicesonline.activities.models.Question;
import net.lzzy.practicesonline.activities.models.QuestionFactory;
import net.lzzy.practicesonline.activities.models.UserCookies;
import net.lzzy.practicesonline.activities.models.view.PracticeReult;
import net.lzzy.practicesonline.activities.models.view.QuestionResult;
import net.lzzy.practicesonline.activities.network.PracticeService;
import net.lzzy.practicesonline.activities.utils.AbstractStaticHandler;
import net.lzzy.practicesonline.activities.utils.AppUtils;
import net.lzzy.practicesonline.activities.utils.ViewUtils;
import org.json.JSONException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static net.lzzy.practicesonline.activities.activities.ResultActivity.POSITION;
import static net.lzzy.practicesonline.activities.activities.ResultActivity.QUESTION;
import static net.lzzy.practicesonline.activities.activities.ResultActivity.RESULT_CODE;
import static net.lzzy.practicesonline.activities.activities.ResultActivity.RESULT_CODE_TWO;
/**
* @author Administrator
*/
public class QuestionActivity extends AppCompatActivity {
private static final int WHAT_PRACTICE_DONE = 0;
private static final int WHAT_EXCEPTION = 1;
public static final int EXTRA_REQUEST_CODE = 0;
public static final int EXTRA_RESULT_CODE = 5;
private String practiceId;
private int apiId;
private List<Question> questions;
private TextView tvView;
private TextView tvCommit;
private ViewPager pager;
private boolean isCommitted = false;
private TextView tvHint;
private int pos;
private LinearLayout container;
private View[] dost;
private DownloadHandler handler = new DownloadHandler(this);
public static final String EXTRA_PRACTICE_ID = "practiceId";
public static final String EXTRA_RESULTS = "results";
private FragmentStatePagerAdapter adapter;
/**
* 自定义线程 返回数据的方法
*/
private static class DownloadHandler extends AbstractStaticHandler<QuestionActivity> {
DownloadHandler(QuestionActivity context) {
super(context);
}
@Override
public void handleMessage(Message msg, QuestionActivity questionActivity) {
switch (msg.what) {
case WHAT_PRACTICE_DONE:
ViewUtils.dismissProgress();
questionActivity.isCommitted = true;
Toast.makeText(questionActivity, "提交成功", Toast.LENGTH_SHORT).show();
UserCookies.getInstance().commitPractice(questionActivity.practiceId);
questionActivity.redirect();
break;
case WHAT_EXCEPTION:
Toast.makeText(questionActivity, "提交失败,请重试", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_question);
AppUtils.addActivity(this);
retrieveDate();
initViews();
initDots();
setListteners();
pos = UserCookies.getInstance().getCurrentQuestion(practiceId);
pager.setCurrentItem(pos);
refreshDots(pos);
UserCookies.getInstance().updateReadCount(questions.get(pos).getId().toString());
}
private void setListteners() {
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
refreshDots(position);
UserCookies.getInstance().updateCurrentQuestion(practiceId, position);
UserCookies.getInstance().updateReadCount(questions.get(position).getId().toString());
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
tvCommit.setOnClickListener(v -> commitPractice());
tvView.setOnClickListener(v -> redirect());
}
/**
* 查看成绩
*/
private void redirect() {
List<QuestionResult> results = UserCookies.getInstance().getResultFromCoolies(questions);
Intent intent = new Intent(this, ResultActivity.class);
intent.putExtra(EXTRA_PRACTICE_ID, practiceId);
intent.putParcelableArrayListExtra(EXTRA_RESULTS, (ArrayList<? extends Parcelable>) results);
startActivityForResult(intent, EXTRA_REQUEST_CODE);
}
/**
* 返回处理
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == EXTRA_REQUEST_CODE && resultCode == RESULT_CODE) {
int position = data.getIntExtra(POSITION, -1);
pager.setCurrentItem(position);
}
//查看收藏
if (requestCode == EXTRA_REQUEST_CODE && resultCode == RESULT_CODE_TWO) {
String result = data.getStringExtra(QUESTION);
if (!result.isEmpty()) {
List<Question> questionList = new ArrayList<>();
FavoriteFactory factory = FavoriteFactory.getInstance();
for (Question q : QuestionFactory.getInstance().getByPractices(result)) {
if (factory.isQuestionStarred(q.getId().toString())) {
questionList.add(q);
}
}
//清空
questions.clear();
//重新加载
questions.addAll(questionList);
initDots();
adapter.notifyDataSetChanged();
if (questions.size() > 0) {
pager.setCurrentItem(0);
refreshDots(0);
}
}
}
}
String info;
/**
* 选择mac地址
*/
private void commitPractice() {
List<QuestionResult> results = UserCookies.getInstance().getResultFromCoolies(questions);
List<String> macs = AppUtils.getMacAddress();
String[] items = new String[macs.size()];
macs.toArray(items);
info = items[0];
new AlertDialog.Builder(this)
.setTitle("选择mac地址")
//单选setSingleChoiceItems,, //多选setMultiChoiceItems
.setSingleChoiceItems(items, 0, (dialog, which) -> info = items[which])
.setNeutralButton("取消", null)
.setPositiveButton("提交", (dialog, which) -> {
PracticeReult result = new PracticeReult(results, apiId, "卓宵飞," + info);
//提交方法
postResult(result);
}).show();
}
private void postResult(PracticeReult result) {
ViewUtils.showProgress(this, "正在提交成绩");
AppUtils.getExecutor().execute(() -> {
try {
int aa = PracticeService.postResult(result);
if (aa >= 200 && aa <= 220) {
handler.sendMessage(handler.obtainMessage(WHAT_PRACTICE_DONE, aa));
}
} catch (IOException | JSONException e) {
e.printStackTrace();
handler.sendMessage(handler.obtainMessage(WHAT_EXCEPTION, e.getMessage()));
}
});
}
private void initDots() {
//region 导航栏
int count = questions.size();
dost = new View[count];
container = findViewById(R.id.activity_question_dots);
container.removeAllViews();
int px = ViewUtils.dp2px(16, this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(px, px);
px = ViewUtils.dp2px(5, this);
params.setMargins(px, px, px, px);
for (int i = 0; i < count; i++) {
TextView tvDot = new TextView(this);
tvDot.setLayoutParams(params);
tvDot.setBackgroundResource(R.drawable.dot_style);
tvDot.setTag(i);
//todo:tvDot添加点击监听
tvDot.setOnClickListener(v -> pager.setCurrentItem((Integer) v.getTag()));
container.addView(tvDot);
dost[i] = tvDot;
}
//endregion
}
private void refreshDots(int pos) {
for (int i = 0; i < dost.length; i++) {
int drawable = i == pos ? R.drawable.dot_fill_style : R.drawable.dot_style;
dost[i].setBackgroundResource(drawable);
}
}
private void initViews() {
tvView = findViewById(R.id.activity_question_tv_view);
tvCommit = findViewById(R.id.activity_question_tv_commit);
tvHint = findViewById(R.id.activity_question_tv_hint);
pager = findViewById(R.id.activity_question_pager);
if (isCommitted) {
tvCommit.setVisibility(View.GONE);
tvView.setVisibility(View.VISIBLE);
tvHint.setVisibility(View.VISIBLE);
} else {
tvCommit.setVisibility(View.VISIBLE);
tvView.setVisibility(View.GONE);
tvHint.setVisibility(View.GONE);
}
adapter = new FragmentStatePagerAdapter(getSupportFragmentManager()) {
int count = 0;
@Override
public Fragment getItem(int position) {
Question question = questions.get(position);
return QuestionFragment.newInstance(question.getId().toString(), position, isCommitted);
}
@Override
public int getCount() {
return questions.size();
}
@Override
public void notifyDataSetChanged() {
count = getCount();
super.notifyDataSetChanged();
}
@Override
public int getItemPosition(@NonNull Object object) {
if (count > 0) {
count--;
return POSITION_NONE;
}
return super.getItemPosition(object);
}
};
pager.setAdapter(adapter);
}
private void retrieveDate() {
practiceId = getIntent().getStringExtra(PracticesActivity.EXTRA_PRACTICE_ID);
apiId = getIntent().getIntExtra(PracticesActivity.EXTRA_API_ID, -1);
questions = QuestionFactory.getInstance().getByPractices(practiceId);
isCommitted = UserCookies.getInstance().isPracticeCommitted(practiceId);
if (apiId < 0 || questions == null || questions.size() == 0) {
Toast.makeText(this, "no questions", Toast.LENGTH_SHORT).show();
finish();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
AppUtils.removeActivity(this);
}
@Override
protected void onResume() {
super.onResume();
AppUtils.setRunning(getLocalClassName());
}
@Override
protected void onStop() {
super.onStop();
AppUtils.setStopped(getLocalClassName());
}
}
| [
"[email protected]"
] | |
5f4adb0ec4213da173f7154251018ab7f64a83f3 | 13d0d6e5b5d4471952d4a7a1c7a4900d5323953c | /tools/feilong-tools-jsoup/src/test/java/com/feilong/tools/jsoup/job51/JobCrawler.java | bf8017c28345e0ccbd2d1e6cee63a748299bf1a1 | [] | no_license | qq122343779/feilong-platform | 3c55867391620eb1283ca95c2aa30ea1bc156b1c | 5824b20445747ecd6e730c5a11c120d4e9f9838a | refs/heads/master | 2021-01-18T11:50:57.837512 | 2014-12-03T06:55:59 | 2014-12-03T06:55:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,734 | java | /*
* Copyright (C) 2008 feilong ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.feilong.tools.jsoup.job51;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.feilong.tools.jsoup.JsoupUtil;
import com.feilong.tools.jsoup.JsoupUtilException;
import com.feilong.tools.jsoup.jinbaowang.entity.Enterprise;
/**
* 网页爬虫---招聘信息.
*
* @author <a href="mailto:[email protected]">金鑫</a>
* @version 1.0 2011-4-12 上午12:40:50
*/
public class JobCrawler{
/** The Constant log. */
private final static Logger log = LoggerFactory.getLogger(JobCrawler.class);
/** 上海所有工作. */
public static String enterprise_ShangHai = "http://search.51job.com/jobsearch/search_result.php?fromJs=1&jobarea=0200&district=0000&funtype=0000&industrytype=00&issuedate=9&providesalary=99&keywordtype=2&curr_page=6&lang=c&stype=2&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=01&lonlat=0,0&radius=-1&ord_field=0&list_type=0&fromType=14";
/**
* Test.
*/
@Test
public void test(){
try{
Document document = Jsoup.connect(enterprise_ShangHai).timeout(3000).get();
//.searchPageNav
Elements elements = document.select(".td2 a");
List<Enterprise> list = new ArrayList<Enterprise>();
for (Element element : elements){
String enterpriseUrl = element.attr("href");
log.info(enterpriseUrl);
Enterprise enterprise = getEnterpriseInfo(enterpriseUrl);
list.add(enterprise);
}
//************************************************************
for (Enterprise enterprise : list){
log.info(enterprise.getName());
log.info(enterprise.getEmail());
log.info(enterprise.getLinkMan());
log.info(enterprise.getTelephone());
}
}catch (IOException e){
log.error(e.getClass().getName(), e);
}
}
/** The url. */
String url = "http://search.51job.com/list/co,c,214871,0000,10,1.html";
/**
* Gets the enterprise info.
*
* @param enterpriseUrl
* the enterprise url
* @return the enterprise info
*/
public Enterprise getEnterpriseInfo(String enterpriseUrl){
//www.51job.com
//zhaopin.com
//chinahr.com
//01job.cn
/*******************************************************************************/
Enterprise enterprise;
try{
String selector_enterpriseName = ".sr_bt";
String selector_email = "p:contains(电子邮箱) a";
String selector_telephone = "p:contains(电):contains(话)";
String selector_linkMan = "p:contains(联):contains(联):contains(人)";
/********************************************************************************/
Document document_enterprise = JsoupUtil.getDocument(enterpriseUrl);
/********************************************************************************/
//enterprise name
Element element_enterpriseName = document_enterprise.select(selector_enterpriseName).first();
//email
Element element_email = document_enterprise.select(selector_email).first();
//电话
Element element_telephone = document_enterprise.select(selector_telephone).first();
//联系人
Element element_linkMan = document_enterprise.select(selector_linkMan).first();
enterprise = new Enterprise();
enterprise.setName(element_enterpriseName.ownText().replace("?", ""));
enterprise.setEmail(element_email == null ? null : element_email.html());
enterprise.setLinkMan(element_telephone == null ? null : element_telephone.html());
enterprise.setTelephone(element_linkMan == null ? null : element_linkMan.html());
return enterprise;
}catch (JsoupUtilException e){
log.error(e.getClass().getName(), e);
}
return null;
//**********************************************************
}
// @Test
// @Ignore
/**
* Gets the enterprise info.
*
*/
public void testGetEnterpriseInfo(){
getEnterpriseInfo(url);
}
}
| [
"[email protected]"
] | |
54858a33727f0864986ddd80554e60eedcd3e292 | 8f623186f6728aeb17e50e1ef1d0afbb35bc95f0 | /src/org/launchcode/l_enumerations_autoboxing_and_annotations/Meta3.java | acff5b9023eef70a56edf8508e8a977ff44516b0 | [] | no_license | skbandari/corejava | ec1c174910b89dc8242347656100736b4787d4b3 | 85edb120ae0f554432f585683901d47d8b160a2c | refs/heads/master | 2021-07-13T00:41:47.959767 | 2019-03-12T20:27:01 | 2019-03-12T20:27:01 | 148,991,252 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 810 | java | package org.launchcode.l_enumerations_autoboxing_and_annotations;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
@Retention(RetentionPolicy.RUNTIME)
@interface
Myannotation3 {
String str() default "teat";
boolean bool() default true;
}
public class Meta3 {
@Myannotation3
public static void mymeth4() throws Exception{
Class<?> c = Meta3.class;
Method m = c.getMethod("mymeth4");
Annotation a[] = m.getAnnotations();
for(Annotation b : a)
System.out.println(b);
}
public static void main(String[] args) {
try{
mymeth4();
} catch(Exception e) {
System.out.println(e);
}
}
}
| [
"[email protected]"
] | |
c2f5afee318a326b713935112f9d2e1ae8f5228b | 69112e903769b48f334d654d920bb74c21a67546 | /processor/src/main/java/com/workday/autoparse/json/codegen/JsonObjectParserTableGenerator.java | c40477fb5758cd26b3cab1425dbddf7e815647e6 | [
"MIT"
] | permissive | fakegithubacct/autoparse-json | 62128a655ed1e55b0437326e8b6cacd4c9e3101c | 76dc6e52548dfc243853ce6eab3e2d8d4e1af1e1 | refs/heads/master | 2020-04-11T04:50:57.644506 | 2017-11-06T21:48:16 | 2017-11-06T21:48:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,865 | java | /*
* Copyright 2016 Workday, Inc.
*
* This software is available under the MIT license.
* Please see the LICENSE.txt file in this project.
*/
package com.workday.autoparse.json.codegen;
import com.squareup.javawriter.JavaWriter;
import com.workday.autoparse.json.annotations.JsonObject;
import com.workday.autoparse.json.context.GeneratedClassNames;
import com.workday.autoparse.json.context.JsonParserSettingsBuilder;
import com.workday.autoparse.json.parser.JsonObjectParser;
import com.workday.autoparse.json.parser.JsonObjectParserTable;
import com.workday.meta.AnnotationUtils;
import com.workday.meta.MetaTypeNames;
import com.workday.meta.Modifiers;
import java.io.IOException;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import javax.tools.JavaFileObject;
/**
* Generates an implementation of {@link JsonObjectParserTable}.
*
* @author nathan.taylor
* @since 2014-10-09
*/
class JsonObjectParserTableGenerator {
private static final String MAP_TYPE =
String.format("Map<String, %s<?>>", JsonObjectParser.class.getSimpleName());
private final ProcessingEnvironment processingEnv;
private final Map<String, TypeElement> discrimValueToClassRequiringGeneratedParserMap;
private final Map<String, TypeElement> discrimValueToClassWithCustomParserMap;
private final PackageElement packageElement;
public JsonObjectParserTableGenerator(ProcessingEnvironment processingEnv,
Map<String, TypeElement>
discrimValueToClassRequiringGeneratedParserMap,
Map<String, TypeElement>
discrimValueToClassWithCustomParserMap,
PackageElement packageElement) {
this.processingEnv = processingEnv;
this.discrimValueToClassRequiringGeneratedParserMap =
discrimValueToClassRequiringGeneratedParserMap;
this.discrimValueToClassWithCustomParserMap = discrimValueToClassWithCustomParserMap;
this.packageElement = packageElement;
}
public void generateParserMap() throws IOException {
String packageName = packageElement != null
? packageElement.getQualifiedName().toString()
: JsonParserSettingsBuilder.DEFAULT_OBJECT_PARSER_PACKAGE;
String qualifiedClassName = GeneratedClassNames.getQualifiedName(packageName,
GeneratedClassNames
.CLASS_JSON_OBJECT_PARSER_TABLE);
JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile(qualifiedClassName);
JavaWriter writer = new JavaWriter(sourceFile.openWriter());
writer.emitPackage(packageName);
writer.emitEmptyLine();
writer.emitImports(getImports());
writer.emitEmptyLine();
writer.beginType(GeneratedClassNames.CLASS_JSON_OBJECT_PARSER_TABLE, "class",
EnumSet.of(Modifier.PUBLIC, Modifier.FINAL), null,
JsonObjectParserTable.class.getCanonicalName());
writer.emitEmptyLine();
writeMapField(writer);
writer.emitEmptyLine();
writeGetter(writer);
writer.emitEmptyLine();
writeKeySet(writer);
writer.endType();
writer.close();
}
private void writeKeySet(JavaWriter writer) throws IOException {
writer.emitAnnotation(Override.class);
writer.beginMethod(JavaWriter.type(Set.class, "String"), "keySet", Modifiers.PUBLIC);
writer.emitStatement("return MAP.keySet()");
writer.endMethod();
}
private Collection<String> getImports() {
Set<String> results = new HashSet<>();
results.add(HashMap.class.getCanonicalName());
results.add(Map.class.getCanonicalName());
results.add(JsonObjectParser.class.getCanonicalName());
if (packageElement != null) {
results.add(JsonObjectParserTable.class.getCanonicalName());
}
return results;
}
private void writeMapField(JavaWriter writer) throws IOException {
writer.emitField(MAP_TYPE, "MAP", Modifiers.PRIVATE_CONSTANT,
String.format("new HashMap<String, %s<?>>()",
JsonObjectParser.class.getSimpleName()));
writer.beginInitializer(true);
for (Map.Entry<String, TypeElement> entry :
discrimValueToClassRequiringGeneratedParserMap.entrySet()) {
String discriminationValue = entry.getKey();
String parserQualifiedName = MetaTypeNames.constructTypeName(entry.getValue(),
GeneratedClassNames
.PARSER_SUFFIX);
writer.emitStatement("MAP.put(\"%s\", %s.INSTANCE)",
discriminationValue,
parserQualifiedName);
}
for (final Map.Entry<String, TypeElement> entry : discrimValueToClassWithCustomParserMap
.entrySet()) {
final TypeElement classElement = entry.getValue();
TypeMirror parserClassMirror = AnnotationUtils.getClassTypeMirrorFromAnnotationValue(
new AnnotationUtils.Getter() {
@Override
public void get() {
classElement.getAnnotation(JsonObject.class).parser();
}
});
String customParserCanonicalName = parserClassMirror.toString();
writer.emitStatement("MAP.put(\"%s\", %s.INSTANCE)",
entry.getKey(),
customParserCanonicalName);
}
writer.endInitializer();
}
private void writeGetter(JavaWriter writer) throws IOException {
writer.emitAnnotation(Override.class);
writer.beginMethod(JavaWriter.type(JsonObjectParser.class, "?"),
"get",
Modifiers.PUBLIC,
"String",
"discriminationValue");
writer.emitStatement("return MAP.get(discriminationValue)");
writer.endMethod();
}
}
| [
"[email protected]"
] | |
3203838b74f5859d65d3b699301e55a62bba5f26 | 6a2569b80a8cf293937e358e1114fa9c760771b0 | /src/org/coursera/dopt/cp/gcoloring/Graph.java | 9034a41dfa9c61e0f1e42ee4d72025e5048cb370 | [] | no_license | anacleto85/DiscreteOptimization | d6c949834fb54b69fc2aa0b240db0da7e200dffc | 2c47224a112fe89a8630a25120cd55fda91e0c05 | refs/heads/master | 2021-02-05T02:51:24.286203 | 2020-02-28T10:28:04 | 2020-02-28T10:28:04 | 243,736,295 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,356 | java | package org.coursera.dopt.cp.gcoloring;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
*
* @author alessandroumbrico
*
*/
public class Graph
{
private int V;
private int E;
private GraphColorDecisionVariableDomain dom;
private GraphNode[] nodes;
private List<GraphNode>[] adjs;
/**
*
* @param colors
*/
@SuppressWarnings("unchecked")
public Graph(int V, int E, int colors) {
this.V = V;
this.E = E;
this.dom = new GraphColorDecisionVariableDomain(colors);
this.nodes = new GraphNode[this.V];
this.adjs = (List<GraphNode>[]) new List[this.V];
}
/**
*
* @param colors
*/
public void clean(int colors) {
// update variable domain
this.dom = new GraphColorDecisionVariableDomain(colors);
// clean all node variables
for (GraphNode node : this.nodes) {
node.setVariableDomain(this.dom);
node.clean();
}
}
/**
*
* @return
*/
public int getV() {
return V;
}
/**
*
* @return
*/
public int getE() {
return E;
}
/**
*
* @param id
*/
public void createNode(int id) {
if (this.nodes[id] == null) {
this.nodes[id] = new GraphNode(id, this.dom, this);
this.adjs[id] = new LinkedList<GraphNode>();
}
}
/**
*
* @param aId
* @param bId
*/
public void addEdge(int aId, int bId) {
if (this.nodes[aId] != null && this.nodes[bId] != null) {
this.adjs[aId].add(this.nodes[bId]);
this.adjs[bId].add(this.nodes[aId]);
}
}
/**
*
* @return
*/
public List<GraphNode> getNodesToColor() {
List<GraphNode> list = new LinkedList<GraphNode>();
for (GraphNode node : this.nodes) {
if (!node.hasColor()) {
list.add(node);
}
}
return list;
}
/**
*
* @return
*/
public List<GraphNode> getAllNodes() {
return Arrays.asList(this.nodes);
}
/**
*
* @param id
* @return
*/
public List<GraphNode> getAdjNodes(int id) {
return this.adjs[id];
}
/**
*
* @return
*/
public String printSolution() {
String sol = "";
for (GraphNode node : this.nodes) {
sol += node.getColor() + " ";
}
return sol;
}
/**
*
*/
@Override
public String toString() {
String desc = "[GRAPH <V=" + this.V + ",E=" + this.E + ">]\n";
for (GraphNode node : this.nodes) {
desc += node + " -> " + "{" + this.adjs[node.getId()] + "}\n";
}
return desc;
}
}
| [
"[email protected]"
] | |
a4e822ae5ffa9d1301edb6bb5cb47d8764151072 | 54b2565cdf395a26711be4e7a3b6aa94c6bbbc84 | /src/eigthbot/FinalAttack.java | 59ae3cff4345e3cdc93baceacb8c4448ecdb5b40 | [] | no_license | IvanGeffner/BC19 | 1d08cf168c795e2be8db5e20f30db2ff59450806 | 8bac1fc9cf411d4b723f2279245cd8310007e4da | refs/heads/master | 2020-04-17T13:11:42.039742 | 2019-01-27T05:52:35 | 2019-01-27T05:52:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,501 | java | package eigthbot;
import btcutils.Robot;
public class FinalAttack {
final int MIN_FUEL = 15000;
final int MIN_TURN = 500;
final int MIN_CONT = 70;
final int BROADCAST_DIST = 45;
MyRobot myRobot;
Utils utils;
Symmetry symmetry;
Broadcast broadcast;
CastleUtils castleUtils;
boolean alreadyCalled = false;
FinalAttack(MyRobot myRobot, CastleUtils castleUtils){
this.myRobot = myRobot;
this.castleUtils = castleUtils;
this.utils = castleUtils.utils;
symmetry = new Symmetry(myRobot, utils);
this.broadcast = castleUtils.broadcast;
}
FinalAttack(MyRobot myRobot, Utils utils, Broadcast broadcast){
this.myRobot = myRobot;
this.utils = utils;
this.broadcast = broadcast;
}
Location getFinalAttackLocation(){
int minDist = Constants.INF;
Location myLoc = new Location(myRobot.me.x, myRobot.me.y);
Location bestLoc = null;
for (Robot r : utils.robotsInVision){
if (broadcast.canReadSignal(r)){
int mes = r.signal/(2* Constants.maxMapSize* Constants.maxMapSize);
if (mes != broadcast.FINAL_ATTACK) continue;
int xObj = (r.signal/ Constants.maxMapSize)% Constants.maxMapSize;
int yObj = r.signal% Constants.maxMapSize;
Location loc = new Location(xObj, yObj);
if (myRobot.me.unit != Constants.CASTLE && myRobot.me.unit != Constants.CRUSADER && utils.distance(myRobot.me.x, myRobot.me.y, r.x, r.y) > BROADCAST_DIST) continue;
if (bestLoc == null || utils.distance(myLoc, loc) < minDist){
minDist = utils.distance(myLoc, loc);
bestLoc = loc;
}
}
}
return bestLoc;
}
void checkFinalAttack(){
if (alreadyCalled) return;
if (myRobot.me.turn < MIN_TURN) return;
//if (castleUtils != null && castleUtils.allCastlesAlive()) return;
Location attackLoc = getFinalAttackLocation();
if (attackLoc == null){
if (myRobot.fuel < MIN_FUEL) return;
if (castleUtils.countProphets() < MIN_CONT) return;
} else castleUtils.countProphets();
alreadyCalled = true;
broadcast.sendTarget(mySymmetric(), broadcast.FINAL_ATTACK, castleUtils.farthestProphet);
}
Location mySymmetric(){
return symmetry.getSymmetric(castleUtils.myLocation);
}
}
| [
"[email protected]"
] | |
3287f5a402ed446da695fcf9cddaa2bc71c2cb87 | 3402ce3738f5d803ca44defe73617c93d5716a94 | /src/main/java/model/Policlinicas.java | 05c0488b083813906e125a8d272a99123cf8d44a | [] | no_license | RogerAlves/saude_rec | 04c14bc73bbc2f8ac1282d463420cbdfba9f2735 | dbf8feb88636555ca7a3d5ea408c7d2ba0300ab4 | refs/heads/master | 2016-09-06T04:18:32.500427 | 2014-01-28T06:16:14 | 2014-01-28T06:16:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,614 | java | package model;
// Generated 27/01/2014 15:23:40 by Hibernate Tools 4.0.0
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* Policlinicas generated by hbm2java
*/
@Entity
@Table(name = "policlinicas", catalog = "saude_rec")
public class Policlinicas implements java.io.Serializable {
private PoliclinicasId id;
public Policlinicas() {
}
public Policlinicas(PoliclinicasId id) {
this.id = id;
}
@EmbeddedId
@AttributeOverrides({
@AttributeOverride(name = "rpa", column = @Column(name = "RPA")),
@AttributeOverride(name = "microRegiao", column = @Column(name = "MICRO_REGIAO")),
@AttributeOverride(name = "cnes", column = @Column(name = "CNES")),
@AttributeOverride(name = "unidade", column = @Column(name = "UNIDADE", length = 50)),
@AttributeOverride(name = "endereco", column = @Column(name = "ENDERECO", length = 50)),
@AttributeOverride(name = "bairro", column = @Column(name = "BAIRRO", length = 50)),
@AttributeOverride(name = "fone", column = @Column(name = "FONE", length = 50)),
@AttributeOverride(name = "especialidades", column = @Column(name = "ESPECIALIDADES", length = 350)),
@AttributeOverride(name = "latitude", column = @Column(name = "LATITUDE", length = 50)),
@AttributeOverride(name = "longitude", column = @Column(name = "LONGITUDE", length = 50)) })
public PoliclinicasId getId() {
return this.id;
}
public void setId(PoliclinicasId id) {
this.id = id;
}
}
| [
"[email protected]"
] | |
97467f73a80b075e87f18bf2cad477ba1e9a1032 | efa0a4c62bfdd480d6e3f1615b2ff67cee20c592 | /app/LibraryControl.java | f11f0f64f58839e107f7bb2b5219c15822ee7ea4 | [] | no_license | berec/library | c150a324984417c4e83495420e7e45504b16ce73 | 9d75a481cdf51ebe076a739567467ae9a2c48cd7 | refs/heads/master | 2021-09-10T09:37:06.171878 | 2018-03-23T18:06:27 | 2018-03-23T18:06:27 | 113,704,803 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,307 | java | package app;
import utils.DataReader;
import utils.LibraryUtils;
import data.Book;
import data.Library;
import data.Magazine;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
public class LibraryControl {
// zmienna do komunikacji z użytkownikiem
private DataReader dataReader;
// "biblioteka" przechowująca dane
private Library library;
public LibraryControl() {
dataReader = new DataReader();
library = new Library();
}
/*
* Główna pętla programu, która pozwala na wybór opcji i interakcję
*/
public void controlLoop() {
Option option = null;
while (option != Option.EXIT) {
try {
printOptions();
option = Option.createFromInt(dataReader.getInt());
switch (option) {
case ADD_BOOK:
addBook();
break;
case ADD_MAGAZINE:
addMagazine();
break;
case PRINT_BOOKS:
printBooks();
break;
case PRINT_MAGAZINES:
printMagazines();
break;
case EXIT:
;
}
} catch (InputMismatchException e) {
System.out.println("Wprowadzono niepoprawne dane, publikacji nie dodano");
} catch (NumberFormatException | NoSuchElementException e) {
System.out.println("Wybrana opcja nie istnieje, wybierz ponownie: ");
}
}
dataReader.close();
}
private void printOptions() {
System.out.println("Wybierz opcję: ");
for (Option o : Option.values()) {
System.out.println(o);
}
}
private void addBook() {
Book book = dataReader.readAndCreateBook();
library.addBook(book);
}
private void printBooks() {
LibraryUtils.printBooks(library);
}
private void addMagazine() {
Magazine magazine = dataReader.readAndCreatemagazine();
library.addMagazine(magazine);
}
private void printMagazines() {
LibraryUtils.printMagazines(library);
}
private enum Option {
EXIT(0, "Wyjście z programu"),
ADD_BOOK(1, "Dodanie książki"),
ADD_MAGAZINE(2, "Dodanie magazynu/gazety"),
PRINT_BOOKS(3, "Wyświetlenie dostępnych książek"),
PRINT_MAGAZINES(4, "Wyświetlenie dostępnych magazynów/gazet");
private int value;
private String description;
Option(int value, String desc) {
this.value = value;
this.description = desc;
}
@Override
public String toString() {
return value + " - " + description;
}
public static Option createFromInt(int option) throws NoSuchElementException {
Option result = null;
try {
result = Option.values()[option];
} catch (ArrayIndexOutOfBoundsException e) {
throw new NoSuchElementException("Brak elementu o wskazanym ID");
}
return result;
}
}
}
| [
"[email protected]"
] | |
b43653e65fc03a716e94e22619b20bff170a80a3 | 3844b2c43fef40cd144612d0be5b0bd7de555f67 | /logger-logback/src/test/java/net/openhft/chronicle/logger/logback/LogbackIndexedChronicleConfigTest.java | f97357b8253f583c84d716a75b10477ea297327c | [
"Apache-2.0"
] | permissive | herburos/Chronicle-Logger | 0468be1575cadb272ca82b317c19b840606ec092 | a96d6d7c6370982bca88c27758354425341d3e6b | refs/heads/master | 2021-01-17T12:36:43.255269 | 2015-03-03T22:54:03 | 2015-03-03T22:54:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,036 | java | /*
* Copyright 2014 Higher Frequency Trading
*
* http://www.higherfrequencytrading.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.logger.logback;
import ch.qos.logback.classic.spi.ILoggingEvent;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.*;
public class LogbackIndexedChronicleConfigTest extends LogbackTestBase {
@Before
public void setup() {
System.setProperty(
"logback.configurationFile",
System.getProperty("resources.path") + "/logback-indexed-chronicle-config.xml"
);
}
// *************************************************************************
//
// *************************************************************************
@Test
public void testBinaryIndexedChronicleAppenderConfig() throws IOException {
final String loggerName = "config-binary-indexed-chronicle";
final String appenderName = "CONFIG-BINARY-INDEXED-CHRONICLE";
try {
final ch.qos.logback.classic.Logger logger = getLoggerContext().getLogger(loggerName);
assertNotNull(logger);
final ch.qos.logback.core.Appender<ILoggingEvent> appender = logger.getAppender(appenderName);
assertNotNull(appender);
assertTrue(appender instanceof BinaryIndexedChronicleAppender);
BinaryIndexedChronicleAppender ba = (BinaryIndexedChronicleAppender) appender;
assertEquals(128, ba.getChronicleConfig().getIndexBlockSize());
} finally {
}
}
@Test
public void testTextIndexedChronicleAppenderConfig() throws IOException {
final String loggerName = "config-text-indexed-chronicle";
final String appenderName = "CONFIG-TEXT-INDEXED-CHRONICLE";
try {
final ch.qos.logback.classic.Logger logger = getLoggerContext().getLogger(loggerName);
assertNotNull(logger);
final ch.qos.logback.core.Appender<ILoggingEvent> appender = logger.getAppender(appenderName);
assertNotNull(appender);
assertTrue(appender instanceof TextIndexedChronicleAppender);
TextIndexedChronicleAppender ba = (TextIndexedChronicleAppender)appender;
assertEquals(128, ba.getChronicleConfig().getIndexBlockSize());
assertNotNull(ba.getDateFormat());
} finally {
//ChronicleTools.deleteOnExit(basePath(loggerName));
}
}
}
| [
"[email protected]"
] | |
570118130325a250deb90308842640682565b570 | 5d17d17c6845e07af2da87d59b148cce9d4f7f24 | /src/datastructures/FasterScanner.java | cb7511ba4c26f7616c3260ea129abb3e5b896eaf | [] | no_license | hitarthk/Algorithms | f08f73ad9912d81c0214e6bca5e1aaa9f114cf23 | 404262b354037e45189bce6de0f3a40d59003356 | refs/heads/master | 2021-01-10T10:00:27.828341 | 2016-01-07T09:41:02 | 2016-01-07T09:41:02 | 49,090,963 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,113 | java | /*
* 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 datastructures;
import java.io.IOException;
import java.util.InputMismatchException;
/**
*
* @author hitarthk
*/
class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
| [
"[email protected]"
] | |
bebb6d8d373849fa4651418c51857d966bd38bdc | 2a20cf43644a894abd1f8734d7b4dd3635c986c0 | /JavaCodingProject/src/com/coding/Multithreading/Deaddemo.java | d9232e87a47469b4afcd61a0c6f548acecf4e03c | [] | no_license | Mayankyadav123/JavaCodePractise | 1f233b87baf145dd1feab69aa00666a9d3e4fec0 | ec5650d7b0f57e1cd02181fc4f1181c8fe1c4c89 | refs/heads/master | 2022-05-20T22:21:20.710605 | 2022-05-06T14:02:11 | 2022-05-06T14:02:11 | 176,207,632 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,114 | java | package com.coding.Multithreading;
public class Deaddemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
final Object ob1= new Object();
final Object ob2= new Object();
Thread t1=new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
synchronized (ob1) {
System.out.println("t1 locked ob1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (ob2) {
System.out.println("t1 locked ob2");
}
}
}
});
Thread t2=new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
synchronized (ob2) {
System.out.println("t2 locked ob2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (ob1) {
System.out.println("t2 locked ob1");
}
}
}
});
t1.start();
t2.start();
}
}
| [
"[email protected]"
] | |
e201588aa0da80dc16de8199d405c365c04bcebb | e5f912dca37a2ac307b65cc54bb00218a06b4060 | /org/telegram/ui/ContactsActivity.java | 264df328c57bbabcc45f7b23bc672f34345a6911 | [] | no_license | lcastro12/TelegramAnalysis2 | eb3c94db166f34c41014e7ac2fb03b10495eba6f | 27d7fa66ed6f37d7f1b0726ac373b4c040bc421c | refs/heads/master | 2021-09-13T23:50:57.135120 | 2018-05-06T03:48:37 | 2018-05-06T03:48:37 | 132,304,318 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 26,885 | java | package org.telegram.ui;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.C0553R;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.ContactsController.Contact;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.NotificationCenter.NotificationCenterDelegate;
import org.telegram.messenger.SecretChatHelper;
import org.telegram.messenger.UserObject;
import org.telegram.messenger.Utilities;
import org.telegram.tgnet.TLRPC.EncryptedChat;
import org.telegram.tgnet.TLRPC.User;
import org.telegram.ui.ActionBar.ActionBar.ActionBarMenuOnItemClick;
import org.telegram.ui.ActionBar.ActionBarMenuItem.ActionBarMenuItemSearchListener;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.Adapters.BaseSectionsAdapter;
import org.telegram.ui.Adapters.ContactsAdapter;
import org.telegram.ui.Adapters.SearchAdapter;
import org.telegram.ui.Cells.UserCell;
import org.telegram.ui.Components.LetterSectionsListView;
public class ContactsActivity extends BaseFragment implements NotificationCenterDelegate {
private boolean allowBots = true;
private boolean allowUsernameSearch = true;
private int chat_id;
private boolean createSecretChat;
private boolean creatingChat = false;
private ContactsActivityDelegate delegate;
private boolean destroyAfterSelect;
private TextView emptyTextView;
private HashMap<Integer, User> ignoreUsers;
private LetterSectionsListView listView;
private BaseSectionsAdapter listViewAdapter;
private boolean needForwardCount = true;
private boolean needPhonebook;
private boolean onlyUsers;
private boolean returnAsResult;
private SearchAdapter searchListViewAdapter;
private boolean searchWas;
private boolean searching;
private String selectAlertString = null;
class C09833 implements OnTouchListener {
C09833() {
}
public boolean onTouch(View v, MotionEvent event) {
return true;
}
}
class C09854 implements OnItemClickListener {
C09854() {
}
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
User user;
if (ContactsActivity.this.searching && ContactsActivity.this.searchWas) {
user = (User) ContactsActivity.this.searchListViewAdapter.getItem(i);
if (user != null) {
if (ContactsActivity.this.searchListViewAdapter.isGlobalSearch(i)) {
ArrayList<User> users = new ArrayList();
users.add(user);
MessagesController.getInstance().putUsers(users, false);
MessagesStorage.getInstance().putUsersAndChats(users, null, false, true);
}
if (ContactsActivity.this.returnAsResult) {
if (ContactsActivity.this.ignoreUsers == null || !ContactsActivity.this.ignoreUsers.containsKey(Integer.valueOf(user.id))) {
ContactsActivity.this.didSelectResult(user, true, null);
return;
}
return;
} else if (ContactsActivity.this.createSecretChat) {
ContactsActivity.this.creatingChat = true;
SecretChatHelper.getInstance().startSecretChat(ContactsActivity.this.getParentActivity(), user);
return;
} else {
Bundle args = new Bundle();
args.putInt("user_id", user.id);
ContactsActivity.this.presentFragment(new ChatActivity(args), true);
return;
}
}
return;
}
int section = ContactsActivity.this.listViewAdapter.getSectionForPosition(i);
int row = ContactsActivity.this.listViewAdapter.getPositionInSectionForPosition(i);
if (row >= 0 && section >= 0) {
if ((ContactsActivity.this.onlyUsers && ContactsActivity.this.chat_id == 0) || section != 0) {
Contact item = ContactsActivity.this.listViewAdapter.getItem(section, row);
if (item instanceof User) {
user = (User) item;
if (ContactsActivity.this.returnAsResult) {
if (ContactsActivity.this.ignoreUsers == null || !ContactsActivity.this.ignoreUsers.containsKey(Integer.valueOf(user.id))) {
ContactsActivity.this.didSelectResult(user, true, null);
}
} else if (ContactsActivity.this.createSecretChat) {
ContactsActivity.this.creatingChat = true;
SecretChatHelper.getInstance().startSecretChat(ContactsActivity.this.getParentActivity(), user);
} else {
args = new Bundle();
args.putInt("user_id", user.id);
ContactsActivity.this.presentFragment(new ChatActivity(args), true);
}
} else if (item instanceof Contact) {
Contact contact = item;
String usePhone = null;
if (!contact.phones.isEmpty()) {
usePhone = (String) contact.phones.get(0);
}
if (usePhone != null && ContactsActivity.this.getParentActivity() != null) {
Builder builder = new Builder(ContactsActivity.this.getParentActivity());
builder.setMessage(LocaleController.getString("InviteUser", C0553R.string.InviteUser));
builder.setTitle(LocaleController.getString("AppName", C0553R.string.AppName));
final String arg1 = usePhone;
builder.setPositiveButton(LocaleController.getString("OK", C0553R.string.OK), new OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
try {
Intent intent = new Intent("android.intent.action.VIEW", Uri.fromParts("sms", arg1, null));
intent.putExtra("sms_body", LocaleController.getString("InviteText", C0553R.string.InviteText));
ContactsActivity.this.getParentActivity().startActivityForResult(intent, 500);
} catch (Throwable e) {
FileLog.m611e("tmessages", e);
}
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", C0553R.string.Cancel), null);
ContactsActivity.this.showDialog(builder.create());
}
}
} else if (ContactsActivity.this.needPhonebook) {
if (row == 0) {
try {
Intent intent = new Intent("android.intent.action.SEND");
intent.setType("text/plain");
intent.putExtra("android.intent.extra.TEXT", ContactsController.getInstance().getInviteText());
ContactsActivity.this.getParentActivity().startActivityForResult(Intent.createChooser(intent, LocaleController.getString("InviteFriends", C0553R.string.InviteFriends)), 500);
} catch (Throwable e) {
FileLog.m611e("tmessages", e);
}
}
} else if (ContactsActivity.this.chat_id != 0) {
if (row == 0) {
ContactsActivity.this.presentFragment(new GroupInviteActivity(ContactsActivity.this.chat_id));
}
} else if (row == 0) {
if (MessagesController.isFeatureEnabled("chat_create", ContactsActivity.this)) {
ContactsActivity.this.presentFragment(new GroupCreateActivity(), false);
}
} else if (row == 1) {
args = new Bundle();
args.putBoolean("onlyUsers", true);
args.putBoolean("destroyAfterSelect", true);
args.putBoolean("createSecretChat", true);
ContactsActivity.this.presentFragment(new ContactsActivity(args), false);
} else if (row == 2 && MessagesController.isFeatureEnabled("broadcast_create", ContactsActivity.this)) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", 0);
if (preferences.getBoolean("channel_intro", false)) {
args = new Bundle();
args.putInt("step", 0);
ContactsActivity.this.presentFragment(new ChannelCreateActivity(args));
return;
}
ContactsActivity.this.presentFragment(new ChannelIntroActivity());
preferences.edit().putBoolean("channel_intro", true).commit();
}
}
}
}
class C09865 implements OnScrollListener {
C09865() {
}
public void onScrollStateChanged(AbsListView absListView, int i) {
if (i == 1 && ContactsActivity.this.searching && ContactsActivity.this.searchWas) {
AndroidUtilities.hideKeyboard(ContactsActivity.this.getParentActivity().getCurrentFocus());
}
}
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (absListView.isFastScrollEnabled()) {
AndroidUtilities.clearDrawableAnimation(absListView);
}
}
}
public interface ContactsActivityDelegate {
void didSelectContact(User user, String str);
}
class C15791 extends ActionBarMenuOnItemClick {
C15791() {
}
public void onItemClick(int id) {
if (id == -1) {
ContactsActivity.this.finishFragment();
}
}
}
class C15802 extends ActionBarMenuItemSearchListener {
C15802() {
}
public void onSearchExpand() {
ContactsActivity.this.searching = true;
}
public void onSearchCollapse() {
ContactsActivity.this.searchListViewAdapter.searchDialogs(null);
ContactsActivity.this.searching = false;
ContactsActivity.this.searchWas = false;
ContactsActivity.this.listView.setAdapter(ContactsActivity.this.listViewAdapter);
ContactsActivity.this.listViewAdapter.notifyDataSetChanged();
if (VERSION.SDK_INT >= 11) {
ContactsActivity.this.listView.setFastScrollAlwaysVisible(true);
}
ContactsActivity.this.listView.setFastScrollEnabled(true);
ContactsActivity.this.listView.setVerticalScrollBarEnabled(false);
ContactsActivity.this.emptyTextView.setText(LocaleController.getString("NoContacts", C0553R.string.NoContacts));
}
public void onTextChanged(EditText editText) {
if (ContactsActivity.this.searchListViewAdapter != null) {
String text = editText.getText().toString();
if (text.length() != 0) {
ContactsActivity.this.searchWas = true;
if (ContactsActivity.this.listView != null) {
ContactsActivity.this.listView.setAdapter(ContactsActivity.this.searchListViewAdapter);
ContactsActivity.this.searchListViewAdapter.notifyDataSetChanged();
if (VERSION.SDK_INT >= 11) {
ContactsActivity.this.listView.setFastScrollAlwaysVisible(false);
}
ContactsActivity.this.listView.setFastScrollEnabled(false);
ContactsActivity.this.listView.setVerticalScrollBarEnabled(true);
}
if (ContactsActivity.this.emptyTextView != null) {
ContactsActivity.this.emptyTextView.setText(LocaleController.getString("NoResult", C0553R.string.NoResult));
}
}
ContactsActivity.this.searchListViewAdapter.searchDialogs(text);
}
}
}
public ContactsActivity(Bundle args) {
super(args);
}
public boolean onFragmentCreate() {
super.onFragmentCreate();
NotificationCenter.getInstance().addObserver(this, NotificationCenter.contactsDidLoaded);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.encryptedChatCreated);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.closeChats);
if (this.arguments != null) {
this.onlyUsers = getArguments().getBoolean("onlyUsers", false);
this.destroyAfterSelect = this.arguments.getBoolean("destroyAfterSelect", false);
this.returnAsResult = this.arguments.getBoolean("returnAsResult", false);
this.createSecretChat = this.arguments.getBoolean("createSecretChat", false);
this.selectAlertString = this.arguments.getString("selectAlertString");
this.allowUsernameSearch = this.arguments.getBoolean("allowUsernameSearch", true);
this.needForwardCount = this.arguments.getBoolean("needForwardCount", true);
this.allowBots = this.arguments.getBoolean("allowBots", true);
this.chat_id = this.arguments.getInt("chat_id", 0);
} else {
this.needPhonebook = true;
}
ContactsController.getInstance().checkInviteText();
return true;
}
public void onFragmentDestroy() {
super.onFragmentDestroy();
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.contactsDidLoaded);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.encryptedChatCreated);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.closeChats);
this.delegate = null;
}
public View createView(Context context) {
boolean z;
this.searching = false;
this.searchWas = false;
this.actionBar.setBackButtonImage(C0553R.drawable.ic_ab_back);
this.actionBar.setAllowOverlayTitle(true);
if (!this.destroyAfterSelect) {
this.actionBar.setTitle(LocaleController.getString("Contacts", C0553R.string.Contacts));
} else if (this.returnAsResult) {
this.actionBar.setTitle(LocaleController.getString("SelectContact", C0553R.string.SelectContact));
} else if (this.createSecretChat) {
this.actionBar.setTitle(LocaleController.getString("NewSecretChat", C0553R.string.NewSecretChat));
} else {
this.actionBar.setTitle(LocaleController.getString("NewMessageTitle", C0553R.string.NewMessageTitle));
}
this.actionBar.setActionBarMenuOnItemClick(new C15791());
this.actionBar.createMenu().addItem(0, (int) C0553R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new C15802()).getSearchField().setHint(LocaleController.getString("Search", C0553R.string.Search));
this.searchListViewAdapter = new SearchAdapter(context, this.ignoreUsers, this.allowUsernameSearch, false, false, this.allowBots);
int i = this.onlyUsers ? 1 : 0;
boolean z2 = this.needPhonebook;
HashMap hashMap = this.ignoreUsers;
if (this.chat_id != 0) {
z = true;
} else {
z = false;
}
this.listViewAdapter = new ContactsAdapter(context, i, z2, hashMap, z);
this.fragmentView = new FrameLayout(context);
LinearLayout emptyTextLayout = new LinearLayout(context);
emptyTextLayout.setVisibility(4);
emptyTextLayout.setOrientation(1);
((FrameLayout) this.fragmentView).addView(emptyTextLayout);
LayoutParams layoutParams = (LayoutParams) emptyTextLayout.getLayoutParams();
layoutParams.width = -1;
layoutParams.height = -1;
layoutParams.gravity = 48;
emptyTextLayout.setLayoutParams(layoutParams);
emptyTextLayout.setOnTouchListener(new C09833());
this.emptyTextView = new TextView(context);
this.emptyTextView.setTextColor(-8355712);
this.emptyTextView.setTextSize(1, 20.0f);
this.emptyTextView.setGravity(17);
this.emptyTextView.setText(LocaleController.getString("NoContacts", C0553R.string.NoContacts));
emptyTextLayout.addView(this.emptyTextView);
LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) this.emptyTextView.getLayoutParams();
layoutParams1.width = -1;
layoutParams1.height = -1;
layoutParams1.weight = 0.5f;
this.emptyTextView.setLayoutParams(layoutParams1);
FrameLayout frameLayout = new FrameLayout(context);
emptyTextLayout.addView(frameLayout);
layoutParams1 = (LinearLayout.LayoutParams) frameLayout.getLayoutParams();
layoutParams1.width = -1;
layoutParams1.height = -1;
layoutParams1.weight = 0.5f;
frameLayout.setLayoutParams(layoutParams1);
this.listView = new LetterSectionsListView(context);
this.listView.setEmptyView(emptyTextLayout);
this.listView.setVerticalScrollBarEnabled(false);
this.listView.setDivider(null);
this.listView.setDividerHeight(0);
this.listView.setFastScrollEnabled(true);
this.listView.setScrollBarStyle(33554432);
this.listView.setAdapter(this.listViewAdapter);
if (VERSION.SDK_INT >= 11) {
this.listView.setFastScrollAlwaysVisible(true);
this.listView.setVerticalScrollbarPosition(LocaleController.isRTL ? 1 : 2);
}
((FrameLayout) this.fragmentView).addView(this.listView);
layoutParams = (LayoutParams) this.listView.getLayoutParams();
layoutParams.width = -1;
layoutParams.height = -1;
this.listView.setLayoutParams(layoutParams);
this.listView.setOnItemClickListener(new C09854());
this.listView.setOnScrollListener(new C09865());
return this.fragmentView;
}
private void didSelectResult(final User user, boolean useAlert, String param) {
if (!useAlert || this.selectAlertString == null) {
if (this.delegate != null) {
this.delegate.didSelectContact(user, param);
this.delegate = null;
}
finishFragment();
} else if (getParentActivity() != null) {
if (user.bot && user.bot_nochats) {
try {
Toast.makeText(getParentActivity(), LocaleController.getString("BotCantJoinGroups", C0553R.string.BotCantJoinGroups), 0).show();
return;
} catch (Throwable e) {
FileLog.m611e("tmessages", e);
return;
}
}
Builder builder = new Builder(getParentActivity());
builder.setTitle(LocaleController.getString("AppName", C0553R.string.AppName));
String message = LocaleController.formatStringSimple(this.selectAlertString, UserObject.getUserName(user));
EditText editText = null;
if (!user.bot && this.needForwardCount) {
message = String.format("%s\n\n%s", new Object[]{message, LocaleController.getString("AddToTheGroupForwardCount", C0553R.string.AddToTheGroupForwardCount)});
editText = new EditText(getParentActivity());
if (VERSION.SDK_INT < 11) {
editText.setBackgroundResource(17301529);
}
editText.setTextSize(18.0f);
editText.setText("50");
editText.setGravity(17);
editText.setInputType(2);
editText.setImeOptions(6);
final EditText editTextFinal = editText;
editText.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void afterTextChanged(Editable s) {
try {
String str = s.toString();
if (str.length() != 0) {
int value = Utilities.parseInt(str).intValue();
if (value < 0) {
editTextFinal.setText("0");
editTextFinal.setSelection(editTextFinal.length());
} else if (value > 300) {
editTextFinal.setText("300");
editTextFinal.setSelection(editTextFinal.length());
} else if (!str.equals("" + value)) {
editTextFinal.setText("" + value);
editTextFinal.setSelection(editTextFinal.length());
}
}
} catch (Throwable e) {
FileLog.m611e("tmessages", e);
}
}
});
builder.setView(editText);
}
builder.setMessage(message);
final EditText finalEditText = editText;
builder.setPositiveButton(LocaleController.getString("OK", C0553R.string.OK), new OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
ContactsActivity.this.didSelectResult(user, false, finalEditText != null ? finalEditText.getText().toString() : "0");
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", C0553R.string.Cancel), null);
showDialog(builder.create());
if (editText != null) {
MarginLayoutParams layoutParams = (MarginLayoutParams) editText.getLayoutParams();
if (layoutParams != null) {
if (layoutParams instanceof LayoutParams) {
((LayoutParams) layoutParams).gravity = 1;
}
int dp = AndroidUtilities.dp(10.0f);
layoutParams.leftMargin = dp;
layoutParams.rightMargin = dp;
editText.setLayoutParams(layoutParams);
}
editText.setSelection(editText.getText().length());
}
}
}
public void onResume() {
super.onResume();
if (this.listViewAdapter != null) {
this.listViewAdapter.notifyDataSetChanged();
}
}
public void onPause() {
super.onPause();
if (this.actionBar != null) {
this.actionBar.closeSearchField();
}
}
public void didReceivedNotification(int id, Object... args) {
if (id == NotificationCenter.contactsDidLoaded) {
if (this.listViewAdapter != null) {
this.listViewAdapter.notifyDataSetChanged();
}
} else if (id == NotificationCenter.updateInterfaces) {
int mask = ((Integer) args[0]).intValue();
if ((mask & 2) != 0 || (mask & 1) != 0 || (mask & 4) != 0) {
updateVisibleRows(mask);
}
} else if (id == NotificationCenter.encryptedChatCreated) {
if (this.createSecretChat && this.creatingChat) {
EncryptedChat encryptedChat = args[0];
Bundle args2 = new Bundle();
args2.putInt("enc_id", encryptedChat.id);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats, new Object[0]);
presentFragment(new ChatActivity(args2), true);
}
} else if (id == NotificationCenter.closeChats && !this.creatingChat) {
removeSelfFromStack();
}
}
private void updateVisibleRows(int mask) {
if (this.listView != null) {
int count = this.listView.getChildCount();
for (int a = 0; a < count; a++) {
View child = this.listView.getChildAt(a);
if (child instanceof UserCell) {
((UserCell) child).update(mask);
}
}
}
}
public void setDelegate(ContactsActivityDelegate delegate) {
this.delegate = delegate;
}
public void setIgnoreUsers(HashMap<Integer, User> users) {
this.ignoreUsers = users;
}
}
| [
"[email protected]"
] | |
da59462349d75dd65f06224c96c4e885105685dc | bf1b51f3e035778f932160b2b27c94449eb4eaab | /src/main/java/com/zoudong/fileserver/config/interceptor/FeginClientInterceptor.java | fc209b781abd85f5fb570e508daa2f1817ceb043 | [] | no_license | zoudong/spring-cloud-fileserver | fc1022ad8e6f5b1a0c2ab535091f94dbc6e9f3c6 | 1a528e3cbbe07f7ac2baf783a71b82c6c233f540 | refs/heads/master | 2020-03-27T10:19:40.098599 | 2018-08-28T08:12:06 | 2018-08-28T08:12:06 | 146,411,873 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,390 | java | package com.zoudong.fileserver.config.interceptor;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
/**
* 发起fegin请求时把herader一起带过去的拦截器
*/
@Component
public class FeginClientInterceptor{
@Bean
public RequestInterceptor headerInterceptor() {
return new RequestInterceptor() {
@Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String values = request.getHeader(name);
requestTemplate.header(name, values);
}
}
}
};
}
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.