blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bdffc68a95ef8e7273253b8831674fc64549ce8e
| 5,205,500,408,026 |
ffba6f30a5a01e281622f82665e929076f1f2deb
|
/FarmaTownSA/src/com/company/Drogas.java
|
d9c3f2f63dfffd718529a2316f39bf39eaeab6c6
|
[] |
no_license
|
TheKamarov/EjerciciosJava
|
https://github.com/TheKamarov/EjerciciosJava
|
6bdda4c7f4f1384177dc6245672b261498c8fa3e
|
4691d3b060cd25cb847fdf2fe27cd6c06cb3f782
|
refs/heads/master
| 2020-08-12T07:19:40.507000 | 2019-10-12T21:09:30 | 2019-10-12T21:09:30 | 214,715,468 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.company;
public class Drogas implements Vendible {
private String nombre;
public Drogas(String nombre){
this.nombre = nombre;
}
@Override
public void vender(Persona unaPersona) {
if(unaPersona.getAlergia().equals(this.nombre)){
System.out.println(unaPersona.getNombre() +" no puede recibir la droga "+ this.nombre + " porque es alergico");
}else{
System.out.println(unaPersona.getNombre() + " puede recibir la droga " + this.nombre);
}
}
}
|
UTF-8
|
Java
| 537 |
java
|
Drogas.java
|
Java
|
[] | null |
[] |
package com.company;
public class Drogas implements Vendible {
private String nombre;
public Drogas(String nombre){
this.nombre = nombre;
}
@Override
public void vender(Persona unaPersona) {
if(unaPersona.getAlergia().equals(this.nombre)){
System.out.println(unaPersona.getNombre() +" no puede recibir la droga "+ this.nombre + " porque es alergico");
}else{
System.out.println(unaPersona.getNombre() + " puede recibir la droga " + this.nombre);
}
}
}
| 537 | 0.633147 | 0.633147 | 20 | 25.85 | 32.882023 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
10
|
7b9a34393deff87db9a4a8a84f468a333bded386
| 11,510,512,390,123 |
4691acca4e62da71a857385cffce2b6b4aef3bb3
|
/persistence-modules/java-mongodb-3/src/test/java/com/baeldung/mongo/insert/InsertArrayOperationLiveTest.java
|
a844a003f0ec7b7c2bacda3367feeb3566d4d6c7
|
[
"MIT"
] |
permissive
|
lor6/tutorials
|
https://github.com/lor6/tutorials
|
800f2e48d7968c047407bbd8a61b47be7ec352f2
|
e993db2c23d559d503b8bf8bc27aab0847224593
|
refs/heads/master
| 2023-05-29T06:17:47.980000 | 2023-05-19T08:37:45 | 2023-05-19T08:37:45 | 145,218,314 | 7 | 11 |
MIT
| true | 2018-08-18T12:29:20 | 2018-08-18T12:29:19 | 2018-08-18T12:01:20 | 2018-08-18T12:01:05 | 108,692 | 0 | 0 | 0 | null | false | null |
package com.baeldung.mongo.insert;
import com.mongodb.*;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.in;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class InsertArrayOperationLiveTest {
private static MongoClient mongoClient;
private static MongoDatabase database;
private static MongoCollection<Document> collection;
private static DB db;
private static DBCollection dbCollection;
@BeforeClass
public static void setUp() {
if (mongoClient == null) {
mongoClient = new MongoClient("localhost", 27017);
database = mongoClient.getDatabase("baeldung");
collection = database.getCollection("student");
db = mongoClient.getDB("baeldung");
dbCollection = db.getCollection("student");
collection.drop();
}
}
@Test
public void givenSingleStudentObjectWithStringArray_whenInsertingDBObject_thenCheckingForDocument() {
BasicDBList coursesList = new BasicDBList();
coursesList.add("Chemistry");
coursesList.add("Science");
DBObject student = new BasicDBObject().append("studentId", "STUD1")
.append("name", "Jim")
.append("age", 13)
.append("courses", coursesList);
dbCollection.insert(student);
Bson filter = eq("studentId", "STUD2");
FindIterable<Document> documents = collection.find(filter);
MongoCursor<Document> cursor = documents.iterator();
assertNotNull(cursor);
assertTrue(cursor.hasNext());
}
@Test
public void givenSingleStudentObjectWithStringArray_whenInsertingDocument_thenCheckingForDocument() {
List<String> coursesList = new ArrayList<>();
coursesList.add("Science");
coursesList.add("Geography");
Document student = new Document().append("studentId", "STUD2")
.append("name", "Sam")
.append("age", 13)
.append("courses", coursesList);
collection.insertOne(student);
Bson filter = eq("studentId", "STUD2");
FindIterable<Document> documents = collection.find(filter);
MongoCursor<Document> cursor = documents.iterator();
assertNotNull(cursor);
assertTrue(cursor.hasNext());
}
@Test
public void givenMultipleStudentObjectsWithStringArray_whenInsertingDocuments_thenCheckingForDocuments() {
List<String> coursesList1 = new ArrayList<>();
coursesList1.add("Chemistry");
coursesList1.add("Geography");
Document student1 = new Document().append("studentId", "STUD3")
.append("name", "Sarah")
.append("age", 12)
.append("courses", coursesList1);
List<String> coursesList2 = new ArrayList<>();
coursesList2.add("Maths");
coursesList2.add("History");
Document student2 = new Document().append("studentId", "STUD4")
.append("name", "Tom")
.append("age", 13)
.append("courses", coursesList2);
List<Document> students = new ArrayList<>();
students.add(student1);
students.add(student2);
collection.insertMany(students);
Bson filter = in("studentId", "STUD3", "STUD4");
FindIterable<Document> documents = collection.find(filter);
MongoCursor<Document> cursor = documents.iterator();
assertNotNull(cursor);
assertTrue(cursor.hasNext());
}
@Test
public void givenSingleStudentObjectWithObjectArray_whenInsertingDocument_thenCheckingForDocument() {
Document course1 = new Document().append("name", "C1")
.append("points", 5);
Document course2 = new Document().append("name", "C2")
.append("points", 7);
List<Document> coursesList = new ArrayList<>();
coursesList.add(course1);
coursesList.add(course2);
Document student = new Document().append("studentId", "STUD5")
.append("name", "Sam")
.append("age", 13)
.append("courses", coursesList);
collection.insertOne(student);
Bson filter = eq("studentId", "STUD5");
FindIterable<Document> documents = collection.find(filter);
MongoCursor<Document> cursor = documents.iterator();
assertNotNull(cursor);
assertTrue(cursor.hasNext());
}
}
|
UTF-8
|
Java
| 4,808 |
java
|
InsertArrayOperationLiveTest.java
|
Java
|
[
{
"context": "studentId\", \"STUD1\")\n .append(\"name\", \"Jim\")\n .append(\"age\", 13)\n .app",
"end": 1616,
"score": 0.9998210072517395,
"start": 1613,
"tag": "NAME",
"value": "Jim"
},
{
"context": "studentId\", \"STUD2\")\n .append(\"name\", \"Sam\")\n .append(\"age\", 13)\n .app",
"end": 2338,
"score": 0.9998353123664856,
"start": 2335,
"tag": "NAME",
"value": "Sam"
},
{
"context": "studentId\", \"STUD3\")\n .append(\"name\", \"Sarah\")\n .append(\"age\", 12)\n .app",
"end": 3074,
"score": 0.9996739625930786,
"start": 3069,
"tag": "NAME",
"value": "Sarah"
},
{
"context": "studentId\", \"STUD4\")\n .append(\"name\", \"Tom\")\n .append(\"age\", 13)\n .app",
"end": 3387,
"score": 0.9998482465744019,
"start": 3384,
"tag": "NAME",
"value": "Tom"
},
{
"context": "studentId\", \"STUD5\")\n .append(\"name\", \"Sam\")\n .append(\"age\", 13)\n .app",
"end": 4432,
"score": 0.9998214840888977,
"start": 4429,
"tag": "NAME",
"value": "Sam"
}
] | null |
[] |
package com.baeldung.mongo.insert;
import com.mongodb.*;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.in;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class InsertArrayOperationLiveTest {
private static MongoClient mongoClient;
private static MongoDatabase database;
private static MongoCollection<Document> collection;
private static DB db;
private static DBCollection dbCollection;
@BeforeClass
public static void setUp() {
if (mongoClient == null) {
mongoClient = new MongoClient("localhost", 27017);
database = mongoClient.getDatabase("baeldung");
collection = database.getCollection("student");
db = mongoClient.getDB("baeldung");
dbCollection = db.getCollection("student");
collection.drop();
}
}
@Test
public void givenSingleStudentObjectWithStringArray_whenInsertingDBObject_thenCheckingForDocument() {
BasicDBList coursesList = new BasicDBList();
coursesList.add("Chemistry");
coursesList.add("Science");
DBObject student = new BasicDBObject().append("studentId", "STUD1")
.append("name", "Jim")
.append("age", 13)
.append("courses", coursesList);
dbCollection.insert(student);
Bson filter = eq("studentId", "STUD2");
FindIterable<Document> documents = collection.find(filter);
MongoCursor<Document> cursor = documents.iterator();
assertNotNull(cursor);
assertTrue(cursor.hasNext());
}
@Test
public void givenSingleStudentObjectWithStringArray_whenInsertingDocument_thenCheckingForDocument() {
List<String> coursesList = new ArrayList<>();
coursesList.add("Science");
coursesList.add("Geography");
Document student = new Document().append("studentId", "STUD2")
.append("name", "Sam")
.append("age", 13)
.append("courses", coursesList);
collection.insertOne(student);
Bson filter = eq("studentId", "STUD2");
FindIterable<Document> documents = collection.find(filter);
MongoCursor<Document> cursor = documents.iterator();
assertNotNull(cursor);
assertTrue(cursor.hasNext());
}
@Test
public void givenMultipleStudentObjectsWithStringArray_whenInsertingDocuments_thenCheckingForDocuments() {
List<String> coursesList1 = new ArrayList<>();
coursesList1.add("Chemistry");
coursesList1.add("Geography");
Document student1 = new Document().append("studentId", "STUD3")
.append("name", "Sarah")
.append("age", 12)
.append("courses", coursesList1);
List<String> coursesList2 = new ArrayList<>();
coursesList2.add("Maths");
coursesList2.add("History");
Document student2 = new Document().append("studentId", "STUD4")
.append("name", "Tom")
.append("age", 13)
.append("courses", coursesList2);
List<Document> students = new ArrayList<>();
students.add(student1);
students.add(student2);
collection.insertMany(students);
Bson filter = in("studentId", "STUD3", "STUD4");
FindIterable<Document> documents = collection.find(filter);
MongoCursor<Document> cursor = documents.iterator();
assertNotNull(cursor);
assertTrue(cursor.hasNext());
}
@Test
public void givenSingleStudentObjectWithObjectArray_whenInsertingDocument_thenCheckingForDocument() {
Document course1 = new Document().append("name", "C1")
.append("points", 5);
Document course2 = new Document().append("name", "C2")
.append("points", 7);
List<Document> coursesList = new ArrayList<>();
coursesList.add(course1);
coursesList.add(course2);
Document student = new Document().append("studentId", "STUD5")
.append("name", "Sam")
.append("age", 13)
.append("courses", coursesList);
collection.insertOne(student);
Bson filter = eq("studentId", "STUD5");
FindIterable<Document> documents = collection.find(filter);
MongoCursor<Document> cursor = documents.iterator();
assertNotNull(cursor);
assertTrue(cursor.hasNext());
}
}
| 4,808 | 0.646007 | 0.636647 | 150 | 31.053333 | 25.436926 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.706667 | false | false |
10
|
770430011af402d3f4894a2d5ccdd59cce2425f5
| 21,560,735,862,164 |
794cce44b35e2c6fa989414373501f021d8cd1a9
|
/baseble/src/main/java/com/vise/baseble/exception/BleException.java
|
57681412be447f5e8e4f44d779803b1f206d7dde
|
[
"Apache-2.0"
] |
permissive
|
eric781ctf/Transaction-medium-BLE-Android-App
|
https://github.com/eric781ctf/Transaction-medium-BLE-Android-App
|
a853f5bb35682d79805758f2f6d2d0554810f56c
|
adf2b011cd209cc5fa546ea4d9ec9bbbf07d7e2f
|
refs/heads/master
| 2020-11-30T10:10:21.168000 | 2019-12-27T04:38:12 | 2019-12-27T04:38:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.vise.baseble.exception;
import com.vise.baseble.common.BleExceptionCode;
import java.io.Serializable;
/**
* @Description: BLE例外基本分類
*/
public class BleException implements Serializable {
private BleExceptionCode code;
private String description;
public BleException(BleExceptionCode code, String description) {
this.code = code;
this.description = description;
}
public BleExceptionCode getCode() {
return code;
}
public BleException setCode(BleExceptionCode code) {
this.code = code;
return this;
}
public String getDescription() {
return description;
}
public BleException setDescription(String description) {
this.description = description;
return this;
}
@Override
public String toString() {
return "BleException{" +
"code=" + code +
", description='" + description + '\'' +
'}';
}
}
|
UTF-8
|
Java
| 1,003 |
java
|
BleException.java
|
Java
|
[] | null |
[] |
package com.vise.baseble.exception;
import com.vise.baseble.common.BleExceptionCode;
import java.io.Serializable;
/**
* @Description: BLE例外基本分類
*/
public class BleException implements Serializable {
private BleExceptionCode code;
private String description;
public BleException(BleExceptionCode code, String description) {
this.code = code;
this.description = description;
}
public BleExceptionCode getCode() {
return code;
}
public BleException setCode(BleExceptionCode code) {
this.code = code;
return this;
}
public String getDescription() {
return description;
}
public BleException setDescription(String description) {
this.description = description;
return this;
}
@Override
public String toString() {
return "BleException{" +
"code=" + code +
", description='" + description + '\'' +
'}';
}
}
| 1,003 | 0.620585 | 0.620585 | 44 | 21.522728 | 19.391293 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false |
10
|
0db5c28ca6c0e052de9c9ada4e022d41c260087a
| 17,403,207,541,276 |
619feef90db73831fd2489f3dbeab7d1912267af
|
/app/src/main/java/hr/vsite/emit/jamp/PatientAnamnesisFragment.java
|
387dd7e0abbab6b1065b665ab09a502ab072a538
|
[] |
no_license
|
emmakova/jamp
|
https://github.com/emmakova/jamp
|
1a97a19f4dd7d5d4c2c92d6df98133d0006b2e19
|
42ef966fbcf989ad728c9af75d546b47e6eb1fd3
|
refs/heads/master
| 2015-08-21T16:06:48.550000 | 2015-03-30T23:25:47 | 2015-03-30T23:25:47 | 32,266,077 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package hr.vsite.emit.jamp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import java.lang.reflect.Field;
import java.util.ArrayList;
import hr.vsite.emit.jamp.adapter.AnamnesisAdapter;
import hr.vsite.emit.jamp.model.Anamnesis;
import hr.vsite.emit.jamp.model.Pacijent;
/**
* Created by Emil Makovac on 23/02/2015.
*/
public class PatientAnamnesisFragment extends Fragment {
private static final String LOG_TAG = "PatientAnamnesisFragment";
private Pacijent pacijent;
private AnamnesisAdapter adapter;
private ListView listAnamnesis;
private ArrayList<Anamnesis> list;
private Anamnesis a;
public PatientAnamnesisFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(LOG_TAG, "onCreate");
Intent i = getActivity().getIntent();
pacijent = (Pacijent) i.getSerializableExtra("pacijent");
list = pacijent.getAnamnesis();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_patient_anamnesis, container, false);
adapter = new AnamnesisAdapter(getActivity(), list);
listAnamnesis = (ListView) rootView.findViewById(R.id.list_view_anamnesis);
listAnamnesis.setAdapter(adapter);
listAnamnesis.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view, int position, long arg3) {
Intent intent = new Intent(getActivity(), DetailsActivity.class);
a = (Anamnesis) adapterView.getItemAtPosition(position);
intent.putExtra("historyObject", a);
intent.putExtra("fragmentTitle", pacijent.getFullName() + " | " + "Anamneza");
startActivity(intent);
}
});
return rootView;
}
@Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
|
UTF-8
|
Java
| 2,764 |
java
|
PatientAnamnesisFragment.java
|
Java
|
[
{
"context": "site.emit.jamp.model.Pacijent;\n\n\n/**\n * Created by Emil Makovac on 23/02/2015.\n */\npublic class PatientAnamnesisF",
"end": 543,
"score": 0.9997631907463074,
"start": 531,
"tag": "NAME",
"value": "Emil Makovac"
},
{
"context": "fragmentTitle\", pacijent.getFullName() + \" | \" + \"Anamneza\");\n startActivity(intent);\n ",
"end": 2183,
"score": 0.9947729110717773,
"start": 2175,
"tag": "NAME",
"value": "Anamneza"
}
] | null |
[] |
package hr.vsite.emit.jamp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import java.lang.reflect.Field;
import java.util.ArrayList;
import hr.vsite.emit.jamp.adapter.AnamnesisAdapter;
import hr.vsite.emit.jamp.model.Anamnesis;
import hr.vsite.emit.jamp.model.Pacijent;
/**
* Created by <NAME> on 23/02/2015.
*/
public class PatientAnamnesisFragment extends Fragment {
private static final String LOG_TAG = "PatientAnamnesisFragment";
private Pacijent pacijent;
private AnamnesisAdapter adapter;
private ListView listAnamnesis;
private ArrayList<Anamnesis> list;
private Anamnesis a;
public PatientAnamnesisFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(LOG_TAG, "onCreate");
Intent i = getActivity().getIntent();
pacijent = (Pacijent) i.getSerializableExtra("pacijent");
list = pacijent.getAnamnesis();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_patient_anamnesis, container, false);
adapter = new AnamnesisAdapter(getActivity(), list);
listAnamnesis = (ListView) rootView.findViewById(R.id.list_view_anamnesis);
listAnamnesis.setAdapter(adapter);
listAnamnesis.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view, int position, long arg3) {
Intent intent = new Intent(getActivity(), DetailsActivity.class);
a = (Anamnesis) adapterView.getItemAtPosition(position);
intent.putExtra("historyObject", a);
intent.putExtra("fragmentTitle", pacijent.getFullName() + " | " + "Anamneza");
startActivity(intent);
}
});
return rootView;
}
@Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
| 2,758 | 0.677641 | 0.674023 | 86 | 31.139534 | 27.095509 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.662791 | false | false |
10
|
66856dda9fcfb35f9a7838af608fa4746cb14700
| 4,621,384,870,618 |
0746b75b2f50bcad41593423852e3af566f6b099
|
/Students/30221/Iosif V. Raluca/animals/Lizard.java
|
06b234b239d449f64733690e062e5bd4638aa660
|
[] |
no_license
|
OOP-30221/OOP-2016
|
https://github.com/OOP-30221/OOP-2016
|
a9f61d530558b24e3ab55f9508b23462b93c82eb
|
be940ba80f76623a5b2cd400cd10966cbfbf7c6e
|
refs/heads/master
| 2019-07-23T12:25:48.768000 | 2016-12-12T14:03:01 | 2016-12-12T14:03:01 | 69,889,111 | 16 | 26 | null | false | 2016-12-13T20:12:16 | 2016-10-03T16:27:40 | 2016-11-08T23:03:16 | 2016-12-13T11:25:29 | 45,211 | 5 | 26 | 4 |
Java
| null | null |
package javasmmr.zoowsome.models.animals;
public class Lizard extends Reptile {
public Lizard (int legs, String name){
this.setName(name);
this.setNrOfLegs(legs);
}
public Lizard(){
this.setName("lizard");
this.setNrOfLegs(4);
}
}
|
UTF-8
|
Java
| 247 |
java
|
Lizard.java
|
Java
|
[
{
"context": "egs(legs);\n\t}\n\t\n\tpublic Lizard(){\n\t\tthis.setName(\"lizard\");\n\t\tthis.setNrOfLegs(4);\n\t}\n}\n",
"end": 215,
"score": 0.9957238435745239,
"start": 209,
"tag": "NAME",
"value": "lizard"
}
] | null |
[] |
package javasmmr.zoowsome.models.animals;
public class Lizard extends Reptile {
public Lizard (int legs, String name){
this.setName(name);
this.setNrOfLegs(legs);
}
public Lizard(){
this.setName("lizard");
this.setNrOfLegs(4);
}
}
| 247 | 0.708502 | 0.704453 | 14 | 16.642857 | 15.040931 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.357143 | false | false |
10
|
e4874fa66179817b732a779b7537b416c8501388
| 29,996,051,638,754 |
4de5ad40b7eea9b3df09deed88eece15d1cac582
|
/cache-service/src/main/java/org/yejt/cacheservice/store/LruDataStore.java
|
0c40e77cda3b668262f4973ffd904e6b903aa7af
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
keys961/DistributedCache
|
https://github.com/keys961/DistributedCache
|
551e93d3c4ffaf85429f43a8e83e8bc5ec4edbe1
|
79a9bd4703a85b1145c5b3a60e663bbed36887fb
|
refs/heads/master
| 2020-03-26T16:16:14.988000 | 2018-12-29T03:16:25 | 2018-12-29T03:16:25 | 145,090,890 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.yejt.cacheservice.store;
import org.yejt.cacheservice.store.value.BaseValueHolder;
import org.yejt.cacheservice.store.value.ValueHolder;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;
/**
* <p>Bounded storage with strict LRU replacement strategy.
* <p>Replacing strategy: LRU
*
* @author keys961
*/
public class LruDataStore<K, V> implements DataStore<K, V> {
private LinkedHashMap<K, ValueHolder<V>> cache;
private ReentrantLock lock = new ReentrantLock();
public LruDataStore(long capacity) {
final int mapCapacity = (int) ((capacity << 2) / 3);
cache = new LinkedHashMap<K, ValueHolder<V>>(mapCapacity) {
@Override
protected boolean removeEldestEntry(Map.Entry<K, ValueHolder<V>> eldest) {
return size() >= capacity;
}
};
}
@Override
public ValueHolder<V> get(K key) {
ValueHolder<V> v;
try {
lock.lock();
v = cache.get(key);
if (v != null) {
cache.remove(key);
cache.put(key, v);
}
} finally {
lock.unlock();
}
return v;
}
@Override
public Set<Map.Entry<K, ValueHolder<V>>> getAll() {
Set<Map.Entry<K, ValueHolder<V>>> entries;
try {
lock.lock();
entries = cache.entrySet();
} finally {
lock.unlock();
}
return entries;
}
@Override
public ValueHolder<V> put(K key, V value) {
ValueHolder<V> holder;
try {
lock.lock();
holder = new BaseValueHolder<>(value);
cache.put(key, holder);
} finally {
lock.unlock();
}
return holder;
}
@Override
public ValueHolder<V> remove(K key) {
ValueHolder<V> v;
try {
lock.lock();
v = cache.remove(key);
} finally {
lock.unlock();
}
return v;
}
@Override
public void clear() {
try {
lock.lock();
cache.clear();
} finally {
lock.unlock();
}
}
}
|
UTF-8
|
Java
| 2,273 |
java
|
LruDataStore.java
|
Java
|
[
{
"context": "ategy.\n * <p>Replacing strategy: LRU\n *\n * @author keys961\n */\npublic class LruDataStore<K, V> implements Da",
"end": 392,
"score": 0.9993352890014648,
"start": 385,
"tag": "USERNAME",
"value": "keys961"
}
] | null |
[] |
package org.yejt.cacheservice.store;
import org.yejt.cacheservice.store.value.BaseValueHolder;
import org.yejt.cacheservice.store.value.ValueHolder;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;
/**
* <p>Bounded storage with strict LRU replacement strategy.
* <p>Replacing strategy: LRU
*
* @author keys961
*/
public class LruDataStore<K, V> implements DataStore<K, V> {
private LinkedHashMap<K, ValueHolder<V>> cache;
private ReentrantLock lock = new ReentrantLock();
public LruDataStore(long capacity) {
final int mapCapacity = (int) ((capacity << 2) / 3);
cache = new LinkedHashMap<K, ValueHolder<V>>(mapCapacity) {
@Override
protected boolean removeEldestEntry(Map.Entry<K, ValueHolder<V>> eldest) {
return size() >= capacity;
}
};
}
@Override
public ValueHolder<V> get(K key) {
ValueHolder<V> v;
try {
lock.lock();
v = cache.get(key);
if (v != null) {
cache.remove(key);
cache.put(key, v);
}
} finally {
lock.unlock();
}
return v;
}
@Override
public Set<Map.Entry<K, ValueHolder<V>>> getAll() {
Set<Map.Entry<K, ValueHolder<V>>> entries;
try {
lock.lock();
entries = cache.entrySet();
} finally {
lock.unlock();
}
return entries;
}
@Override
public ValueHolder<V> put(K key, V value) {
ValueHolder<V> holder;
try {
lock.lock();
holder = new BaseValueHolder<>(value);
cache.put(key, holder);
} finally {
lock.unlock();
}
return holder;
}
@Override
public ValueHolder<V> remove(K key) {
ValueHolder<V> v;
try {
lock.lock();
v = cache.remove(key);
} finally {
lock.unlock();
}
return v;
}
@Override
public void clear() {
try {
lock.lock();
cache.clear();
} finally {
lock.unlock();
}
}
}
| 2,273 | 0.524857 | 0.522657 | 99 | 21.959597 | 18.487736 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.484848 | false | false |
10
|
945fe8edc894e2dc43b32e3788d150ea35bd51a4
| 36,472,862,280,382 |
7d47552171ba133f46e382ce15e4ba08c9c12c1b
|
/src/main/java/com/rexsoft/ejercicioNo1/app/services/impl/IProductoServiceImpl.java
|
7d6f3bfee27bf8d1eeb9fbd9365ae96e26720808
|
[] |
no_license
|
diegoale1994/Exercise-No-1-B
|
https://github.com/diegoale1994/Exercise-No-1-B
|
6a517375276455382b949a7642448caef388ec25
|
17c78b78d3aff4bc9d1ad327d14585c27eeb6c9a
|
refs/heads/master
| 2020-05-17T04:56:01.762000 | 2019-04-27T00:36:04 | 2019-04-27T00:36:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.rexsoft.ejercicioNo1.app.services.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rexsoft.ejercicioNo1.app.models.Producto;
import com.rexsoft.ejercicioNo1.app.repos.IProductoRepo;
import com.rexsoft.ejercicioNo1.services.IProductoService;
@Service
public class IProductoServiceImpl implements IProductoService {
@Autowired
private IProductoRepo productoRepo;
@Override
public Producto registrar(Producto t) {
return productoRepo.save(t);
}
@Override
public Producto modificar(Producto t) {
return productoRepo.save(t);
}
@Override
public Producto leer(Integer id) {
return productoRepo.findById(id).orElse(null);
}
@Override
public List<Producto> listartodos() {
return productoRepo.findAll();
}
@Override
public void eliminar(Integer id) {
productoRepo.deleteById(id);
}
}
|
UTF-8
|
Java
| 930 |
java
|
IProductoServiceImpl.java
|
Java
|
[] | null |
[] |
package com.rexsoft.ejercicioNo1.app.services.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rexsoft.ejercicioNo1.app.models.Producto;
import com.rexsoft.ejercicioNo1.app.repos.IProductoRepo;
import com.rexsoft.ejercicioNo1.services.IProductoService;
@Service
public class IProductoServiceImpl implements IProductoService {
@Autowired
private IProductoRepo productoRepo;
@Override
public Producto registrar(Producto t) {
return productoRepo.save(t);
}
@Override
public Producto modificar(Producto t) {
return productoRepo.save(t);
}
@Override
public Producto leer(Integer id) {
return productoRepo.findById(id).orElse(null);
}
@Override
public List<Producto> listartodos() {
return productoRepo.findAll();
}
@Override
public void eliminar(Integer id) {
productoRepo.deleteById(id);
}
}
| 930 | 0.783871 | 0.77957 | 44 | 20.136364 | 21.053602 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.954545 | false | false |
10
|
f7711a479a43e738975f1881eb3aaade1e662f2a
| 10,471,130,329,493 |
7118ed465a9ec7f7618172e45d7e1447b6c10be1
|
/app/src/main/java/com/tti/unilagmba/UpdateNewsFeed.java
|
4a720707fa7060b1f684efcd462f62edffc44c19
|
[] |
no_license
|
BlackVick/UnilagMBA
|
https://github.com/BlackVick/UnilagMBA
|
c12058aaa6ec6580c3253cd1a468627400713e60
|
be99c1aab642807c58745e4fc61e47b59060c9ec
|
refs/heads/master
| 2022-01-09T00:11:16.875000 | 2019-06-01T06:28:21 | 2019-06-01T06:28:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.tti.unilagmba;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.theartofdev.edmodo.cropper.CropImage;
import com.tti.unilagmba.Common.Common;
import com.tti.unilagmba.Model.DataMessage;
import com.tti.unilagmba.Model.MyResponse;
import com.tti.unilagmba.Model.NewsFeeds;
import com.tti.unilagmba.Remote.APIService;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import dmax.dialog.SpotsDialog;
import id.zelory.compressor.Compressor;
import io.paperdb.Paper;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class UpdateNewsFeed extends AppCompatActivity {
MaterialEditText topic;
EditText broadcast;
Button sendBc;
ImageView imageUpload;
FirebaseDatabase db;
DatabaseReference news, usersRef;
FirebaseStorage storage;
StorageReference storageReference;
Uri imageUri;
private final static int GALLERY_REQUEST_CODE = 2;
private android.app.AlertDialog mDialog;
APIService mService;
String userSav = "";
String thumbDownloadUrl;
static String[] words = {"fuck", "fukk", "fucks", "fucker", "fucking", "fuckin", "fu*k", "phuck", "motherfucker", "muthafuka", "muthafucka",
"shit", "sh*t", "bullshit", "bullcrap",
"arse", "asshole", "arsehole", "bitch", "nigga", "bitchassnigga", "punani", "punk", "puni", "pucci", "pussy", "toto",
"blokus", "puci", "naked", "blowjob", "@$$", "booty", "boobs", "dick", "clit"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_news_feed);
Paper.init(this);
userSav = Paper.book().read(Common.USER_KEY);
mService = Common.getFCMService();
db = FirebaseDatabase.getInstance();
news = db.getReference("NewsFeeds");
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
/*---------- KEEP USERS ONLINE ----------*/
if (Common.currentUser != null) {
usersRef = FirebaseDatabase.getInstance().getReference().child("User").child(Common.currentUser.getMatric());
} else {
usersRef = FirebaseDatabase.getInstance().getReference().child("User").child(userSav);
}
usersRef.child("online").setValue(true);
topic = (MaterialEditText)findViewById(R.id.newsTopic);
broadcast = (EditText)findViewById(R.id.newsDetails);
sendBc = (Button)findViewById(R.id.updateNewsFeedBtn);
imageUpload = (ImageView)findViewById(R.id.uploadNewsImageButton);
imageUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent gallery_intent = new Intent();
gallery_intent.setType("image/*");
gallery_intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gallery_intent, "Pick Image"), GALLERY_REQUEST_CODE);
}
});
sendBc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Common.isConnectedToInternet(getBaseContext())) {
if (!TextUtils.isEmpty(topic.getText().toString()) || !TextUtils.isEmpty(broadcast.getText().toString()))
sendFeed();
} else {
Toast.makeText(UpdateNewsFeed.this, "No Internet Access !", Toast.LENGTH_SHORT).show();
}
}
});
}
private void sendFeed(){
long date = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy h:mm a");
final String dateString = sdf.format(date);
final String censoredTopic = censor(topic.getText().toString().trim());
final String censoredBroadcast = censor(broadcast.getText().toString().trim());
final Map<String, Object> newFeedMap = new HashMap<>();
newFeedMap.put("newsTitle", censoredTopic);
newFeedMap.put("sender", Common.currentUser.getUserName());
newFeedMap.put("newsDetail", censoredBroadcast);
if (imageUri != null)
newFeedMap.put("newsImage", thumbDownloadUrl);
else
newFeedMap.put("newsImage", "");
newFeedMap.put("time", dateString);
news.push().setValue(newFeedMap).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
sendNotification();
Intent clear = new Intent(UpdateNewsFeed.this, MainActivity.class);
startActivity(clear);
finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
});
}
public static String censor(String input) {
StringBuilder s = new StringBuilder(input);
for (int i = 0; i < input.length(); i++) {
for (String word : words) {
try {
if (input.substring(i, word.length() + i).equalsIgnoreCase(word)) {
for (int j = i; j < i + word.length(); j++) {
s.setCharAt(j, '*');
}
}
} catch (Exception e) {
}
}
}
return s.toString();
}
private void sendNotification() {
final String censoredTopic = censor(topic.getText().toString());
final String censoredBroadcast = censor(broadcast.getText().toString());
Map<String, String> dataSend = new HashMap<>();
dataSend.put("title", "News Alert");
dataSend.put("message", censoredTopic);
DataMessage dataMessage = new DataMessage(new StringBuilder("/topics/").append(Common.topicName).toString(), dataSend);
mService.sendNotification(dataMessage)
.enqueue(new Callback<MyResponse>() {
@Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (response.isSuccessful())
Toast.makeText(UpdateNewsFeed.this, "Broadcast Sent!", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<MyResponse> call, Throwable t) {
Toast.makeText(UpdateNewsFeed.this, ""+t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST_CODE && resultCode == RESULT_OK)
{
imageUri = data.getData();
CropImage.activity(imageUri)
.setAspectRatio(1,1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mDialog = new SpotsDialog(UpdateNewsFeed.this, "Uploading Picture");
mDialog.setCancelable(false);
mDialog.setCanceledOnTouchOutside(false);
mDialog.show();
Uri resultUri = result.getUri();
File thumb_filepath = new File(resultUri.getPath());
try {
Bitmap thumb_bitmap = new Compressor(this)
.setQuality(60)
.compressToBitmap(thumb_filepath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 60, baos);
final byte[] thumb_byte = baos.toByteArray();
final StorageReference thumbFilepath = storageReference.child("newsfeedimages").child(censor(topic.getText().toString()) + ".jpg");
thumbFilepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
UploadTask uploadTask = thumbFilepath.putBytes(thumb_byte);
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> thumb_task) {
thumbDownloadUrl = thumb_task.getResult().getDownloadUrl().toString();
if (thumb_task.isSuccessful()){
imageUpload.setImageResource(R.drawable.ic_uploaded_shit);
mDialog.dismiss();
} else {
mDialog.dismiss();
Toast.makeText(UpdateNewsFeed.this, "Error Uploading Thumb", Toast.LENGTH_SHORT).show();
}
}
});
} else {
mDialog.dismiss();
Toast.makeText(UpdateNewsFeed.this, "Error Uploading", Toast.LENGTH_SHORT).show();
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
@Override
protected void onResume() {
super.onResume();
/*---------- KEEP USERS ONLINE ----------*/
if (Common.currentUser != null) {
usersRef = FirebaseDatabase.getInstance().getReference().child("User").child(Common.currentUser.getMatric());
} else {
usersRef = FirebaseDatabase.getInstance().getReference().child("User").child(userSav);
}
usersRef.child("online").setValue(true);
}
@Override
protected void onPause() {
super.onPause();
if (Common.currentUser.getMatric() != null) {
usersRef = FirebaseDatabase.getInstance().getReference().child("User").child(Common.currentUser.getMatric());
usersRef.child("online").setValue(false);
}
}
}
|
UTF-8
|
Java
| 11,923 |
java
|
UpdateNewsFeed.java
|
Java
|
[
{
"context": "om.google.firebase.storage.UploadTask;\nimport com.jaredrummler.materialspinner.MaterialSpinner;\nimport com.rengw",
"end": 887,
"score": 0.9157206416130066,
"start": 875,
"tag": "USERNAME",
"value": "jaredrummler"
},
{
"context": "r.materialspinner.MaterialSpinner;\nimport com.rengwuxian.materialedittext.MaterialEditText;\nimport com.the",
"end": 942,
"score": 0.8853515982627869,
"start": 936,
"tag": "USERNAME",
"value": "wuxian"
}
] | null |
[] |
package com.tti.unilagmba;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.theartofdev.edmodo.cropper.CropImage;
import com.tti.unilagmba.Common.Common;
import com.tti.unilagmba.Model.DataMessage;
import com.tti.unilagmba.Model.MyResponse;
import com.tti.unilagmba.Model.NewsFeeds;
import com.tti.unilagmba.Remote.APIService;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import dmax.dialog.SpotsDialog;
import id.zelory.compressor.Compressor;
import io.paperdb.Paper;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class UpdateNewsFeed extends AppCompatActivity {
MaterialEditText topic;
EditText broadcast;
Button sendBc;
ImageView imageUpload;
FirebaseDatabase db;
DatabaseReference news, usersRef;
FirebaseStorage storage;
StorageReference storageReference;
Uri imageUri;
private final static int GALLERY_REQUEST_CODE = 2;
private android.app.AlertDialog mDialog;
APIService mService;
String userSav = "";
String thumbDownloadUrl;
static String[] words = {"fuck", "fukk", "fucks", "fucker", "fucking", "fuckin", "fu*k", "phuck", "motherfucker", "muthafuka", "muthafucka",
"shit", "sh*t", "bullshit", "bullcrap",
"arse", "asshole", "arsehole", "bitch", "nigga", "bitchassnigga", "punani", "punk", "puni", "pucci", "pussy", "toto",
"blokus", "puci", "naked", "blowjob", "@$$", "booty", "boobs", "dick", "clit"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_news_feed);
Paper.init(this);
userSav = Paper.book().read(Common.USER_KEY);
mService = Common.getFCMService();
db = FirebaseDatabase.getInstance();
news = db.getReference("NewsFeeds");
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
/*---------- KEEP USERS ONLINE ----------*/
if (Common.currentUser != null) {
usersRef = FirebaseDatabase.getInstance().getReference().child("User").child(Common.currentUser.getMatric());
} else {
usersRef = FirebaseDatabase.getInstance().getReference().child("User").child(userSav);
}
usersRef.child("online").setValue(true);
topic = (MaterialEditText)findViewById(R.id.newsTopic);
broadcast = (EditText)findViewById(R.id.newsDetails);
sendBc = (Button)findViewById(R.id.updateNewsFeedBtn);
imageUpload = (ImageView)findViewById(R.id.uploadNewsImageButton);
imageUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent gallery_intent = new Intent();
gallery_intent.setType("image/*");
gallery_intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gallery_intent, "Pick Image"), GALLERY_REQUEST_CODE);
}
});
sendBc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Common.isConnectedToInternet(getBaseContext())) {
if (!TextUtils.isEmpty(topic.getText().toString()) || !TextUtils.isEmpty(broadcast.getText().toString()))
sendFeed();
} else {
Toast.makeText(UpdateNewsFeed.this, "No Internet Access !", Toast.LENGTH_SHORT).show();
}
}
});
}
private void sendFeed(){
long date = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy h:mm a");
final String dateString = sdf.format(date);
final String censoredTopic = censor(topic.getText().toString().trim());
final String censoredBroadcast = censor(broadcast.getText().toString().trim());
final Map<String, Object> newFeedMap = new HashMap<>();
newFeedMap.put("newsTitle", censoredTopic);
newFeedMap.put("sender", Common.currentUser.getUserName());
newFeedMap.put("newsDetail", censoredBroadcast);
if (imageUri != null)
newFeedMap.put("newsImage", thumbDownloadUrl);
else
newFeedMap.put("newsImage", "");
newFeedMap.put("time", dateString);
news.push().setValue(newFeedMap).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
sendNotification();
Intent clear = new Intent(UpdateNewsFeed.this, MainActivity.class);
startActivity(clear);
finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
});
}
public static String censor(String input) {
StringBuilder s = new StringBuilder(input);
for (int i = 0; i < input.length(); i++) {
for (String word : words) {
try {
if (input.substring(i, word.length() + i).equalsIgnoreCase(word)) {
for (int j = i; j < i + word.length(); j++) {
s.setCharAt(j, '*');
}
}
} catch (Exception e) {
}
}
}
return s.toString();
}
private void sendNotification() {
final String censoredTopic = censor(topic.getText().toString());
final String censoredBroadcast = censor(broadcast.getText().toString());
Map<String, String> dataSend = new HashMap<>();
dataSend.put("title", "News Alert");
dataSend.put("message", censoredTopic);
DataMessage dataMessage = new DataMessage(new StringBuilder("/topics/").append(Common.topicName).toString(), dataSend);
mService.sendNotification(dataMessage)
.enqueue(new Callback<MyResponse>() {
@Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (response.isSuccessful())
Toast.makeText(UpdateNewsFeed.this, "Broadcast Sent!", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<MyResponse> call, Throwable t) {
Toast.makeText(UpdateNewsFeed.this, ""+t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST_CODE && resultCode == RESULT_OK)
{
imageUri = data.getData();
CropImage.activity(imageUri)
.setAspectRatio(1,1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mDialog = new SpotsDialog(UpdateNewsFeed.this, "Uploading Picture");
mDialog.setCancelable(false);
mDialog.setCanceledOnTouchOutside(false);
mDialog.show();
Uri resultUri = result.getUri();
File thumb_filepath = new File(resultUri.getPath());
try {
Bitmap thumb_bitmap = new Compressor(this)
.setQuality(60)
.compressToBitmap(thumb_filepath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 60, baos);
final byte[] thumb_byte = baos.toByteArray();
final StorageReference thumbFilepath = storageReference.child("newsfeedimages").child(censor(topic.getText().toString()) + ".jpg");
thumbFilepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
UploadTask uploadTask = thumbFilepath.putBytes(thumb_byte);
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> thumb_task) {
thumbDownloadUrl = thumb_task.getResult().getDownloadUrl().toString();
if (thumb_task.isSuccessful()){
imageUpload.setImageResource(R.drawable.ic_uploaded_shit);
mDialog.dismiss();
} else {
mDialog.dismiss();
Toast.makeText(UpdateNewsFeed.this, "Error Uploading Thumb", Toast.LENGTH_SHORT).show();
}
}
});
} else {
mDialog.dismiss();
Toast.makeText(UpdateNewsFeed.this, "Error Uploading", Toast.LENGTH_SHORT).show();
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
@Override
protected void onResume() {
super.onResume();
/*---------- KEEP USERS ONLINE ----------*/
if (Common.currentUser != null) {
usersRef = FirebaseDatabase.getInstance().getReference().child("User").child(Common.currentUser.getMatric());
} else {
usersRef = FirebaseDatabase.getInstance().getReference().child("User").child(userSav);
}
usersRef.child("online").setValue(true);
}
@Override
protected void onPause() {
super.onPause();
if (Common.currentUser.getMatric() != null) {
usersRef = FirebaseDatabase.getInstance().getReference().child("User").child(Common.currentUser.getMatric());
usersRef.child("online").setValue(false);
}
}
}
| 11,923 | 0.584836 | 0.58383 | 304 | 38.220394 | 32.913277 | 151 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.740132 | false | false |
10
|
9be33cae8aa49a79d86d11d0c0aea161a63bd5cb
| 34,076,270,545,468 |
5019edb5550eb0cc2373d6ec79c730f4ed4aa0b8
|
/requestlater-api/src/main/java/com/neptune/api/requestlater/filter/BasicAuthFilter.java
|
0e4d7ac0d99ee1372e211de7eff7c233704abc45
|
[] |
no_license
|
luizamastelari/requestlater
|
https://github.com/luizamastelari/requestlater
|
6eeb054a57944684fabbd886d08c96abdcc3d311
|
f2ee22b00ec46a7634c6ec2fd344c314fc936d95
|
refs/heads/master
| 2021-10-21T21:16:48.389000 | 2017-08-22T19:55:02 | 2017-08-22T19:55:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.neptune.api.requestlater.filter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response.Status;
import org.glassfish.jersey.internal.util.Base64;
public class BasicAuthFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext)
throws IOException {
String method = requestContext.getMethod();
String path = requestContext.getUriInfo().getPath();
if (method.equals("GET") && (path.equals("application.wadl")
|| path.equals("application.wadl/xsd0.xsd"))) {
return;
}
// OPTIONS is allowed because of CORS
if (method.equals("OPTIONS")) {
return;
}
// Header Auth
String auth = requestContext.getHeaderString("Authorization");
// No Auth, then abort
if (auth == null) {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
// User and Passowrd
List<String> lap = Arrays.asList(this.auth(auth));
// Something wrong...
if (lap == null || lap.size() != 2) {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
// TODO: database checks
if (lap.get(0).equals("voyeur_admin") && lap.get(1).equals("123456")) {
return;
} else {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
}
private String[] auth(String authorization) {
if (authorization != null && authorization.startsWith("Basic")) {
// Authorization: Basic base64credentials
String base64Credentials = authorization.substring("Basic".length())
.trim();
String credentials = new String(
Base64.decode(base64Credentials.getBytes()),
Charset.forName("UTF-8"));
// credentials = username:password
return credentials.split(":", 2);
}
return null;
}
}
|
UTF-8
|
Java
| 2,264 |
java
|
BasicAuthFilter.java
|
Java
|
[] | null |
[] |
package com.neptune.api.requestlater.filter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response.Status;
import org.glassfish.jersey.internal.util.Base64;
public class BasicAuthFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext)
throws IOException {
String method = requestContext.getMethod();
String path = requestContext.getUriInfo().getPath();
if (method.equals("GET") && (path.equals("application.wadl")
|| path.equals("application.wadl/xsd0.xsd"))) {
return;
}
// OPTIONS is allowed because of CORS
if (method.equals("OPTIONS")) {
return;
}
// Header Auth
String auth = requestContext.getHeaderString("Authorization");
// No Auth, then abort
if (auth == null) {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
// User and Passowrd
List<String> lap = Arrays.asList(this.auth(auth));
// Something wrong...
if (lap == null || lap.size() != 2) {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
// TODO: database checks
if (lap.get(0).equals("voyeur_admin") && lap.get(1).equals("123456")) {
return;
} else {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
}
private String[] auth(String authorization) {
if (authorization != null && authorization.startsWith("Basic")) {
// Authorization: Basic base64credentials
String base64Credentials = authorization.substring("Basic".length())
.trim();
String credentials = new String(
Base64.decode(base64Credentials.getBytes()),
Charset.forName("UTF-8"));
// credentials = username:password
return credentials.split(":", 2);
}
return null;
}
}
| 2,264 | 0.613516 | 0.603799 | 75 | 29.200001 | 24.949015 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.413333 | false | false |
10
|
12e908cc6e3202aa1d9e426367866188740dd034
| 36,249,523,982,653 |
726b632416ae29c94a8a7be6ae858ff4e3869764
|
/src/flight/puregt/FlightGTMonitor.java
|
e46f181cb0ea7275080abd201f5b7b3e5aa55932
|
[] |
no_license
|
eMoflon-CEP/FlightGTCEP
|
https://github.com/eMoflon-CEP/FlightGTCEP
|
bbe2c2d6ac926790d29c74156fe6924f01f6121f
|
f5c69a372e9cba219e474c81c573f78605713c91
|
refs/heads/master
| 2020-12-23T01:15:03.701000 | 2020-05-06T11:38:41 | 2020-05-06T11:38:41 | 236,986,989 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package flight.puregt;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.Collectors;
import static org.emoflon.flight.model.util.LongDateHelper.deltaAsString;
import static org.emoflon.flight.model.util.LongDateHelper.getString_mmhhDDMMYYYY;
import FlightGTCEP.api.matches.ConnectingFlightAlternativeMatch;
import FlightGTCEP.api.matches.FlightMatch;
import FlightGTCEP.api.matches.FlightWithArrivalMatch;
import FlightGTCEP.api.matches.TravelHasConnectingFlightMatch;
import FlightGTCEP.api.matches.TravelMatch;
import FlightGTCEP.api.matches.TravelWithFlightMatch;
import Flights.Flight;
import Flights.FlightModel;
import Flights.Plane;
import Flights.Travel;
import flight.monitor.FlightMonitor;
public class FlightGTMonitor extends FlightMonitor{
protected Map<Flight, Long> flight2Arrival;
protected Map<Flight, Set<Travel>> flight2Travels;
protected Map<Travel, Set<TravelHasConnectingFlightMatch>> travel2DelayedConnectingFlights;
protected Map<Travel, Set<TravelHasConnectingFlightMatch>> travel2ConnectingFlights;
protected Map<Travel, SortedSet<ConnectingFlightAlternativeMatch>> travel2AlternativeConnectingFlights;
protected Map<Flight, Set<ConnectingFlightAlternativeMatch>> overfullAlternatives;
@Override
public void initModelAndEngine(String modelPath) {
super.initModelAndEngine(modelPath);
init();
}
@Override
public void initModelAndEngine(FlightModel model) {
super.initModelAndEngine(model);
init();
}
private void init( ) {
flight2Arrival = Collections.synchronizedMap(new HashMap<>());
flight2Travels = Collections.synchronizedMap(new HashMap<>());
travel2DelayedConnectingFlights = Collections.synchronizedMap(new HashMap<>());
travel2ConnectingFlights = Collections.synchronizedMap(new HashMap<>());
travel2AlternativeConnectingFlights = Collections.synchronizedMap(new HashMap<>());
overfullAlternatives = Collections.synchronizedMap(new HashMap<>());
issues = Collections.synchronizedMap(new LinkedHashMap<>());
solutions = Collections.synchronizedMap(new LinkedHashMap<>());
issueMessages = new LinkedBlockingQueue<>();
infoMessages = new LinkedBlockingQueue<>();
solutionMessages = new LinkedBlockingQueue<>();
}
@Override
public void initMatchSubscribers() {
api.flight().subscribeAppearing(this::watchAppearingFlights);
api.flight().subscribeDisappearing(this::watchDisappearingFlights);
api.flightWithArrival().subscribeAppearing(this::watchFlightArrivals);
api.travel().subscribeDisappearing(this::watchDisappearingTravels);
api.travelWithFlight().subscribeAppearing(this::watchAppearingFlightsWithTravels);
api.travelWithFlight().subscribeDisappearing(this::watchDisappearingFlightsWithTravels);
api.travelHasConnectingFlight().subscribeAppearing(this::watchAppearingConnectingFlights);
api.travelHasConnectingFlight().subscribeDisappearing(this::watchDisappearingConnectingFlights);
api.connectingFlightAlternative().subscribeAppearing(this::watchAppearingConnectingFlightAlternatives);
api.connectingFlightAlternative().subscribeDisappearing(this::watchDisappearingConnectingFlightAlternatives);
}
@Override
public synchronized void update(boolean debug) {
api.updateMatches();
if(debug) {
StringBuilder sb = new StringBuilder();
FlightModel container = (FlightModel)api.getModel().getResources().get(0).getContents().get(0);
sb.append("*** Time: " + container.getGlobalTime().getTime() + "\nOverall status:\n***");
sb.append("\nDetected " + flight2Arrival.entrySet().stream()
.filter(entry -> (entry.getValue() != null))
.count()
+ " flights overall.");
sb.append("\nDetected " + flight2Travels.values().stream()
.map(travels -> travels.size())
.reduce(0, (sum, value) -> sum + value)
+ " flights with booked travels.");
sb.append("\nDetected " + flight2Travels.values().stream()
.distinct()
.map(travels -> travels.size())
.reduce(0, (sum, value) -> sum + value)
+ " travels overall.");
sb.append("\nDetected " + travel2ConnectingFlights.values().stream()
.map(travels -> travels.size())
.reduce(0, (sum, value) -> sum + value)
+ " intact connecting flights in travels overall.");
sb.append("\nDetected " + travel2DelayedConnectingFlights.values().stream()
.map(travels -> travels.size())
.reduce(0, (sum, value) -> sum + value)
+ " broken/delayed connecting flights in travels overall.");
sb.append("\nDetected " + travel2AlternativeConnectingFlights.values().stream()
.map(travels -> travels.size())
.reduce(0, (sum, value) -> sum + value)
+ " alternative connecting flights in travels overall.");
// sb.append("\n***\nAppeared issues:\n***");
// while(!issueMessages.isEmpty()) {
// sb.append("\n"+issueMessages.poll());
// }
//
// sb.append("\n***\nAppeared events:\n***");
// while(!infoMessages.isEmpty()) {
// sb.append("\n"+infoMessages.poll());
// }
//
// sb.append("\n***\nAppeared solutions:\n***");
// while(!solutionMessages.isEmpty()) {
// sb.append("\n"+solutionMessages.poll());
// }
sb.append("\n***\n***");
System.out.println(sb.toString());
}
}
@Override
public void shutdown() {
api.terminate();
}
private synchronized void watchAppearingFlights(FlightMatch match) {
flight2Travels.putIfAbsent(match.getFlight(), new HashSet<>());
flight2Arrival.putIfAbsent(match.getFlight(), match.getFlight().getArrival().getTime());
overfullAlternatives.put(match.getFlight(), new HashSet<>());
}
private synchronized void watchDisappearingFlights(FlightMatch match) {
flight2Travels.remove(match.getFlight());
flight2Arrival.remove(match.getFlight());
overfullAlternatives.remove(match.getFlight());
}
private synchronized void watchDisappearingTravels(TravelMatch match) {
Collection<Flight> flights = match.getTravel().getFlights();
for(Flight flight : flights) {
Set<Travel> travels = flight2Travels.get(flight);
if(travels != null) {
travels.remove(match.getTravel());
}
}
travel2ConnectingFlights.remove(match.getTravel());
if(travel2DelayedConnectingFlights.containsKey(match.getTravel())) {
travel2DelayedConnectingFlights.get(match.getTravel())
.forEach(connectingFlight -> {
removeIssue(connectingFlight);
infoMessages.add("Travel "+match.getTravel().getID()+" completed or canceled. Therefore, the issue concerning the delayed connecting flight "+connectingFlight.getConnectingFlight().getID()+" has been resolved.\n");
});
}
travel2DelayedConnectingFlights.remove(match.getTravel());
travel2AlternativeConnectingFlights.remove(match.getTravel());
//TODO: Cleanup issues and solutions!
}
private synchronized void watchAppearingFlightsWithTravels(TravelWithFlightMatch match) {
final Flight flight = match.getFlight();
Set<Travel> travels = flight2Travels.get(flight);
if(travels == null) {
travels = new HashSet<>();
flight2Travels.put(flight, travels);
}
travels.add(match.getTravel());
Plane plane = match.getPlane();
if(plane.getCapacity() <= travels.size()) {
if(plane.getCapacity() < travels.size()) {
addIssue(match, "Plane on flight "+flight.getID()+" is overbooked (#travels="+travels.size()+") and capacity is "+plane.getCapacity()+".");
}else {
infoMessages.add("Plane on flight "+flight.getID()+" is full (#travels="+travels.size()+") and capacity is "+plane.getCapacity()+".");
}
List<ConnectingFlightAlternativeMatch> removedAlternatives = travel2AlternativeConnectingFlights.values()
.parallelStream()
.flatMap(altMatchSet -> altMatchSet.stream())
.filter(altMatch -> altMatch.getFlight().equals(flight))
.collect(Collectors.toList());
for(ConnectingFlightAlternativeMatch removal : removedAlternatives) {
Set<ConnectingFlightAlternativeMatch> alternatives = travel2AlternativeConnectingFlights.get(removal.getTravel());
if(alternatives != null) {
alternatives.remove(removal);
Set<ConnectingFlightAlternativeMatch> overfull = overfullAlternatives.get(flight);
if(overfull == null) {
overfull = new HashSet<>();
overfullAlternatives.put(flight, overfull);
}
overfull.add(removal);
//TODO: Does this become an issue?
infoMessages.add("Travel "+removal.getTravel().getID() + " hast lost its alternative connecting flight " + removal.getReplacementFlight().getID() + " since the plane is full..\n");
}
}
}
}
private synchronized void watchDisappearingFlightsWithTravels(TravelWithFlightMatch match) {
Flight flight = match.getFlight();
Set<Travel> travels = flight2Travels.get(flight);
if(travels != null) {
Plane plane = match.getPlane();
if(plane.getCapacity() > travels.size() - 1) {
List<ConnectingFlightAlternativeMatch> removals = new LinkedList<>();
Set<ConnectingFlightAlternativeMatch> overfull = overfullAlternatives.get(flight);
if(overfull != null) {
for(ConnectingFlightAlternativeMatch alternative : overfull) {
infoMessages.add("Travel "+alternative.getTravel().getID() + " has gained an alternative connecting flight " + alternative.getReplacementFlight().getID() + " since the plane some seats left.\n");
removals.add(alternative);
SortedSet<ConnectingFlightAlternativeMatch> alternatives = travel2AlternativeConnectingFlights.get(alternative.getTravel());
if(alternatives == null) {
alternatives = createSortedSet();
travel2AlternativeConnectingFlights.put(alternative.getTravel(), alternatives);
}
alternatives.add(alternative);
if(alternatives.first().equals(alternative)) {
//TODO: Search for the correct connecting flight -> TravelWithFlightMatch match is the wrong type of issue match!
addSolution(match, alternative, "Travel "+match.getTravel().getID()+" can reach its destination via alternative connecting flight "+alternative.getReplacementFlight().getID()+".\n"+
"---> ETA: "+getString_mmhhDDMMYYYY(alternative.getFlight().getArrival().getTime()) + ", ETD: "+getString_mmhhDDMMYYYY(alternative.getReplacementDeparture().getTime()));
}
}
}
overfull.removeAll(removals);
}
travels.remove(match.getTravel());
}
}
private synchronized void watchAppearingConnectingFlights(TravelHasConnectingFlightMatch match) {
long dGates = calcGateDistance(match.getTransitAirport(), match.getArrivalGate(), match.getDepartingGate());
long arrival = match.getFlight().getArrival().getTime();
long departure = match.getConnectingFlight().getDeparture().getTime();
if(arrival+dGates > departure) {
addIssue(match, "Travel "+match.getTravel().getID()+" will miss its connecting flight "+match.getConnectingFlight().getID()+" due to a delayed arrival time.\n"+
"---> ETA: "+getString_mmhhDDMMYYYY(arrival)+", distance to gate: "+deltaAsString(dGates)+", ETD: "+getString_mmhhDDMMYYYY(departure));
Set<TravelHasConnectingFlightMatch> brokenFlights = travel2DelayedConnectingFlights.get(match.getTravel());
if(brokenFlights == null) {
brokenFlights = new HashSet<>();
travel2DelayedConnectingFlights.put(match.getTravel(), brokenFlights);
}
brokenFlights.add(match);
Set<TravelHasConnectingFlightMatch> connectingFlights = travel2ConnectingFlights.get(match.getTravel());
if(connectingFlights != null) {
connectingFlights.remove(match);
}
Set<ConnectingFlightAlternativeMatch> connectingAlternatives = travel2AlternativeConnectingFlights.get(match.getTravel());
if(connectingAlternatives!=null) {
for(ConnectingFlightAlternativeMatch connectingFlightAlternative : connectingAlternatives) {
long dGatesAlt = calcGateDistance(match.getTransitAirport(), match.getArrivalGate(), connectingFlightAlternative.getReplacementFlight().getSrc());
long arrivalAlt = match.getFlight().getArrival().getTime();
long departureAlt = connectingFlightAlternative.getReplacementFlight().getDeparture().getTime();
if(arrivalAlt + dGatesAlt <= departureAlt
&& connectingFlightAlternative.getFlight().getPlane().getCapacity() >= flight2Travels.get(connectingFlightAlternative.getFlight()).size() + 1) {
if(match.getTransitAirport() == connectingFlightAlternative.getTransitAirport() && match.getConnectingRoute().getTrg() == connectingFlightAlternative.getConnectingRoute().getTrg()) {
addSolution(match, connectingFlightAlternative, "Travel "+match.getTravel().getID()+" can reach its destination via alternative connecting flight "+connectingFlightAlternative.getReplacementFlight().getID()+".\n"+
"---> ETA: "+getString_mmhhDDMMYYYY(arrivalAlt)+", distance to gate: "+deltaAsString(dGatesAlt)+", ETD: "+getString_mmhhDDMMYYYY(departureAlt));
break;
}
}
}
}
return;
}
Set<TravelHasConnectingFlightMatch> connectingFlights = travel2ConnectingFlights.get(match.getTravel());
if(connectingFlights == null) {
connectingFlights = new HashSet<>();
travel2ConnectingFlights.put(match.getTravel(), connectingFlights);
}
connectingFlights.add(match);
Set<TravelHasConnectingFlightMatch> brokenFlights = travel2DelayedConnectingFlights.get(match.getTravel());
if(brokenFlights != null) {
if(brokenFlights.remove(match)) {
infoMessages.add("Travel "+match.getTravel().getID()+" will make its connecting flight "+match.getConnectingFlight().getID()+" since the delay has been resolved.\n"+
"---> ETA: "+getString_mmhhDDMMYYYY(arrival)+", distance to gate: "+deltaAsString(dGates)+", ETD: "+getString_mmhhDDMMYYYY(departure));
connectingFlights.add(match);
removeIssue(match);
}
}
}
private synchronized void watchDisappearingConnectingFlights(TravelHasConnectingFlightMatch match) {
Set<TravelHasConnectingFlightMatch> brokenFlights = travel2DelayedConnectingFlights.get(match.getTravel());
if(brokenFlights == null) {
brokenFlights = new HashSet<>();
travel2DelayedConnectingFlights.put(match.getTravel(), brokenFlights);
}
addIssue(match, "Travel "+match.getTravel().getID()+" will miss its connecting flight "+match.getConnectingFlight().getID());
brokenFlights.add(match);
Set<TravelHasConnectingFlightMatch> connectingFlights = travel2ConnectingFlights.get(match.getTravel());
if(connectingFlights != null) {
connectingFlights.remove(match);
}
Set<ConnectingFlightAlternativeMatch> connectingAlternatives = travel2AlternativeConnectingFlights.get(match.getTravel());
if(connectingAlternatives!=null) {
for(ConnectingFlightAlternativeMatch connectingFlightAlternative : connectingAlternatives) {
long dGatesAlt = calcGateDistance(match.getTransitAirport(), match.getArrivalGate(), connectingFlightAlternative.getReplacementFlight().getSrc());
long arrivalAlt = match.getFlight().getArrival().getTime();
long departureAlt = connectingFlightAlternative.getReplacementFlight().getDeparture().getTime();
if(flight2Travels.get(connectingFlightAlternative.getFlight()) == null)
continue;
if(arrivalAlt + dGatesAlt <= departureAlt
&& connectingFlightAlternative.getFlight().getPlane().getCapacity() >= flight2Travels.get(connectingFlightAlternative.getFlight()).size() + 1) {
if(match.getTransitAirport() == connectingFlightAlternative.getTransitAirport() && match.getConnectingRoute().getTrg() == connectingFlightAlternative.getConnectingRoute().getTrg()) {
addSolution(match, connectingFlightAlternative, "Travel "+match.getTravel().getID()+" can reach its destination via alternative connecting flight "+connectingFlightAlternative.getReplacementFlight().getID()+".\n"+
"---> ETA: "+getString_mmhhDDMMYYYY(arrivalAlt)+", distance to gate: "+deltaAsString(dGatesAlt)+", ETD: "+getString_mmhhDDMMYYYY(departureAlt));
break;
}
}
}
}
}
private synchronized void watchFlightArrivals(FlightWithArrivalMatch match) {
Long prevArrival = flight2Arrival.get(match.getFlight());
if(prevArrival == null)
return;
Long currentArrival = match.getFlight().getArrival().getTime();
flight2Arrival.replace(match.getFlight(), currentArrival);
Set<Travel> travels = flight2Travels.get(match.getFlight());
if(travels == null)
return;
// check travels in case of a early arrival
if(currentArrival<prevArrival) {
infoMessages.add("Flight "+match.getFlight().getID()+" will arrive early by "+ deltaAsString(prevArrival-currentArrival) +"minutes.\n"+
"---> current ETA: "+getString_mmhhDDMMYYYY(currentArrival)+", original ETA: "+getString_mmhhDDMMYYYY(prevArrival));
for(Travel travel : travels) {
Set<TravelHasConnectingFlightMatch> brokenFlights = travel2DelayedConnectingFlights.get(travel);
if(brokenFlights == null)
continue;
Set<TravelHasConnectingFlightMatch> removedFlights = new HashSet<>();
for(TravelHasConnectingFlightMatch brokenFlight : brokenFlights) {
long dGates = calcGateDistance(brokenFlight.getTransitAirport(), brokenFlight.getArrivalGate(), brokenFlight.getDepartingGate());
long arrival = brokenFlight.getFlight().getArrival().getTime();
long departure = brokenFlight.getConnectingFlight().getDeparture().getTime();
if(arrival+dGates <= departure) {
infoMessages.add("Travel "+brokenFlight.getTravel().getID()+" will now make its connecting flight "+brokenFlight.getConnectingFlight().getID()+" since the delay has been resolved.\n"+
"---> ETA: "+getString_mmhhDDMMYYYY(arrival)+", distance to gate: "+deltaAsString(dGates)+", ETD: "+getString_mmhhDDMMYYYY(departure));
removeIssue(brokenFlight);
//TODO: Delete issues!
Set<TravelHasConnectingFlightMatch> connectedFlights = travel2ConnectingFlights.get(brokenFlight.getTravel());
if(connectedFlights == null) {
connectedFlights = new HashSet<>();
travel2DelayedConnectingFlights.put(brokenFlight.getTravel(), connectedFlights);
}
connectedFlights.add(brokenFlight);
removedFlights.add(brokenFlight);
}
}
brokenFlights.removeAll(removedFlights);
}
}
// check travels in case of a delay
else if(currentArrival>prevArrival) {
infoMessages.add("Flight "+match.getFlight().getID()+" currently has a delay of "+ deltaAsString(currentArrival-prevArrival) +"minutes.\n"+
"---> current ETA: "+getString_mmhhDDMMYYYY(currentArrival)+", original ETA: "+getString_mmhhDDMMYYYY(prevArrival));
for(Travel travel : travels) {
Set<TravelHasConnectingFlightMatch> connectingFlights = travel2ConnectingFlights.get(travel);
if(connectingFlights == null)
continue;
Set<TravelHasConnectingFlightMatch> removedFlights = new HashSet<>();
for(TravelHasConnectingFlightMatch connectingFlight : connectingFlights) {
long dGates = calcGateDistance(connectingFlight.getTransitAirport(), connectingFlight.getArrivalGate(), connectingFlight.getDepartingGate());
long arrival = connectingFlight.getFlight().getArrival().getTime();
long departure = connectingFlight.getConnectingFlight().getDeparture().getTime();
if(arrival+dGates > departure) {
addIssue(connectingFlight, "Travel "+connectingFlight.getTravel().getID()+" will miss its connecting flight "+connectingFlight.getConnectingFlight().getID()+" due to a delayed arrival time.\n"+
"---> ETA: "+getString_mmhhDDMMYYYY(arrival)+", distance to gate: "+deltaAsString(dGates)+", ETD: "+getString_mmhhDDMMYYYY(departure));
Set<TravelHasConnectingFlightMatch> brokenFlights = travel2DelayedConnectingFlights.get(connectingFlight.getTravel());
if(brokenFlights == null) {
brokenFlights = new HashSet<>();
travel2DelayedConnectingFlights.put(connectingFlight.getTravel(), brokenFlights);
}
brokenFlights.add(connectingFlight);
removedFlights.add(connectingFlight);
Set<ConnectingFlightAlternativeMatch> connectingAlternatives = travel2AlternativeConnectingFlights.get(connectingFlight.getTravel());
if(connectingAlternatives!=null) {
for(ConnectingFlightAlternativeMatch connectingFlightAlternative : connectingAlternatives) {
long dGatesAlt = calcGateDistance(connectingFlight.getTransitAirport(), connectingFlight.getArrivalGate(), connectingFlightAlternative.getReplacementFlight().getSrc());
long arrivalAlt = connectingFlightAlternative.getFlight().getArrival().getTime();
long departureAlt = connectingFlightAlternative.getReplacementFlight().getDeparture().getTime();
if(flight2Travels.get(connectingFlightAlternative.getFlight()) == null)
continue;
if(arrivalAlt + dGatesAlt <= departureAlt
&& connectingFlightAlternative.getFlight().getPlane().getCapacity() >= flight2Travels.get(connectingFlightAlternative.getFlight()).size() + 1) {
if(connectingFlight.getTransitAirport() == connectingFlightAlternative.getTransitAirport() && connectingFlight.getConnectingRoute().getTrg() == connectingFlightAlternative.getConnectingRoute().getTrg()) {
addSolution(connectingFlight, connectingFlightAlternative, "Travel "+connectingFlight.getTravel().getID()+" can reach its destination via alternative connecting flight "+connectingFlightAlternative.getReplacementFlight().getID()+".\n"+
"---> ETA: "+getString_mmhhDDMMYYYY(arrivalAlt)+", distance to gate: "+deltaAsString(dGatesAlt)+", ETD: "+getString_mmhhDDMMYYYY(departureAlt));
break;
}
}
}
}
}
}
connectingFlights.removeAll(removedFlights);
}
}
}
private synchronized void watchAppearingConnectingFlightAlternatives(ConnectingFlightAlternativeMatch match) {
SortedSet<ConnectingFlightAlternativeMatch> alternatives = travel2AlternativeConnectingFlights.get(match.getTravel());
if(alternatives == null) {
alternatives = createSortedSet();
travel2AlternativeConnectingFlights.put(match.getTravel(), alternatives);
}
long dGates = calcGateDistance(match.getTransitAirport(), match.getArrivalGate(), match.getReplacementFlight().getSrc());
long arrival = match.getFlight().getArrival().getTime();
long departure = match.getReplacementFlight().getDeparture().getTime();
if(arrival + dGates <= departure
&& match.getFlight().getPlane().getCapacity() >= flight2Travels.get(match.getFlight()).size() + 1) {
alternatives.add(match);
Set<TravelHasConnectingFlightMatch> brokenConnectingFlights = travel2DelayedConnectingFlights.get(match.getTravel());
if(brokenConnectingFlights != null && match.equals(alternatives.first())) {
for(TravelHasConnectingFlightMatch brokenConnectingFlight : brokenConnectingFlights) {
if(match.getConnectingRoute() == brokenConnectingFlight.getConnectingRoute()) {
addSolution(brokenConnectingFlight, match, "Travel "+brokenConnectingFlight.getTravel().getID()+" can reach its destination via alternative connecting flight "+match.getReplacementFlight().getID()+".\n"+
"---> ETA: "+getString_mmhhDDMMYYYY(arrival)+", distance to gate: "+deltaAsString(dGates)+", ETD: "+getString_mmhhDDMMYYYY(departure));
}
}
}
}
}
private synchronized void watchDisappearingConnectingFlightAlternatives(ConnectingFlightAlternativeMatch match) {
Set<ConnectingFlightAlternativeMatch> alternatives = travel2AlternativeConnectingFlights.get(match.getTravel());
if(alternatives != null) {
alternatives.remove(match);
}
}
@Override
public long getWorkingConnectingFlightTravels() {
return travel2ConnectingFlights.values().stream().flatMap(set -> set.stream()).collect(Collectors.toSet()).size();
}
@Override
public long getDelayedConnectingFlightTravels() {
return travel2DelayedConnectingFlights.values().stream().flatMap(set -> set.stream()).collect(Collectors.toSet()).size();
}
}
|
UTF-8
|
Java
| 24,175 |
java
|
FlightGTMonitor.java
|
Java
|
[] | null |
[] |
package flight.puregt;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.Collectors;
import static org.emoflon.flight.model.util.LongDateHelper.deltaAsString;
import static org.emoflon.flight.model.util.LongDateHelper.getString_mmhhDDMMYYYY;
import FlightGTCEP.api.matches.ConnectingFlightAlternativeMatch;
import FlightGTCEP.api.matches.FlightMatch;
import FlightGTCEP.api.matches.FlightWithArrivalMatch;
import FlightGTCEP.api.matches.TravelHasConnectingFlightMatch;
import FlightGTCEP.api.matches.TravelMatch;
import FlightGTCEP.api.matches.TravelWithFlightMatch;
import Flights.Flight;
import Flights.FlightModel;
import Flights.Plane;
import Flights.Travel;
import flight.monitor.FlightMonitor;
public class FlightGTMonitor extends FlightMonitor{
protected Map<Flight, Long> flight2Arrival;
protected Map<Flight, Set<Travel>> flight2Travels;
protected Map<Travel, Set<TravelHasConnectingFlightMatch>> travel2DelayedConnectingFlights;
protected Map<Travel, Set<TravelHasConnectingFlightMatch>> travel2ConnectingFlights;
protected Map<Travel, SortedSet<ConnectingFlightAlternativeMatch>> travel2AlternativeConnectingFlights;
protected Map<Flight, Set<ConnectingFlightAlternativeMatch>> overfullAlternatives;
@Override
public void initModelAndEngine(String modelPath) {
super.initModelAndEngine(modelPath);
init();
}
@Override
public void initModelAndEngine(FlightModel model) {
super.initModelAndEngine(model);
init();
}
private void init( ) {
flight2Arrival = Collections.synchronizedMap(new HashMap<>());
flight2Travels = Collections.synchronizedMap(new HashMap<>());
travel2DelayedConnectingFlights = Collections.synchronizedMap(new HashMap<>());
travel2ConnectingFlights = Collections.synchronizedMap(new HashMap<>());
travel2AlternativeConnectingFlights = Collections.synchronizedMap(new HashMap<>());
overfullAlternatives = Collections.synchronizedMap(new HashMap<>());
issues = Collections.synchronizedMap(new LinkedHashMap<>());
solutions = Collections.synchronizedMap(new LinkedHashMap<>());
issueMessages = new LinkedBlockingQueue<>();
infoMessages = new LinkedBlockingQueue<>();
solutionMessages = new LinkedBlockingQueue<>();
}
@Override
public void initMatchSubscribers() {
api.flight().subscribeAppearing(this::watchAppearingFlights);
api.flight().subscribeDisappearing(this::watchDisappearingFlights);
api.flightWithArrival().subscribeAppearing(this::watchFlightArrivals);
api.travel().subscribeDisappearing(this::watchDisappearingTravels);
api.travelWithFlight().subscribeAppearing(this::watchAppearingFlightsWithTravels);
api.travelWithFlight().subscribeDisappearing(this::watchDisappearingFlightsWithTravels);
api.travelHasConnectingFlight().subscribeAppearing(this::watchAppearingConnectingFlights);
api.travelHasConnectingFlight().subscribeDisappearing(this::watchDisappearingConnectingFlights);
api.connectingFlightAlternative().subscribeAppearing(this::watchAppearingConnectingFlightAlternatives);
api.connectingFlightAlternative().subscribeDisappearing(this::watchDisappearingConnectingFlightAlternatives);
}
@Override
public synchronized void update(boolean debug) {
api.updateMatches();
if(debug) {
StringBuilder sb = new StringBuilder();
FlightModel container = (FlightModel)api.getModel().getResources().get(0).getContents().get(0);
sb.append("*** Time: " + container.getGlobalTime().getTime() + "\nOverall status:\n***");
sb.append("\nDetected " + flight2Arrival.entrySet().stream()
.filter(entry -> (entry.getValue() != null))
.count()
+ " flights overall.");
sb.append("\nDetected " + flight2Travels.values().stream()
.map(travels -> travels.size())
.reduce(0, (sum, value) -> sum + value)
+ " flights with booked travels.");
sb.append("\nDetected " + flight2Travels.values().stream()
.distinct()
.map(travels -> travels.size())
.reduce(0, (sum, value) -> sum + value)
+ " travels overall.");
sb.append("\nDetected " + travel2ConnectingFlights.values().stream()
.map(travels -> travels.size())
.reduce(0, (sum, value) -> sum + value)
+ " intact connecting flights in travels overall.");
sb.append("\nDetected " + travel2DelayedConnectingFlights.values().stream()
.map(travels -> travels.size())
.reduce(0, (sum, value) -> sum + value)
+ " broken/delayed connecting flights in travels overall.");
sb.append("\nDetected " + travel2AlternativeConnectingFlights.values().stream()
.map(travels -> travels.size())
.reduce(0, (sum, value) -> sum + value)
+ " alternative connecting flights in travels overall.");
// sb.append("\n***\nAppeared issues:\n***");
// while(!issueMessages.isEmpty()) {
// sb.append("\n"+issueMessages.poll());
// }
//
// sb.append("\n***\nAppeared events:\n***");
// while(!infoMessages.isEmpty()) {
// sb.append("\n"+infoMessages.poll());
// }
//
// sb.append("\n***\nAppeared solutions:\n***");
// while(!solutionMessages.isEmpty()) {
// sb.append("\n"+solutionMessages.poll());
// }
sb.append("\n***\n***");
System.out.println(sb.toString());
}
}
@Override
public void shutdown() {
api.terminate();
}
private synchronized void watchAppearingFlights(FlightMatch match) {
flight2Travels.putIfAbsent(match.getFlight(), new HashSet<>());
flight2Arrival.putIfAbsent(match.getFlight(), match.getFlight().getArrival().getTime());
overfullAlternatives.put(match.getFlight(), new HashSet<>());
}
private synchronized void watchDisappearingFlights(FlightMatch match) {
flight2Travels.remove(match.getFlight());
flight2Arrival.remove(match.getFlight());
overfullAlternatives.remove(match.getFlight());
}
private synchronized void watchDisappearingTravels(TravelMatch match) {
Collection<Flight> flights = match.getTravel().getFlights();
for(Flight flight : flights) {
Set<Travel> travels = flight2Travels.get(flight);
if(travels != null) {
travels.remove(match.getTravel());
}
}
travel2ConnectingFlights.remove(match.getTravel());
if(travel2DelayedConnectingFlights.containsKey(match.getTravel())) {
travel2DelayedConnectingFlights.get(match.getTravel())
.forEach(connectingFlight -> {
removeIssue(connectingFlight);
infoMessages.add("Travel "+match.getTravel().getID()+" completed or canceled. Therefore, the issue concerning the delayed connecting flight "+connectingFlight.getConnectingFlight().getID()+" has been resolved.\n");
});
}
travel2DelayedConnectingFlights.remove(match.getTravel());
travel2AlternativeConnectingFlights.remove(match.getTravel());
//TODO: Cleanup issues and solutions!
}
private synchronized void watchAppearingFlightsWithTravels(TravelWithFlightMatch match) {
final Flight flight = match.getFlight();
Set<Travel> travels = flight2Travels.get(flight);
if(travels == null) {
travels = new HashSet<>();
flight2Travels.put(flight, travels);
}
travels.add(match.getTravel());
Plane plane = match.getPlane();
if(plane.getCapacity() <= travels.size()) {
if(plane.getCapacity() < travels.size()) {
addIssue(match, "Plane on flight "+flight.getID()+" is overbooked (#travels="+travels.size()+") and capacity is "+plane.getCapacity()+".");
}else {
infoMessages.add("Plane on flight "+flight.getID()+" is full (#travels="+travels.size()+") and capacity is "+plane.getCapacity()+".");
}
List<ConnectingFlightAlternativeMatch> removedAlternatives = travel2AlternativeConnectingFlights.values()
.parallelStream()
.flatMap(altMatchSet -> altMatchSet.stream())
.filter(altMatch -> altMatch.getFlight().equals(flight))
.collect(Collectors.toList());
for(ConnectingFlightAlternativeMatch removal : removedAlternatives) {
Set<ConnectingFlightAlternativeMatch> alternatives = travel2AlternativeConnectingFlights.get(removal.getTravel());
if(alternatives != null) {
alternatives.remove(removal);
Set<ConnectingFlightAlternativeMatch> overfull = overfullAlternatives.get(flight);
if(overfull == null) {
overfull = new HashSet<>();
overfullAlternatives.put(flight, overfull);
}
overfull.add(removal);
//TODO: Does this become an issue?
infoMessages.add("Travel "+removal.getTravel().getID() + " hast lost its alternative connecting flight " + removal.getReplacementFlight().getID() + " since the plane is full..\n");
}
}
}
}
private synchronized void watchDisappearingFlightsWithTravels(TravelWithFlightMatch match) {
Flight flight = match.getFlight();
Set<Travel> travels = flight2Travels.get(flight);
if(travels != null) {
Plane plane = match.getPlane();
if(plane.getCapacity() > travels.size() - 1) {
List<ConnectingFlightAlternativeMatch> removals = new LinkedList<>();
Set<ConnectingFlightAlternativeMatch> overfull = overfullAlternatives.get(flight);
if(overfull != null) {
for(ConnectingFlightAlternativeMatch alternative : overfull) {
infoMessages.add("Travel "+alternative.getTravel().getID() + " has gained an alternative connecting flight " + alternative.getReplacementFlight().getID() + " since the plane some seats left.\n");
removals.add(alternative);
SortedSet<ConnectingFlightAlternativeMatch> alternatives = travel2AlternativeConnectingFlights.get(alternative.getTravel());
if(alternatives == null) {
alternatives = createSortedSet();
travel2AlternativeConnectingFlights.put(alternative.getTravel(), alternatives);
}
alternatives.add(alternative);
if(alternatives.first().equals(alternative)) {
//TODO: Search for the correct connecting flight -> TravelWithFlightMatch match is the wrong type of issue match!
addSolution(match, alternative, "Travel "+match.getTravel().getID()+" can reach its destination via alternative connecting flight "+alternative.getReplacementFlight().getID()+".\n"+
"---> ETA: "+getString_mmhhDDMMYYYY(alternative.getFlight().getArrival().getTime()) + ", ETD: "+getString_mmhhDDMMYYYY(alternative.getReplacementDeparture().getTime()));
}
}
}
overfull.removeAll(removals);
}
travels.remove(match.getTravel());
}
}
private synchronized void watchAppearingConnectingFlights(TravelHasConnectingFlightMatch match) {
long dGates = calcGateDistance(match.getTransitAirport(), match.getArrivalGate(), match.getDepartingGate());
long arrival = match.getFlight().getArrival().getTime();
long departure = match.getConnectingFlight().getDeparture().getTime();
if(arrival+dGates > departure) {
addIssue(match, "Travel "+match.getTravel().getID()+" will miss its connecting flight "+match.getConnectingFlight().getID()+" due to a delayed arrival time.\n"+
"---> ETA: "+getString_mmhhDDMMYYYY(arrival)+", distance to gate: "+deltaAsString(dGates)+", ETD: "+getString_mmhhDDMMYYYY(departure));
Set<TravelHasConnectingFlightMatch> brokenFlights = travel2DelayedConnectingFlights.get(match.getTravel());
if(brokenFlights == null) {
brokenFlights = new HashSet<>();
travel2DelayedConnectingFlights.put(match.getTravel(), brokenFlights);
}
brokenFlights.add(match);
Set<TravelHasConnectingFlightMatch> connectingFlights = travel2ConnectingFlights.get(match.getTravel());
if(connectingFlights != null) {
connectingFlights.remove(match);
}
Set<ConnectingFlightAlternativeMatch> connectingAlternatives = travel2AlternativeConnectingFlights.get(match.getTravel());
if(connectingAlternatives!=null) {
for(ConnectingFlightAlternativeMatch connectingFlightAlternative : connectingAlternatives) {
long dGatesAlt = calcGateDistance(match.getTransitAirport(), match.getArrivalGate(), connectingFlightAlternative.getReplacementFlight().getSrc());
long arrivalAlt = match.getFlight().getArrival().getTime();
long departureAlt = connectingFlightAlternative.getReplacementFlight().getDeparture().getTime();
if(arrivalAlt + dGatesAlt <= departureAlt
&& connectingFlightAlternative.getFlight().getPlane().getCapacity() >= flight2Travels.get(connectingFlightAlternative.getFlight()).size() + 1) {
if(match.getTransitAirport() == connectingFlightAlternative.getTransitAirport() && match.getConnectingRoute().getTrg() == connectingFlightAlternative.getConnectingRoute().getTrg()) {
addSolution(match, connectingFlightAlternative, "Travel "+match.getTravel().getID()+" can reach its destination via alternative connecting flight "+connectingFlightAlternative.getReplacementFlight().getID()+".\n"+
"---> ETA: "+getString_mmhhDDMMYYYY(arrivalAlt)+", distance to gate: "+deltaAsString(dGatesAlt)+", ETD: "+getString_mmhhDDMMYYYY(departureAlt));
break;
}
}
}
}
return;
}
Set<TravelHasConnectingFlightMatch> connectingFlights = travel2ConnectingFlights.get(match.getTravel());
if(connectingFlights == null) {
connectingFlights = new HashSet<>();
travel2ConnectingFlights.put(match.getTravel(), connectingFlights);
}
connectingFlights.add(match);
Set<TravelHasConnectingFlightMatch> brokenFlights = travel2DelayedConnectingFlights.get(match.getTravel());
if(brokenFlights != null) {
if(brokenFlights.remove(match)) {
infoMessages.add("Travel "+match.getTravel().getID()+" will make its connecting flight "+match.getConnectingFlight().getID()+" since the delay has been resolved.\n"+
"---> ETA: "+getString_mmhhDDMMYYYY(arrival)+", distance to gate: "+deltaAsString(dGates)+", ETD: "+getString_mmhhDDMMYYYY(departure));
connectingFlights.add(match);
removeIssue(match);
}
}
}
private synchronized void watchDisappearingConnectingFlights(TravelHasConnectingFlightMatch match) {
Set<TravelHasConnectingFlightMatch> brokenFlights = travel2DelayedConnectingFlights.get(match.getTravel());
if(brokenFlights == null) {
brokenFlights = new HashSet<>();
travel2DelayedConnectingFlights.put(match.getTravel(), brokenFlights);
}
addIssue(match, "Travel "+match.getTravel().getID()+" will miss its connecting flight "+match.getConnectingFlight().getID());
brokenFlights.add(match);
Set<TravelHasConnectingFlightMatch> connectingFlights = travel2ConnectingFlights.get(match.getTravel());
if(connectingFlights != null) {
connectingFlights.remove(match);
}
Set<ConnectingFlightAlternativeMatch> connectingAlternatives = travel2AlternativeConnectingFlights.get(match.getTravel());
if(connectingAlternatives!=null) {
for(ConnectingFlightAlternativeMatch connectingFlightAlternative : connectingAlternatives) {
long dGatesAlt = calcGateDistance(match.getTransitAirport(), match.getArrivalGate(), connectingFlightAlternative.getReplacementFlight().getSrc());
long arrivalAlt = match.getFlight().getArrival().getTime();
long departureAlt = connectingFlightAlternative.getReplacementFlight().getDeparture().getTime();
if(flight2Travels.get(connectingFlightAlternative.getFlight()) == null)
continue;
if(arrivalAlt + dGatesAlt <= departureAlt
&& connectingFlightAlternative.getFlight().getPlane().getCapacity() >= flight2Travels.get(connectingFlightAlternative.getFlight()).size() + 1) {
if(match.getTransitAirport() == connectingFlightAlternative.getTransitAirport() && match.getConnectingRoute().getTrg() == connectingFlightAlternative.getConnectingRoute().getTrg()) {
addSolution(match, connectingFlightAlternative, "Travel "+match.getTravel().getID()+" can reach its destination via alternative connecting flight "+connectingFlightAlternative.getReplacementFlight().getID()+".\n"+
"---> ETA: "+getString_mmhhDDMMYYYY(arrivalAlt)+", distance to gate: "+deltaAsString(dGatesAlt)+", ETD: "+getString_mmhhDDMMYYYY(departureAlt));
break;
}
}
}
}
}
private synchronized void watchFlightArrivals(FlightWithArrivalMatch match) {
Long prevArrival = flight2Arrival.get(match.getFlight());
if(prevArrival == null)
return;
Long currentArrival = match.getFlight().getArrival().getTime();
flight2Arrival.replace(match.getFlight(), currentArrival);
Set<Travel> travels = flight2Travels.get(match.getFlight());
if(travels == null)
return;
// check travels in case of a early arrival
if(currentArrival<prevArrival) {
infoMessages.add("Flight "+match.getFlight().getID()+" will arrive early by "+ deltaAsString(prevArrival-currentArrival) +"minutes.\n"+
"---> current ETA: "+getString_mmhhDDMMYYYY(currentArrival)+", original ETA: "+getString_mmhhDDMMYYYY(prevArrival));
for(Travel travel : travels) {
Set<TravelHasConnectingFlightMatch> brokenFlights = travel2DelayedConnectingFlights.get(travel);
if(brokenFlights == null)
continue;
Set<TravelHasConnectingFlightMatch> removedFlights = new HashSet<>();
for(TravelHasConnectingFlightMatch brokenFlight : brokenFlights) {
long dGates = calcGateDistance(brokenFlight.getTransitAirport(), brokenFlight.getArrivalGate(), brokenFlight.getDepartingGate());
long arrival = brokenFlight.getFlight().getArrival().getTime();
long departure = brokenFlight.getConnectingFlight().getDeparture().getTime();
if(arrival+dGates <= departure) {
infoMessages.add("Travel "+brokenFlight.getTravel().getID()+" will now make its connecting flight "+brokenFlight.getConnectingFlight().getID()+" since the delay has been resolved.\n"+
"---> ETA: "+getString_mmhhDDMMYYYY(arrival)+", distance to gate: "+deltaAsString(dGates)+", ETD: "+getString_mmhhDDMMYYYY(departure));
removeIssue(brokenFlight);
//TODO: Delete issues!
Set<TravelHasConnectingFlightMatch> connectedFlights = travel2ConnectingFlights.get(brokenFlight.getTravel());
if(connectedFlights == null) {
connectedFlights = new HashSet<>();
travel2DelayedConnectingFlights.put(brokenFlight.getTravel(), connectedFlights);
}
connectedFlights.add(brokenFlight);
removedFlights.add(brokenFlight);
}
}
brokenFlights.removeAll(removedFlights);
}
}
// check travels in case of a delay
else if(currentArrival>prevArrival) {
infoMessages.add("Flight "+match.getFlight().getID()+" currently has a delay of "+ deltaAsString(currentArrival-prevArrival) +"minutes.\n"+
"---> current ETA: "+getString_mmhhDDMMYYYY(currentArrival)+", original ETA: "+getString_mmhhDDMMYYYY(prevArrival));
for(Travel travel : travels) {
Set<TravelHasConnectingFlightMatch> connectingFlights = travel2ConnectingFlights.get(travel);
if(connectingFlights == null)
continue;
Set<TravelHasConnectingFlightMatch> removedFlights = new HashSet<>();
for(TravelHasConnectingFlightMatch connectingFlight : connectingFlights) {
long dGates = calcGateDistance(connectingFlight.getTransitAirport(), connectingFlight.getArrivalGate(), connectingFlight.getDepartingGate());
long arrival = connectingFlight.getFlight().getArrival().getTime();
long departure = connectingFlight.getConnectingFlight().getDeparture().getTime();
if(arrival+dGates > departure) {
addIssue(connectingFlight, "Travel "+connectingFlight.getTravel().getID()+" will miss its connecting flight "+connectingFlight.getConnectingFlight().getID()+" due to a delayed arrival time.\n"+
"---> ETA: "+getString_mmhhDDMMYYYY(arrival)+", distance to gate: "+deltaAsString(dGates)+", ETD: "+getString_mmhhDDMMYYYY(departure));
Set<TravelHasConnectingFlightMatch> brokenFlights = travel2DelayedConnectingFlights.get(connectingFlight.getTravel());
if(brokenFlights == null) {
brokenFlights = new HashSet<>();
travel2DelayedConnectingFlights.put(connectingFlight.getTravel(), brokenFlights);
}
brokenFlights.add(connectingFlight);
removedFlights.add(connectingFlight);
Set<ConnectingFlightAlternativeMatch> connectingAlternatives = travel2AlternativeConnectingFlights.get(connectingFlight.getTravel());
if(connectingAlternatives!=null) {
for(ConnectingFlightAlternativeMatch connectingFlightAlternative : connectingAlternatives) {
long dGatesAlt = calcGateDistance(connectingFlight.getTransitAirport(), connectingFlight.getArrivalGate(), connectingFlightAlternative.getReplacementFlight().getSrc());
long arrivalAlt = connectingFlightAlternative.getFlight().getArrival().getTime();
long departureAlt = connectingFlightAlternative.getReplacementFlight().getDeparture().getTime();
if(flight2Travels.get(connectingFlightAlternative.getFlight()) == null)
continue;
if(arrivalAlt + dGatesAlt <= departureAlt
&& connectingFlightAlternative.getFlight().getPlane().getCapacity() >= flight2Travels.get(connectingFlightAlternative.getFlight()).size() + 1) {
if(connectingFlight.getTransitAirport() == connectingFlightAlternative.getTransitAirport() && connectingFlight.getConnectingRoute().getTrg() == connectingFlightAlternative.getConnectingRoute().getTrg()) {
addSolution(connectingFlight, connectingFlightAlternative, "Travel "+connectingFlight.getTravel().getID()+" can reach its destination via alternative connecting flight "+connectingFlightAlternative.getReplacementFlight().getID()+".\n"+
"---> ETA: "+getString_mmhhDDMMYYYY(arrivalAlt)+", distance to gate: "+deltaAsString(dGatesAlt)+", ETD: "+getString_mmhhDDMMYYYY(departureAlt));
break;
}
}
}
}
}
}
connectingFlights.removeAll(removedFlights);
}
}
}
private synchronized void watchAppearingConnectingFlightAlternatives(ConnectingFlightAlternativeMatch match) {
SortedSet<ConnectingFlightAlternativeMatch> alternatives = travel2AlternativeConnectingFlights.get(match.getTravel());
if(alternatives == null) {
alternatives = createSortedSet();
travel2AlternativeConnectingFlights.put(match.getTravel(), alternatives);
}
long dGates = calcGateDistance(match.getTransitAirport(), match.getArrivalGate(), match.getReplacementFlight().getSrc());
long arrival = match.getFlight().getArrival().getTime();
long departure = match.getReplacementFlight().getDeparture().getTime();
if(arrival + dGates <= departure
&& match.getFlight().getPlane().getCapacity() >= flight2Travels.get(match.getFlight()).size() + 1) {
alternatives.add(match);
Set<TravelHasConnectingFlightMatch> brokenConnectingFlights = travel2DelayedConnectingFlights.get(match.getTravel());
if(brokenConnectingFlights != null && match.equals(alternatives.first())) {
for(TravelHasConnectingFlightMatch brokenConnectingFlight : brokenConnectingFlights) {
if(match.getConnectingRoute() == brokenConnectingFlight.getConnectingRoute()) {
addSolution(brokenConnectingFlight, match, "Travel "+brokenConnectingFlight.getTravel().getID()+" can reach its destination via alternative connecting flight "+match.getReplacementFlight().getID()+".\n"+
"---> ETA: "+getString_mmhhDDMMYYYY(arrival)+", distance to gate: "+deltaAsString(dGates)+", ETD: "+getString_mmhhDDMMYYYY(departure));
}
}
}
}
}
private synchronized void watchDisappearingConnectingFlightAlternatives(ConnectingFlightAlternativeMatch match) {
Set<ConnectingFlightAlternativeMatch> alternatives = travel2AlternativeConnectingFlights.get(match.getTravel());
if(alternatives != null) {
alternatives.remove(match);
}
}
@Override
public long getWorkingConnectingFlightTravels() {
return travel2ConnectingFlights.values().stream().flatMap(set -> set.stream()).collect(Collectors.toSet()).size();
}
@Override
public long getDelayedConnectingFlightTravels() {
return travel2DelayedConnectingFlights.values().stream().flatMap(set -> set.stream()).collect(Collectors.toSet()).size();
}
}
| 24,175 | 0.739483 | 0.736256 | 489 | 48.43763 | 48.500298 | 245 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.824131 | false | false |
10
|
feba37bd10301d818653a22705a60fd1cdabdbbc
| 33,801,392,632,500 |
408d475dbdd2a9ba936dc3622b9a6332d016fc46
|
/app/src/main/java/cn/cheney/app/MainActivity.java
|
5a67661d8b4889601ff2760311a97c0c6e94d1da
|
[] |
no_license
|
showingcp/XRouter
|
https://github.com/showingcp/XRouter
|
757e7500b1d4601b56cad2023b902dd372d7d59d
|
e70282c0439d058835102f0803c0ba29327d43ae
|
refs/heads/master
| 2021-02-08T13:29:27.676000 | 2020-03-01T13:38:52 | 2020-03-01T13:38:52 | 244,156,684 | 1 | 0 | null | true | 2020-03-01T13:43:37 | 2020-03-01T13:43:36 | 2020-03-01T13:38:54 | 2020-03-01T13:38:52 | 231 | 0 | 0 | 0 | null | false | false |
package cn.cheney.app;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Map;
import cn.cheney.xrouter.core.RouteCallback;
import cn.cheney.xrouter.core.XRouter;
import cn.cheney.xrouter.core.util.Logger;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Book book = new Book();
book.name = "Kotlin";
Integer requestCode = XRouter.page("home/page")
.put("testParam", book)
.action("cn.cheney.xrouter")
.anim(R.anim.enter_bottom, R.anim.exit_bottom)
.requestCode(1000)
.call();
Logger.d("Route Page requestCode= " + requestCode);
}
});
findViewById(R.id.btn2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Book book = new Book();
book.name = "Kotlin";
Book bookReturn = XRouter.<Book>method("home/getBookName")
.put("book", book)
.call();
Logger.d("getSyncBookName bookReturn= " + bookReturn);
}
});
findViewById(R.id.btn3).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Book book = new Book();
book.name = "Kotlin";
XRouter.<Book>method("home/getAsyncBookName")
.put("book", book)
.call(new RouteCallback() {
@Override
public void onResult(Map<String, Object> result) {
Logger.d("getAsyncBookName bookReturn= " + result);
}
});
}
});
findViewById(R.id.btn4).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Book book = new Book();
book.name = "Kotlin";
Book bookError = XRouter.<Book>method(null)
.put("book", book)
.call(new RouteCallback() {
@Override
public void onResult(Map<String, Object> result) {
Logger.d("getaaa bookReturn= " + result);
}
});
Logger.d("getaaa bookError= " + bookError);
}
});
findViewById(R.id.btn5).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Book book = new Book();
book.name = "Kotlin";
Integer requestCode = XRouter.page("test/page1")
.action("cn.cheney.xrouter")
.anim(R.anim.enter_bottom, R.anim.exit_bottom)
.requestCode(1000)
.call();
Logger.d("Route test Module page1 requestCode= " + requestCode);
}
});
}
}
|
UTF-8
|
Java
| 3,578 |
java
|
MainActivity.java
|
Java
|
[
{
"context": "k book = new Book();\n book.name = \"Kotlin\";\n Book bookError = XRouter.<Book>",
"end": 2480,
"score": 0.9948744177818298,
"start": 2474,
"tag": "NAME",
"value": "Kotlin"
},
{
"context": "k book = new Book();\n book.name = \"Kotlin\";\n Integer requestCode = XRouter.p",
"end": 3193,
"score": 0.9965407252311707,
"start": 3187,
"tag": "NAME",
"value": "Kotlin"
}
] | null |
[] |
package cn.cheney.app;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Map;
import cn.cheney.xrouter.core.RouteCallback;
import cn.cheney.xrouter.core.XRouter;
import cn.cheney.xrouter.core.util.Logger;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Book book = new Book();
book.name = "Kotlin";
Integer requestCode = XRouter.page("home/page")
.put("testParam", book)
.action("cn.cheney.xrouter")
.anim(R.anim.enter_bottom, R.anim.exit_bottom)
.requestCode(1000)
.call();
Logger.d("Route Page requestCode= " + requestCode);
}
});
findViewById(R.id.btn2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Book book = new Book();
book.name = "Kotlin";
Book bookReturn = XRouter.<Book>method("home/getBookName")
.put("book", book)
.call();
Logger.d("getSyncBookName bookReturn= " + bookReturn);
}
});
findViewById(R.id.btn3).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Book book = new Book();
book.name = "Kotlin";
XRouter.<Book>method("home/getAsyncBookName")
.put("book", book)
.call(new RouteCallback() {
@Override
public void onResult(Map<String, Object> result) {
Logger.d("getAsyncBookName bookReturn= " + result);
}
});
}
});
findViewById(R.id.btn4).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Book book = new Book();
book.name = "Kotlin";
Book bookError = XRouter.<Book>method(null)
.put("book", book)
.call(new RouteCallback() {
@Override
public void onResult(Map<String, Object> result) {
Logger.d("getaaa bookReturn= " + result);
}
});
Logger.d("getaaa bookError= " + bookError);
}
});
findViewById(R.id.btn5).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Book book = new Book();
book.name = "Kotlin";
Integer requestCode = XRouter.page("test/page1")
.action("cn.cheney.xrouter")
.anim(R.anim.enter_bottom, R.anim.exit_bottom)
.requestCode(1000)
.call();
Logger.d("Route test Module page1 requestCode= " + requestCode);
}
});
}
}
| 3,578 | 0.485187 | 0.480995 | 96 | 36.270832 | 24.158539 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.458333 | false | false |
10
|
aa0246a68999287628f5c219c3a4ab4029d4aa98
| 9,594,956,974,502 |
f6caa350ba9bd68eb479b3996df17d6475e000d1
|
/app/src/main/java/com/example/photographerbookingapp/ProfileActivity.java
|
fea6161c772d7f8699769d8d18b04a30c0b36af4
|
[] |
no_license
|
Azrbarudin/PhotographerBookingApp
|
https://github.com/Azrbarudin/PhotographerBookingApp
|
60d19af4ecc0ecbd96376d9172e2fa9335e5e3f8
|
caf5e33b0636ed9990630810e06450005f5bbc88
|
refs/heads/master
| 2023-07-21T21:21:41.129000 | 2021-08-08T13:45:14 | 2021-08-08T13:45:14 | 393,972,217 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.photographerbookingapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class ProfileActivity extends AppCompatActivity {
FirebaseUser user;
DatabaseReference reference;
String userID,fullname, email, phoneNo;
TextView fullnameLabel,emailLabel,phoneNoLabel;
Button btnUpdate,deleteBtn;
private static final String TAG = "ProfileActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
//get current user
user = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("client");
userID = user.getUid();
fullnameLabel = findViewById(R.id.fullname_profile);
emailLabel = findViewById(R.id.email_profile);
phoneNoLabel = findViewById(R.id.phoneNo_profile);
btnUpdate = findViewById(R.id.update);
deleteBtn = findViewById(R.id.deleteBtn);
reference.child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
ModelClient clientProfile = snapshot.getValue(ModelClient.class);
if(clientProfile!=null){
fullname = clientProfile.name;
email = clientProfile.email;
phoneNo = clientProfile.phoneNo;
fullnameLabel.setText(fullname);
emailLabel.setText(email);
phoneNoLabel.setText(phoneNo);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(ProfileActivity.this,"Something wrong happened", Toast.LENGTH_LONG).show();
}
});
//update user
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(),UpdateProfileActivity.class);
i.putExtra("name",fullname);
i.putExtra("email",email);
i.putExtra("phoneNo",phoneNo);
startActivity(i);
}
});
//delete user
deleteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//show delete confirm dialog
AlertDialog.Builder builder=new AlertDialog.Builder(ProfileActivity.this);
builder.setTitle("Delete")
.setMessage("Are you sure you want to delete your account?")
.setPositiveButton("DELETE", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//delete account client + all booking made by client
deleteData(userID);
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//cancel delete
dialog.dismiss();
}
}).show();
}
});
//initialize and assign value navigation bar
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
//set Home Selected
bottomNavigationView.setSelectedItemId(R.id.profile);
//perform ItemSelectedListener
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener(){
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.booking:
startActivity(new Intent(getApplicationContext(), BookingActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.home:
startActivity(new Intent(getApplicationContext(), MainActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.profile:
return true;
}
return false;}
});
}
private void deleteData(String userID) {
DatabaseReference bookingRef = FirebaseDatabase.getInstance().getReference("booking");
bookingRef.orderByChild("clientID").equalTo(userID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for(DataSnapshot bookSnapshot: snapshot.getChildren()){
bookSnapshot.getRef().removeValue();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(getApplicationContext(),""+error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
DatabaseReference ratingRef = FirebaseDatabase.getInstance().getReference("rating");
ratingRef.orderByChild("clientID").equalTo(userID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for(DataSnapshot rateSnapshot: snapshot.getChildren()){
rateSnapshot.getRef().removeValue();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(getApplicationContext(),""+error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
reference.child(userID).removeValue(); //remove from client table
user.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Toast.makeText(getApplicationContext(),"Account Deleted", Toast.LENGTH_SHORT).show();
startActivity(new Intent(ProfileActivity.this,HomeActivity.class));
finish();
}
}); // delete user
}
}
|
UTF-8
|
Java
| 7,491 |
java
|
ProfileActivity.java
|
Java
|
[] | null |
[] |
package com.example.photographerbookingapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class ProfileActivity extends AppCompatActivity {
FirebaseUser user;
DatabaseReference reference;
String userID,fullname, email, phoneNo;
TextView fullnameLabel,emailLabel,phoneNoLabel;
Button btnUpdate,deleteBtn;
private static final String TAG = "ProfileActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
//get current user
user = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("client");
userID = user.getUid();
fullnameLabel = findViewById(R.id.fullname_profile);
emailLabel = findViewById(R.id.email_profile);
phoneNoLabel = findViewById(R.id.phoneNo_profile);
btnUpdate = findViewById(R.id.update);
deleteBtn = findViewById(R.id.deleteBtn);
reference.child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
ModelClient clientProfile = snapshot.getValue(ModelClient.class);
if(clientProfile!=null){
fullname = clientProfile.name;
email = clientProfile.email;
phoneNo = clientProfile.phoneNo;
fullnameLabel.setText(fullname);
emailLabel.setText(email);
phoneNoLabel.setText(phoneNo);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(ProfileActivity.this,"Something wrong happened", Toast.LENGTH_LONG).show();
}
});
//update user
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(),UpdateProfileActivity.class);
i.putExtra("name",fullname);
i.putExtra("email",email);
i.putExtra("phoneNo",phoneNo);
startActivity(i);
}
});
//delete user
deleteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//show delete confirm dialog
AlertDialog.Builder builder=new AlertDialog.Builder(ProfileActivity.this);
builder.setTitle("Delete")
.setMessage("Are you sure you want to delete your account?")
.setPositiveButton("DELETE", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//delete account client + all booking made by client
deleteData(userID);
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//cancel delete
dialog.dismiss();
}
}).show();
}
});
//initialize and assign value navigation bar
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
//set Home Selected
bottomNavigationView.setSelectedItemId(R.id.profile);
//perform ItemSelectedListener
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener(){
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.booking:
startActivity(new Intent(getApplicationContext(), BookingActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.home:
startActivity(new Intent(getApplicationContext(), MainActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.profile:
return true;
}
return false;}
});
}
private void deleteData(String userID) {
DatabaseReference bookingRef = FirebaseDatabase.getInstance().getReference("booking");
bookingRef.orderByChild("clientID").equalTo(userID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for(DataSnapshot bookSnapshot: snapshot.getChildren()){
bookSnapshot.getRef().removeValue();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(getApplicationContext(),""+error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
DatabaseReference ratingRef = FirebaseDatabase.getInstance().getReference("rating");
ratingRef.orderByChild("clientID").equalTo(userID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for(DataSnapshot rateSnapshot: snapshot.getChildren()){
rateSnapshot.getRef().removeValue();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(getApplicationContext(),""+error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
reference.child(userID).removeValue(); //remove from client table
user.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Toast.makeText(getApplicationContext(),"Account Deleted", Toast.LENGTH_SHORT).show();
startActivity(new Intent(ProfileActivity.this,HomeActivity.class));
finish();
}
}); // delete user
}
}
| 7,491 | 0.601922 | 0.601388 | 193 | 37.818653 | 30.041996 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.564767 | false | false |
10
|
a59e509c3a4c3934d60f6c9308d2f5df698c5dc3
| 9,594,956,974,428 |
e635e6687cbf60c379049e265003e7143a77e17f
|
/app/src/main/java/com/example/checkapartment/MVPloging/ILoging.java
|
85f9e06065d129ee0ee06a38c7f76eb87a5e508f
|
[] |
no_license
|
DVERA82/CheckApartment
|
https://github.com/DVERA82/CheckApartment
|
bf06ca55adcf9da86876e361154c901e56d167e6
|
f63b71c3ae9c9208dcbdc83a605df319d6b34777
|
refs/heads/master
| 2023-02-15T10:45:52.219000 | 2021-01-14T22:00:55 | 2021-01-14T22:00:55 | 329,031,783 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.checkapartment.MVPloging;
public interface ILoging {
void validarPassword(String password);
String mensajeLoging();
int contadorLoging();
}
|
UTF-8
|
Java
| 175 |
java
|
ILoging.java
|
Java
|
[] | null |
[] |
package com.example.checkapartment.MVPloging;
public interface ILoging {
void validarPassword(String password);
String mensajeLoging();
int contadorLoging();
}
| 175 | 0.748571 | 0.748571 | 9 | 18.444445 | 17.50626 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false |
10
|
3a9a3549ec8a344c96335325c70ea615d1ac0311
| 7,258,494,800,084 |
f470fb9c51bae305eaf17bdd0424365e2ddb94cf
|
/AndroidExpensesRegistration/src/androidexpensesregistration/domain/datamappers/ExpenseDataMapper.java
|
59177d1fccef0829eecf5bb134d7c02a2c7bd7b9
|
[] |
no_license
|
rudy-on-rails/AndroidExpensesRegistrationProject
|
https://github.com/rudy-on-rails/AndroidExpensesRegistrationProject
|
c788677c43322585847295f8521c6edb2fee88ae
|
dbdba19b4a3c4b24bbbc576763eec3e9a83fa959
|
refs/heads/master
| 2022-04-14T19:26:38.836000 | 2020-04-02T23:32:11 | 2020-04-02T23:32:11 | 2,359,273 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package androidexpensesregistration.domain.datamappers;
import java.math.BigDecimal;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import androidexpensesregistration.domain.model.Expense;
import androidexpensesregistration.domain.model.IGenericRecord;
import androidexpensesregistration.domain.repository.ExpenseTypeRepository;
import androidexpensesregistration.helpers.DateHelper;
public class ExpenseDataMapper implements DataMapper<Expense>{
private final int COL_ID = 0;
private final int COL_EXPENSE_TYPE_ID = 1;
private final int COL_VALUE = 2;
private final int COL_EXPENSE_DATE = 3;
private final int COL_DESCRIPTION = 4;
private final int COL_QUANTITY = 5;
@Override
public ContentValues getContentValues(IGenericRecord iGenericRecord) {
if (!(iGenericRecord instanceof Expense))
throw new IllegalArgumentException("Argument must be an Expense instance!");
ContentValues contentValues = new ContentValues();
Expense expense = (Expense)iGenericRecord;
if (expense.getExpenseType() != null)
contentValues.put("expense_type_id", expense.getExpenseType().getId());
contentValues.put("quantity", expense.getQuantity());
contentValues.put("value", expense.getExpenseValue().floatValue());
contentValues.put("description", expense.getDescription());
contentValues.put("date_expense", DateHelper.getFormattedDataStringForDB(expense.getDateExpenseWasTaken()));
return contentValues;
}
@Override
public ArrayList<Expense> getCursorValues(Cursor cursor, Context context){
ArrayList<Expense> expensesArrayList = new ArrayList<Expense>();
while (cursor.moveToNext()) {
Expense expense = new Expense();
expense.setId(cursor.getInt(COL_ID));
expense.setDescription(cursor.getString(COL_DESCRIPTION));
expense.setExpenseValue(BigDecimal.valueOf(cursor.getFloat(COL_VALUE)));
expense.setQuantity(cursor.getInt(COL_QUANTITY));
try {
if (cursor.getInt(COL_EXPENSE_TYPE_ID) != 0)
expense.setExpenseType(new ExpenseTypeRepository(context).findById(cursor.getInt(COL_EXPENSE_TYPE_ID)));
} catch (Exception e) {
Log.d("Error getting expense type...", e.getMessage());
}
expense.setDateExpenseWasTaken(DateHelper.parseDateInputStringToDate(cursor.getString(COL_EXPENSE_DATE)));
expensesArrayList.add(expense);
}
return expensesArrayList;
}
}
|
UTF-8
|
Java
| 2,445 |
java
|
ExpenseDataMapper.java
|
Java
|
[] | null |
[] |
package androidexpensesregistration.domain.datamappers;
import java.math.BigDecimal;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import androidexpensesregistration.domain.model.Expense;
import androidexpensesregistration.domain.model.IGenericRecord;
import androidexpensesregistration.domain.repository.ExpenseTypeRepository;
import androidexpensesregistration.helpers.DateHelper;
public class ExpenseDataMapper implements DataMapper<Expense>{
private final int COL_ID = 0;
private final int COL_EXPENSE_TYPE_ID = 1;
private final int COL_VALUE = 2;
private final int COL_EXPENSE_DATE = 3;
private final int COL_DESCRIPTION = 4;
private final int COL_QUANTITY = 5;
@Override
public ContentValues getContentValues(IGenericRecord iGenericRecord) {
if (!(iGenericRecord instanceof Expense))
throw new IllegalArgumentException("Argument must be an Expense instance!");
ContentValues contentValues = new ContentValues();
Expense expense = (Expense)iGenericRecord;
if (expense.getExpenseType() != null)
contentValues.put("expense_type_id", expense.getExpenseType().getId());
contentValues.put("quantity", expense.getQuantity());
contentValues.put("value", expense.getExpenseValue().floatValue());
contentValues.put("description", expense.getDescription());
contentValues.put("date_expense", DateHelper.getFormattedDataStringForDB(expense.getDateExpenseWasTaken()));
return contentValues;
}
@Override
public ArrayList<Expense> getCursorValues(Cursor cursor, Context context){
ArrayList<Expense> expensesArrayList = new ArrayList<Expense>();
while (cursor.moveToNext()) {
Expense expense = new Expense();
expense.setId(cursor.getInt(COL_ID));
expense.setDescription(cursor.getString(COL_DESCRIPTION));
expense.setExpenseValue(BigDecimal.valueOf(cursor.getFloat(COL_VALUE)));
expense.setQuantity(cursor.getInt(COL_QUANTITY));
try {
if (cursor.getInt(COL_EXPENSE_TYPE_ID) != 0)
expense.setExpenseType(new ExpenseTypeRepository(context).findById(cursor.getInt(COL_EXPENSE_TYPE_ID)));
} catch (Exception e) {
Log.d("Error getting expense type...", e.getMessage());
}
expense.setDateExpenseWasTaken(DateHelper.parseDateInputStringToDate(cursor.getString(COL_EXPENSE_DATE)));
expensesArrayList.add(expense);
}
return expensesArrayList;
}
}
| 2,445 | 0.777914 | 0.775051 | 57 | 41.894737 | 28.118599 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.596491 | false | false |
10
|
84fe5e89d45028d714badd9f013f325608c5594f
| 33,887,291,985,448 |
180596628eadff4f125cfc2c9e5cc93a650082ae
|
/app/src/main/java/MMA/triviaquiz/PlayAgain.java
|
ccbe22ba010a96595a3e1cdab08e8d1ec552f11e
|
[
"MIT"
] |
permissive
|
BatMando/REQUIZET-Demo
|
https://github.com/BatMando/REQUIZET-Demo
|
e7d6405d545e75173ed3e82d560fc29ec022695f
|
1a67cb87dd68f3afc2437075b98ddb13678b272d
|
refs/heads/main
| 2023-04-19T16:52:45.567000 | 2021-05-04T17:48:32 | 2021-05-04T17:48:32 | 364,339,603 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package MMA.triviaquiz;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import mehdi.sakout.fancybuttons.FancyButton;
public class PlayAgain extends Activity {
FancyButton playAgain;
TextView wrongAnsText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play_again);
playAgain = (FancyButton) findViewById(R.id.playAgainButton);
wrongAnsText = (TextView)findViewById(R.id.wrongAns);
playAgain.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(PlayAgain.this, HomeScreen.class);
startActivity(intent);
finish();
}
});
Typeface typeface = Typeface.createFromAsset(getAssets(),"fonts/lemon_milk.otf");
wrongAnsText.setTypeface(typeface);
}
@Override
public void onBackPressed() {
finish();
}
}
|
UTF-8
|
Java
| 1,188 |
java
|
PlayAgain.java
|
Java
|
[] | null |
[] |
package MMA.triviaquiz;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import mehdi.sakout.fancybuttons.FancyButton;
public class PlayAgain extends Activity {
FancyButton playAgain;
TextView wrongAnsText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play_again);
playAgain = (FancyButton) findViewById(R.id.playAgainButton);
wrongAnsText = (TextView)findViewById(R.id.wrongAns);
playAgain.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(PlayAgain.this, HomeScreen.class);
startActivity(intent);
finish();
}
});
Typeface typeface = Typeface.createFromAsset(getAssets(),"fonts/lemon_milk.otf");
wrongAnsText.setTypeface(typeface);
}
@Override
public void onBackPressed() {
finish();
}
}
| 1,188 | 0.676768 | 0.676768 | 40 | 28.700001 | 22.524652 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false |
10
|
41a534287cc98a2dee7229db1cbad363c3d6ba2e
| 22,608,707,907,149 |
96460bb2cf3dae97c7fd3ffa377216c4e9e70ab9
|
/MyApplication/flplayer/src/main/java/com/luzuzu/videoplayer/player/ProgressManager.java
|
bab983b769bbbc821372edea634c7bbfff0fe6fe
|
[] |
no_license
|
tflgithub/dspProject
|
https://github.com/tflgithub/dspProject
|
65dc25e63168ae453b3057832dbd6ae57b3bd8c1
|
68668e02c5a8232254eb928ca3314c845cbc7f5d
|
refs/heads/master
| 2023-03-10T16:45:46.918000 | 2019-05-31T02:36:05 | 2019-05-31T02:36:05 | 189,514,438 | 0 | 0 | null | false | 2023-02-27T22:45:23 | 2019-05-31T02:33:35 | 2019-05-31T02:40:09 | 2023-02-27T22:45:23 | 14,892 | 0 | 0 | 4 |
Java
| false | false |
package com.luzuzu.videoplayer.player;
/**
* Created by fula on 2019/5/16.
*/
public abstract class ProgressManager {
public abstract void saveProgress(String url, long progress);
public abstract long getSavedProgress(String url);
}
|
UTF-8
|
Java
| 247 |
java
|
ProgressManager.java
|
Java
|
[
{
"context": " com.luzuzu.videoplayer.player;\n\n/**\n * Created by fula on 2019/5/16.\n */\n\npublic abstract class Progress",
"end": 62,
"score": 0.9995518326759338,
"start": 58,
"tag": "USERNAME",
"value": "fula"
}
] | null |
[] |
package com.luzuzu.videoplayer.player;
/**
* Created by fula on 2019/5/16.
*/
public abstract class ProgressManager {
public abstract void saveProgress(String url, long progress);
public abstract long getSavedProgress(String url);
}
| 247 | 0.740891 | 0.712551 | 12 | 19.583334 | 23.357576 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
10
|
2c500573b5e3238c434420635790a0f36c180f62
| 36,472,862,283,215 |
b5c485493f675bcc19dcadfecf9e775b7bb700ed
|
/jee-utility/src/main/java/org/cyk/utility/string/StringCollection.java
|
a45d63ecf805c6bec580945c045e98d3f8280a1e
|
[] |
no_license
|
devlopper/org.cyk.utility
|
https://github.com/devlopper/org.cyk.utility
|
148a1aafccfc4af23a941585cae61229630b96ec
|
14ec3ba5cfe0fa14f0e2b1439ef0f728c52ec775
|
refs/heads/master
| 2023-03-05T23:45:40.165000 | 2021-04-03T16:34:06 | 2021-04-03T16:34:06 | 16,252,993 | 1 | 0 | null | false | 2022-10-12T20:09:48 | 2014-01-26T12:52:24 | 2021-04-03T16:35:57 | 2022-10-12T20:09:46 | 16,037 | 1 | 0 | 11 |
Java
| false | false |
package org.cyk.utility.string;
public interface StringCollection {
}
|
UTF-8
|
Java
| 72 |
java
|
StringCollection.java
|
Java
|
[] | null |
[] |
package org.cyk.utility.string;
public interface StringCollection {
}
| 72 | 0.791667 | 0.791667 | 5 | 13.4 | 16.057398 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
10
|
da7c34fd915d0756811590622e1d49d3a1663b93
| 7,352,984,057,347 |
e71fb56c9d6bff32aa6ef7bd5dc4445ba60c11e8
|
/src/main/java/edu/rice/comp504/model/res/RoomUsersResponse.java
|
87375df8f5b5a764eda19cfd7ad3f48c4eddfaea
|
[] |
no_license
|
11manu96/Final_CA
|
https://github.com/11manu96/Final_CA
|
5b0132cb33fe2a4a5d6e36ab35d211df22ee51aa
|
c32e8c4f1424d967b87ab0a381239372214641d6
|
refs/heads/master
| 2020-04-07T13:55:49.389000 | 2018-11-27T18:13:10 | 2018-11-27T18:13:10 | 158,427,645 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package edu.rice.comp504.model.res;
import java.util.Map;
/**
* Response when sending room users list.
*/
public class RoomUsersResponse extends AResponse {
private int roomId;
private Map<Integer, String> users;
/**
* Constructor.
* @param roomId room id
* @param users users in room
*/
public RoomUsersResponse(int roomId, Map<Integer, String> users) {
super("RoomUsers");
this.roomId = roomId;
this.users = users;
}
}
|
UTF-8
|
Java
| 490 |
java
|
RoomUsersResponse.java
|
Java
|
[] | null |
[] |
package edu.rice.comp504.model.res;
import java.util.Map;
/**
* Response when sending room users list.
*/
public class RoomUsersResponse extends AResponse {
private int roomId;
private Map<Integer, String> users;
/**
* Constructor.
* @param roomId room id
* @param users users in room
*/
public RoomUsersResponse(int roomId, Map<Integer, String> users) {
super("RoomUsers");
this.roomId = roomId;
this.users = users;
}
}
| 490 | 0.636735 | 0.630612 | 22 | 21.272728 | 18.483854 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false |
10
|
8d34c5ebb072a1ada1ad2035b87da8a82da2f1d8
| 32,495,722,625,655 |
acc80ca9232b251858558dca61aa302504975bec
|
/src/main/java/leetcode/Solution016.java
|
82a9d77f56924aceb3493ed57e335765a5ff2986
|
[] |
no_license
|
shaoyihe/leetcode
|
https://github.com/shaoyihe/leetcode
|
9348e575bcca5f6fc4627dbe1d22c3274d9b4403
|
d109de0b1967cce517a6f5058ff5506bb2208c00
|
refs/heads/master
| 2021-11-24T14:02:51.274000 | 2019-02-10T06:36:17 | 2019-02-10T06:36:17 | 143,421,908 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package leetcode;
import java.util.Arrays;
/**
* <pre>
* https://leetcode.com/problems/3sum-closest/description/
* 16. 3Sum Closest
* </pre>
* on 2018/8/2.
*/
public class Solution016 {
public static void main(String[] args) {
Solution016 solution11 = new Solution016();
System.err.println(solution11.threeSumClosest(new int[]{-1, 2, 1, -4}, 1));
}
public int threeSumClosest(int[] nums, int target) {
if (nums == null || nums.length < 3) return Integer.MAX_VALUE;
Arrays.sort(nums);
int closetAbs = Integer.MAX_VALUE;
int closet = -1;
for (int i = 0; i < nums.length - 2; ++i) {
int required = target - nums[i];
for (int j = i + 1, t = nums.length - 1; j < t; ) {
//计算相对偏差
int deviation = nums[j] + nums[t] - required;
if (Math.abs(deviation) < closetAbs) {
closetAbs = Math.abs(deviation);
closet = nums[j] + nums[t] + nums[i];
}
if (deviation > 0) {
--t;
} else if (deviation == 0) {
return closet;
} else {
++j;
}
}
for (; i < nums.length - 2 && nums[i + 1] == nums[i]; ++i) ;
}
return closet;
}
}
|
UTF-8
|
Java
| 1,391 |
java
|
Solution016.java
|
Java
|
[] | null |
[] |
package leetcode;
import java.util.Arrays;
/**
* <pre>
* https://leetcode.com/problems/3sum-closest/description/
* 16. 3Sum Closest
* </pre>
* on 2018/8/2.
*/
public class Solution016 {
public static void main(String[] args) {
Solution016 solution11 = new Solution016();
System.err.println(solution11.threeSumClosest(new int[]{-1, 2, 1, -4}, 1));
}
public int threeSumClosest(int[] nums, int target) {
if (nums == null || nums.length < 3) return Integer.MAX_VALUE;
Arrays.sort(nums);
int closetAbs = Integer.MAX_VALUE;
int closet = -1;
for (int i = 0; i < nums.length - 2; ++i) {
int required = target - nums[i];
for (int j = i + 1, t = nums.length - 1; j < t; ) {
//计算相对偏差
int deviation = nums[j] + nums[t] - required;
if (Math.abs(deviation) < closetAbs) {
closetAbs = Math.abs(deviation);
closet = nums[j] + nums[t] + nums[i];
}
if (deviation > 0) {
--t;
} else if (deviation == 0) {
return closet;
} else {
++j;
}
}
for (; i < nums.length - 2 && nums[i + 1] == nums[i]; ++i) ;
}
return closet;
}
}
| 1,391 | 0.464104 | 0.436548 | 46 | 28.97826 | 22.83922 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.673913 | false | false |
10
|
ef6455b86a3d42579a90c25763f9a28afc8130ee
| 27,685,359,223,320 |
f9a19e5724825cee540523da15a623a4bcf21df5
|
/src/main/java/ejercicio3_herencia/Programa3.java
|
0463f8aaf63f813bb51d796a569a7cfcc9df8a11
|
[] |
no_license
|
JhovinB/JavaWeb_Intro_CuentaBancaria
|
https://github.com/JhovinB/JavaWeb_Intro_CuentaBancaria
|
1e1e07cc1e69a52eabcae5a4e67e11920450ea94
|
8dbbf4c2ab7d258fe04781af202fd5decb248c73
|
refs/heads/master
| 2022-12-09T00:25:02.480000 | 2020-09-16T05:08:29 | 2020-09-16T05:08:29 | 295,928,650 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ejercicio3_herencia;
public class Programa3 {
public static void main(String[] args) {
CuentaBancariaEmpresa cuentaEmpresa = new CuentaBancariaEmpresa("12345","Kenia",100);
System.out.println("Cuenta Empresa: "+cuentaEmpresa.toString());
cuentaEmpresa.prestamo(60);
System.out.println("Cuenta: "+cuentaEmpresa.toString());
cuentaEmpresa.prestamo(150);
System.out.println("Cuenta: "+cuentaEmpresa.toString());
CuentaBancaria cuentaEmpresa2 = new CuentaBancariaEmpresa("12345","Diego",100);
System.out.println("Cuenta 2: "+cuentaEmpresa2.toString());
//Caste de Clase
CuentaBancariaEmpresa cuenta3 =(CuentaBancariaEmpresa)cuentaEmpresa2;
cuenta3.prestamo(40);
System.out.println("Cuenta 3: "+cuenta3.toString());
}
}
|
UTF-8
|
Java
| 776 |
java
|
Programa3.java
|
Java
|
[
{
"context": "uentaEmpresa = new CuentaBancariaEmpresa(\"12345\",\"Kenia\",100);\n\t\t\n\t\tSystem.out.println(\"Cuenta Empresa: \"",
"end": 182,
"score": 0.999696671962738,
"start": 177,
"tag": "NAME",
"value": "Kenia"
},
{
"context": "entaEmpresa2 = new CuentaBancariaEmpresa(\"12345\",\"Diego\",100);\n\t\tSystem.out.println(\"Cuenta 2: \"+cuentaEm",
"end": 522,
"score": 0.9996657371520996,
"start": 517,
"tag": "NAME",
"value": "Diego"
}
] | null |
[] |
package ejercicio3_herencia;
public class Programa3 {
public static void main(String[] args) {
CuentaBancariaEmpresa cuentaEmpresa = new CuentaBancariaEmpresa("12345","Kenia",100);
System.out.println("Cuenta Empresa: "+cuentaEmpresa.toString());
cuentaEmpresa.prestamo(60);
System.out.println("Cuenta: "+cuentaEmpresa.toString());
cuentaEmpresa.prestamo(150);
System.out.println("Cuenta: "+cuentaEmpresa.toString());
CuentaBancaria cuentaEmpresa2 = new CuentaBancariaEmpresa("12345","Diego",100);
System.out.println("Cuenta 2: "+cuentaEmpresa2.toString());
//Caste de Clase
CuentaBancariaEmpresa cuenta3 =(CuentaBancariaEmpresa)cuentaEmpresa2;
cuenta3.prestamo(40);
System.out.println("Cuenta 3: "+cuenta3.toString());
}
}
| 776 | 0.733247 | 0.690722 | 27 | 27.74074 | 28.524963 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.148148 | false | false |
10
|
e846a1640431852982ccd0153469ce68c036804f
| 9,363,028,746,602 |
3d72a81557b18ca53a9a82fc4f4405eede0ca20d
|
/mybatisfast/src/java/com/tang/mapper/UserMapper.java
|
a072420b01049359dcc0a47129fdb14292648090
|
[] |
no_license
|
tangyaxing/mytest
|
https://github.com/tangyaxing/mytest
|
e6e489caf196d763b72e47674a97fd8d9da9e350
|
d8d0c2daa5fa6fdf0c5f8b708a6169731797f5a3
|
refs/heads/master
| 2020-04-02T15:43:39.512000 | 2018-10-24T23:41:21 | 2018-10-24T23:41:21 | 154,581,005 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.tang.mapper;
import com.tang.pojo.Order;
import com.tang.pojo.QueryVo;
import com.tang.pojo.User;
import java.util.List;
public interface UserMapper {
User selectUserById(int id);
void addUser(User user);
List<User> selectUserByCondition(QueryVo queryVo);
List<User> selectUserByUsernameAndSex(User user);
void dynamicUpdateUserById(User user);
void batchInsertUser(List<User> list);
void batchDeleteUser(Integer[] array );
List<Order> selectAllOrderAndUser();
List<User> selectAllUserAndOrder();
}
|
UTF-8
|
Java
| 559 |
java
|
UserMapper.java
|
Java
|
[] | null |
[] |
package com.tang.mapper;
import com.tang.pojo.Order;
import com.tang.pojo.QueryVo;
import com.tang.pojo.User;
import java.util.List;
public interface UserMapper {
User selectUserById(int id);
void addUser(User user);
List<User> selectUserByCondition(QueryVo queryVo);
List<User> selectUserByUsernameAndSex(User user);
void dynamicUpdateUserById(User user);
void batchInsertUser(List<User> list);
void batchDeleteUser(Integer[] array );
List<Order> selectAllOrderAndUser();
List<User> selectAllUserAndOrder();
}
| 559 | 0.735242 | 0.735242 | 28 | 18.964285 | 19.000906 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
10
|
9b173599c5957e0e84b61dfa185f9f3c159efcf8
| 8,521,215,146,373 |
49073faa994bd933a30f2b7f525eb2ae102b0d58
|
/src/test/java/org/jenkins/plugins/blocksamebuilds/CheckBuildPropertyTest.java
|
baf9dc65fdd3b1c98daa703916d39e6d020a361f
|
[] |
no_license
|
mamh-java/block-same-builds-plugin
|
https://github.com/mamh-java/block-same-builds-plugin
|
ff6ad64b56264a05fe73cb7864491febf9b1c18b
|
191c455716403aff664e9671087506978367b485
|
refs/heads/master
| 2021-06-17T05:33:05.047000 | 2017-05-04T16:55:01 | 2017-05-04T16:55:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.jenkins.plugins.blocksamebuilds;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.SystemUtils;
import org.jenkinsci.plugins.blocksamebuilds.CheckBuildJobProperty;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import hudson.model.BooleanParameterDefinition;
import hudson.model.BooleanParameterValue;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.model.ParameterDefinition;
import hudson.model.ParameterValue;
import hudson.model.ParametersAction;
import hudson.model.ParametersDefinitionProperty;
import hudson.model.Result;
import hudson.model.StringParameterDefinition;
import hudson.model.StringParameterValue;
import hudson.tasks.BatchFile;
import hudson.tasks.Shell;
public class CheckBuildPropertyTest {
@Rule
public JenkinsRule j = new JenkinsRule();
// @Test
// public void first() throws Exception {
// FreeStyleProject project = j.createFreeStyleProject();
// if (SystemUtils.IS_OS_WINDOWS) {
// project.getBuildersList().add(new BatchFile("echo test"));
// } else {
// project.getBuildersList().add(new Shell("sleep 20"));
// }
//
// ParameterDefinition pd1 = new StringParameterDefinition("param1", "1");
// ParameterDefinition pd2 = new BooleanParameterDefinition("param2", false, "");
//
// project.addProperty(new ParametersDefinitionProperty(pd1, pd2));
// project.addProperty(new CheckBuildJobProperty("", true));
//
// FreeStyleBuild build = project.scheduleBuild2(0).get();
// // FreeStyleBuild build2 = project.scheduleBuild2(5).get();
// // FreeStyleBuild build3 = project.scheduleBuild2(10).get();
// // FreeStyleBuild build4 = project.scheduleBuild2(15).get();
//
// j.assertBuildStatus(Result.SUCCESS, build);
// // j.assertBuildStatus(Result.NOT_BUILT, build2);
// // j.assertBuildStatus(Result.NOT_BUILT, build3);
// // j.assertBuildStatus(Result.NOT_BUILT, build4);
// }
}
|
UTF-8
|
Java
| 1,997 |
java
|
CheckBuildPropertyTest.java
|
Java
|
[] | null |
[] |
package org.jenkins.plugins.blocksamebuilds;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.SystemUtils;
import org.jenkinsci.plugins.blocksamebuilds.CheckBuildJobProperty;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import hudson.model.BooleanParameterDefinition;
import hudson.model.BooleanParameterValue;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.model.ParameterDefinition;
import hudson.model.ParameterValue;
import hudson.model.ParametersAction;
import hudson.model.ParametersDefinitionProperty;
import hudson.model.Result;
import hudson.model.StringParameterDefinition;
import hudson.model.StringParameterValue;
import hudson.tasks.BatchFile;
import hudson.tasks.Shell;
public class CheckBuildPropertyTest {
@Rule
public JenkinsRule j = new JenkinsRule();
// @Test
// public void first() throws Exception {
// FreeStyleProject project = j.createFreeStyleProject();
// if (SystemUtils.IS_OS_WINDOWS) {
// project.getBuildersList().add(new BatchFile("echo test"));
// } else {
// project.getBuildersList().add(new Shell("sleep 20"));
// }
//
// ParameterDefinition pd1 = new StringParameterDefinition("param1", "1");
// ParameterDefinition pd2 = new BooleanParameterDefinition("param2", false, "");
//
// project.addProperty(new ParametersDefinitionProperty(pd1, pd2));
// project.addProperty(new CheckBuildJobProperty("", true));
//
// FreeStyleBuild build = project.scheduleBuild2(0).get();
// // FreeStyleBuild build2 = project.scheduleBuild2(5).get();
// // FreeStyleBuild build3 = project.scheduleBuild2(10).get();
// // FreeStyleBuild build4 = project.scheduleBuild2(15).get();
//
// j.assertBuildStatus(Result.SUCCESS, build);
// // j.assertBuildStatus(Result.NOT_BUILT, build2);
// // j.assertBuildStatus(Result.NOT_BUILT, build3);
// // j.assertBuildStatus(Result.NOT_BUILT, build4);
// }
}
| 1,997 | 0.768653 | 0.756134 | 57 | 34.035088 | 23.310991 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.578947 | false | false |
10
|
a4a997f997538b69b5681363dacb36afa61e5898
| 32,203,664,806,490 |
8e7147a2b7b8faddb0c768446da7b8d76274f36c
|
/Amazon/LeetCodeQ349.Intersection_of_Two_Arrays.java
|
e5fe3c61e8c9cd31cd261933b0f1b581aa4c551d
|
[] |
no_license
|
abxcytf/Java_coding_notes
|
https://github.com/abxcytf/Java_coding_notes
|
86d70c57d0d6e33dd51e2cbb20463a529d824025
|
85218bcf7f5b4915e826cf0a47c2db0a1f87be86
|
refs/heads/master
| 2021-01-23T06:55:33.442000 | 2018-04-01T05:35:43 | 2018-04-01T05:35:43 | 86,412,194 | 6 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
349. Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
. Each element in the result must be unique.
. The result can be in any order.
*/
public class Solution {
//Set implementation, time complexity O(n), space complexity O(n)
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
return new int[0];
}
Set<Integer> set = new HashSet<>();
Set<Integer> intersect = new HashSet<>();
for (int i = 0; i < nums1.length; i++) {
set.add(nums1[i]);
}
for (int i = 0; i < nums2.length; i++) {
if (set.contains(nums2[i])) {
intersect.add(nums2[i]);
}
}
int[] result = new int[intersect.size()];
int index = 0;
for (Integer num : intersect) {
result[index++] = num;
}
return result;
}
/***************************************************************************************/
Sort both arrays, use two pointers, time complexity O(nlogn) sort, space complexity O(n)
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
return new int[0];
}
Set<Integer> set = new HashSet<>();
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0;
int j = 0;
while (i < nums1.length && j < nums2.length) {
if (nums1[i] < nums2[j]) {
i++;
} else if (nums1[i] > nums2[j]) {
j++;
} else {
set.add(nums1[i]);
i++;
j++;
}
}
int[] result = new int[set.size()];
int index = 0;
for (Integer num : set) {
result[index++] = num;
}
return result;
}
/*********************************************************************************************/
//binary search implementation, time O(nlogn) - sort, binary search
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
return new int[0];
}
Set<Integer> set = new HashSet<>();
Arrays.sort(nums2);
for (Integer num : nums1) {
if (binarySearch(nums2, num)) {
set.add(num);
}
}
int[] result = new int[set.size()];
int index = 0;
for (Integer num : set) {
result[index++] = num;
}
return result;
}
private boolean binarySearch(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left + 1 < right) {
int mid = (left + right) >>> 1;
if (nums[mid] == target) {
return true;
} else if (nums[mid] > target) {
right = mid;
} else {
left = mid;
}
}
if (nums[left] == target || nums[right] == target) {
return true;
} else {
return false;
}
}
}
|
UTF-8
|
Java
| 3,412 |
java
|
LeetCodeQ349.Intersection_of_Two_Arrays.java
|
Java
|
[] | null |
[] |
/*
349. Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
. Each element in the result must be unique.
. The result can be in any order.
*/
public class Solution {
//Set implementation, time complexity O(n), space complexity O(n)
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
return new int[0];
}
Set<Integer> set = new HashSet<>();
Set<Integer> intersect = new HashSet<>();
for (int i = 0; i < nums1.length; i++) {
set.add(nums1[i]);
}
for (int i = 0; i < nums2.length; i++) {
if (set.contains(nums2[i])) {
intersect.add(nums2[i]);
}
}
int[] result = new int[intersect.size()];
int index = 0;
for (Integer num : intersect) {
result[index++] = num;
}
return result;
}
/***************************************************************************************/
Sort both arrays, use two pointers, time complexity O(nlogn) sort, space complexity O(n)
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
return new int[0];
}
Set<Integer> set = new HashSet<>();
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0;
int j = 0;
while (i < nums1.length && j < nums2.length) {
if (nums1[i] < nums2[j]) {
i++;
} else if (nums1[i] > nums2[j]) {
j++;
} else {
set.add(nums1[i]);
i++;
j++;
}
}
int[] result = new int[set.size()];
int index = 0;
for (Integer num : set) {
result[index++] = num;
}
return result;
}
/*********************************************************************************************/
//binary search implementation, time O(nlogn) - sort, binary search
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
return new int[0];
}
Set<Integer> set = new HashSet<>();
Arrays.sort(nums2);
for (Integer num : nums1) {
if (binarySearch(nums2, num)) {
set.add(num);
}
}
int[] result = new int[set.size()];
int index = 0;
for (Integer num : set) {
result[index++] = num;
}
return result;
}
private boolean binarySearch(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left + 1 < right) {
int mid = (left + right) >>> 1;
if (nums[mid] == target) {
return true;
} else if (nums[mid] > target) {
right = mid;
} else {
left = mid;
}
}
if (nums[left] == target || nums[right] == target) {
return true;
} else {
return false;
}
}
}
| 3,412 | 0.431712 | 0.412075 | 113 | 29.194691 | 22.68322 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.734513 | false | false |
10
|
3ee816976a4855f8dde03026c33d981448f1df8a
| 2,654,289,803,145 |
64bd0fda18e77455d34fb1968ad3ade4078955e6
|
/src/sw/builder/gui/controller/DisplayBoardController.java
|
52d239dc2ebb04bebc42ece94d172b7280060658
|
[] |
no_license
|
vanshajc/SixesWild
|
https://github.com/vanshajc/SixesWild
|
4a5022fd41d5470c32652878389df6af42e834a3
|
09072f4c24b02470e07f34360a0264a8e28b10e5
|
refs/heads/master
| 2020-06-13T09:04:48.759000 | 2015-05-05T21:45:28 | 2015-05-05T21:45:28 | 75,429,642 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package sw.builder.gui.controller;
import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.border.EmptyBorder;
import sw.app.gui.view.board.BoardPanel;
import sw.builder.gui.layout.BuilderLayoutManager;
import sw.builder.gui.layout.LevelBuilderView;
import sw.common.model.entity.Board;
import sw.common.model.entity.Level;
import sw.common.model.entity.Statistics;
import sw.common.model.entity.Tile;
import sw.common.system.factory.LevelFactory;
/**
* @author scyevchak
*/
/** Controller for the display button */
public class DisplayBoardController implements ActionListener {
/** Controls which screen is displayed */
BuilderLayoutManager blm;
/** The view that has the current board */
LevelBuilderView lbv;
/**
* Constructor to display the board created.
* @param blm view currently on.
* @param lbv the data containing the board.
*/
public DisplayBoardController(BuilderLayoutManager blm, LevelBuilderView lbv) {
this.blm = blm;
this.lbv = lbv;
}
/**
* Sets the board and displays it in a new view.
*/
@Override
public void actionPerformed(ActionEvent arg0) {
String[][] b = lbv.getBoard();
Board b1;
try {
b1 = setBoardView(b,lbv);
blm.switchToScreen(LevelBuilderView.boardPanel);
LevelBuilderView.boardPanel.getBoard().copy(b1);
LevelBuilderView.boardPanel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
blm.switchToLevelBuilder();
}
});
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
/**
* Sets the board to be displayed
* @param b the string array containing data about the board.
* @param lbv the level builder containing the board object.
* @return the Board set
* @throws Exception stops invalid boards from being displayed.
*/
public static Board setBoardView(String[][] b,LevelBuilderView lbv) throws Exception {
Board b1 = new Board();
Tile t1;
int mult = -1;
int value = -1;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
Point p1 = new Point(i, j);
String val = b[i][j].substring(0, 1);
String mul = b[i][j].substring(2);
if (!val.equals("*") && !mul.equals("*")) {
value = Integer.parseInt(val);
mult = Integer.parseInt(mul);
}
if (mul.equals("*") || val.equals("*")) {
if(!lbv.getModeList().equals("Release")){
throw new Exception("Invalid board type for tile selection");
}
CreateButtonController.board.getSquare(p1).setTile(null);
CreateButtonController.board.getSquare(p1).setOnlySix(true);
} else if (value == 0 || mult == 0) {
CreateButtonController.board.getSquare(p1).setTile(null);
} else if(value != -1 || mult != -1) {
if(value == 6 && lbv.getModeList().equals("Elimination") && lbv.getModeList().equals("Release")){
throw new Exception("Invalid board type for tile selection");
}
t1 = new Tile(value, mult);
CreateButtonController.board.getSquare(p1).setTile(t1);
System.out.println(CreateButtonController.board.getSquare(p1).getTile());
} else {
}
}
}
b1 = CreateButtonController.board;
return b1;
}
}
|
UTF-8
|
Java
| 3,457 |
java
|
DisplayBoardController.java
|
Java
|
[
{
"context": "mmon.system.factory.LevelFactory;\r\n/**\r\n * @author scyevchak\r\n */\r\n/** Controller for the display button */\r\np",
"end": 684,
"score": 0.9995387196540833,
"start": 675,
"tag": "USERNAME",
"value": "scyevchak"
}
] | null |
[] |
package sw.builder.gui.controller;
import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.border.EmptyBorder;
import sw.app.gui.view.board.BoardPanel;
import sw.builder.gui.layout.BuilderLayoutManager;
import sw.builder.gui.layout.LevelBuilderView;
import sw.common.model.entity.Board;
import sw.common.model.entity.Level;
import sw.common.model.entity.Statistics;
import sw.common.model.entity.Tile;
import sw.common.system.factory.LevelFactory;
/**
* @author scyevchak
*/
/** Controller for the display button */
public class DisplayBoardController implements ActionListener {
/** Controls which screen is displayed */
BuilderLayoutManager blm;
/** The view that has the current board */
LevelBuilderView lbv;
/**
* Constructor to display the board created.
* @param blm view currently on.
* @param lbv the data containing the board.
*/
public DisplayBoardController(BuilderLayoutManager blm, LevelBuilderView lbv) {
this.blm = blm;
this.lbv = lbv;
}
/**
* Sets the board and displays it in a new view.
*/
@Override
public void actionPerformed(ActionEvent arg0) {
String[][] b = lbv.getBoard();
Board b1;
try {
b1 = setBoardView(b,lbv);
blm.switchToScreen(LevelBuilderView.boardPanel);
LevelBuilderView.boardPanel.getBoard().copy(b1);
LevelBuilderView.boardPanel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
blm.switchToLevelBuilder();
}
});
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
/**
* Sets the board to be displayed
* @param b the string array containing data about the board.
* @param lbv the level builder containing the board object.
* @return the Board set
* @throws Exception stops invalid boards from being displayed.
*/
public static Board setBoardView(String[][] b,LevelBuilderView lbv) throws Exception {
Board b1 = new Board();
Tile t1;
int mult = -1;
int value = -1;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
Point p1 = new Point(i, j);
String val = b[i][j].substring(0, 1);
String mul = b[i][j].substring(2);
if (!val.equals("*") && !mul.equals("*")) {
value = Integer.parseInt(val);
mult = Integer.parseInt(mul);
}
if (mul.equals("*") || val.equals("*")) {
if(!lbv.getModeList().equals("Release")){
throw new Exception("Invalid board type for tile selection");
}
CreateButtonController.board.getSquare(p1).setTile(null);
CreateButtonController.board.getSquare(p1).setOnlySix(true);
} else if (value == 0 || mult == 0) {
CreateButtonController.board.getSquare(p1).setTile(null);
} else if(value != -1 || mult != -1) {
if(value == 6 && lbv.getModeList().equals("Elimination") && lbv.getModeList().equals("Release")){
throw new Exception("Invalid board type for tile selection");
}
t1 = new Tile(value, mult);
CreateButtonController.board.getSquare(p1).setTile(t1);
System.out.println(CreateButtonController.board.getSquare(p1).getTile());
} else {
}
}
}
b1 = CreateButtonController.board;
return b1;
}
}
| 3,457 | 0.668209 | 0.658953 | 106 | 30.613207 | 22.474543 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.650943 | false | false |
10
|
84950263cba50dd8acdf4c753d5b3ebea2d504a9
| 3,006,477,144,716 |
fb2aa5125c7b477bbb244ba0ad099021d344784f
|
/app/src/main/java/cn/share/phone/MessageListActivity.java
|
3d83bf9d537b5ca21545f708e93f0ef9aaef1392
|
[] |
no_license
|
kimljx/Share_android
|
https://github.com/kimljx/Share_android
|
5fccaa0febb0321302eadfee1fa9f2d22e2c0ce3
|
0a30e37dc90924dd893b1ff65a62e980a2c50fb1
|
refs/heads/master
| 2021-01-20T13:12:33.749000 | 2017-05-21T11:08:17 | 2017-05-21T11:08:17 | 90,464,771 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cn.share.phone;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.TextView;
import cn.share.Common;
import cn.share.R;
import cn.share.RestBLL;
import cn.share.phone.uc.PGACTIVITY;
import cn.vipapps.CALLBACK;
import cn.vipapps.MESSAGE;
import org.json.JSONArray;
import org.json.JSONObject;
import uc.SegmentView;
import uc.XListView;
//通知列表页
public class MessageListActivity extends PGACTIVITY {
private int type = 0;
XListView listView;
BaseAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_list);
//
MESSAGE.receive(Common.MSG_MESSAGEREFESH, new CALLBACK<Bundle>() {
@Override
public void run(boolean isError, Bundle result) {
onStart();
reloadData();
}
});
listView = (XListView) findViewById(R.id.msg_listview);
listView.setXListViewListener(new XListView.IXListViewListener() {
@Override
public void onRefresh() {
reloadData();
}
@Override
public void onLoadMore() {
}
});
//每个Item的点击事件,进入详细页
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("onItemClick: ", i + " "+(i - listView.getHeaderViewsCount()));
int j = i - listView.getHeaderViewsCount();
String notificationId = ((JSONObject) adapter.getItem(j)).optString("notificationId");
String messageId = ((JSONObject) adapter.getItem(j)).optString("messageId");
Intent intent = new Intent(MessageListActivity.this, MessageDetailActivity.class);
//传递消息ID和通知Id给下一个页面
intent.putExtra("notificationId", notificationId);
intent.putExtra("messageId", messageId);
startActivity(intent);
}
});
reloadData();
//适配器绑定数据
adapter = new BaseAdapter() {
@Override
public int getCount() {
return allMessage.length();
}
@Override
public JSONObject getItem(int i) {
return allMessage.optJSONObject(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
MSGPH msgPH;
if (view == null) {
msgPH = new MSGPH();
view = View.inflate(getBaseContext(), R.layout.item_listview_msg, null);
msgPH.message = (TextView) view.findViewById(R.id.message);
msgPH.time = (TextView) view.findViewById(R.id.time);
view.setTag(msgPH);
} else {
msgPH = (MSGPH) view.getTag();
}
JSONObject message = getItem(i);
msgPH.message.setText(message.optString("notificationInfo"));
return view;
}
};
listView.setAdapter(adapter);
//接收广播,刷新页面
MESSAGE.receive(Common.MSG_NOTIFICATION, new CALLBACK<Bundle>() {
@Override
public void run(boolean isError, Bundle result) {
onStart();
reloadData();
}
});
}
int select = 0;
@Override
protected void onStart() {
super.onStart();
//设置切换选项控件
SegmentView segmentView = new SegmentView(this);
String[] title = new String[]{"未读", "已读"};
segmentView.setTitles(title);
segmentView.setSeclect(select);
segmentView.setOnSegmentViewClickListener(new SegmentView.onSegmentViewClickListener() {
@Override
public void onSegmentViewClick(View v, int position) {
if (position == 0) {
type = 0;
} else {
type = 1;
}
select = position;
reloadData();
}
});
this.navigationBar().titleView(segmentView);
}
JSONArray allMessage;
//调用接口获取数据
private void reloadData() {
allMessage = new JSONArray();
listView.setPullLoadEnable(false);
RestBLL.notificationList(String.valueOf(type),new CALLBACK<JSONArray>() {
@Override
public void run(boolean isError, JSONArray result) {
if (isError) {
listView.stopRefresh();
return;
}
//更新数据
allMessage = result;
adapter.notifyDataSetChanged();
listView.stopRefresh();
}
});
}
public class MSGPH {
TextView message, time;
}
}
|
UTF-8
|
Java
| 5,436 |
java
|
MessageListActivity.java
|
Java
|
[] | null |
[] |
package cn.share.phone;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.TextView;
import cn.share.Common;
import cn.share.R;
import cn.share.RestBLL;
import cn.share.phone.uc.PGACTIVITY;
import cn.vipapps.CALLBACK;
import cn.vipapps.MESSAGE;
import org.json.JSONArray;
import org.json.JSONObject;
import uc.SegmentView;
import uc.XListView;
//通知列表页
public class MessageListActivity extends PGACTIVITY {
private int type = 0;
XListView listView;
BaseAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_list);
//
MESSAGE.receive(Common.MSG_MESSAGEREFESH, new CALLBACK<Bundle>() {
@Override
public void run(boolean isError, Bundle result) {
onStart();
reloadData();
}
});
listView = (XListView) findViewById(R.id.msg_listview);
listView.setXListViewListener(new XListView.IXListViewListener() {
@Override
public void onRefresh() {
reloadData();
}
@Override
public void onLoadMore() {
}
});
//每个Item的点击事件,进入详细页
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("onItemClick: ", i + " "+(i - listView.getHeaderViewsCount()));
int j = i - listView.getHeaderViewsCount();
String notificationId = ((JSONObject) adapter.getItem(j)).optString("notificationId");
String messageId = ((JSONObject) adapter.getItem(j)).optString("messageId");
Intent intent = new Intent(MessageListActivity.this, MessageDetailActivity.class);
//传递消息ID和通知Id给下一个页面
intent.putExtra("notificationId", notificationId);
intent.putExtra("messageId", messageId);
startActivity(intent);
}
});
reloadData();
//适配器绑定数据
adapter = new BaseAdapter() {
@Override
public int getCount() {
return allMessage.length();
}
@Override
public JSONObject getItem(int i) {
return allMessage.optJSONObject(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
MSGPH msgPH;
if (view == null) {
msgPH = new MSGPH();
view = View.inflate(getBaseContext(), R.layout.item_listview_msg, null);
msgPH.message = (TextView) view.findViewById(R.id.message);
msgPH.time = (TextView) view.findViewById(R.id.time);
view.setTag(msgPH);
} else {
msgPH = (MSGPH) view.getTag();
}
JSONObject message = getItem(i);
msgPH.message.setText(message.optString("notificationInfo"));
return view;
}
};
listView.setAdapter(adapter);
//接收广播,刷新页面
MESSAGE.receive(Common.MSG_NOTIFICATION, new CALLBACK<Bundle>() {
@Override
public void run(boolean isError, Bundle result) {
onStart();
reloadData();
}
});
}
int select = 0;
@Override
protected void onStart() {
super.onStart();
//设置切换选项控件
SegmentView segmentView = new SegmentView(this);
String[] title = new String[]{"未读", "已读"};
segmentView.setTitles(title);
segmentView.setSeclect(select);
segmentView.setOnSegmentViewClickListener(new SegmentView.onSegmentViewClickListener() {
@Override
public void onSegmentViewClick(View v, int position) {
if (position == 0) {
type = 0;
} else {
type = 1;
}
select = position;
reloadData();
}
});
this.navigationBar().titleView(segmentView);
}
JSONArray allMessage;
//调用接口获取数据
private void reloadData() {
allMessage = new JSONArray();
listView.setPullLoadEnable(false);
RestBLL.notificationList(String.valueOf(type),new CALLBACK<JSONArray>() {
@Override
public void run(boolean isError, JSONArray result) {
if (isError) {
listView.stopRefresh();
return;
}
//更新数据
allMessage = result;
adapter.notifyDataSetChanged();
listView.stopRefresh();
}
});
}
public class MSGPH {
TextView message, time;
}
}
| 5,436 | 0.54779 | 0.546845 | 172 | 29.77907 | 23.825382 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.581395 | false | false |
10
|
2a2c7b049c10c25bbfa723eb245ee7ec6229e64e
| 5,153,960,756,009 |
8e1cea7a5e30e7502b581c1c3746a1491378cbfb
|
/src/LearnComparator.java
|
12dca59732ee966fa7c367c4e0c1b828d76b08da
|
[] |
no_license
|
poojadalaya/LearnJava
|
https://github.com/poojadalaya/LearnJava
|
6d80fa31625fb546f6a21404f3a384f6c33ec704
|
c0d2bb080d6294090e09cacffaf41ddab0311d45
|
refs/heads/main
| 2023-08-02T22:24:34.194000 | 2021-09-12T19:07:59 | 2021-09-12T19:07:59 | 359,007,168 | 0 | 0 | null | false | 2021-04-18T01:41:45 | 2021-04-17T23:59:46 | 2021-04-18T01:08:59 | 2021-04-18T01:41:44 | 0 | 0 | 0 | 0 |
Java
| false | false |
import java.util.Date;
public class LearnComparator {
public static void main(String args[]) {
Date d1 = new Date(2021, 10, 5);
Date d2 = new Date(2021, 8, 5);
int compareValue = d1.compareTo(d2);
System.out.println("Higher date(10/5/2021) compared to lower date(8/5/2021):"+compareValue);
compareValue = d2.compareTo(d1);
System.out.println("Lower date(8/5/2021) compared to higher date(10/5/2021):"+compareValue);
d2 = new Date(2021, 10, 5);
compareValue = d1.compareTo(d2);
System.out.println("Same date:"+compareValue);
Date d3 = new Date();
System.out.println("New date gives the current timestamp:"+d3);
d2 = null;
compareValue = d2.compareTo(d1);
System.out.println("If input to compareTo is null:"+compareValue);
}
}
|
UTF-8
|
Java
| 848 |
java
|
LearnComparator.java
|
Java
|
[] | null |
[] |
import java.util.Date;
public class LearnComparator {
public static void main(String args[]) {
Date d1 = new Date(2021, 10, 5);
Date d2 = new Date(2021, 8, 5);
int compareValue = d1.compareTo(d2);
System.out.println("Higher date(10/5/2021) compared to lower date(8/5/2021):"+compareValue);
compareValue = d2.compareTo(d1);
System.out.println("Lower date(8/5/2021) compared to higher date(10/5/2021):"+compareValue);
d2 = new Date(2021, 10, 5);
compareValue = d1.compareTo(d2);
System.out.println("Same date:"+compareValue);
Date d3 = new Date();
System.out.println("New date gives the current timestamp:"+d3);
d2 = null;
compareValue = d2.compareTo(d1);
System.out.println("If input to compareTo is null:"+compareValue);
}
}
| 848 | 0.622642 | 0.551887 | 22 | 37.545456 | 28.614567 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.954545 | false | false |
10
|
6fcc2bddd8ee104e3a0538e551c0577f79e63a3a
| 16,492,674,452,310 |
0f6bdf28f9e2b701b776ed8b3906b64921478e30
|
/sem2/Ugolki/src/main/java/ru/itis/inf/Server/src/main/java/ru/itis/inf/MainForMultithreadedServer.java
|
894cb961268de3fb4ec2a0658ee1ab87119b7d50
|
[] |
no_license
|
delechka247/MyTestApplication
|
https://github.com/delechka247/MyTestApplication
|
dcaa22c9e2e80477cf80b76104e9b3a1b2dde021
|
313fe156b301eb7f60c9523df6aaba06e946681f
|
refs/heads/master
| 2023-05-10T16:43:11.846000 | 2022-01-25T07:54:15 | 2022-01-25T07:54:15 | 266,096,937 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ru.itis.inf;
import ru.itis.inf.game.ConsoleGameService;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
public class MainForMultithreadedServer {
public static final int PORT = 4321;
public static LinkedList<MultithreadedServer> serverList = new LinkedList<>();
public static ConsoleGameService cgs = new ConsoleGameService();
public static boolean isFirst = true;
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(PORT, 2);
System.out.println("Server started at " + PORT);
try {
while (serverList.size() < 2) {
Socket socket = server.accept();
try {
serverList.add(new MultithreadedServer(socket));
System.out.println("Новый клиент! Осталось ожидать игроков: " + (2 - serverList.size()));
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
} finally {
server.close();
}
}
}
|
UTF-8
|
Java
| 1,197 |
java
|
MainForMultithreadedServer.java
|
Java
|
[] | null |
[] |
package ru.itis.inf;
import ru.itis.inf.game.ConsoleGameService;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
public class MainForMultithreadedServer {
public static final int PORT = 4321;
public static LinkedList<MultithreadedServer> serverList = new LinkedList<>();
public static ConsoleGameService cgs = new ConsoleGameService();
public static boolean isFirst = true;
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(PORT, 2);
System.out.println("Server started at " + PORT);
try {
while (serverList.size() < 2) {
Socket socket = server.accept();
try {
serverList.add(new MultithreadedServer(socket));
System.out.println("Новый клиент! Осталось ожидать игроков: " + (2 - serverList.size()));
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
} finally {
server.close();
}
}
}
| 1,197 | 0.598797 | 0.592784 | 35 | 32.285713 | 25.664396 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.514286 | false | false |
10
|
61c0bb028a521ddb3b907ddef71f62aa47a3d3cf
| 26,852,135,549,692 |
aa96af3393f0585be2acef09518a6b61f1d9b41b
|
/Arrays/Let414.java
|
44134f39ead6f8ab62119e79cec0223356aa83cb
|
[] |
no_license
|
oovever/LeetCodeByJava
|
https://github.com/oovever/LeetCodeByJava
|
7f3078391a41df9da2ddb512c67002abc7b97706
|
b9c4670753b297eb10eafce8299516d61eebd83e
|
refs/heads/master
| 2021-07-24T20:22:06.941000 | 2017-11-04T13:14:12 | 2017-11-04T13:14:12 | 93,377,252 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Created by OovEver on 2017/4/8.
*/
public class Let414 {
public static int thirdMax(int[] nums) {
if(nums==null)
return 0;
else if(nums.length==1)
return nums[0];
int fir=Integer.MIN_VALUE;
Integer sec=null;
Integer thr=null;
for(int i=0;i<nums.length;i++){
fir=fir<nums[i]?nums[i]:fir;
}
for(int i=0;i<nums.length;i++){
if(nums[i]<fir&&sec==null){
sec=nums[i];
}
if(nums[i]<fir&&sec<nums[i]){
sec=nums[i];
}
}
if(sec==null)
return fir;
for(int i=0;i<nums.length;i++){
if(nums[i]<sec&&thr==null){
thr=nums[i];
}
if(nums[i]<sec&&thr<nums[i]){
thr=nums[i]; }
}
if(thr==null)
return fir;
return thr;
}
public static void main(String[] args) {
int[] nums={1,2,-2147483648};
thirdMax(nums);
System.out.println(thirdMax(nums));
}
}
|
UTF-8
|
Java
| 1,108 |
java
|
Let414.java
|
Java
|
[
{
"context": "/**\n * Created by OovEver on 2017/4/8.\n */\npublic class Let414 {\n public",
"end": 25,
"score": 0.9184118509292603,
"start": 18,
"tag": "USERNAME",
"value": "OovEver"
}
] | null |
[] |
/**
* Created by OovEver on 2017/4/8.
*/
public class Let414 {
public static int thirdMax(int[] nums) {
if(nums==null)
return 0;
else if(nums.length==1)
return nums[0];
int fir=Integer.MIN_VALUE;
Integer sec=null;
Integer thr=null;
for(int i=0;i<nums.length;i++){
fir=fir<nums[i]?nums[i]:fir;
}
for(int i=0;i<nums.length;i++){
if(nums[i]<fir&&sec==null){
sec=nums[i];
}
if(nums[i]<fir&&sec<nums[i]){
sec=nums[i];
}
}
if(sec==null)
return fir;
for(int i=0;i<nums.length;i++){
if(nums[i]<sec&&thr==null){
thr=nums[i];
}
if(nums[i]<sec&&thr<nums[i]){
thr=nums[i]; }
}
if(thr==null)
return fir;
return thr;
}
public static void main(String[] args) {
int[] nums={1,2,-2147483648};
thirdMax(nums);
System.out.println(thirdMax(nums));
}
}
| 1,108 | 0.433213 | 0.408845 | 47 | 22.574469 | 14.476312 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.510638 | false | false |
10
|
b3c03b0d07a2d6f2e5e3027506b4443b04472e8f
| 31,009,663,903,107 |
48ef0cde41a038fd7b07205e819c2f48f8c1cf62
|
/src/main/java/gyh/gxsz/mapper/AuditMapper.java
|
fff16afc70343d8d2a1cfd94befe1c9046a59def
|
[] |
no_license
|
GuoTailor/gxsz
|
https://github.com/GuoTailor/gxsz
|
c94d32430452c31f0e821e89234ae4c76d7efa12
|
f53f21695db5741a78fc6ddf787b719907a613ed
|
refs/heads/master
| 2020-07-11T10:21:49.161000 | 2019-09-06T04:57:13 | 2019-09-06T04:57:13 | 204,511,377 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package gyh.gxsz.mapper;
import gyh.gxsz.bean.Approval;
import gyh.gxsz.bean.Audit;
import java.util.List;
/**
* Created by gyh on 2019/8/26.
*/
public interface AuditMapper {
int deleteByPrimaryKey(Integer id);
int insert(Audit record);
int insertOrUpdate(Audit record);
int insertOrUpdateSelective(Audit record);
int insertSelective(Audit record);
Audit selectByPrimaryKey(Integer id);
List<Approval> getAllAudit(String search);
int updateByPrimaryKeySelective(Audit record);
int updateByPrimaryKey(Audit record);
Audit selectByUserId(Integer userId);
}
|
UTF-8
|
Java
| 609 |
java
|
AuditMapper.java
|
Java
|
[
{
"context": ".Audit;\n\nimport java.util.List;\n\n/**\n * Created by gyh on 2019/8/26.\n */\npublic interface AuditMapper {\n",
"end": 131,
"score": 0.9996012449264526,
"start": 128,
"tag": "USERNAME",
"value": "gyh"
}
] | null |
[] |
package gyh.gxsz.mapper;
import gyh.gxsz.bean.Approval;
import gyh.gxsz.bean.Audit;
import java.util.List;
/**
* Created by gyh on 2019/8/26.
*/
public interface AuditMapper {
int deleteByPrimaryKey(Integer id);
int insert(Audit record);
int insertOrUpdate(Audit record);
int insertOrUpdateSelective(Audit record);
int insertSelective(Audit record);
Audit selectByPrimaryKey(Integer id);
List<Approval> getAllAudit(String search);
int updateByPrimaryKeySelective(Audit record);
int updateByPrimaryKey(Audit record);
Audit selectByUserId(Integer userId);
}
| 609 | 0.735632 | 0.724138 | 31 | 18.67742 | 18.582661 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.451613 | false | false |
10
|
b3fe7e46a0b867353af6a4008a309a69ee4619b2
| 5,128,190,992,906 |
63f947e72b05ebeeb9bbdfbfa07d62992aa40863
|
/src/Hzfengsy/IR/IRInstruction/IRUnaryExprInstruction.java
|
4895ad651d3a8aceff7173ba0c03427b0b6ce1d2
|
[] |
no_license
|
Hzfengsy/M-Compiler
|
https://github.com/Hzfengsy/M-Compiler
|
573a8dbf3f31e5af9a084a81998fc2af76f7dc8f
|
b2de6d5902c28d3b5a5ea25f2b1011b576f688c6
|
refs/heads/master
| 2020-03-07T20:10:04.353000 | 2018-06-05T13:03:02 | 2018-06-05T13:03:02 | 127,690,439 | 7 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Hzfengsy.IR.IRInstruction;
import Hzfengsy.IR.IRExpr.*;
public class IRUnaryExprInstruction extends IRBaseInstruction
{
private IRExpr result;
private IRExpr right;
private IROperations.unaryOp operator;
public IRUnaryExprInstruction(IRExpr result, IROperations.unaryOp op, IRExpr right) {
this.result = result;
this.operator = op;
this.right = right;
}
@Override
public void setResult(IRExpr result) {
this.result = result;
}
public IRExpr getResult() {
return result;
}
@Override
public String toString() {
return result + " = " + operator.name() + " " + right;
}
public IROperations.unaryOp getOperator() {
return operator;
}
public IRExpr getRight() {
return right;
}
@Override
public void analyze() {
this.setDef(result);
if (result instanceof IRMem || (result instanceof IRVar && ((IRVar) result).isGlobe())) {
useInst();
}
}
@Override
public void useInst() {
if (!this.used) {
this.setUse(right);
this.used = true;
}
}
}
|
UTF-8
|
Java
| 1,178 |
java
|
IRUnaryExprInstruction.java
|
Java
|
[] | null |
[] |
package Hzfengsy.IR.IRInstruction;
import Hzfengsy.IR.IRExpr.*;
public class IRUnaryExprInstruction extends IRBaseInstruction
{
private IRExpr result;
private IRExpr right;
private IROperations.unaryOp operator;
public IRUnaryExprInstruction(IRExpr result, IROperations.unaryOp op, IRExpr right) {
this.result = result;
this.operator = op;
this.right = right;
}
@Override
public void setResult(IRExpr result) {
this.result = result;
}
public IRExpr getResult() {
return result;
}
@Override
public String toString() {
return result + " = " + operator.name() + " " + right;
}
public IROperations.unaryOp getOperator() {
return operator;
}
public IRExpr getRight() {
return right;
}
@Override
public void analyze() {
this.setDef(result);
if (result instanceof IRMem || (result instanceof IRVar && ((IRVar) result).isGlobe())) {
useInst();
}
}
@Override
public void useInst() {
if (!this.used) {
this.setUse(right);
this.used = true;
}
}
}
| 1,178 | 0.589134 | 0.589134 | 54 | 20.814816 | 21.113516 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false |
10
|
6f1fdf15b4ec0a0e0ae4baf07b090980b9cde380
| 4,209,067,990,035 |
b93f6195ca8d379cc54aed438e37eeee895392b1
|
/service/src/main/java/com/aerofs/baseline/admin/InvalidCommandException.java
|
607a77366e2e4a736c1e528e60efa1d63b34590a
|
[
"Apache-2.0"
] |
permissive
|
aerofs/baseline
|
https://github.com/aerofs/baseline
|
5ab277caf210ca603b9be790a404912c5f551f32
|
e1eef4059727ef9ee293e414059876c7f5cad148
|
refs/heads/master
| 2016-09-15T08:20:40.112000 | 2016-03-11T07:46:45 | 2016-03-11T07:46:45 | 26,773,737 | 2 | 2 | null | false | 2015-11-03T19:56:06 | 2014-11-17T19:38:51 | 2015-08-07T04:48:18 | 2015-11-03T19:56:05 | 459 | 1 | 1 | 0 |
Java
| null | null |
/*
* Copyright 2015 Air Computing Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aerofs.baseline.admin;
import javax.annotation.concurrent.Immutable;
/**
* Thrown when the caller specifies a command that was
* not registered withe the service.
*/
@Immutable
public final class InvalidCommandException extends Exception {
private static final long serialVersionUID = -322542459999916222L;
/**
* Constructor.
*
* @param name name of the command that could not be found
*/
public InvalidCommandException(String name) {
super("no command named " + name);
}
}
|
UTF-8
|
Java
| 1,138 |
java
|
InvalidCommandException.java
|
Java
|
[] | null |
[] |
/*
* Copyright 2015 Air Computing Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aerofs.baseline.admin;
import javax.annotation.concurrent.Immutable;
/**
* Thrown when the caller specifies a command that was
* not registered withe the service.
*/
@Immutable
public final class InvalidCommandException extends Exception {
private static final long serialVersionUID = -322542459999916222L;
/**
* Constructor.
*
* @param name name of the command that could not be found
*/
public InvalidCommandException(String name) {
super("no command named " + name);
}
}
| 1,138 | 0.72232 | 0.699473 | 38 | 28.947369 | 27.251217 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.236842 | false | false |
10
|
06e8b67678e365891023ff19d27a3b3a0d52149a
| 7,748,121,039,906 |
60d81b99e478a68de909103249fbae81d287564e
|
/WM-Tippspiel/src/Controller/Database/UserTable.java
|
7ca70219e6df73e605175028b021e306986e81d6
|
[] |
no_license
|
ThomasDueck/Thomas-projects
|
https://github.com/ThomasDueck/Thomas-projects
|
a4ba4d5d7eff70fd2722d82be607fcfe4cb90ed5
|
37e6fb750e4246958e01237bb24d64ff99d754ee
|
refs/heads/master
| 2022-06-09T00:06:29.611000 | 2018-06-25T16:57:26 | 2018-06-25T16:57:26 | 138,065,937 | 0 | 0 | null | false | 2022-05-20T20:49:40 | 2018-06-20T17:39:11 | 2021-06-12T21:03:40 | 2022-05-20T20:49:40 | 879 | 0 | 0 | 1 |
Java
| false | false |
package controller.database;
import model.Team;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import static controller.database.SQLDriverConnection.connect;
public class UserTable {
/**
* Gets all Users from the database table USER
* @return ArrayList<Team> of all Users. Team
*/
public static ArrayList<Team> getUser() {
connect();
String sql = "SELECT * FROM User";
ArrayList<Team> allUser = new ArrayList<>();
try {
PreparedStatement stmt = SQLDriverConnection.conn.prepareStatement(sql);
ResultSet user = stmt.executeQuery();
while (user.next()) {
allUser.add(new Team(user.getString(1), user.getInt(2)));
}
SQLDriverConnection.conn.close();
} catch (SQLException e) {
System.out.println("User couldnt get selected from table");
} finally {
return allUser;
}
}
/**
* Gets all Users and inserts them into an ObservableList<String>
* @return ObservableList<String>
*/
public static ObservableList<String> getObservableUser() { ;
ArrayList<Team> teams = getUser();
ObservableList<String> teamList = FXCollections.observableArrayList();
for (Team t : teams) {
teamList.add(t.getTeamname());
}
Collections.sort(teamList);
return teamList;
}
/**
* Adds a User into the database Table USER
* @param user - username to be added
* @return true if success, false otherwise
*/
public static boolean addUser(String user) {
connect();
String sql = "INSERT INTO User (user) VALUES (?)";
try {
PreparedStatement stmt = SQLDriverConnection.conn.prepareStatement(sql);
stmt.setString(1, user);
int res = stmt.executeUpdate();
SQLDriverConnection.conn.close();
if(res > 0) return true;
else return false;
} catch (SQLException e) {
System.out.println("User could not be inserted");
return false;
}
}
/**
* Checks if a username is already taken by someone else
* @param user - User to be checked
* @return - true if user already exists, false if not.
*/
public static boolean checkUser(String user) {
connect();
String sql = "SELECT * FROM USER where user = ?";
try {
PreparedStatement stmt = SQLDriverConnection.conn.prepareStatement(sql);
stmt.setString(1, user);
ResultSet rs = stmt.executeQuery();
SQLDriverConnection.conn.close();
if (rs.next()) {
return true;
} else return false;
} catch (SQLException e) {
System.out.println("User could not be checked");
return true;
}
}
/**
* Deletes a User from the database
* @param user - username
* @return true with success, false if not
*/
public static boolean delUser(String user) {
connect();
String sql = "DELETE FROM User WHERE User = ?";
try {
PreparedStatement stmt = SQLDriverConnection.conn.prepareStatement(sql);
stmt.setString(1, user);
int res = stmt.executeUpdate();
SQLDriverConnection.conn.close();
if(res > 0) return true;
else return false;
} catch (SQLException e) {
System.out.println("User could not be deleted");
return false;
}
}
}
|
UTF-8
|
Java
| 3,776 |
java
|
UserTable.java
|
Java
|
[
{
"context": "etes a User from the database\n * @param user - username\n * @return true with success, false if not\n ",
"end": 3160,
"score": 0.9916300177574158,
"start": 3152,
"tag": "USERNAME",
"value": "username"
}
] | null |
[] |
package controller.database;
import model.Team;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import static controller.database.SQLDriverConnection.connect;
public class UserTable {
/**
* Gets all Users from the database table USER
* @return ArrayList<Team> of all Users. Team
*/
public static ArrayList<Team> getUser() {
connect();
String sql = "SELECT * FROM User";
ArrayList<Team> allUser = new ArrayList<>();
try {
PreparedStatement stmt = SQLDriverConnection.conn.prepareStatement(sql);
ResultSet user = stmt.executeQuery();
while (user.next()) {
allUser.add(new Team(user.getString(1), user.getInt(2)));
}
SQLDriverConnection.conn.close();
} catch (SQLException e) {
System.out.println("User couldnt get selected from table");
} finally {
return allUser;
}
}
/**
* Gets all Users and inserts them into an ObservableList<String>
* @return ObservableList<String>
*/
public static ObservableList<String> getObservableUser() { ;
ArrayList<Team> teams = getUser();
ObservableList<String> teamList = FXCollections.observableArrayList();
for (Team t : teams) {
teamList.add(t.getTeamname());
}
Collections.sort(teamList);
return teamList;
}
/**
* Adds a User into the database Table USER
* @param user - username to be added
* @return true if success, false otherwise
*/
public static boolean addUser(String user) {
connect();
String sql = "INSERT INTO User (user) VALUES (?)";
try {
PreparedStatement stmt = SQLDriverConnection.conn.prepareStatement(sql);
stmt.setString(1, user);
int res = stmt.executeUpdate();
SQLDriverConnection.conn.close();
if(res > 0) return true;
else return false;
} catch (SQLException e) {
System.out.println("User could not be inserted");
return false;
}
}
/**
* Checks if a username is already taken by someone else
* @param user - User to be checked
* @return - true if user already exists, false if not.
*/
public static boolean checkUser(String user) {
connect();
String sql = "SELECT * FROM USER where user = ?";
try {
PreparedStatement stmt = SQLDriverConnection.conn.prepareStatement(sql);
stmt.setString(1, user);
ResultSet rs = stmt.executeQuery();
SQLDriverConnection.conn.close();
if (rs.next()) {
return true;
} else return false;
} catch (SQLException e) {
System.out.println("User could not be checked");
return true;
}
}
/**
* Deletes a User from the database
* @param user - username
* @return true with success, false if not
*/
public static boolean delUser(String user) {
connect();
String sql = "DELETE FROM User WHERE User = ?";
try {
PreparedStatement stmt = SQLDriverConnection.conn.prepareStatement(sql);
stmt.setString(1, user);
int res = stmt.executeUpdate();
SQLDriverConnection.conn.close();
if(res > 0) return true;
else return false;
} catch (SQLException e) {
System.out.println("User could not be deleted");
return false;
}
}
}
| 3,776 | 0.590307 | 0.588453 | 118 | 31 | 22.189095 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.525424 | false | false |
10
|
9f25bcd480c1fed5dbd90f0311632ca6411359ba
| 4,767,413,739,093 |
95d20c83d8aff34e314c56a3ecb2b87c9fa9fc86
|
/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/compositeeditor/DataTypeCellRenderer.java
|
358c42b509cd3d8967d47a2433c6fc8b94cc883f
|
[
"GPL-1.0-or-later",
"GPL-3.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LGPL-2.1-only",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
NationalSecurityAgency/ghidra
|
https://github.com/NationalSecurityAgency/ghidra
|
969fe0d2ca25cb8ac72f66f0f90fc7fb2dbfa68d
|
7cc135eb6bfabd166cbc23f7951dae09a7e03c39
|
refs/heads/master
| 2023-08-31T21:20:23.376000 | 2023-08-29T23:08:54 | 2023-08-29T23:08:54 | 173,228,436 | 45,212 | 6,204 |
Apache-2.0
| false | 2023-09-14T18:00:39 | 2019-03-01T03:27:48 | 2023-09-14T16:08:34 | 2023-09-14T18:00:38 | 315,176 | 42,614 | 5,179 | 1,427 |
Java
| false | false |
/* ###
* IP: GHIDRA
*
* 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 ghidra.app.plugin.core.compositeeditor;
import java.awt.Component;
import javax.swing.JLabel;
import docking.widgets.table.GTableCellRenderer;
import docking.widgets.table.GTableCellRenderingData;
import generic.theme.GThemeDefaults.Colors;
import ghidra.app.util.ToolTipUtils;
import ghidra.program.model.data.*;
import ghidra.util.HTMLUtilities;
import ghidra.util.SystemUtilities;
public class DataTypeCellRenderer extends GTableCellRenderer {
private static final long serialVersionUID = 1L;
private DataTypeManager originalDTM;
public DataTypeCellRenderer(DataTypeManager originalDataTypeManager) {
this.originalDTM = originalDataTypeManager;
}
@Override
public Component getTableCellRendererComponent(GTableCellRenderingData data) {
Object value = data.getValue();
String dtString = "";
String tooltipText = null;
boolean showError = false;
DataType dt = null;
if (value instanceof DataTypeInstance) {
dt = ((DataTypeInstance) value).getDataType();
tooltipText = getDataTypeToolTip(dt);
dtString = dt.getDisplayName();
if (dt.isNotYetDefined()) {
showError = true;
}
}
GTableCellRenderingData renderData = data.copyWithNewValue(dtString);
JLabel c = (JLabel) super.getTableCellRendererComponent(renderData);
c.setToolTipText(tooltipText);
if (showError) {
c.setForeground(Colors.ERROR);
}
return c;
}
private String getDataTypeToolTip(DataType dataType) {
DataTypeManager dataTypeManager = dataType.getDataTypeManager();
// This checks for null dataTypeManager below since BadDataType won't have one.
SourceArchive sourceArchive = dataType.getSourceArchive();
boolean localSource = (sourceArchive == null) ||
((dataTypeManager != null) && SystemUtilities.isEqual(dataTypeManager.getUniversalID(),
sourceArchive.getSourceArchiveID()));
if (localSource) {
sourceArchive = originalDTM.getSourceArchive(originalDTM.getUniversalID());
}
DataType foundDataType = originalDTM.getDataType(dataType.getDataTypePath());
String displayName = "";
if (foundDataType != null && (dataTypeManager != null)) {
displayName = dataTypeManager.getName();
}
displayName += dataType.getPathName();
if (!localSource) {
displayName += " (" + sourceArchive.getName() + ")";
}
displayName = HTMLUtilities.friendlyEncodeHTML(displayName);
String toolTipText = ToolTipUtils.getToolTipText(dataType);
String headerText = "<HTML><b>" + displayName + "</b><BR>";
toolTipText = toolTipText.replace("<HTML>", headerText);
return toolTipText;
}
}
|
UTF-8
|
Java
| 3,145 |
java
|
DataTypeCellRenderer.java
|
Java
|
[
{
"context": "/* ###\n * IP: GHIDRA\n *\n * Licensed under the Apache License, Ver",
"end": 15,
"score": 0.528255045413971,
"start": 14,
"tag": "NAME",
"value": "G"
}
] | null |
[] |
/* ###
* IP: GHIDRA
*
* 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 ghidra.app.plugin.core.compositeeditor;
import java.awt.Component;
import javax.swing.JLabel;
import docking.widgets.table.GTableCellRenderer;
import docking.widgets.table.GTableCellRenderingData;
import generic.theme.GThemeDefaults.Colors;
import ghidra.app.util.ToolTipUtils;
import ghidra.program.model.data.*;
import ghidra.util.HTMLUtilities;
import ghidra.util.SystemUtilities;
public class DataTypeCellRenderer extends GTableCellRenderer {
private static final long serialVersionUID = 1L;
private DataTypeManager originalDTM;
public DataTypeCellRenderer(DataTypeManager originalDataTypeManager) {
this.originalDTM = originalDataTypeManager;
}
@Override
public Component getTableCellRendererComponent(GTableCellRenderingData data) {
Object value = data.getValue();
String dtString = "";
String tooltipText = null;
boolean showError = false;
DataType dt = null;
if (value instanceof DataTypeInstance) {
dt = ((DataTypeInstance) value).getDataType();
tooltipText = getDataTypeToolTip(dt);
dtString = dt.getDisplayName();
if (dt.isNotYetDefined()) {
showError = true;
}
}
GTableCellRenderingData renderData = data.copyWithNewValue(dtString);
JLabel c = (JLabel) super.getTableCellRendererComponent(renderData);
c.setToolTipText(tooltipText);
if (showError) {
c.setForeground(Colors.ERROR);
}
return c;
}
private String getDataTypeToolTip(DataType dataType) {
DataTypeManager dataTypeManager = dataType.getDataTypeManager();
// This checks for null dataTypeManager below since BadDataType won't have one.
SourceArchive sourceArchive = dataType.getSourceArchive();
boolean localSource = (sourceArchive == null) ||
((dataTypeManager != null) && SystemUtilities.isEqual(dataTypeManager.getUniversalID(),
sourceArchive.getSourceArchiveID()));
if (localSource) {
sourceArchive = originalDTM.getSourceArchive(originalDTM.getUniversalID());
}
DataType foundDataType = originalDTM.getDataType(dataType.getDataTypePath());
String displayName = "";
if (foundDataType != null && (dataTypeManager != null)) {
displayName = dataTypeManager.getName();
}
displayName += dataType.getPathName();
if (!localSource) {
displayName += " (" + sourceArchive.getName() + ")";
}
displayName = HTMLUtilities.friendlyEncodeHTML(displayName);
String toolTipText = ToolTipUtils.getToolTipText(dataType);
String headerText = "<HTML><b>" + displayName + "</b><BR>";
toolTipText = toolTipText.replace("<HTML>", headerText);
return toolTipText;
}
}
| 3,145 | 0.75008 | 0.74849 | 101 | 30.138615 | 26.774464 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.594059 | false | false |
10
|
7257d9136665ec2c693549c89afdb07145321891
| 2,302,102,515,565 |
9ff2b368f7f208fcaab70f47ad17d46b2c24c21f
|
/mifosio-core-lang/src/main/java/io/mifos/core/lang/ServiceException.java
|
acfe537801024e90f1cba1152457e8a15b06ec04
|
[] |
no_license
|
liseri/mifosio
|
https://github.com/liseri/mifosio
|
a481944422f42d6777641510953eb76d784e893f
|
33f28ffd7d2269162137a46742a43a55130bb1b5
|
refs/heads/master
| 2021-05-11T06:57:26.458000 | 2018-02-10T15:53:18 | 2018-02-10T15:53:18 | 118,004,103 | 0 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright 2017 The Mifos Initiative
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mifos.core.lang;
import java.text.MessageFormat;
@SuppressWarnings({"WeakerAccess", "unused"})
public final class ServiceException extends RuntimeException {
private final ServiceError serviceError;
public ServiceException(final ServiceError serviceError) {
super(serviceError.getMessage());
this.serviceError = serviceError;
}
public static ServiceException badRequest(final String message, final Object... args) {
return new ServiceException(ServiceError
.create(400)
.message(MessageFormat.format(message, args))
.build());
}
public static ServiceException notFound(final String message, final Object... args) {
return new ServiceException(ServiceError
.create(404)
.message(MessageFormat.format(message, args))
.build());
}
public static ServiceException conflict(final String message, final Object... args) {
return new ServiceException(ServiceError
.create(409)
.message(MessageFormat.format(message, args))
.build());
}
public static ServiceException internalError(final String message, final Object... args) {
return new ServiceException(ServiceError
.create(500)
.message(MessageFormat.format(message, args))
.build());
}
public ServiceError serviceError() {
return this.serviceError;
}
@Override
public String toString() {
return "ServiceException{" +
"serviceError=" + serviceError +
'}';
}
}
|
UTF-8
|
Java
| 2,113 |
java
|
ServiceException.java
|
Java
|
[] | null |
[] |
/*
* Copyright 2017 The Mifos Initiative
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mifos.core.lang;
import java.text.MessageFormat;
@SuppressWarnings({"WeakerAccess", "unused"})
public final class ServiceException extends RuntimeException {
private final ServiceError serviceError;
public ServiceException(final ServiceError serviceError) {
super(serviceError.getMessage());
this.serviceError = serviceError;
}
public static ServiceException badRequest(final String message, final Object... args) {
return new ServiceException(ServiceError
.create(400)
.message(MessageFormat.format(message, args))
.build());
}
public static ServiceException notFound(final String message, final Object... args) {
return new ServiceException(ServiceError
.create(404)
.message(MessageFormat.format(message, args))
.build());
}
public static ServiceException conflict(final String message, final Object... args) {
return new ServiceException(ServiceError
.create(409)
.message(MessageFormat.format(message, args))
.build());
}
public static ServiceException internalError(final String message, final Object... args) {
return new ServiceException(ServiceError
.create(500)
.message(MessageFormat.format(message, args))
.build());
}
public ServiceError serviceError() {
return this.serviceError;
}
@Override
public String toString() {
return "ServiceException{" +
"serviceError=" + serviceError +
'}';
}
}
| 2,113 | 0.704212 | 0.694747 | 69 | 29.623188 | 27.05341 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.362319 | false | false |
10
|
075747dad9c163935e779909baa7459a88989368
| 11,390,253,311,616 |
4cb6716bb94ce3eb8b06b233608ecfde7171e1c9
|
/solution/src/test/java/com/merikan/junit5/todo/examples/RepeatedTests.java
|
d7f4065782e9b8a0ee22b90be6ac332d726c3c24
|
[
"Apache-2.0"
] |
permissive
|
merikan/junit5-demo
|
https://github.com/merikan/junit5-demo
|
3c60985a5f07e86bd1cdef5071bcf5a9219e37d3
|
d8c6b773f1383e84272fe8e3f295f29944694f47
|
refs/heads/master
| 2022-04-20T22:04:44.861000 | 2020-03-30T14:14:17 | 2020-03-30T14:14:17 | 246,106,699 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.merikan.junit5.todo.examples;
import org.junit.jupiter.api.RepeatedTest;
public class RepeatedTests {
@RepeatedTest(5)
void repeatedTest() {
// ...
}
}
|
UTF-8
|
Java
| 188 |
java
|
RepeatedTests.java
|
Java
|
[] | null |
[] |
package com.merikan.junit5.todo.examples;
import org.junit.jupiter.api.RepeatedTest;
public class RepeatedTests {
@RepeatedTest(5)
void repeatedTest() {
// ...
}
}
| 188 | 0.659574 | 0.648936 | 12 | 14.666667 | 15.53133 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false |
10
|
402138bd7f0bc640f14b2035ba2b6f4f7ac79e3c
| 25,933,012,585,831 |
7d4ee4e6f569c20a5a799679e1c1782cf7a9e8fa
|
/src/Main.java
|
6e643f018f3b0d8792652dcb13486c96daa53734
|
[] |
no_license
|
GrzegorzG19/Zadanie-7.4
|
https://github.com/GrzegorzG19/Zadanie-7.4
|
63c6b53e34ddb6a8e5d15f10e35f6f68e8789eb7
|
08461287b1534f75d1fcbcbedfb96e388dbc2af3
|
refs/heads/master
| 2020-05-26T14:07:33.678000 | 2019-05-23T15:16:03 | 2019-05-23T15:16:03 | 188,258,754 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int a;
Scanner scan = new Scanner(System.in);
do {
System.out.println("podaj liczbe");
a = scan.nextInt();
if (a < 100) {
System.out.println("Podana liczba jest za mała ");
} else if (a > 200) {
System.out.println("Podana liczba jest za duża");
} else if (a % 3 != 0) {
System.out.println("podana liczba nie jest podzielna przez 3");
}
} while (a % 3 != 0 || a <= 100 || a >= 200);
System.out.println("podana liczba jest ok");
}
}
|
UTF-8
|
Java
| 696 |
java
|
Main.java
|
Java
|
[] | null |
[] |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int a;
Scanner scan = new Scanner(System.in);
do {
System.out.println("podaj liczbe");
a = scan.nextInt();
if (a < 100) {
System.out.println("Podana liczba jest za mała ");
} else if (a > 200) {
System.out.println("Podana liczba jest za duża");
} else if (a % 3 != 0) {
System.out.println("podana liczba nie jest podzielna przez 3");
}
} while (a % 3 != 0 || a <= 100 || a >= 200);
System.out.println("podana liczba jest ok");
}
}
| 696 | 0.491354 | 0.466859 | 26 | 25.692308 | 24.106764 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.538462 | false | false |
10
|
c58d902e53f31ec6ee7591f9a2f0647df6a20ec7
| 32,968,169,019,992 |
6d53b3ec97f042af0c77ac1fe603ab130794ca4e
|
/src/main/java/com/royalevolution/royalcommands/commands/CommandFly.java
|
cc064de95450ebd11efc0bd26f90cc951b9dd73d
|
[] |
no_license
|
bwluera/royal-core-mc
|
https://github.com/bwluera/royal-core-mc
|
cdf8167b34af9ea4021d43eafc67003d1edfd5ab
|
4c2e9457430bff7829595a2e83b13d284d60df38
|
refs/heads/master
| 2023-07-06T12:31:41.292000 | 2019-07-10T08:33:40 | 2019-07-10T08:33:40 | 195,235,407 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.royalevolution.royalcommands.commands;
import java.util.Arrays;
import org.bukkit.entity.Player;
import com.royalevolution.royalcommands.RoyalCore;
import com.royalevolution.royalcommands.utils.Common;
import net.md_5.bungee.api.ChatColor;
public class CommandFly extends PlayerCommand {
public CommandFly() {
super("fly");
setAliases(Arrays.asList("rfly"));
setDescription("Enables flight for you or another player.");
setUsage("/fly [user]");
}
@Override
protected void run(Player sender, String[] args) {
final String prefix = RoyalCore.getChatPrefix();
if (sender.hasPermission("rc.fly")) {
if (args.length == 0) { //no args. sender = target
if (!sender.getAllowFlight()) {
sender.setAllowFlight(true);
Common.tell(sender, prefix + "Your flight has been &aenabled");
} else {
sender.setAllowFlight(false);
Common.tell(sender, prefix + "Your flight has been &cdisabled");
}
} else if (args.length == 1) { //arg arg0 = target
if (sender.hasPermission("rc.fly.others")) {
final String targetName = args[0];
for (final Player player : RoyalCore.getOnlinePlayers())
if (ChatColor.stripColor(player.getDisplayName()).equals(targetName)) {
if (!player.getAllowFlight()) {
player.setAllowFlight(true);
Common.tell(player, prefix + "Your flight has been &aenabled &rby &b" + sender.getName());
} else {
player.setAllowFlight(false);
Common.tell(player, prefix + "Your flight has been &cdisabled &rby &b" + sender.getName());
}
} else
//player not found
Common.tell(sender, prefix + "&cPlayer not found!");
} else return; // no permission message for flying others
} else {
Common.tell(sender, prefix + "&cSyntax error. Usage: &b/fly [player]");
//syntax error
}
} else return; // no permission for using /fly
}
}
|
UTF-8
|
Java
| 1,897 |
java
|
CommandFly.java
|
Java
|
[] | null |
[] |
package com.royalevolution.royalcommands.commands;
import java.util.Arrays;
import org.bukkit.entity.Player;
import com.royalevolution.royalcommands.RoyalCore;
import com.royalevolution.royalcommands.utils.Common;
import net.md_5.bungee.api.ChatColor;
public class CommandFly extends PlayerCommand {
public CommandFly() {
super("fly");
setAliases(Arrays.asList("rfly"));
setDescription("Enables flight for you or another player.");
setUsage("/fly [user]");
}
@Override
protected void run(Player sender, String[] args) {
final String prefix = RoyalCore.getChatPrefix();
if (sender.hasPermission("rc.fly")) {
if (args.length == 0) { //no args. sender = target
if (!sender.getAllowFlight()) {
sender.setAllowFlight(true);
Common.tell(sender, prefix + "Your flight has been &aenabled");
} else {
sender.setAllowFlight(false);
Common.tell(sender, prefix + "Your flight has been &cdisabled");
}
} else if (args.length == 1) { //arg arg0 = target
if (sender.hasPermission("rc.fly.others")) {
final String targetName = args[0];
for (final Player player : RoyalCore.getOnlinePlayers())
if (ChatColor.stripColor(player.getDisplayName()).equals(targetName)) {
if (!player.getAllowFlight()) {
player.setAllowFlight(true);
Common.tell(player, prefix + "Your flight has been &aenabled &rby &b" + sender.getName());
} else {
player.setAllowFlight(false);
Common.tell(player, prefix + "Your flight has been &cdisabled &rby &b" + sender.getName());
}
} else
//player not found
Common.tell(sender, prefix + "&cPlayer not found!");
} else return; // no permission message for flying others
} else {
Common.tell(sender, prefix + "&cSyntax error. Usage: &b/fly [player]");
//syntax error
}
} else return; // no permission for using /fly
}
}
| 1,897 | 0.669478 | 0.666842 | 57 | 32.280701 | 26.200144 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.491228 | false | false |
10
|
08be3155d04021e2a7b69755adadcb84c0536cd9
| 25,288,767,439,004 |
41bf7ac6cf9c828f227fb91feb87685963b902c3
|
/app/src/main/java/com/chsra/imdbapp/SearchMovies.java
|
294b50f0183d5528cecea70b1545ef8c3d707851
|
[] |
no_license
|
raviteja73/Android_IMDBMovieApp_JsonParsing
|
https://github.com/raviteja73/Android_IMDBMovieApp_JsonParsing
|
e76d9e853cb6055320d07552129a565095560bf7
|
e588d9a1324cf6b0c4465af8f2be43e6cee58493
|
refs/heads/master
| 2016-08-09T11:33:32.299000 | 2016-03-04T04:52:58 | 2016-03-04T04:52:58 | 53,107,546 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.chsra.imdbapp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.xml.sax.SAXException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class SearchMovies extends Activity {
Intent intent;
LinearLayout layout;
ArrayList<Movie> movies;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_movies);
setTitle("Search Movies");
intent = getIntent();
layout = (LinearLayout) findViewById(R.id.moviesLLayout);
String searchParam = intent.getStringExtra(MainActivity.SEARCH_TITLE);
String moddedParam = searchParam.replaceAll("\\s", "+");
new GetSearchResults().execute(moddedParam);
}
public class GetSearchResults extends AsyncTask<String,Void,ArrayList<Movie>> {
StringBuilder searchURL = new StringBuilder("http://www.omdbapi.com/?type=movie&s=");
ProgressDialog dialog;
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(SearchMovies.this);
dialog.setMessage("Getting Movies");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.show();
super.onPreExecute();
}
@Override
protected void onPostExecute(final ArrayList<Movie> movies) {
super.onPostExecute(movies);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
llp.setMargins(0, 25, 0, 0);
if (movies != null) {
for (int i = 0; i < movies.size(); i++) {
final TextView movieView = new TextView(SearchMovies.this);
movieView.setText(movies.get(i).getTitle() + " (" + movies.get(i).getYear() + ")");
movieView.setTextColor(Color.BLACK);
movieView.setTextSize(18);
movieView.setPadding(10, 20, 0, 20);
final int j = i;
movieView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
movieView.setBackgroundColor(Color.CYAN);
Intent intent = new Intent(SearchMovies.this, MovieDetails.class);
intent.putParcelableArrayListExtra("MOVIE_ID", movies);
intent.putExtra("INDEX", j);
startActivity(intent);
finish();
}
});
layout.addView(movieView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
dialog.dismiss();
}
}else {
TextView movieView = new TextView(SearchMovies.this);
movieView.setText("No Movies Found");
layout.addView(movieView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
dialog.dismiss();
}
}
@Override
protected ArrayList<Movie> doInBackground(String... params) {
searchURL.append(params[0]);
JSONObject obj = new JSONObject();
JSONArray results;
movies = new ArrayList<Movie>();
Log.d("demo","Working");
try {
BufferedReader reader;
URL url = new URL(searchURL.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
int statuscode = urlConnection.getResponseCode();
if (statuscode == HttpURLConnection.HTTP_OK) {
InputStream in = urlConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
String line;
JSONTokener tokener;
while ((line = reader.readLine()) != null) {
tokener = new JSONTokener(line);
obj = (JSONObject) tokener.nextValue();
}
results = obj.getJSONArray("Search");
for(int i=0;i<results.length();i++){
JSONObject object = results.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(object.getString("Title"));
movie.setYear(object.getString("Year"));
movie.setImdbID(object.getString("imdbID"));
movie.setPoster(object.getString("Poster"));
movies.add(movie);
}
Collections.sort(movies, new Comparator<Movie>() {
@Override
public int compare(Movie lhs, Movie rhs) {
return rhs.year.compareTo(lhs.year);
}
});
return movies;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
|
UTF-8
|
Java
| 6,343 |
java
|
SearchMovies.java
|
Java
|
[] | null |
[] |
package com.chsra.imdbapp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.xml.sax.SAXException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class SearchMovies extends Activity {
Intent intent;
LinearLayout layout;
ArrayList<Movie> movies;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_movies);
setTitle("Search Movies");
intent = getIntent();
layout = (LinearLayout) findViewById(R.id.moviesLLayout);
String searchParam = intent.getStringExtra(MainActivity.SEARCH_TITLE);
String moddedParam = searchParam.replaceAll("\\s", "+");
new GetSearchResults().execute(moddedParam);
}
public class GetSearchResults extends AsyncTask<String,Void,ArrayList<Movie>> {
StringBuilder searchURL = new StringBuilder("http://www.omdbapi.com/?type=movie&s=");
ProgressDialog dialog;
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(SearchMovies.this);
dialog.setMessage("Getting Movies");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.show();
super.onPreExecute();
}
@Override
protected void onPostExecute(final ArrayList<Movie> movies) {
super.onPostExecute(movies);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
llp.setMargins(0, 25, 0, 0);
if (movies != null) {
for (int i = 0; i < movies.size(); i++) {
final TextView movieView = new TextView(SearchMovies.this);
movieView.setText(movies.get(i).getTitle() + " (" + movies.get(i).getYear() + ")");
movieView.setTextColor(Color.BLACK);
movieView.setTextSize(18);
movieView.setPadding(10, 20, 0, 20);
final int j = i;
movieView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
movieView.setBackgroundColor(Color.CYAN);
Intent intent = new Intent(SearchMovies.this, MovieDetails.class);
intent.putParcelableArrayListExtra("MOVIE_ID", movies);
intent.putExtra("INDEX", j);
startActivity(intent);
finish();
}
});
layout.addView(movieView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
dialog.dismiss();
}
}else {
TextView movieView = new TextView(SearchMovies.this);
movieView.setText("No Movies Found");
layout.addView(movieView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
dialog.dismiss();
}
}
@Override
protected ArrayList<Movie> doInBackground(String... params) {
searchURL.append(params[0]);
JSONObject obj = new JSONObject();
JSONArray results;
movies = new ArrayList<Movie>();
Log.d("demo","Working");
try {
BufferedReader reader;
URL url = new URL(searchURL.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
int statuscode = urlConnection.getResponseCode();
if (statuscode == HttpURLConnection.HTTP_OK) {
InputStream in = urlConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
String line;
JSONTokener tokener;
while ((line = reader.readLine()) != null) {
tokener = new JSONTokener(line);
obj = (JSONObject) tokener.nextValue();
}
results = obj.getJSONArray("Search");
for(int i=0;i<results.length();i++){
JSONObject object = results.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(object.getString("Title"));
movie.setYear(object.getString("Year"));
movie.setImdbID(object.getString("imdbID"));
movie.setPoster(object.getString("Poster"));
movies.add(movie);
}
Collections.sort(movies, new Comparator<Movie>() {
@Override
public int compare(Movie lhs, Movie rhs) {
return rhs.year.compareTo(lhs.year);
}
});
return movies;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
| 6,343 | 0.563456 | 0.560776 | 192 | 32.03125 | 28.140442 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.65625 | false | false |
10
|
488c26006e0a6f4cabdc0c13309dd2fb2c2f90b9
| 30,769,145,747,605 |
f46174266eb651e4e935533d688f5e5ee41b1c30
|
/LearningJava-19102020/src/day2/Cylinder.java
|
249561935634611b0efe7a9457f01ed08ec0a6e5
|
[] |
no_license
|
saurabhd2106/LearningJava-19192020
|
https://github.com/saurabhd2106/LearningJava-19192020
|
8500daed63dd6018c4ddf0491f06d8cc05c2ffac
|
38295a4a7da73070b9044a0a6fe6f030f0e868aa
|
refs/heads/master
| 2023-01-06T11:33:58.970000 | 2020-10-31T12:06:32 | 2020-10-31T12:06:32 | 305,368,365 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package day2;
public class Cylinder extends Shape{
@Override
public double calculateArea(int side) {
return Math.PI * side * side;
}
}
|
UTF-8
|
Java
| 146 |
java
|
Cylinder.java
|
Java
|
[] | null |
[] |
package day2;
public class Cylinder extends Shape{
@Override
public double calculateArea(int side) {
return Math.PI * side * side;
}
}
| 146 | 0.69863 | 0.691781 | 11 | 12.272727 | 15.009639 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.818182 | false | false |
10
|
60b9a8e9c9df3a30a4e7442dbd9c6b82ad9f9a3c
| 20,126,216,798,200 |
d649d0261fcc864cc73f317927eb19ab4d93764e
|
/src/main/java/com/emirovschi/sm/lab5/oauth/AuthorizationServerConfiguration.java
|
b424485e4354e35034a153775bc4738832cc6b91
|
[] |
no_license
|
emirovschi/SM
|
https://github.com/emirovschi/SM
|
cad065d09fd35b6f647ca60f29cb16967e59ba7b
|
7d69534589873f3a9c05a33c76e065a343d47d0f
|
refs/heads/master
| 2020-03-18T23:43:03.831000 | 2018-05-30T10:57:54 | 2018-05-30T10:57:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.emirovschi.sm.lab5.oauth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.approval.UserApprovalHandler;
import org.springframework.security.oauth2.provider.token.TokenStore;
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter
{
@Autowired
private TokenStore tokenStore;
@Autowired
private UserApprovalHandler userApprovalHandler;
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Override
public void configure(final ClientDetailsServiceConfigurer clients) throws Exception
{
clients.inMemory()
.withClient("web")
.authorizedGrantTypes("password", "refresh_token")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("basic")
.accessTokenValiditySeconds(120)
.refreshTokenValiditySeconds(600);
}
@Override
public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception
{
endpoints.tokenStore(tokenStore)
.userApprovalHandler(userApprovalHandler)
.authenticationManager(authenticationManager);
}
@Override
public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception
{
oauthServer.allowFormAuthenticationForClients();
}
}
|
UTF-8
|
Java
| 2,304 |
java
|
AuthorizationServerConfiguration.java
|
Java
|
[] | null |
[] |
package com.emirovschi.sm.lab5.oauth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.approval.UserApprovalHandler;
import org.springframework.security.oauth2.provider.token.TokenStore;
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter
{
@Autowired
private TokenStore tokenStore;
@Autowired
private UserApprovalHandler userApprovalHandler;
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Override
public void configure(final ClientDetailsServiceConfigurer clients) throws Exception
{
clients.inMemory()
.withClient("web")
.authorizedGrantTypes("password", "refresh_token")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("basic")
.accessTokenValiditySeconds(120)
.refreshTokenValiditySeconds(600);
}
@Override
public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception
{
endpoints.tokenStore(tokenStore)
.userApprovalHandler(userApprovalHandler)
.authenticationManager(authenticationManager);
}
@Override
public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception
{
oauthServer.allowFormAuthenticationForClients();
}
}
| 2,304 | 0.786024 | 0.779948 | 54 | 41.666668 | 36.502155 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.37037 | false | false |
10
|
79a021b5fe8dbe30a590b74c570f0b9eaf16ca7d
| 30,520,037,663,935 |
e84e8f2f12370d3c950b88382c013bdf5864bf84
|
/src/me/pjq/rotate3d/CubeView.java
|
d463adcc29dcd8bbfe3bf6b8a4c8cefe68fc3f4f
|
[] |
no_license
|
Han01/Animation
|
https://github.com/Han01/Animation
|
73963ab328bc021230aa8a8fbe239a016351441c
|
1aee4da8b8d6f19fce58012a9cc9fca10285e469
|
refs/heads/master
| 2020-04-06T05:35:54.104000 | 2012-05-11T09:30:12 | 2012-05-11T09:30:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package me.pjq.rotate3d;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;
/**
* 图片三维翻转
* @author chroya
*/
public class CubeView extends View {
//摄像机
private Camera mCamera;
//翻转用的图片
private Bitmap mBitmap;
private Matrix mMatrix = new Matrix();
private Paint mPaint = new Paint();
private int mLastMotionX, mLastMotionY;
//图片的中心点坐标
private int mCenterX, mCenterY;
//转动的总距离,跟度数比例1:1
private int mDeltaX, mDeltaY;
//图片宽度高度
private int mWidth, mHeight;
public CubeView(Context context) {
super(context);
setWillNotDraw(false);
mCamera = new Camera();
mPaint.setAntiAlias(true);
mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.photo1);
mWidth = mBitmap.getWidth();
mHeight = mBitmap.getHeight();
mCenterX = mWidth>>1;
mCenterY = mHeight>>1;
}
/**
* 转动
* @param degreeX
* @param degreeY
*/
void rotate(int degreeX, int degreeY) {
mDeltaX += degreeX;
mDeltaY += degreeY;
mCamera.save();
mCamera.rotateY(mDeltaX);
mCamera.rotateX(-mDeltaY);
mCamera.translate(0, 0, -mCenterX);
mCamera.getMatrix(mMatrix);
mCamera.restore();
//以图片的中心点为旋转中心,如果不加这两句,就是以(0,0)点为旋转中心
mMatrix.preTranslate(-mCenterX, -mCenterY);
mMatrix.postTranslate(mCenterX, mCenterY);
mCamera.save();
postInvalidate();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
mLastMotionX = x;
mLastMotionY = y;
break;
case MotionEvent.ACTION_MOVE:
int dx = x - mLastMotionX;
int dy = y - mLastMotionY;
rotate(dx, dy);
mLastMotionX = x;
mLastMotionY = y;
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
@Override
public void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
canvas.drawBitmap(mBitmap, mMatrix, mPaint);
}
}
|
UTF-8
|
Java
| 2,709 |
java
|
CubeView.java
|
Java
|
[
{
"context": "mport android.view.View;\n\n/**\n * 图片三维翻转\n * @author chroya\n */\npublic class CubeView extends View {\n //摄像",
"end": 347,
"score": 0.9966685771942139,
"start": 341,
"tag": "USERNAME",
"value": "chroya"
}
] | null |
[] |
package me.pjq.rotate3d;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;
/**
* 图片三维翻转
* @author chroya
*/
public class CubeView extends View {
//摄像机
private Camera mCamera;
//翻转用的图片
private Bitmap mBitmap;
private Matrix mMatrix = new Matrix();
private Paint mPaint = new Paint();
private int mLastMotionX, mLastMotionY;
//图片的中心点坐标
private int mCenterX, mCenterY;
//转动的总距离,跟度数比例1:1
private int mDeltaX, mDeltaY;
//图片宽度高度
private int mWidth, mHeight;
public CubeView(Context context) {
super(context);
setWillNotDraw(false);
mCamera = new Camera();
mPaint.setAntiAlias(true);
mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.photo1);
mWidth = mBitmap.getWidth();
mHeight = mBitmap.getHeight();
mCenterX = mWidth>>1;
mCenterY = mHeight>>1;
}
/**
* 转动
* @param degreeX
* @param degreeY
*/
void rotate(int degreeX, int degreeY) {
mDeltaX += degreeX;
mDeltaY += degreeY;
mCamera.save();
mCamera.rotateY(mDeltaX);
mCamera.rotateX(-mDeltaY);
mCamera.translate(0, 0, -mCenterX);
mCamera.getMatrix(mMatrix);
mCamera.restore();
//以图片的中心点为旋转中心,如果不加这两句,就是以(0,0)点为旋转中心
mMatrix.preTranslate(-mCenterX, -mCenterY);
mMatrix.postTranslate(mCenterX, mCenterY);
mCamera.save();
postInvalidate();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
mLastMotionX = x;
mLastMotionY = y;
break;
case MotionEvent.ACTION_MOVE:
int dx = x - mLastMotionX;
int dy = y - mLastMotionY;
rotate(dx, dy);
mLastMotionX = x;
mLastMotionY = y;
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
@Override
public void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
canvas.drawBitmap(mBitmap, mMatrix, mPaint);
}
}
| 2,709 | 0.588442 | 0.584537 | 98 | 25.132652 | 15.348096 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.704082 | false | false |
10
|
b48d9b8d7ac1133736c5995ea718517a21d88aa9
| 19,275,813,270,198 |
3d84ab2c3c6f6227c21bb811dc12beb298276c34
|
/cocacolaSRV/src/main/java/com/ko/cds/report/metrics/IGenerateMetricsServiceReport.java
|
a1bae8fe2c0c5ed28fdfc777b0431f0dd9726ffa
|
[] |
no_license
|
shibajiJava/cokeALL
|
https://github.com/shibajiJava/cokeALL
|
d87e8de8461b6d2c968362d414955a58857cb844
|
f999dea8d7271efebab72b867118535489318483
|
refs/heads/master
| 2020-04-02T12:29:30.747000 | 2018-10-24T04:02:41 | 2018-10-24T04:02:41 | 154,435,979 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ko.cds.report.metrics;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.springframework.stereotype.Component;
import com.ko.cds.exceptions.BadRequestException;
@Component
@Path("/cds/v1")
public interface IGenerateMetricsServiceReport {
@GET
@Path("/metricsReport")
@Produces({MediaType.APPLICATION_JSON})
public Response generateReport(@QueryParam("startTime")String startTime , @QueryParam("endTime")String endTime) throws BadRequestException;
}
|
UTF-8
|
Java
| 610 |
java
|
IGenerateMetricsServiceReport.java
|
Java
|
[] | null |
[] |
package com.ko.cds.report.metrics;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.springframework.stereotype.Component;
import com.ko.cds.exceptions.BadRequestException;
@Component
@Path("/cds/v1")
public interface IGenerateMetricsServiceReport {
@GET
@Path("/metricsReport")
@Produces({MediaType.APPLICATION_JSON})
public Response generateReport(@QueryParam("startTime")String startTime , @QueryParam("endTime")String endTime) throws BadRequestException;
}
| 610 | 0.795082 | 0.793443 | 22 | 26.727272 | 29.941126 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.681818 | false | false |
10
|
8c2f96aeff2fc51f8da687207cf2fa48d128142c
| 23,665,269,845,896 |
dc2b2e4afff4fa4cee783a576f4c43d16bc4b23d
|
/org.kardo.language.aspectj.resource.aspectj/src-gen/org/kardo/language/aspectj/resource/aspectj/util/AspectjTextResourceUtil.java
|
f99a71fb2bbcde6197dbf77b90dc4bd80a464227
|
[] |
no_license
|
zygote1984/InstancePointcuts
|
https://github.com/zygote1984/InstancePointcuts
|
37d1702293e5b623059cd6bffa627a0f3e74466d
|
a24f6b68b0454eab57a04b8a02bfccd26c3fd948
|
refs/heads/master
| 2019-07-29T13:54:48.564000 | 2012-11-08T15:45:37 | 2012-11-08T15:45:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* <copyright>
* </copyright>
*
*
*/
package org.kardo.language.aspectj.resource.aspectj.util;
/**
* Class AspectjTextResourceUtil can be used to perform common tasks on text
* resources, such as loading and saving resources, as well as, checking them for
* errors. This class is deprecated and has been replaced by
* org.kardo.language.aspectj.resource.aspectj.util.AspectjResourceUtil.
*/
public class AspectjTextResourceUtil {
/**
* Use
* org.kardo.language.aspectj.resource.aspectj.util.AspectjResourceUtil.getResource
* () instead.
*/
@Deprecated
public static org.kardo.language.aspectj.resource.aspectj.mopp.AspectjResource getResource(org.eclipse.core.resources.IFile file) {
return new org.kardo.language.aspectj.resource.aspectj.util.AspectjEclipseProxy().getResource(file);
}
/**
* Use
* org.kardo.language.aspectj.resource.aspectj.util.AspectjResourceUtil.getResource
* () instead.
*/
@Deprecated
public static org.kardo.language.aspectj.resource.aspectj.mopp.AspectjResource getResource(java.io.File file, java.util.Map<?,?> options) {
return org.kardo.language.aspectj.resource.aspectj.util.AspectjResourceUtil.getResource(file, options);
}
/**
* Use
* org.kardo.language.aspectj.resource.aspectj.util.AspectjResourceUtil.getResource
* () instead.
*/
@Deprecated
public static org.kardo.language.aspectj.resource.aspectj.mopp.AspectjResource getResource(org.eclipse.emf.common.util.URI uri) {
return org.kardo.language.aspectj.resource.aspectj.util.AspectjResourceUtil.getResource(uri);
}
/**
* Use
* org.kardo.language.aspectj.resource.aspectj.util.AspectjResourceUtil.getResource
* () instead.
*/
@Deprecated
public static org.kardo.language.aspectj.resource.aspectj.mopp.AspectjResource getResource(org.eclipse.emf.common.util.URI uri, java.util.Map<?,?> options) {
return org.kardo.language.aspectj.resource.aspectj.util.AspectjResourceUtil.getResource(uri, options);
}
}
|
UTF-8
|
Java
| 1,975 |
java
|
AspectjTextResourceUtil.java
|
Java
|
[] | null |
[] |
/**
* <copyright>
* </copyright>
*
*
*/
package org.kardo.language.aspectj.resource.aspectj.util;
/**
* Class AspectjTextResourceUtil can be used to perform common tasks on text
* resources, such as loading and saving resources, as well as, checking them for
* errors. This class is deprecated and has been replaced by
* org.kardo.language.aspectj.resource.aspectj.util.AspectjResourceUtil.
*/
public class AspectjTextResourceUtil {
/**
* Use
* org.kardo.language.aspectj.resource.aspectj.util.AspectjResourceUtil.getResource
* () instead.
*/
@Deprecated
public static org.kardo.language.aspectj.resource.aspectj.mopp.AspectjResource getResource(org.eclipse.core.resources.IFile file) {
return new org.kardo.language.aspectj.resource.aspectj.util.AspectjEclipseProxy().getResource(file);
}
/**
* Use
* org.kardo.language.aspectj.resource.aspectj.util.AspectjResourceUtil.getResource
* () instead.
*/
@Deprecated
public static org.kardo.language.aspectj.resource.aspectj.mopp.AspectjResource getResource(java.io.File file, java.util.Map<?,?> options) {
return org.kardo.language.aspectj.resource.aspectj.util.AspectjResourceUtil.getResource(file, options);
}
/**
* Use
* org.kardo.language.aspectj.resource.aspectj.util.AspectjResourceUtil.getResource
* () instead.
*/
@Deprecated
public static org.kardo.language.aspectj.resource.aspectj.mopp.AspectjResource getResource(org.eclipse.emf.common.util.URI uri) {
return org.kardo.language.aspectj.resource.aspectj.util.AspectjResourceUtil.getResource(uri);
}
/**
* Use
* org.kardo.language.aspectj.resource.aspectj.util.AspectjResourceUtil.getResource
* () instead.
*/
@Deprecated
public static org.kardo.language.aspectj.resource.aspectj.mopp.AspectjResource getResource(org.eclipse.emf.common.util.URI uri, java.util.Map<?,?> options) {
return org.kardo.language.aspectj.resource.aspectj.util.AspectjResourceUtil.getResource(uri, options);
}
}
| 1,975 | 0.762532 | 0.762532 | 57 | 33.649124 | 44.337025 | 158 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.105263 | false | false |
10
|
6e967df4e5e1973db4721935158dde3571766935
| 23,665,269,845,351 |
eeeba7d460b7b2e8a235133f2b2585b0b95f4df0
|
/08-Weighted-Span-Trees/02-Lazy-Prim/src/com/baobao/algo/LazyPrimMST.java
|
99b712b87313641f2ca6c4438f0fc799b5a7c382
|
[] |
no_license
|
suifengbaobao/Algorithm-Basic
|
https://github.com/suifengbaobao/Algorithm-Basic
|
50b4d1a0c721bd819f83b16d24c384431618b501
|
f9ade93e459c5d7be45f48116a31deeb72ed5c9b
|
refs/heads/master
| 2021-01-02T09:17:31.351000 | 2017-08-06T13:21:01 | 2017-08-06T13:21:01 | 99,184,780 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.baobao.algo;
import java.util.ArrayList;
import java.util.List;
/**
* LazyPrim算法实现的最小生成树
* Created by suife on 2017/8/3.
*/
public class LazyPrimMST<Weight extends Number & Comparable> {
private WeightedGraph<Weight> G; // 加权图的引用
private List<Edge<Weight>> mst; // 最小生成树包含的所有边
private MinHeap<Edge<Weight>> pq; // 最小堆,算法的辅助数据结构
private boolean[] marked; // 标记数组,算法在运行过程中节点i是否被访问
private Number mstWeight; // 最小生成树的权值
// 构造器初始化
public LazyPrimMST(WeightedGraph<Weight> graph){
this.G = graph; // 初始化图
mst = new ArrayList<>(G.V());
pq = new MinHeap<>(G.E());
marked = new boolean[G.V()];
// LazyPrim Algorithm core code
visit(0);// 从0节点开始访问
// 每访问一个节点,找出最小的权值的边添加到最小生成树种mst
while(! pq.isEmpty()){
// 使用最小堆找出已经访问的边中权值最小的边
Edge<Weight> e = pq.delMin();
// 如果这条边的两个节点都被访问,则仍掉这条边
if(marked[e.v()] == marked[e.w()]){
continue;
}
// 否则这条边应该在最小生成树中
mst.add(e);
// 继续访问这条边的另一个节点
if(! marked[e.v()]){
visit(e.v());
}else if(! marked[e.w()]){
visit(e.w());
}
}
// 计算最小生成树的权值
mstWeight = mst.get(0).wt();
for(int i = 1; i < mst.size(); i ++){
mstWeight = mstWeight.doubleValue() + mst.get(i).wt().doubleValue();
}
}
/**
* 返回最小生成树
* @return mst
*/
public List<Edge<Weight>> getMst(){
return mst;
}
/**
* 返回最小生成树的权值
* @return mstWeight
*/
public Number getMstWeight(){
return mstWeight;
}
/**
* 访问一个节点的所有边,找出堆中没有的边加入堆中
* @param v 节点
*/
private void visit(int v) {
assert !marked[v];
marked[v] = true;// 标记访问过的节点
for(Edge<Weight> edge : G.adj(v)){// 遍历该节点相连的边
if(! marked[edge.other(v)]){// 如果边的另一个节点没有被访问过,则表示该边不存在堆中
pq.insert(edge);
}
}
}
}
|
UTF-8
|
Java
| 2,642 |
java
|
LazyPrimMST.java
|
Java
|
[
{
"context": "til.List;\n\n/**\n * LazyPrim算法实现的最小生成树\n * Created by suife on 2017/8/3.\n */\npublic class LazyPrimMST<Weight ",
"end": 123,
"score": 0.9996182918548584,
"start": 118,
"tag": "USERNAME",
"value": "suife"
}
] | null |
[] |
package com.baobao.algo;
import java.util.ArrayList;
import java.util.List;
/**
* LazyPrim算法实现的最小生成树
* Created by suife on 2017/8/3.
*/
public class LazyPrimMST<Weight extends Number & Comparable> {
private WeightedGraph<Weight> G; // 加权图的引用
private List<Edge<Weight>> mst; // 最小生成树包含的所有边
private MinHeap<Edge<Weight>> pq; // 最小堆,算法的辅助数据结构
private boolean[] marked; // 标记数组,算法在运行过程中节点i是否被访问
private Number mstWeight; // 最小生成树的权值
// 构造器初始化
public LazyPrimMST(WeightedGraph<Weight> graph){
this.G = graph; // 初始化图
mst = new ArrayList<>(G.V());
pq = new MinHeap<>(G.E());
marked = new boolean[G.V()];
// LazyPrim Algorithm core code
visit(0);// 从0节点开始访问
// 每访问一个节点,找出最小的权值的边添加到最小生成树种mst
while(! pq.isEmpty()){
// 使用最小堆找出已经访问的边中权值最小的边
Edge<Weight> e = pq.delMin();
// 如果这条边的两个节点都被访问,则仍掉这条边
if(marked[e.v()] == marked[e.w()]){
continue;
}
// 否则这条边应该在最小生成树中
mst.add(e);
// 继续访问这条边的另一个节点
if(! marked[e.v()]){
visit(e.v());
}else if(! marked[e.w()]){
visit(e.w());
}
}
// 计算最小生成树的权值
mstWeight = mst.get(0).wt();
for(int i = 1; i < mst.size(); i ++){
mstWeight = mstWeight.doubleValue() + mst.get(i).wt().doubleValue();
}
}
/**
* 返回最小生成树
* @return mst
*/
public List<Edge<Weight>> getMst(){
return mst;
}
/**
* 返回最小生成树的权值
* @return mstWeight
*/
public Number getMstWeight(){
return mstWeight;
}
/**
* 访问一个节点的所有边,找出堆中没有的边加入堆中
* @param v 节点
*/
private void visit(int v) {
assert !marked[v];
marked[v] = true;// 标记访问过的节点
for(Edge<Weight> edge : G.adj(v)){// 遍历该节点相连的边
if(! marked[edge.other(v)]){// 如果边的另一个节点没有被访问过,则表示该边不存在堆中
pq.insert(edge);
}
}
}
}
| 2,642 | 0.502865 | 0.49809 | 78 | 25.846153 | 18.735046 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.346154 | false | false |
10
|
45f9cc22d10c609652c0aed837ca4debdcfbd8d3
| 22,600,117,935,430 |
0e9f96807ddd81661e02aea813f9b61654041878
|
/src/com/datastructuresandalgorithms/linkedlist/CircularlyLinkedList.java
|
a88bfdef5936603d3f70273136bb8c5feb0ea529
|
[] |
no_license
|
LNarcisoOV/data-structure-algorithms-study
|
https://github.com/LNarcisoOV/data-structure-algorithms-study
|
23aebeaae599ea33262fa532f3d1d34cfa4b6771
|
59c780ed0700a1e8b0ca00de24e759f32beab013
|
refs/heads/master
| 2022-06-25T07:24:29.353000 | 2022-05-30T21:34:45 | 2022-05-30T21:34:45 | 176,739,633 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.datastructuresandalgorithms.linkedlist;
import com.datastructuresandalgorithms.model.ListNode;
public class CircularlyLinkedList {
// instance variables of the CircularlyLinkedList
private ListNode<String> tail = null; // we store tail (but not head)
private int size = 0; // number of nodes in the list
public CircularlyLinkedList() {
} // constructs an initially empty list
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public String first() { // returns (but does not remove) the first element
if (isEmpty())
return null;
return tail.getNext().getElement(); // the head is *after* the tail
}
public String last() { // returns (but does not remove) the last element
if (isEmpty())
return null;
return tail.getElement();
}
// update methods
public void rotate() { // rotate the first element to the back of the
// list
if (tail != null) // if empty, do nothing
tail = tail.getNext(); // the old head becomes the new tail
}
public void addFirst(String e) { // adds element e to the front of the list
if (size == 0) {
tail = new ListNode<>(e, null);
tail.setNext(tail); // link to itself circularly
} else {
ListNode<String> newest = new ListNode<>(e, tail.getNext());
tail.setNext(newest);
}
size++;
}
public void addLast(String e) { // adds element e to the end of the list
addFirst(e); // insert new element at front of list
tail = tail.getNext(); // now new element becomes the tail
}
public String removeFirst() { // removes and returns the first element
if (isEmpty())
return null; // nothing to remove
ListNode<String> head = tail.getNext();
if (head == tail)
tail = null; // must be the only node left
else
tail.setNext(head.getNext()); // removes ”head” from the list
size--;
return head.getElement();
}
}
|
UTF-8
|
Java
| 1,871 |
java
|
CircularlyLinkedList.java
|
Java
|
[] | null |
[] |
package com.datastructuresandalgorithms.linkedlist;
import com.datastructuresandalgorithms.model.ListNode;
public class CircularlyLinkedList {
// instance variables of the CircularlyLinkedList
private ListNode<String> tail = null; // we store tail (but not head)
private int size = 0; // number of nodes in the list
public CircularlyLinkedList() {
} // constructs an initially empty list
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public String first() { // returns (but does not remove) the first element
if (isEmpty())
return null;
return tail.getNext().getElement(); // the head is *after* the tail
}
public String last() { // returns (but does not remove) the last element
if (isEmpty())
return null;
return tail.getElement();
}
// update methods
public void rotate() { // rotate the first element to the back of the
// list
if (tail != null) // if empty, do nothing
tail = tail.getNext(); // the old head becomes the new tail
}
public void addFirst(String e) { // adds element e to the front of the list
if (size == 0) {
tail = new ListNode<>(e, null);
tail.setNext(tail); // link to itself circularly
} else {
ListNode<String> newest = new ListNode<>(e, tail.getNext());
tail.setNext(newest);
}
size++;
}
public void addLast(String e) { // adds element e to the end of the list
addFirst(e); // insert new element at front of list
tail = tail.getNext(); // now new element becomes the tail
}
public String removeFirst() { // removes and returns the first element
if (isEmpty())
return null; // nothing to remove
ListNode<String> head = tail.getNext();
if (head == tail)
tail = null; // must be the only node left
else
tail.setNext(head.getNext()); // removes ”head” from the list
size--;
return head.getElement();
}
}
| 1,871 | 0.678093 | 0.676486 | 68 | 26.455883 | 25.488424 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.75 | false | false |
10
|
f91b840e57e8b9a1a7c45c9903959be74e201c5f
| 26,328,149,557,895 |
d94fa538f0dcfa52c37767018b2601a371787cf1
|
/JMXCommon/src/main/java/com/logicmonitor/ft/jmx/jmxclient/AbstractClient.java
|
a21e7a4639a899ea12bc9a82897c87fb32bc33ff
|
[
"BSD-3-Clause"
] |
permissive
|
HHtiger/jmx-clt
|
https://github.com/HHtiger/jmx-clt
|
89c4e24c2754666c1824c844c926d671f43ca041
|
30219feb3598d3a2fd01a88598af697fa678cdb9
|
refs/heads/master
| 2017-07-31T13:13:38.923000 | 2014-11-10T05:39:18 | 2014-11-10T05:39:18 | 94,954,628 | 1 | 0 | null | true | 2017-06-21T02:29:57 | 2017-06-21T02:29:57 | 2016-10-12T07:47:49 | 2014-11-10T05:41:00 | 674 | 0 | 0 | 0 | null | null | null |
package com.logicmonitor.ft.jmx.jmxclient;
import javax.management.MalformedObjectNameException;
import java.io.IOException;
import java.util.ArrayList;
/**
* Created by dengxianzhi on 14-3-25.
*/
public abstract class AbstractClient {
/**
* There are four types of JMXPath. Client will use different
* algorithms to deal with them.
* <p/>
* 1. A JMXPath with an index property such as Catalina:type=Cache,host=localhost,path=*
* <p/>
* Client will returns an array of values of the property 'path' such as [/, /admin, /core, ...]
* <p/>
* 2. A JMXPath with 2 index properties such as Catalina:type=Cache,host=*,path=*
* <p/>
* Client will returns an array of String[2] such as [[localhost, /], [localhost, /admin], ...]
* <p/>
* 3. A JMXPath with a complete ObjectName but selector such as Catalina:type=Cache,host=localhost,path=/admin
* <p/>
* Client will returns an array of names of all attribute of the MBean such as [accessCount, cacheMaxSize,
* hitsCount, maxAllocateInterations, spareNotFoundEntries, cacheSize, desiedEntryAccessRatio, modelerType]
* <p/>
* 4. A JMXPath with a complete ObjectName and selector
* such as Catalina:type=Cache,host=localhost,path=/admin:accessCount
* <p/>
* 5. A JMXPath with a wildcard * in domain.
* <p/>
* Client will returns an array of names matching the domain.
* <p/>
* Client will treat the value of a MBean attribute as a tree with the name of the attribute as
* the root. Client will returns all sub-nodes of the node refered by the selector.
*
* @throws java.io.IOException
*/
public ArrayList evaluatePath(com.logicmonitor.ft.jmx.jmxclient.JMXPath path)
throws IOException {
try {
if (path.isWildcardDomain() && !path.hasIndexProperty()) {
return _listDomains(path);
}
else if (path.isWildcardDomain() && path.hasIndexProperty()) {
return _listDomainsAndProperties(path);
}
else if (path.hasTwoIndexProperties()) {
return _listValuesOfIndexProperty2(path);
}
else if (path.hasIndexProperty()) {
return _listValuesOfIndexProperty(path);
}
else if (!path.hasSelector()) {
return _listAttributeNames(path);
}
else {
return _listSubNodes(path);
}
}
catch (MalformedObjectNameException e) {
throw new IOException(e);
}
}
public ArrayList evaluatePath(String path) throws IOException {
return evaluatePath(com.logicmonitor.ft.jmx.jmxclient.JMXPath.valueOf(path));
}
/**
* * Given a JMX path without properties, and the domain has wildcard , return the list of values. For example, given the path
* java.lang.*:type=Cache, this method will returns [["localhost", "/"], ["localhost", "/admin"], ...]
* @param path
* @return
* @throws java.io.IOException
* @throws javax.management.MalformedObjectNameException
*/
protected abstract ArrayList<String> _listDomains(com.logicmonitor.ft.jmx.jmxclient.JMXPath path)throws IOException, MalformedObjectNameException;
/**
* Given a JMX path with a index properties, and the domain has wildcard , return the list of values. For example, given the path
* java.lang.*:type=Cache,path=*, this method will returns [["localhost", "/"], ["localhost", "/admin"], ...]
* @param path
* @return
* @throws java.io.IOException
* @throws javax.management.MalformedObjectNameException
*/
protected abstract ArrayList<String[]> _listDomainsAndProperties(com.logicmonitor.ft.jmx.jmxclient.JMXPath path) throws IOException, MalformedObjectNameException;
/**
* Given a JMX path with two index properties, returns the list of values. For example, given the path
* Catalina:type=Cache,host=*,path=*, this method will returns [["localhost", "/"], ["localhost", "/admin"], ...]
*
* @param path the JMX path with 2 index properties
* @return An array of tuples
* @throws java.io.IOException
* @throws javax.management.MalformedObjectNameException if path is invalid
*/
protected abstract ArrayList<String[]> _listValuesOfIndexProperty2(com.logicmonitor.ft.jmx.jmxclient.JMXPath path) throws IOException, MalformedObjectNameException;
/**
* Given a JMX path withn an index property, returns the list of values. For example, given the path
* Catalina:type=Cache,host=localhost,path=*, this method will returns ["/", "/admin", "/manager", ...]
*
* @param path the JMX path with an index property
* @return An array of values of the index property.
* @throws java.io.IOException
* @throws javax.management.MalformedObjectNameException if path is invalid
*/
protected abstract ArrayList<String> _listValuesOfIndexProperty(com.logicmonitor.ft.jmx.jmxclient.JMXPath path) throws IOException, MalformedObjectNameException;
/**
* Returns an array of attribute name exposed by the MBean. For example, given the
* JMX path "Catalian:type=Cache,host=localhost,path=/", the moethod will return
* [modelerType, accessCount, cacheMaxSize, hitsCount, maxAllocateIterations,
* spareNotFoundEntries, ...]
*
* @param path The JMX path with a complete ObjectName but the selector
* @return An array of attribute names exposed by the MBean
* @throws java.io.IOException
* @throws javax.management.MalformedObjectNameException if path is invalid
*/
protected abstract ArrayList<String> _listAttributeNames(com.logicmonitor.ft.jmx.jmxclient.JMXPath path) throws IOException, MalformedObjectNameException;
/**
* Returns the sub-nodes of the node refered by the selector in the path. We
* trreat the value of a MBean attribute as a tree with the attribute name as the
* root. The selector acts like a file system path, which guides us to traverse
* the tree and returns all sub-nodes.
*
* @param path the JMX path
* @return an array of sub-nodes of the node
* @throws java.io.IOException
* @throws javax.management.MalformedObjectNameException
*/
protected abstract ArrayList<String> _listSubNodes(com.logicmonitor.ft.jmx.jmxclient.JMXPath path) throws IOException, MalformedObjectNameException;
/**
* return the string value from the given jmx path
* @param spath
* @return
* @throws java.io.IOException
*/
public String getValue(String spath) throws IOException {
com.logicmonitor.ft.jmx.jmxclient.JMXPath path = com.logicmonitor.ft.jmx.jmxclient.JMXPath.valueOf(spath);
ArrayList<?> rs = evaluatePath(path);
if (rs == null || rs.size() == 0) {
return null;
}
Object r = rs.get(0);
return r.toString();
}
/**
* get the array value from the given jmx path
* @param spath
* @return
* @throws java.io.IOException
*/
public Object[] getChildren(String spath) throws IOException {
com.logicmonitor.ft.jmx.jmxclient.JMXPath path = com.logicmonitor.ft.jmx.jmxclient.JMXPath.valueOf(spath);
ArrayList rs = evaluatePath(path);
if (rs == null) {
return new Object[0];
}
return rs.toArray();
}
public void close() {
}
}
|
UTF-8
|
Java
| 7,522 |
java
|
AbstractClient.java
|
Java
|
[
{
"context": "on;\nimport java.util.ArrayList;\n\n/**\n * Created by dengxianzhi on 14-3-25.\n */\npublic abstract class AbstractCli",
"end": 184,
"score": 0.9989943504333496,
"start": 173,
"tag": "USERNAME",
"value": "dengxianzhi"
}
] | null |
[] |
package com.logicmonitor.ft.jmx.jmxclient;
import javax.management.MalformedObjectNameException;
import java.io.IOException;
import java.util.ArrayList;
/**
* Created by dengxianzhi on 14-3-25.
*/
public abstract class AbstractClient {
/**
* There are four types of JMXPath. Client will use different
* algorithms to deal with them.
* <p/>
* 1. A JMXPath with an index property such as Catalina:type=Cache,host=localhost,path=*
* <p/>
* Client will returns an array of values of the property 'path' such as [/, /admin, /core, ...]
* <p/>
* 2. A JMXPath with 2 index properties such as Catalina:type=Cache,host=*,path=*
* <p/>
* Client will returns an array of String[2] such as [[localhost, /], [localhost, /admin], ...]
* <p/>
* 3. A JMXPath with a complete ObjectName but selector such as Catalina:type=Cache,host=localhost,path=/admin
* <p/>
* Client will returns an array of names of all attribute of the MBean such as [accessCount, cacheMaxSize,
* hitsCount, maxAllocateInterations, spareNotFoundEntries, cacheSize, desiedEntryAccessRatio, modelerType]
* <p/>
* 4. A JMXPath with a complete ObjectName and selector
* such as Catalina:type=Cache,host=localhost,path=/admin:accessCount
* <p/>
* 5. A JMXPath with a wildcard * in domain.
* <p/>
* Client will returns an array of names matching the domain.
* <p/>
* Client will treat the value of a MBean attribute as a tree with the name of the attribute as
* the root. Client will returns all sub-nodes of the node refered by the selector.
*
* @throws java.io.IOException
*/
public ArrayList evaluatePath(com.logicmonitor.ft.jmx.jmxclient.JMXPath path)
throws IOException {
try {
if (path.isWildcardDomain() && !path.hasIndexProperty()) {
return _listDomains(path);
}
else if (path.isWildcardDomain() && path.hasIndexProperty()) {
return _listDomainsAndProperties(path);
}
else if (path.hasTwoIndexProperties()) {
return _listValuesOfIndexProperty2(path);
}
else if (path.hasIndexProperty()) {
return _listValuesOfIndexProperty(path);
}
else if (!path.hasSelector()) {
return _listAttributeNames(path);
}
else {
return _listSubNodes(path);
}
}
catch (MalformedObjectNameException e) {
throw new IOException(e);
}
}
public ArrayList evaluatePath(String path) throws IOException {
return evaluatePath(com.logicmonitor.ft.jmx.jmxclient.JMXPath.valueOf(path));
}
/**
* * Given a JMX path without properties, and the domain has wildcard , return the list of values. For example, given the path
* java.lang.*:type=Cache, this method will returns [["localhost", "/"], ["localhost", "/admin"], ...]
* @param path
* @return
* @throws java.io.IOException
* @throws javax.management.MalformedObjectNameException
*/
protected abstract ArrayList<String> _listDomains(com.logicmonitor.ft.jmx.jmxclient.JMXPath path)throws IOException, MalformedObjectNameException;
/**
* Given a JMX path with a index properties, and the domain has wildcard , return the list of values. For example, given the path
* java.lang.*:type=Cache,path=*, this method will returns [["localhost", "/"], ["localhost", "/admin"], ...]
* @param path
* @return
* @throws java.io.IOException
* @throws javax.management.MalformedObjectNameException
*/
protected abstract ArrayList<String[]> _listDomainsAndProperties(com.logicmonitor.ft.jmx.jmxclient.JMXPath path) throws IOException, MalformedObjectNameException;
/**
* Given a JMX path with two index properties, returns the list of values. For example, given the path
* Catalina:type=Cache,host=*,path=*, this method will returns [["localhost", "/"], ["localhost", "/admin"], ...]
*
* @param path the JMX path with 2 index properties
* @return An array of tuples
* @throws java.io.IOException
* @throws javax.management.MalformedObjectNameException if path is invalid
*/
protected abstract ArrayList<String[]> _listValuesOfIndexProperty2(com.logicmonitor.ft.jmx.jmxclient.JMXPath path) throws IOException, MalformedObjectNameException;
/**
* Given a JMX path withn an index property, returns the list of values. For example, given the path
* Catalina:type=Cache,host=localhost,path=*, this method will returns ["/", "/admin", "/manager", ...]
*
* @param path the JMX path with an index property
* @return An array of values of the index property.
* @throws java.io.IOException
* @throws javax.management.MalformedObjectNameException if path is invalid
*/
protected abstract ArrayList<String> _listValuesOfIndexProperty(com.logicmonitor.ft.jmx.jmxclient.JMXPath path) throws IOException, MalformedObjectNameException;
/**
* Returns an array of attribute name exposed by the MBean. For example, given the
* JMX path "Catalian:type=Cache,host=localhost,path=/", the moethod will return
* [modelerType, accessCount, cacheMaxSize, hitsCount, maxAllocateIterations,
* spareNotFoundEntries, ...]
*
* @param path The JMX path with a complete ObjectName but the selector
* @return An array of attribute names exposed by the MBean
* @throws java.io.IOException
* @throws javax.management.MalformedObjectNameException if path is invalid
*/
protected abstract ArrayList<String> _listAttributeNames(com.logicmonitor.ft.jmx.jmxclient.JMXPath path) throws IOException, MalformedObjectNameException;
/**
* Returns the sub-nodes of the node refered by the selector in the path. We
* trreat the value of a MBean attribute as a tree with the attribute name as the
* root. The selector acts like a file system path, which guides us to traverse
* the tree and returns all sub-nodes.
*
* @param path the JMX path
* @return an array of sub-nodes of the node
* @throws java.io.IOException
* @throws javax.management.MalformedObjectNameException
*/
protected abstract ArrayList<String> _listSubNodes(com.logicmonitor.ft.jmx.jmxclient.JMXPath path) throws IOException, MalformedObjectNameException;
/**
* return the string value from the given jmx path
* @param spath
* @return
* @throws java.io.IOException
*/
public String getValue(String spath) throws IOException {
com.logicmonitor.ft.jmx.jmxclient.JMXPath path = com.logicmonitor.ft.jmx.jmxclient.JMXPath.valueOf(spath);
ArrayList<?> rs = evaluatePath(path);
if (rs == null || rs.size() == 0) {
return null;
}
Object r = rs.get(0);
return r.toString();
}
/**
* get the array value from the given jmx path
* @param spath
* @return
* @throws java.io.IOException
*/
public Object[] getChildren(String spath) throws IOException {
com.logicmonitor.ft.jmx.jmxclient.JMXPath path = com.logicmonitor.ft.jmx.jmxclient.JMXPath.valueOf(spath);
ArrayList rs = evaluatePath(path);
if (rs == null) {
return new Object[0];
}
return rs.toArray();
}
public void close() {
}
}
| 7,522 | 0.660861 | 0.658468 | 174 | 42.229885 | 40.767551 | 168 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.586207 | false | false |
10
|
740d36efd892141e1e2afeda0c4d10b66267b3c1
| 16,252,156,275,896 |
bddadcd7661e82e5b82ae50ef403a762325ff5b0
|
/level19/lesson10/bonus01/Solution.java
|
f5594538bcf8ee04e5519eb4d466ce58f26ea262
|
[] |
no_license
|
arhanechka/javarush
|
https://github.com/arhanechka/javarush
|
8cb25e8bf3965f307c9254bdff3f915a597ab296
|
2d03bd7126bcf9daf97801c1908313c915703db8
|
refs/heads/master
| 2021-01-13T13:07:02.603000 | 2017-03-04T08:39:15 | 2017-03-04T08:39:15 | 78,663,923 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.javarush.test.level19.lesson10.bonus01;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/* Отслеживаем изменения
Считать в консоли 2 имени файла - file1, file2.
Файлы содержат строки, file2 является обновленной версией file1, часть строк совпадают.
Нужно создать объединенную версию строк, записать их в список lines
Операции ADDED и REMOVED не могут идти подряд, они всегда разделены SAME
Пример:
оригинальный редактированный общий
file1: file2: результат:(lines)
строка1 строка1 SAME строка1
строка2 REMOVED строка2
строка3 строка3 SAME строка3
строка4 REMOVED строка4
строка5 строка5 SAME строка5
строка0 ADDED строка0
строка1 строка1 SAME строка1
строка2 REMOVED строка2
строка3 строка3 SAME строка3
строка5 ADDED строка5
строка4 строка4 SAME строка4
строка5 REMOVED строка5
*/
public class Solution {
public static List<LineItem> lines = new ArrayList<LineItem>();
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String fileName1 = br.readLine();
String fileName2 = br.readLine();
br.close();
ArrayList<String> file1 = new ArrayList<>();
ArrayList<String> file2 = new ArrayList<>();
BufferedReader br1= new BufferedReader(new FileReader(fileName1));
while (br1.ready())
file1.add(br1.readLine());
br1.close();
BufferedReader br2= new BufferedReader(new FileReader(fileName2));
while (br2.ready())
file2.add(br2.readLine());
br2.close();
int i=0;
try
{while (!(file1.isEmpty() && file2.isEmpty()))
if (!file1.isEmpty() && file2.isEmpty())
{lines.add(new LineItem(Type.REMOVED, file1.get(i)));
file1.remove(i);}
else if (file1.isEmpty() && !file2.isEmpty())
{
lines.add(new LineItem(Type.ADDED, file2.get(i)));
file2.remove(i);}
else if (file1.get(i).equals(file2.get(i)))
{lines.add(new LineItem(Type.SAME, file1.get(i)));
file1.remove(i);
file2.remove(i);
}
else if (file1.size()>1 && !file1.get(i).equals(file2.get(i)) && (file1.get(i+1).equals(file2.get(i))))
{lines.add(new LineItem(Type.REMOVED, file1.get(i)));
file1.remove(i);}
else if (file2.size()>1 && !file1.get(i).equals(file2.get(i)) && (file1.get(i).equals(file2.get(i+1))))
{
lines.add(new LineItem(Type.ADDED, file2.get(i)));
file2.remove(i);
}
else if (file1.size()==1 && file2.size()>1)
{
lines.add(new LineItem(Type.ADDED, file2.get(i)));
file2.remove(i);
}
else if (file2.size()==1 && file1.size()>1)
{
lines.add(new LineItem(Type.REMOVED, file1.get(i)));
file1.remove(i);}}
catch (IndexOutOfBoundsException e)
{}
for (LineItem line1 : lines)
{
System.out.println(line1.type+" "+line1.line);
}
}
public static enum Type {
ADDED, //добавлена новая строка
REMOVED, //удалена строка
SAME //без изменений
}
public static class LineItem {
public Type type;
public String line;
public LineItem(Type type, String line) {
this.type = type;
this.line = line;
}
}
}
|
UTF-8
|
Java
| 4,425 |
java
|
Solution.java
|
Java
|
[] | null |
[] |
package com.javarush.test.level19.lesson10.bonus01;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/* Отслеживаем изменения
Считать в консоли 2 имени файла - file1, file2.
Файлы содержат строки, file2 является обновленной версией file1, часть строк совпадают.
Нужно создать объединенную версию строк, записать их в список lines
Операции ADDED и REMOVED не могут идти подряд, они всегда разделены SAME
Пример:
оригинальный редактированный общий
file1: file2: результат:(lines)
строка1 строка1 SAME строка1
строка2 REMOVED строка2
строка3 строка3 SAME строка3
строка4 REMOVED строка4
строка5 строка5 SAME строка5
строка0 ADDED строка0
строка1 строка1 SAME строка1
строка2 REMOVED строка2
строка3 строка3 SAME строка3
строка5 ADDED строка5
строка4 строка4 SAME строка4
строка5 REMOVED строка5
*/
public class Solution {
public static List<LineItem> lines = new ArrayList<LineItem>();
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String fileName1 = br.readLine();
String fileName2 = br.readLine();
br.close();
ArrayList<String> file1 = new ArrayList<>();
ArrayList<String> file2 = new ArrayList<>();
BufferedReader br1= new BufferedReader(new FileReader(fileName1));
while (br1.ready())
file1.add(br1.readLine());
br1.close();
BufferedReader br2= new BufferedReader(new FileReader(fileName2));
while (br2.ready())
file2.add(br2.readLine());
br2.close();
int i=0;
try
{while (!(file1.isEmpty() && file2.isEmpty()))
if (!file1.isEmpty() && file2.isEmpty())
{lines.add(new LineItem(Type.REMOVED, file1.get(i)));
file1.remove(i);}
else if (file1.isEmpty() && !file2.isEmpty())
{
lines.add(new LineItem(Type.ADDED, file2.get(i)));
file2.remove(i);}
else if (file1.get(i).equals(file2.get(i)))
{lines.add(new LineItem(Type.SAME, file1.get(i)));
file1.remove(i);
file2.remove(i);
}
else if (file1.size()>1 && !file1.get(i).equals(file2.get(i)) && (file1.get(i+1).equals(file2.get(i))))
{lines.add(new LineItem(Type.REMOVED, file1.get(i)));
file1.remove(i);}
else if (file2.size()>1 && !file1.get(i).equals(file2.get(i)) && (file1.get(i).equals(file2.get(i+1))))
{
lines.add(new LineItem(Type.ADDED, file2.get(i)));
file2.remove(i);
}
else if (file1.size()==1 && file2.size()>1)
{
lines.add(new LineItem(Type.ADDED, file2.get(i)));
file2.remove(i);
}
else if (file2.size()==1 && file1.size()>1)
{
lines.add(new LineItem(Type.REMOVED, file1.get(i)));
file1.remove(i);}}
catch (IndexOutOfBoundsException e)
{}
for (LineItem line1 : lines)
{
System.out.println(line1.type+" "+line1.line);
}
}
public static enum Type {
ADDED, //добавлена новая строка
REMOVED, //удалена строка
SAME //без изменений
}
public static class LineItem {
public Type type;
public String line;
public LineItem(Type type, String line) {
this.type = type;
this.line = line;
}
}
}
| 4,425 | 0.556738 | 0.529382 | 112 | 34.25 | 24.76046 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
10
|
8f3b86ea6d280e7b22d20a71f7248b11932821e7
| 11,751,030,572,006 |
bf7b4c21300a8ccebb380e0e0a031982466ccd83
|
/middlewareConcepts2014-master/Assignment3/lib/jacorb-3.4/src/generated/org/omg/dds/QueryCondition.java
|
4d1eee8895c94c2bed35f0770478362b6ab2b6fe
|
[] |
no_license
|
Puriakshat/Tuberlin
|
https://github.com/Puriakshat/Tuberlin
|
3fe36b970aabad30ed95e8a07c2f875e4912a3db
|
28dcf7f7edfe7320c740c306b1c0593a6c1b3115
|
refs/heads/master
| 2021-01-19T07:30:16.857000 | 2014-11-06T18:49:16 | 2014-11-06T18:49:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.omg.dds;
/**
* Generated from IDL interface "QueryCondition".
*
* @author JacORB IDL compiler V @project.version@
* @version generated at 27-May-2014 20:14:30
*/
public interface QueryCondition
extends QueryConditionOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity, org.omg.dds.ReadCondition
{
}
|
UTF-8
|
Java
| 334 |
java
|
QueryCondition.java
|
Java
|
[] | null |
[] |
package org.omg.dds;
/**
* Generated from IDL interface "QueryCondition".
*
* @author JacORB IDL compiler V @project.version@
* @version generated at 27-May-2014 20:14:30
*/
public interface QueryCondition
extends QueryConditionOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity, org.omg.dds.ReadCondition
{
}
| 334 | 0.757485 | 0.721557 | 13 | 24.692308 | 32.629353 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false |
10
|
a2a1eb84ae2c2c7a67142bd6310e9997072ced93
| 7,928,509,670,474 |
c388ac0b01b207478d2e1333090e468324da78b6
|
/src/com/rockbite/bootcamp/util/observer/ObservationSubject.java
|
ad72af2277ea3fd75bfe943204e3828e6f4cceab
|
[] |
no_license
|
rockbite-bootcamp/product-shop-arayik0530
|
https://github.com/rockbite-bootcamp/product-shop-arayik0530
|
14e2fac26a5ffe57c66d32cdc3869b43a44c8d7a
|
ffab6fd4cd01960b36323e1e4b3e2d3d3fd013d5
|
refs/heads/master
| 2022-12-05T09:18:53.916000 | 2020-08-13T11:34:06 | 2020-08-13T11:34:06 | 285,370,466 | 0 | 0 | null | false | 2020-08-05T18:19:11 | 2020-08-05T18:19:05 | 2020-08-05T18:19:05 | 2020-08-05T18:19:10 | 0 | 0 | 0 | 1 | null | false | false |
package com.rockbite.bootcamp.util.observer;
import java.util.ArrayList;
import java.util.List;
/**
* Subject to which observers are subscribed
*/
public class ObservationSubject {
//observers
private final List<Observer> observers;
//subjects state
private int productListLength;
public ObservationSubject(final int productListLength) {
this.observers = new ArrayList<>();
this.productListLength = productListLength;
}
/**
* state changing method
*
* @param length Products's count in the shop
*/
public void setState(int length) {
this.productListLength = length;
notifyAllObservers();
}
/**
* observers notifying method
*/
public void notifyAllObservers() {
for (Observer observer : observers) {
observer.update();
}
}
/**
* subscribing method to subject
*
* @param observer Observer
*/
public void subscribe(Observer observer) {
this.observers.add(observer);
}
/**
* unsubscribing method to subject
*
* @param observer Observer
*/
public void unsubscribe(Observer observer) {
this.observers.remove(observer);
}
//Getter
public int getProductListLength() {
return productListLength;
}
}
|
UTF-8
|
Java
| 1,341 |
java
|
ObservationSubject.java
|
Java
|
[] | null |
[] |
package com.rockbite.bootcamp.util.observer;
import java.util.ArrayList;
import java.util.List;
/**
* Subject to which observers are subscribed
*/
public class ObservationSubject {
//observers
private final List<Observer> observers;
//subjects state
private int productListLength;
public ObservationSubject(final int productListLength) {
this.observers = new ArrayList<>();
this.productListLength = productListLength;
}
/**
* state changing method
*
* @param length Products's count in the shop
*/
public void setState(int length) {
this.productListLength = length;
notifyAllObservers();
}
/**
* observers notifying method
*/
public void notifyAllObservers() {
for (Observer observer : observers) {
observer.update();
}
}
/**
* subscribing method to subject
*
* @param observer Observer
*/
public void subscribe(Observer observer) {
this.observers.add(observer);
}
/**
* unsubscribing method to subject
*
* @param observer Observer
*/
public void unsubscribe(Observer observer) {
this.observers.remove(observer);
}
//Getter
public int getProductListLength() {
return productListLength;
}
}
| 1,341 | 0.621924 | 0.621924 | 64 | 19.953125 | 17.878435 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.203125 | false | false |
10
|
0a6c6090ddc27a1e8e76352cf4491cab118eea1c
| 30,305,289,306,978 |
a4ac83719d1e06fa0abdcfd255258853137035db
|
/app/src/main/java/com/neosolusi/expresslingua/data/repo/BaseRepository.java
|
fa30d2379f0dace9cdd16c725e0ce8ff71061907
|
[] |
no_license
|
NTRsolutions/ExpressLingua
|
https://github.com/NTRsolutions/ExpressLingua
|
299ad0f69a935765947da5bec0fb640e8762226a
|
4bee749a2f2e4b16b41e13ea9ba6478512453b1b
|
refs/heads/master
| 2020-03-27T06:33:06.455000 | 2018-08-25T16:53:52 | 2018-08-25T16:53:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.neosolusi.expresslingua.data.repo;
import android.arch.lifecycle.LiveData;
import com.neosolusi.expresslingua.data.dao.Dao;
import com.neosolusi.expresslingua.data.util.DataContract;
import java.util.HashMap;
import java.util.List;
import io.realm.Case;
import io.realm.RealmObject;
import io.realm.RealmQuery;
import io.realm.RealmResults;
import io.realm.Sort;
public abstract class BaseRepository<T extends RealmObject> implements DataContract<T> {
protected final Dao mDao;
public BaseRepository(Dao dao) {
this.mDao = dao;
}
abstract public boolean isFetchNeeded();
abstract public void wakeup();
@Override public T findFirstEqualTo(String column, String criteria) {
return (T) mDao.findFirstEqualTo(column, criteria);
}
@Override public T findFirstEqualTo(String column, boolean criteria) {
return (T) mDao.findFirstEqualTo(column, criteria);
}
@Override public T findFirstEqualTo(String column, int criteria) {
return (T) mDao.findFirstEqualTo(column, criteria);
}
@Override public T findFirstEqualTo(String column, long criteria) {
return (T) mDao.findFirstEqualTo(column, criteria);
}
@Override public T findFirstEqualTo(HashMap<String, Object> criterias) {
return (T) mDao.findFirstEqualTo(criterias);
}
@Override public T findFirstCopyEqualTo(String column, String criteria) {
return (T) mDao.findFirstCopyEqualTo(column, criteria);
}
@Override public T findFirstCopyEqualTo(String column, boolean criteria) {
return (T) mDao.findFirstCopyEqualTo(column, criteria);
}
@Override public T findFirstCopyEqualTo(String column, int criteria) {
return (T) mDao.findFirstCopyEqualTo(column, criteria);
}
@Override public T findFirstCopyEqualTo(String column, long criteria) {
return (T) mDao.findFirstCopyEqualTo(column, criteria);
}
@Override public T findFirstCopyEqualTo(HashMap<String, Object> criterias) {
return (T) mDao.findFirstCopyEqualTo(criterias);
}
@Override public T findFirstNotEqualTo(String column, String criteria) {
return (T) mDao.findFirstNotEqualTo(column, criteria);
}
@Override public T findFirstNotEqualTo(String column, long criteria) {
return (T) mDao.findFirstNotEqualTo(column, criteria);
}
@Override public RealmResults<T> findAll() {
return mDao.findAll();
}
@Override public RealmResults<T> findAllEqualTo(String column, String search) {
return mDao.findAllEqualTo(column, search);
}
@Override public RealmResults<T> findAllEqualTo(String column, long search) {
return mDao.findAllEqualTo(column, search);
}
@Override public RealmResults<T> findAllEqualTo(String column, boolean search) {
return mDao.findAllEqualTo(column, search);
}
@Override public RealmResults<T> findAllEqualTo(String column, int search) {
return mDao.findAllEqualTo(column, search);
}
@Override public LiveData<RealmResults<T>> findAllAsync() {
return mDao.findAllAsync();
}
@Override public LiveData<RealmResults<T>> findAllAsync(String column, Sort sort) {
return mDao.findAllAsync(column, sort);
}
@Override public LiveData<RealmResults<T>> findAllEqualToAsync(String column, boolean search) {
return mDao.findAllEqualToAsync(column, search);
}
@Override public LiveData<RealmResults<T>> findAllEqualToAsync(String column, int search, String sortColumn, Sort sort) {
return mDao.findAllEqualToAsync(column, search, sortColumn, sort);
}
@Override public LiveData<RealmResults<T>> findAllEqualToAsync(String column, long search, String sortColumn, Sort sort) {
return mDao.findAllEqualToAsync(column, search, sortColumn, sort);
}
@Override public LiveData<RealmResults<T>> findAllEqualToAsync(HashMap<String, Object> criterias) {
return mDao.findAllEqualToAsync(criterias);
}
@Override public LiveData<RealmResults<T>> findAllEqualToAsync(HashMap<String, Object> criterias, String sortColumn, Sort sort) {
return mDao.findAllEqualToAsync(criterias, sortColumn, sort);
}
@Override public void insertAsync(T entity) {
mDao.insertAsync(entity);
}
@Override public void insertAsync(List<T> entities) {
mDao.insertAsync(entities);
}
@Override public T copyFromDb(T entity) {
return (T) mDao.copyFromDb(entity);
}
@Override public List<T> copyFromDb(Iterable<T> entities) {
return mDao.copyFromDb(entities);
}
@Override public T copyOrUpdate(T entity) {
return (T) mDao.copyOrUpdate(entity);
}
@Override public void copyOrUpdate(List<T> entities) {
mDao.copyOrUpdate(entities);
}
@Override public void copyOrUpdateAsync(T entity) {
mDao.copyOrUpdateAsync(entity);
}
@Override public void copyOrUpdateAsync(List<T> entities) {
mDao.copyOrUpdateAsync(entities);
}
@Override public void deleteAll() {
mDao.deleteAll();
}
@Override public void delete(T entity) {
mDao.delete(entity);
}
@Override public int count() {
return mDao.count();
}
@Override public RealmQuery<T> where() {
return mDao.where();
}
}
|
UTF-8
|
Java
| 5,367 |
java
|
BaseRepository.java
|
Java
|
[] | null |
[] |
package com.neosolusi.expresslingua.data.repo;
import android.arch.lifecycle.LiveData;
import com.neosolusi.expresslingua.data.dao.Dao;
import com.neosolusi.expresslingua.data.util.DataContract;
import java.util.HashMap;
import java.util.List;
import io.realm.Case;
import io.realm.RealmObject;
import io.realm.RealmQuery;
import io.realm.RealmResults;
import io.realm.Sort;
public abstract class BaseRepository<T extends RealmObject> implements DataContract<T> {
protected final Dao mDao;
public BaseRepository(Dao dao) {
this.mDao = dao;
}
abstract public boolean isFetchNeeded();
abstract public void wakeup();
@Override public T findFirstEqualTo(String column, String criteria) {
return (T) mDao.findFirstEqualTo(column, criteria);
}
@Override public T findFirstEqualTo(String column, boolean criteria) {
return (T) mDao.findFirstEqualTo(column, criteria);
}
@Override public T findFirstEqualTo(String column, int criteria) {
return (T) mDao.findFirstEqualTo(column, criteria);
}
@Override public T findFirstEqualTo(String column, long criteria) {
return (T) mDao.findFirstEqualTo(column, criteria);
}
@Override public T findFirstEqualTo(HashMap<String, Object> criterias) {
return (T) mDao.findFirstEqualTo(criterias);
}
@Override public T findFirstCopyEqualTo(String column, String criteria) {
return (T) mDao.findFirstCopyEqualTo(column, criteria);
}
@Override public T findFirstCopyEqualTo(String column, boolean criteria) {
return (T) mDao.findFirstCopyEqualTo(column, criteria);
}
@Override public T findFirstCopyEqualTo(String column, int criteria) {
return (T) mDao.findFirstCopyEqualTo(column, criteria);
}
@Override public T findFirstCopyEqualTo(String column, long criteria) {
return (T) mDao.findFirstCopyEqualTo(column, criteria);
}
@Override public T findFirstCopyEqualTo(HashMap<String, Object> criterias) {
return (T) mDao.findFirstCopyEqualTo(criterias);
}
@Override public T findFirstNotEqualTo(String column, String criteria) {
return (T) mDao.findFirstNotEqualTo(column, criteria);
}
@Override public T findFirstNotEqualTo(String column, long criteria) {
return (T) mDao.findFirstNotEqualTo(column, criteria);
}
@Override public RealmResults<T> findAll() {
return mDao.findAll();
}
@Override public RealmResults<T> findAllEqualTo(String column, String search) {
return mDao.findAllEqualTo(column, search);
}
@Override public RealmResults<T> findAllEqualTo(String column, long search) {
return mDao.findAllEqualTo(column, search);
}
@Override public RealmResults<T> findAllEqualTo(String column, boolean search) {
return mDao.findAllEqualTo(column, search);
}
@Override public RealmResults<T> findAllEqualTo(String column, int search) {
return mDao.findAllEqualTo(column, search);
}
@Override public LiveData<RealmResults<T>> findAllAsync() {
return mDao.findAllAsync();
}
@Override public LiveData<RealmResults<T>> findAllAsync(String column, Sort sort) {
return mDao.findAllAsync(column, sort);
}
@Override public LiveData<RealmResults<T>> findAllEqualToAsync(String column, boolean search) {
return mDao.findAllEqualToAsync(column, search);
}
@Override public LiveData<RealmResults<T>> findAllEqualToAsync(String column, int search, String sortColumn, Sort sort) {
return mDao.findAllEqualToAsync(column, search, sortColumn, sort);
}
@Override public LiveData<RealmResults<T>> findAllEqualToAsync(String column, long search, String sortColumn, Sort sort) {
return mDao.findAllEqualToAsync(column, search, sortColumn, sort);
}
@Override public LiveData<RealmResults<T>> findAllEqualToAsync(HashMap<String, Object> criterias) {
return mDao.findAllEqualToAsync(criterias);
}
@Override public LiveData<RealmResults<T>> findAllEqualToAsync(HashMap<String, Object> criterias, String sortColumn, Sort sort) {
return mDao.findAllEqualToAsync(criterias, sortColumn, sort);
}
@Override public void insertAsync(T entity) {
mDao.insertAsync(entity);
}
@Override public void insertAsync(List<T> entities) {
mDao.insertAsync(entities);
}
@Override public T copyFromDb(T entity) {
return (T) mDao.copyFromDb(entity);
}
@Override public List<T> copyFromDb(Iterable<T> entities) {
return mDao.copyFromDb(entities);
}
@Override public T copyOrUpdate(T entity) {
return (T) mDao.copyOrUpdate(entity);
}
@Override public void copyOrUpdate(List<T> entities) {
mDao.copyOrUpdate(entities);
}
@Override public void copyOrUpdateAsync(T entity) {
mDao.copyOrUpdateAsync(entity);
}
@Override public void copyOrUpdateAsync(List<T> entities) {
mDao.copyOrUpdateAsync(entities);
}
@Override public void deleteAll() {
mDao.deleteAll();
}
@Override public void delete(T entity) {
mDao.delete(entity);
}
@Override public int count() {
return mDao.count();
}
@Override public RealmQuery<T> where() {
return mDao.where();
}
}
| 5,367 | 0.696851 | 0.696851 | 172 | 30.203489 | 31.84938 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.598837 | false | false |
10
|
c53ccb06bea2554dac99a184f1adb6261385058a
| 27,144,193,328,951 |
01fecc2e7517880c814b6a49840a3657d19c5039
|
/src/test/java/com/obzen/spark/application/batch/cjo/FileToKafkaBatchCJO_20200121.java
|
1a5e795274ff63eeecbd40e49f62f015394d7de3
|
[
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] |
permissive
|
joyspapa/joy-spark
|
https://github.com/joyspapa/joy-spark
|
792a0faf3e3eda54d6ec3e632e671dbc770bc791
|
6dcfb2a7659e8bd117f92df7748aa22baa9fd445
|
refs/heads/master
| 2021-07-25T14:04:34.856000 | 2020-07-08T10:02:48 | 2020-07-08T10:02:48 | 195,354,386 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.obzen.spark.application.batch.cjo;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.SparkSession.Builder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by hanmin on 17. 3. 2.
*/
public class FileToKafkaBatchCJO_20200121 implements Serializable {
private static final long serialVersionUID = 8965924708608823997L;
private static final Logger logger = LoggerFactory.getLogger(FileToKafkaBatchCJO_20200121.class);
private static SparkSession sparkSession;
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS");
private static String topicPrefix = "-IN-TOPIC";
private static String fileNames = "click_pc_web,click_mobile_webview,click_mobile_web,tracker_mobile_app,tracker_mobile_webview,tracker_mobile_web,tracker_pc_web";
public void setUpSparkConfig(boolean isLocal) {
SparkConf sparkConf = new SparkConf().setAppName("CJ OShopping Spark Batch Application");
sparkConf.set("mapreduce.fileoutputcommitter.marksuccessfuljobs", "false");
sparkConf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer");
//sparkConf.registerKryoClasses(new Class<?>[] { KafkaProducerWrapperCJO.class/*, CJmallLogVO.class*/ });
Builder sparkBuilder = SparkSession.builder().appName("FileToKafkaBatchTest")
.config("parquet.enable.summary-metadata", false).config("parquet.metadata.read.parallelism", "10")
.config("mapreduce.fileoutputcommitter.marksuccessfuljobs", false).config(sparkConf);
if (isLocal) {
sparkBuilder.master("local[*]");
}
sparkSession = sparkBuilder.getOrCreate();
}
public static void main(String[] args) throws Exception {
String topic = "CJO-LOG-IN-TOPIC";
logger.info("[main] begin ...");
long startTime = System.currentTimeMillis();
FileToKafkaBatchCJO_20200121 simple = new FileToKafkaBatchCJO_20200121();
String sourceFileRootDir = "C:\\working\\201710\\head_10_line\\";
String sourceFileName = "click_pc_web.log.2017-10-05_10";
if (args[0].equals("local")) {
logger.info("[FileBatchMain] local ...");
//sourceFileName = "C:\\working\\splunk_log_1day\\tracker_mobile_clickzone.log.2017-09-12";
sourceFileName = "tracker_mobile_app.log.2017-10-05_10";
//sourceFileName = "click_mobile_webview.log.2017-10-05";
topic = "TRACKER_MOBILE_APP-IN-TOPIC";
} else if ((args.length == 1 && args[0].contains(".log."))) {
boolean isExistTopic = false;
sourceFileRootDir = "/user/ecube/obzen/batch/indata/";
for (String fileName : fileNames.split(",", -1)) {
if (args[0].contains(fileName)) {
topic = fileName.toUpperCase() + topicPrefix;
isExistTopic = true;
break;
}
}
if (!isExistTopic) {
throw new IllegalArgumentException(
"Check Topic Name about the File Name! [ Parameters must be a file name. ex) click_pc_web.log.2017-10-05 ] : "
+ args.toString());
}
logger.info("topic name : " + topic);
sourceFileName = args[0];
} else if (args.length >= 3 && args[1].contains("-") && args[2].endsWith(".log")) {
boolean isExistTopic = false;
sourceFileRootDir = "/user/ecube/obzen/batch/indata/"+args[0]+"/" +args[1]+"/" ;
logger.warn(">>> args[0] : " + args[0] + ", args[1] : " + args[1] + ", args[2] : " + args[2]);
for (String fileName : fileNames.split(",", -1)) {
if (args[2].contains(fileName)) {
topic = fileName.toUpperCase() + topicPrefix;
isExistTopic = true;
break;
}
}
if (!isExistTopic) {
throw new IllegalArgumentException(
"Check Topic Name about the File Name! [ Parameters must be a log_server_name, date, FILE_NAME, ex)server1 2017-10-05 click_pc_web.log ] : "
);
}
sourceFileName = args[2] + "." + args[1];
logger.info(">>> topic name : " + topic + ", sourceFileName name : " + sourceFileName);
} else {
throw new IllegalArgumentException(
"Check Parameter! [ Parameters must be a file name. ex) click_pc_web.log.2017-10-05 ] : "
+ args.toString());
}
//===============================================
try {
simple.setUpSparkConfig(args[0].equals("local"));
if(args[0].equals("local")) {
simple.readTest(sourceFileRootDir, sourceFileName);
return;
}
simple.process(sourceFileRootDir, sourceFileName, topic);
} finally {
try {
sparkSession.stop();
} catch (Exception ex) {
//kafkaClientProducer = null;
ex.printStackTrace();
}
}
//===============================================
logger.info("[main] end ... Elapsed : " + (System.currentTimeMillis() - startTime) + " ms");
//Thread.sleep(30000);
}
/*
public void processOld(String sourceFileRootDir, String sourceFileName, String topicName,
KafkaProducerWrapperTest producerWrapper) {
JavaRDD<String> lines = sparkSession.read().textFile(sourceFileRootDir + sourceFileName).javaRDD();
lines.cache();
lines.filter(currentLine -> {
if (currentLine == null) {
logger.warn("Invalid (null):" + currentLine);
return false;
}
if (currentLine.isEmpty()) {
logger.warn("Invalid (empty):" + currentLine);
return false;
}
try {
dateFormat.parse(currentLine.substring(0, 23));
} catch (ParseException | NumberFormatException pe) {
logger.warn("Invalid (DateFormat-ParseException):" + currentLine);
return false;
}
return true;
}).foreach(filteredLine -> {
//producerWrapper.sendEventMessage(topicName, sourceFileName.split("\\.")[0], filteredLine);
producerWrapper.sendEventMessage(topicName, filteredLine);
});
lines.unpersist();
}
*/
public void process(String sourceFileRootDir, String sourceFileName, String topicName) {
JavaRDD<String> lines = sparkSession.read().textFile(sourceFileRootDir + sourceFileName).javaRDD();
lines.cache();
lines.filter(currentLine -> {
if (currentLine == null) {
logger.warn("Invalid (null):" + currentLine);
return false;
}
if (currentLine.isEmpty()) {
logger.warn("Invalid (empty):" + currentLine);
return false;
}
// try {
// dateFormat.parse(currentLine.substring(0, 23));
// //} catch (ParseException | NumberFormatException pe) {
// } catch (Exception pe) {
// logger.warn("Invalid (DateFormat-ParseException):" + currentLine);
// return false;
// }
return true;
}).foreachPartition(partition -> {
//int keyIndex = 0;
while (partition.hasNext()) {
StringBuilder concatDateField = new StringBuilder();
concatDateField.append(partition.next());
if (topicName.toLowerCase().contains("click_pc_web")) {
concatDateField.append(", ");
concatDateField.append("host=\"web_click\", ");
concatDateField.append("sourcetype=\"CPCW\"");
} else if (topicName.toLowerCase().contains("click_mobile_webview")) {
concatDateField.append(", ");
concatDateField.append("host=\"web_click\", ");
concatDateField.append("sourcetype=\"CMWV\"");
} else if (topicName.toLowerCase().contains("click_mobile_web")) {
concatDateField.append(", ");
concatDateField.append("host=\"web_click\", ");
concatDateField.append("sourcetype=\"CMOW\"");
} else if (topicName.toLowerCase().contains("tracker_pc_web")) {
concatDateField.append(", ");
concatDateField.append("host=\"m_logger\", ");
concatDateField.append("sourcetype=\"TPCW\"");
} else if (topicName.toLowerCase().contains("tracker_mobile_webview")) {
concatDateField.append(", ");
concatDateField.append("host=\"m_logger\", ");
concatDateField.append("sourcetype=\"TMWV\"");
} else if (topicName.toLowerCase().contains("tracker_mobile_web")) {
concatDateField.append(", ");
concatDateField.append("host=\"m_logger\", ");
concatDateField.append("sourcetype=\"TMOW\"");
} else if (topicName.toLowerCase().contains("tracker_mobile_app")) {
concatDateField.append(", ");
concatDateField.append("host=\"app_logger\", ");
concatDateField.append("sourcetype=\"TAPP\"");
}
//producerWrapper.sendEventMessage("MIG_CORE_LOG_IN_TOPIC", /*topicName+"_"+String.valueOf(keyIndex++),*/ concatDateField.toString());
//producerWrapper.sendEventMessage(topicName, /*topicName+"_"+String.valueOf(keyIndex++),*/ partition.next());
}
});
lines.unpersist();
}
/*
public void processBulk(String sourceFileRootDir, String sourceFileName, String topicName,
KafkaProducerWrapperTest producerWrapper) {
JavaRDD<String> lines = sparkSession.read().textFile(sourceFileRootDir + sourceFileName).javaRDD();
lines.cache();
lines.filter(currentLine -> {
if (currentLine == null) {
logger.warn("Invalid (null):" + currentLine);
return false;
}
if (currentLine.isEmpty()) {
logger.warn("Invalid (empty):" + currentLine);
return false;
}
try {
dateFormat.parse(currentLine.substring(0, 23));
} catch (ParseException | NumberFormatException pe) {
logger.warn("Invalid (DateFormat-ParseException):" + currentLine);
return false;
}
return true;
}).foreachPartition(partition -> {
List<KeyedMessage> listMessage = new ArrayList<KeyedMessage>();
//KeyedMessage message = null;
int keyIndex = 0;
while (partition.hasNext()) {
listMessage.add(new KeyedMessage(topicName, partition.next()));
}
producerWrapper.sendEventMessage(topicName, listMessage);
listMessage.clear();
});
lines.unpersist();
}
*/
public void readTest(String sourceFileName, String outputFileName) throws Exception {
sourceFileName = "hdfs://210.122.104.136:8020/user/hduser/obzen/parquet/CJO-LOG-HDFS/CJO-LOG/*";
//sourceFileName = "C:\\working\\201709\\output\\app\\*";
Dataset<Row> readDataset = sparkSession.read().parquet(sourceFileName);
readDataset.cache();
//readDataset.show();
// readDataset.createOrReplaceTempView("cjo_log");
//
// StringBuilder sql = new StringBuilder();
// sql.append("select uid, cust_cd, cust_id from cjo_log ");
// sql.append("where ");
// sql.append("sourcetype='CMWV' ");
// sql.append("AND uid='Ubc6d1a30a7e10f4278b8fab941a6adcf857c1507173708' ");
// sql.append("limit 10");
//
// Dataset<Row> resultDataset = readDataset.sqlContext().sql(sql.toString());
//
// resultDataset.show();
//readDataset.select("count").show(200);
//logger.info("[readTest] readDataset.toJavaRDD().getNumPartitions() : "
// + readDataset.toJavaRDD().getNumPartitions());
logger.info("[readTest] readDataset.count() : " + readDataset.count());
}
}
|
UTF-8
|
Java
| 10,757 |
java
|
FileToKafkaBatchCJO_20200121.java
|
Java
|
[
{
"context": "import org.slf4j.LoggerFactory;\n\n/**\n * Created by hanmin on 17. 3. 2.\n */\npublic class FileToKafkaBatchCJO",
"end": 434,
"score": 0.9994819164276123,
"start": 428,
"tag": "USERNAME",
"value": "hanmin"
},
{
"context": "\t//KeyedMessage message = null;\n\t\t\tint keyIndex = 0;\n\t\t\twhile (partition.hasNext()) {\n\t\t\t\tlistMessage",
"end": 9447,
"score": 0.8029463291168213,
"start": 9446,
"tag": "KEY",
"value": "0"
},
{
"context": "e) throws Exception {\n\n\t\tsourceFileName = \"hdfs://210.122.104.136:8020/user/hduser/obzen/parquet/CJO-LOG-HDFS/CJO-L",
"end": 9811,
"score": 0.9996897578239441,
"start": 9796,
"tag": "IP_ADDRESS",
"value": "210.122.104.136"
}
] | null |
[] |
package com.obzen.spark.application.batch.cjo;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.SparkSession.Builder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by hanmin on 17. 3. 2.
*/
public class FileToKafkaBatchCJO_20200121 implements Serializable {
private static final long serialVersionUID = 8965924708608823997L;
private static final Logger logger = LoggerFactory.getLogger(FileToKafkaBatchCJO_20200121.class);
private static SparkSession sparkSession;
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS");
private static String topicPrefix = "-IN-TOPIC";
private static String fileNames = "click_pc_web,click_mobile_webview,click_mobile_web,tracker_mobile_app,tracker_mobile_webview,tracker_mobile_web,tracker_pc_web";
public void setUpSparkConfig(boolean isLocal) {
SparkConf sparkConf = new SparkConf().setAppName("CJ OShopping Spark Batch Application");
sparkConf.set("mapreduce.fileoutputcommitter.marksuccessfuljobs", "false");
sparkConf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer");
//sparkConf.registerKryoClasses(new Class<?>[] { KafkaProducerWrapperCJO.class/*, CJmallLogVO.class*/ });
Builder sparkBuilder = SparkSession.builder().appName("FileToKafkaBatchTest")
.config("parquet.enable.summary-metadata", false).config("parquet.metadata.read.parallelism", "10")
.config("mapreduce.fileoutputcommitter.marksuccessfuljobs", false).config(sparkConf);
if (isLocal) {
sparkBuilder.master("local[*]");
}
sparkSession = sparkBuilder.getOrCreate();
}
public static void main(String[] args) throws Exception {
String topic = "CJO-LOG-IN-TOPIC";
logger.info("[main] begin ...");
long startTime = System.currentTimeMillis();
FileToKafkaBatchCJO_20200121 simple = new FileToKafkaBatchCJO_20200121();
String sourceFileRootDir = "C:\\working\\201710\\head_10_line\\";
String sourceFileName = "click_pc_web.log.2017-10-05_10";
if (args[0].equals("local")) {
logger.info("[FileBatchMain] local ...");
//sourceFileName = "C:\\working\\splunk_log_1day\\tracker_mobile_clickzone.log.2017-09-12";
sourceFileName = "tracker_mobile_app.log.2017-10-05_10";
//sourceFileName = "click_mobile_webview.log.2017-10-05";
topic = "TRACKER_MOBILE_APP-IN-TOPIC";
} else if ((args.length == 1 && args[0].contains(".log."))) {
boolean isExistTopic = false;
sourceFileRootDir = "/user/ecube/obzen/batch/indata/";
for (String fileName : fileNames.split(",", -1)) {
if (args[0].contains(fileName)) {
topic = fileName.toUpperCase() + topicPrefix;
isExistTopic = true;
break;
}
}
if (!isExistTopic) {
throw new IllegalArgumentException(
"Check Topic Name about the File Name! [ Parameters must be a file name. ex) click_pc_web.log.2017-10-05 ] : "
+ args.toString());
}
logger.info("topic name : " + topic);
sourceFileName = args[0];
} else if (args.length >= 3 && args[1].contains("-") && args[2].endsWith(".log")) {
boolean isExistTopic = false;
sourceFileRootDir = "/user/ecube/obzen/batch/indata/"+args[0]+"/" +args[1]+"/" ;
logger.warn(">>> args[0] : " + args[0] + ", args[1] : " + args[1] + ", args[2] : " + args[2]);
for (String fileName : fileNames.split(",", -1)) {
if (args[2].contains(fileName)) {
topic = fileName.toUpperCase() + topicPrefix;
isExistTopic = true;
break;
}
}
if (!isExistTopic) {
throw new IllegalArgumentException(
"Check Topic Name about the File Name! [ Parameters must be a log_server_name, date, FILE_NAME, ex)server1 2017-10-05 click_pc_web.log ] : "
);
}
sourceFileName = args[2] + "." + args[1];
logger.info(">>> topic name : " + topic + ", sourceFileName name : " + sourceFileName);
} else {
throw new IllegalArgumentException(
"Check Parameter! [ Parameters must be a file name. ex) click_pc_web.log.2017-10-05 ] : "
+ args.toString());
}
//===============================================
try {
simple.setUpSparkConfig(args[0].equals("local"));
if(args[0].equals("local")) {
simple.readTest(sourceFileRootDir, sourceFileName);
return;
}
simple.process(sourceFileRootDir, sourceFileName, topic);
} finally {
try {
sparkSession.stop();
} catch (Exception ex) {
//kafkaClientProducer = null;
ex.printStackTrace();
}
}
//===============================================
logger.info("[main] end ... Elapsed : " + (System.currentTimeMillis() - startTime) + " ms");
//Thread.sleep(30000);
}
/*
public void processOld(String sourceFileRootDir, String sourceFileName, String topicName,
KafkaProducerWrapperTest producerWrapper) {
JavaRDD<String> lines = sparkSession.read().textFile(sourceFileRootDir + sourceFileName).javaRDD();
lines.cache();
lines.filter(currentLine -> {
if (currentLine == null) {
logger.warn("Invalid (null):" + currentLine);
return false;
}
if (currentLine.isEmpty()) {
logger.warn("Invalid (empty):" + currentLine);
return false;
}
try {
dateFormat.parse(currentLine.substring(0, 23));
} catch (ParseException | NumberFormatException pe) {
logger.warn("Invalid (DateFormat-ParseException):" + currentLine);
return false;
}
return true;
}).foreach(filteredLine -> {
//producerWrapper.sendEventMessage(topicName, sourceFileName.split("\\.")[0], filteredLine);
producerWrapper.sendEventMessage(topicName, filteredLine);
});
lines.unpersist();
}
*/
public void process(String sourceFileRootDir, String sourceFileName, String topicName) {
JavaRDD<String> lines = sparkSession.read().textFile(sourceFileRootDir + sourceFileName).javaRDD();
lines.cache();
lines.filter(currentLine -> {
if (currentLine == null) {
logger.warn("Invalid (null):" + currentLine);
return false;
}
if (currentLine.isEmpty()) {
logger.warn("Invalid (empty):" + currentLine);
return false;
}
// try {
// dateFormat.parse(currentLine.substring(0, 23));
// //} catch (ParseException | NumberFormatException pe) {
// } catch (Exception pe) {
// logger.warn("Invalid (DateFormat-ParseException):" + currentLine);
// return false;
// }
return true;
}).foreachPartition(partition -> {
//int keyIndex = 0;
while (partition.hasNext()) {
StringBuilder concatDateField = new StringBuilder();
concatDateField.append(partition.next());
if (topicName.toLowerCase().contains("click_pc_web")) {
concatDateField.append(", ");
concatDateField.append("host=\"web_click\", ");
concatDateField.append("sourcetype=\"CPCW\"");
} else if (topicName.toLowerCase().contains("click_mobile_webview")) {
concatDateField.append(", ");
concatDateField.append("host=\"web_click\", ");
concatDateField.append("sourcetype=\"CMWV\"");
} else if (topicName.toLowerCase().contains("click_mobile_web")) {
concatDateField.append(", ");
concatDateField.append("host=\"web_click\", ");
concatDateField.append("sourcetype=\"CMOW\"");
} else if (topicName.toLowerCase().contains("tracker_pc_web")) {
concatDateField.append(", ");
concatDateField.append("host=\"m_logger\", ");
concatDateField.append("sourcetype=\"TPCW\"");
} else if (topicName.toLowerCase().contains("tracker_mobile_webview")) {
concatDateField.append(", ");
concatDateField.append("host=\"m_logger\", ");
concatDateField.append("sourcetype=\"TMWV\"");
} else if (topicName.toLowerCase().contains("tracker_mobile_web")) {
concatDateField.append(", ");
concatDateField.append("host=\"m_logger\", ");
concatDateField.append("sourcetype=\"TMOW\"");
} else if (topicName.toLowerCase().contains("tracker_mobile_app")) {
concatDateField.append(", ");
concatDateField.append("host=\"app_logger\", ");
concatDateField.append("sourcetype=\"TAPP\"");
}
//producerWrapper.sendEventMessage("MIG_CORE_LOG_IN_TOPIC", /*topicName+"_"+String.valueOf(keyIndex++),*/ concatDateField.toString());
//producerWrapper.sendEventMessage(topicName, /*topicName+"_"+String.valueOf(keyIndex++),*/ partition.next());
}
});
lines.unpersist();
}
/*
public void processBulk(String sourceFileRootDir, String sourceFileName, String topicName,
KafkaProducerWrapperTest producerWrapper) {
JavaRDD<String> lines = sparkSession.read().textFile(sourceFileRootDir + sourceFileName).javaRDD();
lines.cache();
lines.filter(currentLine -> {
if (currentLine == null) {
logger.warn("Invalid (null):" + currentLine);
return false;
}
if (currentLine.isEmpty()) {
logger.warn("Invalid (empty):" + currentLine);
return false;
}
try {
dateFormat.parse(currentLine.substring(0, 23));
} catch (ParseException | NumberFormatException pe) {
logger.warn("Invalid (DateFormat-ParseException):" + currentLine);
return false;
}
return true;
}).foreachPartition(partition -> {
List<KeyedMessage> listMessage = new ArrayList<KeyedMessage>();
//KeyedMessage message = null;
int keyIndex = 0;
while (partition.hasNext()) {
listMessage.add(new KeyedMessage(topicName, partition.next()));
}
producerWrapper.sendEventMessage(topicName, listMessage);
listMessage.clear();
});
lines.unpersist();
}
*/
public void readTest(String sourceFileName, String outputFileName) throws Exception {
sourceFileName = "hdfs://192.168.3.11:8020/user/hduser/obzen/parquet/CJO-LOG-HDFS/CJO-LOG/*";
//sourceFileName = "C:\\working\\201709\\output\\app\\*";
Dataset<Row> readDataset = sparkSession.read().parquet(sourceFileName);
readDataset.cache();
//readDataset.show();
// readDataset.createOrReplaceTempView("cjo_log");
//
// StringBuilder sql = new StringBuilder();
// sql.append("select uid, cust_cd, cust_id from cjo_log ");
// sql.append("where ");
// sql.append("sourcetype='CMWV' ");
// sql.append("AND uid='Ubc6d1a30a7e10f4278b8fab941a6adcf857c1507173708' ");
// sql.append("limit 10");
//
// Dataset<Row> resultDataset = readDataset.sqlContext().sql(sql.toString());
//
// resultDataset.show();
//readDataset.select("count").show(200);
//logger.info("[readTest] readDataset.toJavaRDD().getNumPartitions() : "
// + readDataset.toJavaRDD().getNumPartitions());
logger.info("[readTest] readDataset.count() : " + readDataset.count());
}
}
| 10,754 | 0.670912 | 0.649995 | 336 | 31.014881 | 31.438759 | 164 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.949405 | false | false |
10
|
c643b2d8f81163409c4b83cdbfcf8025c1afbcc9
| 15,315,853,411,247 |
e7661adc286a837eda860a4f497f4c491c2e7355
|
/common/src/main/java/com/swt/concurrent/synchronizer/test019/MyContainer1.java
|
f1cea0617bcb0c002532e90e594fc07b9c9d670a
|
[] |
no_license
|
wtshen/springbootExam
|
https://github.com/wtshen/springbootExam
|
3b50957759f9766fc855c5abf9a77720024184cd
|
aee8d2ecc8dfa618cf7934cbe73175ead622e77a
|
refs/heads/master
| 2022-12-11T10:08:16.410000 | 2020-07-11T01:01:30 | 2020-07-11T01:01:30 | 121,858,717 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.swt.concurrent.synchronizer.test019;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @Author: wtshen
* @Description:
* 实现一个容易, 提供两个方法, add size
* 写两个线程,线程1添加10个元素到容器中,线程2实现监控元素的个数,当个数到5的时候,线程2给出提示并结束
*
* 给lists添加volatile后,t2能够接到通知,但是,t2线程的死循环很浪费cpu
* @Date: Created in 下午11:07 18/3/7.
* @Modified By:
*/
public class MyContainer1 {
volatile List lists = Lists.newArrayList();
void add(Object o) {
lists.add(o);
}
int size() {
return lists.size();
}
public static void main(String[] args) {
MyContainer1 myContainer1 = new MyContainer1();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
myContainer1.add(i);
System.out.println("add" + i);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "t1").start();
new Thread(() -> {
while (true) {
if (myContainer1.size() == 5) {
break;
}
}
System.out.println(Thread.currentThread().getName() + " end");
}, "t2").start();
}
}
|
UTF-8
|
Java
| 1,475 |
java
|
MyContainer1.java
|
Java
|
[
{
"context": "rt java.util.concurrent.TimeUnit;\n\n/**\n * @Author: wtshen\n * @Description:\n * 实现一个容易, 提供两个方法, add size\n * 写",
"end": 175,
"score": 0.99969083070755,
"start": 169,
"tag": "USERNAME",
"value": "wtshen"
}
] | null |
[] |
package com.swt.concurrent.synchronizer.test019;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @Author: wtshen
* @Description:
* 实现一个容易, 提供两个方法, add size
* 写两个线程,线程1添加10个元素到容器中,线程2实现监控元素的个数,当个数到5的时候,线程2给出提示并结束
*
* 给lists添加volatile后,t2能够接到通知,但是,t2线程的死循环很浪费cpu
* @Date: Created in 下午11:07 18/3/7.
* @Modified By:
*/
public class MyContainer1 {
volatile List lists = Lists.newArrayList();
void add(Object o) {
lists.add(o);
}
int size() {
return lists.size();
}
public static void main(String[] args) {
MyContainer1 myContainer1 = new MyContainer1();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
myContainer1.add(i);
System.out.println("add" + i);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "t1").start();
new Thread(() -> {
while (true) {
if (myContainer1.size() == 5) {
break;
}
}
System.out.println(Thread.currentThread().getName() + " end");
}, "t2").start();
}
}
| 1,475 | 0.519333 | 0.495072 | 55 | 22.981817 | 18.721394 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.527273 | false | false |
10
|
9300c636884ee95db3600c9a7d1a57f7a11c2bd5
| 17,815,524,382,308 |
027b9b2caee329a90357dba2055fb73b7c6fae92
|
/java-demo/src/main/java/demo/pattern/singleton/threadLocal/ExecutorThread.java
|
651103108d0c968bd3d0a4b3f7e8aadd395769f3
|
[] |
no_license
|
zhouchao4664/spring-boot-demo
|
https://github.com/zhouchao4664/spring-boot-demo
|
e25f20cd7f504c8fcb3c5859c969a7fed5a1631e
|
f4e9867c1c2c403d45d8b2d336fae3a1fafb7628
|
refs/heads/master
| 2023-04-13T17:20:39.566000 | 2023-04-04T20:14:11 | 2023-04-04T20:14:11 | 195,481,155 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package demo.pattern.singleton.threadLocal;
/**
* 2019/3/14
* zhouchao
*/
public class ExecutorThread implements Runnable {
@Override
public void run() {
ThreadLocalSingleton singleton = ThreadLocalSingleton.getInstance();
System.out.println(singleton);
}
}
|
UTF-8
|
Java
| 291 |
java
|
ExecutorThread.java
|
Java
|
[] | null |
[] |
package demo.pattern.singleton.threadLocal;
/**
* 2019/3/14
* zhouchao
*/
public class ExecutorThread implements Runnable {
@Override
public void run() {
ThreadLocalSingleton singleton = ThreadLocalSingleton.getInstance();
System.out.println(singleton);
}
}
| 291 | 0.694158 | 0.670103 | 14 | 19.785715 | 22.35486 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.214286 | false | false |
10
|
f43a0de06f25c0955b244b0327cc58ae1b12a71d
| 14,834,817,059,014 |
db7a0931bf4647afb970500c441e357d204900b4
|
/code/taxoffice/src/cn/bronze/services/AdminRoleService.java
|
cce961596873072117afd59c166f8b4f8239884c
|
[] |
no_license
|
webyulibo/webFrame
|
https://github.com/webyulibo/webFrame
|
66441db04e28743b0b6cb5e5c523d6f87652176b
|
8ce60d122f02f7c9f26f0119f680bbe176284d27
|
refs/heads/master
| 2021-01-20T08:02:47.704000 | 2017-08-02T06:01:42 | 2017-08-02T06:01:42 | 90,088,751 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cn.bronze.services;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import cn.bronze.daos.TAuthorityMapper;
import cn.bronze.daos.TRoleMapper;
import cn.bronze.entities.TRole;
import cn.bronze.entities.TRoleExample;
import cn.bronze.entities.TRoleExampleCustom;
import cn.bronze.util.page.PageParameter;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-*.xml")
@Service
public class AdminRoleService extends GenernicServiceImpl<TRole, TRoleExample> {
@Autowired
private TRoleMapper dao;
/*
*
* 分页查询
* @param page 分页参数
* */
public List<TRole> getroleswithpage(PageParameter page){
TRoleExampleCustom tRoleExampleCustom=new TRoleExampleCustom();
tRoleExampleCustom.setPage(page);
TRoleExample.Criteria criteria=tRoleExampleCustom.createCriteria();
List<TRole>roles=dao.selectByExample(tRoleExampleCustom);
if(roles!=null&&roles.size()>0)
return roles;
else
return null;
}
/*
*
* 根据id值删除对应角色
*
* */
public boolean deleterolebyid(Integer id){
Integer status=0;
//Integer id=8;
status=dao.deleteByPrimaryKey(id);
if(status!=null&&status>0)
return true;
else
return false;
}
/*
*
* 添加角色
* */
public boolean addrole(String rolename){
//String rolename="系统管理员";
TRole tRole=new TRole();
tRole.setRolename(rolename);
Integer status=dao.insert(tRole);
if(status!=null&&status>0)
return true;
else
return false;
}
/*
*
* 根据角色名称,判断是否有该角色
* */
public boolean getrolebyrolename(String rolename){
//String rolename="管理员";
TRoleExampleCustom tRoleExampleCustom=new TRoleExampleCustom();
TRoleExample.Criteria criteria=tRoleExampleCustom.createCriteria();
criteria.andRolenameEqualTo(rolename);
List<TRole> roles=dao.selectByExample(tRoleExampleCustom);
if(roles!=null&&roles.size()>0)
return true;
else
return false;
}
/*
*
* 根据id更新角色
*
* */
public boolean updaterolebyrolename(TRole role){
Integer status=dao.updateByPrimaryKey(role);
if(status!=null&&status>0)
return true;
else
return false;
}
/*
*
* 根据角色名字,获取对应的id值
* */
public int getidbyrolename(String rolename){
//int roleid=0;
//String rolename="系统管理员";
TRoleExample example=new TRoleExample();
TRoleExample.Criteria criteria=example.createCriteria();
criteria.andRolenameEqualTo(rolename);
List<TRole>roles=dao.selectByExample(example);
if(roles!=null&&roles.size()>0)
return roles.get(0).getId();
else
return 0;
//System.out.println(roleid);
}
}
|
UTF-8
|
Java
| 2,987 |
java
|
AdminRoleService.java
|
Java
|
[
{
"context": "byrolename(String rolename){\n\t\t//String rolename=\"管理员\";\n\t\tTRoleExampleCustom tRoleExampleCustom=new TRo",
"end": 1871,
"score": 0.9183567762374878,
"start": 1868,
"tag": "USERNAME",
"value": "管理员"
},
{
"context": "rolename){\n\t\t//int roleid=0;\n\t\t//String rolename=\"系统管理员\";\n\t\tTRoleExample example=new TRoleExample();\n\t\tTR",
"end": 2529,
"score": 0.9745105504989624,
"start": 2524,
"tag": "USERNAME",
"value": "系统管理员"
}
] | null |
[] |
package cn.bronze.services;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import cn.bronze.daos.TAuthorityMapper;
import cn.bronze.daos.TRoleMapper;
import cn.bronze.entities.TRole;
import cn.bronze.entities.TRoleExample;
import cn.bronze.entities.TRoleExampleCustom;
import cn.bronze.util.page.PageParameter;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-*.xml")
@Service
public class AdminRoleService extends GenernicServiceImpl<TRole, TRoleExample> {
@Autowired
private TRoleMapper dao;
/*
*
* 分页查询
* @param page 分页参数
* */
public List<TRole> getroleswithpage(PageParameter page){
TRoleExampleCustom tRoleExampleCustom=new TRoleExampleCustom();
tRoleExampleCustom.setPage(page);
TRoleExample.Criteria criteria=tRoleExampleCustom.createCriteria();
List<TRole>roles=dao.selectByExample(tRoleExampleCustom);
if(roles!=null&&roles.size()>0)
return roles;
else
return null;
}
/*
*
* 根据id值删除对应角色
*
* */
public boolean deleterolebyid(Integer id){
Integer status=0;
//Integer id=8;
status=dao.deleteByPrimaryKey(id);
if(status!=null&&status>0)
return true;
else
return false;
}
/*
*
* 添加角色
* */
public boolean addrole(String rolename){
//String rolename="系统管理员";
TRole tRole=new TRole();
tRole.setRolename(rolename);
Integer status=dao.insert(tRole);
if(status!=null&&status>0)
return true;
else
return false;
}
/*
*
* 根据角色名称,判断是否有该角色
* */
public boolean getrolebyrolename(String rolename){
//String rolename="管理员";
TRoleExampleCustom tRoleExampleCustom=new TRoleExampleCustom();
TRoleExample.Criteria criteria=tRoleExampleCustom.createCriteria();
criteria.andRolenameEqualTo(rolename);
List<TRole> roles=dao.selectByExample(tRoleExampleCustom);
if(roles!=null&&roles.size()>0)
return true;
else
return false;
}
/*
*
* 根据id更新角色
*
* */
public boolean updaterolebyrolename(TRole role){
Integer status=dao.updateByPrimaryKey(role);
if(status!=null&&status>0)
return true;
else
return false;
}
/*
*
* 根据角色名字,获取对应的id值
* */
public int getidbyrolename(String rolename){
//int roleid=0;
//String rolename="系统管理员";
TRoleExample example=new TRoleExample();
TRoleExample.Criteria criteria=example.createCriteria();
criteria.andRolenameEqualTo(rolename);
List<TRole>roles=dao.selectByExample(example);
if(roles!=null&&roles.size()>0)
return roles.get(0).getId();
else
return 0;
//System.out.println(roleid);
}
}
| 2,987 | 0.734128 | 0.729218 | 125 | 21.808001 | 20.91189 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.768 | false | false |
10
|
05029a7ca62e858995754d9135f9f9bb5d93fad4
| 13,013,750,976,739 |
d39d055ce1179abdb7117f29d9f516e4e8114a04
|
/ChamadaApplication/src/com/application/chamada/domain/Disciplina.java
|
0de85e0acd8c8338b41e006ee02c0b2f735f7f9b
|
[] |
no_license
|
diegocamara/ChamadaApplication
|
https://github.com/diegocamara/ChamadaApplication
|
89aa8ede348d330256f47746f53f8e96fb9cc990
|
0ef4124ce1a58e8a8f500e40365c7df46bcc9f5f
|
refs/heads/master
| 2016-09-09T17:38:12.279000 | 2014-07-26T23:52:30 | 2014-07-26T23:52:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.application.chamada.domain;
import java.io.Serializable;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.joda.time.DateTime;
import com.j256.ormlite.dao.ForeignCollection;
import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "DISCIPLINA")
public class Disciplina implements Serializable {
private static final long serialVersionUID = 1L;
public static final String DISCIPLINA_KEY = "disciplina";
public static final String CODIGO = "CODIGO";
public static final String NOME = "NOME";
public static final String DATA_INICIO = "DATA_INICIO";
public static final String DATA_FIM = "DATA_FIM";
public static final String HORARIOS = "HORARIOS";
@DatabaseField(generatedId = true, columnName = CODIGO)
private int codigo;
@DatabaseField(canBeNull = false, columnName = NOME)
private String nome;
@DatabaseField(canBeNull = false, dataType = DataType.DATE_TIME, columnName = DATA_INICIO)
private DateTime dataInicio;
@DatabaseField(canBeNull = false, dataType = DataType.DATE_TIME, columnName = DATA_FIM)
private DateTime dataFim;
// @ForeignCollectionField
// private ForeignCollection<Aluno> alunos;
@ForeignCollectionField
private ForeignCollection<Horario> horarios;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public DateTime getDataInicio() {
return dataInicio;
}
public void setDataInicio(DateTime dataInicio) {
this.dataInicio = dataInicio;
}
public DateTime getDataFim() {
return dataFim;
}
public void setDataFim(DateTime dataFim) {
this.dataFim = dataFim;
}
public int getCodigo() {
return codigo;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public ForeignCollection<Horario> getHorarios() {
return horarios;
}
public void setHorarios(ForeignCollection<Horario> horarios) {
this.horarios = horarios;
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(this.codigo).toHashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Disciplina) {
final Disciplina disciplina = (Disciplina) obj;
return new EqualsBuilder().append(this.codigo,
disciplina.getCodigo()).isEquals();
} else {
return false;
}
}
}
|
UTF-8
|
Java
| 2,579 |
java
|
Disciplina.java
|
Java
|
[] | null |
[] |
package com.application.chamada.domain;
import java.io.Serializable;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.joda.time.DateTime;
import com.j256.ormlite.dao.ForeignCollection;
import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "DISCIPLINA")
public class Disciplina implements Serializable {
private static final long serialVersionUID = 1L;
public static final String DISCIPLINA_KEY = "disciplina";
public static final String CODIGO = "CODIGO";
public static final String NOME = "NOME";
public static final String DATA_INICIO = "DATA_INICIO";
public static final String DATA_FIM = "DATA_FIM";
public static final String HORARIOS = "HORARIOS";
@DatabaseField(generatedId = true, columnName = CODIGO)
private int codigo;
@DatabaseField(canBeNull = false, columnName = NOME)
private String nome;
@DatabaseField(canBeNull = false, dataType = DataType.DATE_TIME, columnName = DATA_INICIO)
private DateTime dataInicio;
@DatabaseField(canBeNull = false, dataType = DataType.DATE_TIME, columnName = DATA_FIM)
private DateTime dataFim;
// @ForeignCollectionField
// private ForeignCollection<Aluno> alunos;
@ForeignCollectionField
private ForeignCollection<Horario> horarios;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public DateTime getDataInicio() {
return dataInicio;
}
public void setDataInicio(DateTime dataInicio) {
this.dataInicio = dataInicio;
}
public DateTime getDataFim() {
return dataFim;
}
public void setDataFim(DateTime dataFim) {
this.dataFim = dataFim;
}
public int getCodigo() {
return codigo;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public ForeignCollection<Horario> getHorarios() {
return horarios;
}
public void setHorarios(ForeignCollection<Horario> horarios) {
this.horarios = horarios;
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(this.codigo).toHashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Disciplina) {
final Disciplina disciplina = (Disciplina) obj;
return new EqualsBuilder().append(this.codigo,
disciplina.getCodigo()).isEquals();
} else {
return false;
}
}
}
| 2,579 | 0.723149 | 0.716169 | 104 | 22.798077 | 22.460384 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.269231 | false | false |
10
|
eb4804dec1ed7302b93d0c5f38e02b00543b736e
| 4,432,406,288,023 |
ea502e754e4f6322dd49cad21c500156de046155
|
/src/main/java/zx/learn/collection/testCollection.java
|
e7ca35a04da8eb1ce08e23534d9d34c4b6302b91
|
[] |
no_license
|
xox-moe/LearnJava
|
https://github.com/xox-moe/LearnJava
|
ca547092e57e4bb3729a32a91efdf9c90558aff9
|
1fb2d1fd5d9b730e14be7268af5c2f26bf2e76a5
|
refs/heads/master
| 2020-04-29T11:07:51.494000 | 2019-09-18T09:28:56 | 2019-09-18T09:28:56 | 176,086,268 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package zx.learn.collection;
import java.io.Console;
import java.util.Collection;
import java.util.HashSet;
import java.util.Scanner;
/**
* @Auther: quxue
* @Date: 2019/2/28 15:29
* @Description:
*/
public class testCollection {
public static void main(String[] args) {
String a = "1234568";
String bb = " abcdefgHIGKLMN "; //果然是UTF-16
// System.out.println("字符串长度:"+bb.length());
// System.out.println("码点长度:"+bb.codePointCount(0,bb.length()));
// System.out.println(bb.trim());
String[] strings = {"A","b","c","d","E"};
// System.out.println();
Scanner scanner = new Scanner(System.in);
Console console = System.console();
String userName = console.readLine("userName");
char[] passowrd = console.readPassword("password:");
System.out.println(System.getProperty("user.dir"));
for(int i = 10;i>0;i--)
{
System.out.println(i);
}
}
}
|
UTF-8
|
Java
| 1,017 |
java
|
testCollection.java
|
Java
|
[
{
"context": "ashSet;\nimport java.util.Scanner;\n\n/**\n * @Auther: quxue\n * @Date: 2019/2/28 15:29\n * @Description:\n */\npu",
"end": 157,
"score": 0.9996697902679443,
"start": 152,
"tag": "USERNAME",
"value": "quxue"
},
{
"context": "le();\n String userName = console.readLine(\"userName\");\n char[] passowrd = console.readPassword",
"end": 764,
"score": 0.6710628271102905,
"start": 756,
"tag": "USERNAME",
"value": "userName"
}
] | null |
[] |
package zx.learn.collection;
import java.io.Console;
import java.util.Collection;
import java.util.HashSet;
import java.util.Scanner;
/**
* @Auther: quxue
* @Date: 2019/2/28 15:29
* @Description:
*/
public class testCollection {
public static void main(String[] args) {
String a = "1234568";
String bb = " abcdefgHIGKLMN "; //果然是UTF-16
// System.out.println("字符串长度:"+bb.length());
// System.out.println("码点长度:"+bb.codePointCount(0,bb.length()));
// System.out.println(bb.trim());
String[] strings = {"A","b","c","d","E"};
// System.out.println();
Scanner scanner = new Scanner(System.in);
Console console = System.console();
String userName = console.readLine("userName");
char[] passowrd = console.readPassword("password:");
System.out.println(System.getProperty("user.dir"));
for(int i = 10;i>0;i--)
{
System.out.println(i);
}
}
}
| 1,017 | 0.58544 | 0.561173 | 42 | 22.547619 | 21.31979 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.595238 | false | false |
10
|
8c55955f788c8b14b9fc03340e7f10198bc64c0d
| 6,107,443,550,408 |
5be44f022a14d3a1587f557958d64d6958cfe9c3
|
/spring-boot/spring-boot-testing/src/main/java/io/reflectoring/testing/domain/RegisterUseCase.java
|
ae88db4ad0ec60eb80b98faa7cfeeb846a159857
|
[
"MIT"
] |
permissive
|
thombergs/code-examples
|
https://github.com/thombergs/code-examples
|
4608b7d9ea3201ffa26d305f24d1ac1aa77f2c08
|
ca500ac4d4a0e501565e30dcdea37bb17d4d26e7
|
refs/heads/master
| 2023-09-04T23:14:37.811000 | 2023-08-14T21:04:33 | 2023-08-14T21:04:33 | 98,801,926 | 2,492 | 2,710 |
MIT
| false | 2023-09-10T20:42:50 | 2017-07-30T14:12:24 | 2023-09-10T19:37:53 | 2023-09-10T20:42:49 | 121,585 | 2,429 | 2,522 | 112 |
Java
| false | false |
package io.reflectoring.testing.domain;
import java.time.LocalDateTime;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class RegisterUseCase {
private final SaveUserPort saveUserPort;
private final SendMailPort sendMailPort;
public Long registerUser(User user, boolean sendWelcomeMail) {
user.setRegistrationDate(LocalDateTime.now());
if(sendWelcomeMail){
sendMailPort.sendMail("Welcome!", "Thanks for registering.");
}
return saveUserPort.saveUser(user);
}
}
|
UTF-8
|
Java
| 579 |
java
|
RegisterUseCase.java
|
Java
|
[] | null |
[] |
package io.reflectoring.testing.domain;
import java.time.LocalDateTime;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class RegisterUseCase {
private final SaveUserPort saveUserPort;
private final SendMailPort sendMailPort;
public Long registerUser(User user, boolean sendWelcomeMail) {
user.setRegistrationDate(LocalDateTime.now());
if(sendWelcomeMail){
sendMailPort.sendMail("Welcome!", "Thanks for registering.");
}
return saveUserPort.saveUser(user);
}
}
| 579 | 0.777202 | 0.777202 | 26 | 21.26923 | 21.983486 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.423077 | false | false |
10
|
76772b68f7c10167ab0c26d2d89bade93fb92323
| 17,274,358,527,114 |
988b1fdae5e0d903ad94b1215e711de598fea9df
|
/wifi_detector/src/org/ruboto/examples/wifi_detector/WifiReceiver.java
|
1d2ef48c4c34f40e63c71e5f2f2ea899e6cca1a8
|
[] |
no_license
|
webofbits/ruboto
|
https://github.com/webofbits/ruboto
|
c18f81e9749948adc93e1bd5c0255de393709bed
|
40fcfac3e2eb1601c749d8d3a0c5aa8d73d6d78c
|
refs/heads/master
| 2018-01-11T20:43:00.718000 | 2016-03-16T12:03:56 | 2016-03-16T12:03:56 | 54,028,271 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.ruboto.examples.wifi_detector;
import org.ruboto.JRubyAdapter;
public class WifiReceiver extends org.ruboto.RubotoBroadcastReceiver {
}
|
UTF-8
|
Java
| 150 |
java
|
WifiReceiver.java
|
Java
|
[] | null |
[] |
package org.ruboto.examples.wifi_detector;
import org.ruboto.JRubyAdapter;
public class WifiReceiver extends org.ruboto.RubotoBroadcastReceiver {
}
| 150 | 0.833333 | 0.833333 | 6 | 24 | 26.362852 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
10
|
a58e3f38b094b5aedb10a96496878824fd9f2ebc
| 23,210,003,312,720 |
f9d5fe1ee766fc70569eb80e41f2caab8a835d41
|
/src/main/java/br/com/temasistemas/workshop/testes/utils/Query.java
|
445d7c3552ce9223baf7fb47211eeefd9bb735ad
|
[] |
no_license
|
temasistemas/testes
|
https://github.com/temasistemas/testes
|
7448eb734d01594937a6a861561a1e4cff7dedfa
|
e0cfe42c5bddbf3527ca2f8ed9c751a9504bde8c
|
refs/heads/master
| 2022-02-17T05:33:29.287000 | 2019-07-23T15:08:39 | 2019-07-23T15:08:39 | 193,357,027 | 1 | 0 | null | false | 2022-01-21T23:26:04 | 2019-06-23T14:20:51 | 2020-08-27T04:05:16 | 2022-01-21T23:26:03 | 729,468 | 1 | 0 | 11 |
Java
| false | false |
package br.com.temasistemas.workshop.testes.utils;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlElement;
public class Query implements Serializable {
private static final long serialVersionUID = 1L;
private String sql;
private final Map<String, Integer> indexParameter;
private String sqlParse;
public Query() {
super();
this.indexParameter = new HashMap<>();
}
public Query(final String sql) {
this();
this.sql = sql;
}
@XmlElement(required = true, nillable = false, name = "sql")
public String getSql() {
return this.sql;
}
public void setSql(final String sql) {
this.sql = sql;
}
public synchronized String getSqlParse() {
if (this.sqlParse == null) {
this.sqlParse = this.parse();
}
return this.sqlParse;
}
private String parse() {
if (this.sql == null || this.sql.trim().isEmpty()) {
throw new GenericException("Sql da query não foi informado");
}
final String query = this.sql;
final int length = query.length();
final StringBuilder parsedQuery = new StringBuilder(length);
boolean inSingleQuote = false;
boolean inDoubleQuote = false;
int index = 1;
for (int i = 0; i < length; i++) {
char c = query.charAt(i);
if (inSingleQuote) {
if (c == '\'') {
inSingleQuote = false;
}
} else if (inDoubleQuote) {
if (c == '"') {
inDoubleQuote = false;
}
} else {
if (c == '\'') {
inSingleQuote = true;
} else if (c == '"') {
inDoubleQuote = true;
} else if (c == ':' && i + 1 < length && Character.isJavaIdentifierStart(query.charAt(i + 1))) {
int j = i + 2;
while (j < length && Character.isJavaIdentifierPart(query.charAt(j))) {
j++;
}
final String name = query.substring(i + 1, j);
c = '?';
i += name.length();
this.indexParameter.put(name, index);
index++;
}
}
parsedQuery.append(c);
}
return parsedQuery.toString();
}
public Map<String, Integer> getIndexParameter() {
return this.indexParameter;
}
}
|
ISO-8859-1
|
Java
| 2,078 |
java
|
Query.java
|
Java
|
[] | null |
[] |
package br.com.temasistemas.workshop.testes.utils;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlElement;
public class Query implements Serializable {
private static final long serialVersionUID = 1L;
private String sql;
private final Map<String, Integer> indexParameter;
private String sqlParse;
public Query() {
super();
this.indexParameter = new HashMap<>();
}
public Query(final String sql) {
this();
this.sql = sql;
}
@XmlElement(required = true, nillable = false, name = "sql")
public String getSql() {
return this.sql;
}
public void setSql(final String sql) {
this.sql = sql;
}
public synchronized String getSqlParse() {
if (this.sqlParse == null) {
this.sqlParse = this.parse();
}
return this.sqlParse;
}
private String parse() {
if (this.sql == null || this.sql.trim().isEmpty()) {
throw new GenericException("Sql da query não foi informado");
}
final String query = this.sql;
final int length = query.length();
final StringBuilder parsedQuery = new StringBuilder(length);
boolean inSingleQuote = false;
boolean inDoubleQuote = false;
int index = 1;
for (int i = 0; i < length; i++) {
char c = query.charAt(i);
if (inSingleQuote) {
if (c == '\'') {
inSingleQuote = false;
}
} else if (inDoubleQuote) {
if (c == '"') {
inDoubleQuote = false;
}
} else {
if (c == '\'') {
inSingleQuote = true;
} else if (c == '"') {
inDoubleQuote = true;
} else if (c == ':' && i + 1 < length && Character.isJavaIdentifierStart(query.charAt(i + 1))) {
int j = i + 2;
while (j < length && Character.isJavaIdentifierPart(query.charAt(j))) {
j++;
}
final String name = query.substring(i + 1, j);
c = '?';
i += name.length();
this.indexParameter.put(name, index);
index++;
}
}
parsedQuery.append(c);
}
return parsedQuery.toString();
}
public Map<String, Integer> getIndexParameter() {
return this.indexParameter;
}
}
| 2,078 | 0.627829 | 0.624458 | 101 | 19.564356 | 20.121126 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.29703 | false | false |
10
|
e8985054e6a5ecdced74a017e612d253ac6132fe
| 22,832,046,199,200 |
d2144efb04fcbe6815d95b48e7638ed77d353051
|
/apiWeb/src/main/java/co/kr/daesung/app/center/api/web/aops/ResultDataFormatAdvice.java
|
67ae7a0b13693996c1417126e0ac3ef52575cae8
|
[] |
no_license
|
xyzlast/ds-common-app-center
|
https://github.com/xyzlast/ds-common-app-center
|
3dddd706c043b144163ef34dfd51e08de025aca4
|
ad7cdbd3a46a5fac056483b16d0aa6ec49eded18
|
refs/heads/master
| 2016-09-05T21:42:38.983000 | 2013-12-13T17:52:22 | 2013-12-13T17:52:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package co.kr.daesung.app.center.api.web.aops;
import co.kr.daesung.app.center.api.web.vos.ResultData;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
/**
* Created with IntelliJ IDEA.
* User: ykyoon
* Date: 11/18/13
* Time: 2:42 AM
* To change this template use File | Settings | File Templates.
*/
@Component
@Aspect
public class ResultDataFormatAdvice implements Ordered {
@Pointcut(value = "@annotation(co.kr.daesung.app.center.api.web.aops.ResultDataFormat)")
private void resultDataFormatPointcut() {
}
@Around("resultDataFormatPointcut()")
public Object wrapResponseObject(ProceedingJoinPoint pjp) throws Throwable {
try {
Object ret = pjp.proceed();
return new ResultData(ret);
} catch (Exception ex) {
return new ResultData(ex);
}
}
@Override
public int getOrder() {
return 2;
}
}
|
UTF-8
|
Java
| 1,122 |
java
|
ResultDataFormatAdvice.java
|
Java
|
[
{
"context": "nent;\n\n/**\n * Created with IntelliJ IDEA.\n * User: ykyoon\n * Date: 11/18/13\n * Time: 2:42 AM\n * To change t",
"end": 421,
"score": 0.9996420741081238,
"start": 415,
"tag": "USERNAME",
"value": "ykyoon"
}
] | null |
[] |
package co.kr.daesung.app.center.api.web.aops;
import co.kr.daesung.app.center.api.web.vos.ResultData;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
/**
* Created with IntelliJ IDEA.
* User: ykyoon
* Date: 11/18/13
* Time: 2:42 AM
* To change this template use File | Settings | File Templates.
*/
@Component
@Aspect
public class ResultDataFormatAdvice implements Ordered {
@Pointcut(value = "@annotation(co.kr.daesung.app.center.api.web.aops.ResultDataFormat)")
private void resultDataFormatPointcut() {
}
@Around("resultDataFormatPointcut()")
public Object wrapResponseObject(ProceedingJoinPoint pjp) throws Throwable {
try {
Object ret = pjp.proceed();
return new ResultData(ret);
} catch (Exception ex) {
return new ResultData(ex);
}
}
@Override
public int getOrder() {
return 2;
}
}
| 1,122 | 0.702317 | 0.693405 | 39 | 27.76923 | 23.222958 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.358974 | false | false |
10
|
1a41cd89d0337497f14c46d0b14a546cf42c0bc6
| 12,506,944,832,056 |
3206b44c9758b05aad5d8b13ca82f032f25398b3
|
/core-components/src/main/java/net/techreadiness/persistence/dao/FileDAOImpl.java
|
b678603141a1f3bce30e7acba9b34dfd333f6072
|
[
"Apache-2.0"
] |
permissive
|
SmarterApp/TechnologyReadinessTool
|
https://github.com/SmarterApp/TechnologyReadinessTool
|
0bd9c7ffc008e307ebd2834aeed160c42de3b7db
|
9cac501050fe849be5348b6a45921ce5c3ae4e00
|
refs/heads/master
| 2020-12-24T14:35:39.754000 | 2020-06-24T22:22:14 | 2020-06-24T22:22:14 | 19,116,210 | 4 | 6 |
Apache-2.0
| false | 2020-06-24T22:21:31 | 2014-04-24T16:47:20 | 2020-06-24T22:20:48 | 2020-06-24T22:21:31 | 2,444 | 8 | 14 | 5 |
Java
| false | false |
package net.techreadiness.persistence.dao;
import net.techreadiness.persistence.domain.FileDO;
import org.springframework.stereotype.Repository;
@Repository
public class FileDAOImpl extends BaseDAOImpl<FileDO> implements FileDAO {
// No additional methods are needed
}
|
UTF-8
|
Java
| 273 |
java
|
FileDAOImpl.java
|
Java
|
[] | null |
[] |
package net.techreadiness.persistence.dao;
import net.techreadiness.persistence.domain.FileDO;
import org.springframework.stereotype.Repository;
@Repository
public class FileDAOImpl extends BaseDAOImpl<FileDO> implements FileDAO {
// No additional methods are needed
}
| 273 | 0.831502 | 0.831502 | 10 | 26.299999 | 25.682873 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
10
|
f10f9a7341584e28a19c9af7d7debaa9daba4693
| 6,579,889,940,179 |
a151aa91e601862c80b92bc3e6307da6d25ffbe9
|
/src/lesson4/Prog9.java
|
558176a2dd3234d9ae69cb1c34f0392dc2268feb
|
[] |
no_license
|
ltolok/projectproject
|
https://github.com/ltolok/projectproject
|
55e257250747f64953275c9e0e8acabe098cf8bf
|
4d179818294b1223896a38db44342fbf6c91512e
|
refs/heads/master
| 2021-01-01T06:15:47.097000 | 2017-12-08T18:42:07 | 2017-12-08T18:42:07 | 97,397,006 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package lesson4;
import java.util.Scanner;
public class Prog9 {
public static void main(String[] args) {
System.out.print("Введите натуральное число: ");
Scanner scn = new Scanner(System.in);
int i, n, f;
if (scn.hasNextInt()) {
n = scn.nextInt();
if (n == 0) {
System.out.println("Факториал числа равен " + 1);
} else {
f = 1;
for (i = 1; i <= n; i++) {
f = f * i;
}
System.out.println("Факториал числа равен " + f);
}
} else {
System.out.println("Вы ввели не натуральное число");
}
}
}
|
UTF-8
|
Java
| 792 |
java
|
Prog9.java
|
Java
|
[] | null |
[] |
package lesson4;
import java.util.Scanner;
public class Prog9 {
public static void main(String[] args) {
System.out.print("Введите натуральное число: ");
Scanner scn = new Scanner(System.in);
int i, n, f;
if (scn.hasNextInt()) {
n = scn.nextInt();
if (n == 0) {
System.out.println("Факториал числа равен " + 1);
} else {
f = 1;
for (i = 1; i <= n; i++) {
f = f * i;
}
System.out.println("Факториал числа равен " + f);
}
} else {
System.out.println("Вы ввели не натуральное число");
}
}
}
| 792 | 0.447592 | 0.439093 | 25 | 27.24 | 19.625046 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false |
10
|
93f76dda90b968566e989b6ca79a9d16700d3f57
| 26,895,085,252,921 |
452d8583d31179f2ef68dbe6a71524b0718060de
|
/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/warnings/RemoveWarnings.java
|
13e40f6f0079021095f1d50035b00324953d032e
|
[
"Apache-2.0",
"Elastic-2.0",
"SSPL-1.0",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
ianuoui/elasticsearch
|
https://github.com/ianuoui/elasticsearch
|
8b22db8bdf4ebfba0f3b0e443cd4668d68ef9bf1
|
7ea2a2c4090e9af1caf29677be1bbc57d25a80a8
|
refs/heads/master
| 2023-01-25T01:41:00.686000 | 2023-01-21T20:19:44 | 2023-01-21T20:19:44 | 122,552,945 | 1 | 0 |
Apache-2.0
| true | 2018-02-23T00:35:00 | 2018-02-23T00:35:00 | 2018-02-22T23:38:03 | 2018-02-22T23:57:47 | 387,652 | 0 | 0 | 0 | null | false | null |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.gradle.internal.test.rest.transform.warnings;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.elasticsearch.gradle.internal.test.rest.transform.RestTestContext;
import org.elasticsearch.gradle.internal.test.rest.transform.RestTestTransformByParentObject;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.Optional;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* A transformation to to remove any warnings that match exactly.
* If this removes all of the warnings, this will not remove the feature from the setup and/or teardown and will leave behind an empty array
* While it would be more technically correct to do so, the effort/complexity does not warrant it, since for the expected usage it makes
* no difference.
*/
public class RemoveWarnings implements RestTestTransformByParentObject {
private final Set<String> warnings;
private String testName;
/**
* @param warnings The allowed warnings to inject
*/
public RemoveWarnings(Set<String> warnings) {
this.warnings = warnings;
}
/**
* @param warnings The allowed warnings to inject
* @param testName The testName to inject
*/
public RemoveWarnings(Set<String> warnings, String testName) {
this.warnings = warnings;
this.testName = testName;
}
@Override
public void transformTest(ObjectNode doNodeParent) {
ObjectNode doNodeValue = (ObjectNode) doNodeParent.get(getKeyToFind());
ArrayNode arrayWarnings = (ArrayNode) doNodeValue.get("warnings");
if (arrayWarnings == null) {
return;
}
List<String> keepWarnings = new ArrayList<>();
arrayWarnings.elements().forEachRemaining(warning -> {
String warningValue = warning.textValue();
if (warnings.contains(warningValue) == false) {
keepWarnings.add(warningValue);
}
});
arrayWarnings.removeAll();
keepWarnings.forEach(arrayWarnings::add);
}
@Override
@Internal
public String getKeyToFind() {
return "do";
}
@Input
public Set<String> getWarnings() {
return warnings;
}
@Override
public boolean shouldApply(RestTestContext testContext) {
return testName == null || testContext.testName().equals(testName);
}
@Input
@Optional
public String getTestName() {
return testName;
}
}
|
UTF-8
|
Java
| 2,948 |
java
|
RemoveWarnings.java
|
Java
|
[] | null |
[] |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.gradle.internal.test.rest.transform.warnings;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.elasticsearch.gradle.internal.test.rest.transform.RestTestContext;
import org.elasticsearch.gradle.internal.test.rest.transform.RestTestTransformByParentObject;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.Optional;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* A transformation to to remove any warnings that match exactly.
* If this removes all of the warnings, this will not remove the feature from the setup and/or teardown and will leave behind an empty array
* While it would be more technically correct to do so, the effort/complexity does not warrant it, since for the expected usage it makes
* no difference.
*/
public class RemoveWarnings implements RestTestTransformByParentObject {
private final Set<String> warnings;
private String testName;
/**
* @param warnings The allowed warnings to inject
*/
public RemoveWarnings(Set<String> warnings) {
this.warnings = warnings;
}
/**
* @param warnings The allowed warnings to inject
* @param testName The testName to inject
*/
public RemoveWarnings(Set<String> warnings, String testName) {
this.warnings = warnings;
this.testName = testName;
}
@Override
public void transformTest(ObjectNode doNodeParent) {
ObjectNode doNodeValue = (ObjectNode) doNodeParent.get(getKeyToFind());
ArrayNode arrayWarnings = (ArrayNode) doNodeValue.get("warnings");
if (arrayWarnings == null) {
return;
}
List<String> keepWarnings = new ArrayList<>();
arrayWarnings.elements().forEachRemaining(warning -> {
String warningValue = warning.textValue();
if (warnings.contains(warningValue) == false) {
keepWarnings.add(warningValue);
}
});
arrayWarnings.removeAll();
keepWarnings.forEach(arrayWarnings::add);
}
@Override
@Internal
public String getKeyToFind() {
return "do";
}
@Input
public Set<String> getWarnings() {
return warnings;
}
@Override
public boolean shouldApply(RestTestContext testContext) {
return testName == null || testContext.testName().equals(testName);
}
@Input
@Optional
public String getTestName() {
return testName;
}
}
| 2,948 | 0.694708 | 0.692673 | 93 | 30.698925 | 30.811527 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.430108 | false | false |
10
|
87cb628c8807122906c5a318b718d700e81b11da
| 463,856,522,010 |
a666ac40ad2c33d130d9d6b06925a5948b25cc6a
|
/JavaConcurrencyPatternInAction/src/main/java/io/github/viscent/mtpattern/ch7/pc/Channel.java
|
7e9f75c3472a2bce9f2f083396702bbf6b7f9f13
|
[] |
no_license
|
hotenglish/StudyInAction
|
https://github.com/hotenglish/StudyInAction
|
e8a46ef963be6a9c506cc4606c96a7433a974c7d
|
941d7a254dbbd22976d8110ff5cf0d18166c0462
|
refs/heads/master
| 2022-12-22T16:04:32.592000 | 2020-06-23T23:30:40 | 2020-06-23T23:30:40 | 137,567,024 | 0 | 0 | null | false | 2022-12-16T07:16:06 | 2018-06-16T08:51:49 | 2020-06-23T23:31:57 | 2022-12-16T07:16:01 | 241,099 | 0 | 0 | 107 |
HTML
| false | false |
package io.github.viscent.mtpattern.ch7.pc;
/**
* 对通道参与者进行抽象。
*
* @author Viscent Huang
*
* @param <P>
* “产品”类型
*/
public interface Channel<P> {
/**
* 从通道中取出一个“产品”。
*
* @return “产品”
* @throws InterruptedException
*/
P take() throws InterruptedException;
/**
* 往通道中存储一个“产品”。
*
* @param product
* “产品”
* @throws InterruptedException
*/
void put(P product)throws InterruptedException;
}
|
UTF-8
|
Java
| 612 |
java
|
Channel.java
|
Java
|
[
{
"context": "package io.github.viscent.mtpattern.ch7.pc;\r\n\r\n/**\r\n * 对通道参与者进行抽象。\r\n *\r\n * ",
"end": 25,
"score": 0.5914239883422852,
"start": 18,
"tag": "USERNAME",
"value": "viscent"
},
{
"context": "ern.ch7.pc;\r\n\r\n/**\r\n * 对通道参与者进行抽象。\r\n *\r\n * @author Viscent Huang\r\n *\r\n * @param <P>\r\n * “产品”类型\r\n */\r\npubl",
"end": 96,
"score": 0.9998443126678467,
"start": 83,
"tag": "NAME",
"value": "Viscent Huang"
}
] | null |
[] |
package io.github.viscent.mtpattern.ch7.pc;
/**
* 对通道参与者进行抽象。
*
* @author <NAME>
*
* @param <P>
* “产品”类型
*/
public interface Channel<P> {
/**
* 从通道中取出一个“产品”。
*
* @return “产品”
* @throws InterruptedException
*/
P take() throws InterruptedException;
/**
* 往通道中存储一个“产品”。
*
* @param product
* “产品”
* @throws InterruptedException
*/
void put(P product)throws InterruptedException;
}
| 605 | 0.515686 | 0.513726 | 28 | 16.214285 | 14.170788 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.107143 | false | false |
10
|
71d10593457ea1846e9d22a1e90c17ec1de42d9a
| 17,119,739,649,123 |
7ffa6bdfc8d548529d2dd40dea7ea411fad970ca
|
/src/gittest2/AdminUI.java
|
ebc2f3029ae91716f7a25948de789756e6d6c3f5
|
[] |
no_license
|
jobbnas/Gittest
|
https://github.com/jobbnas/Gittest
|
5f29592c3e11814fe037105e54f086b1cbf0b1dc
|
6510e187c709610ee62bef5b81c5558d6086d6c8
|
refs/heads/master
| 2021-01-19T10:11:52.588000 | 2017-05-24T11:02:49 | 2017-05-24T11:02:49 | 87,838,019 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gittest2;
import java.util.Scanner;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
*
* @author El Rey
*/
public class AdminUI extends javax.swing.JFrame {
boolean boolLäggTillP = false;
public boolean isBoolLäggTillP() {
return boolLäggTillP;
}
public void setBoolLäggTillP(boolean boolLäggTillP) {
this.boolLäggTillP = boolLäggTillP;
}
public AdminUI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Förnamn", "Efternamn", "Personnummer", "Adress", "Postnummer", "Ort", "Användarnamn", "Position", "Kompetens"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
if (jTable1.getColumnModel().getColumnCount() > 0) {
jTable1.getColumnModel().getColumn(0).setResizable(false);
jTable1.getColumnModel().getColumn(1).setResizable(false);
jTable1.getColumnModel().getColumn(2).setResizable(false);
jTable1.getColumnModel().getColumn(3).setResizable(false);
jTable1.getColumnModel().getColumn(4).setResizable(false);
jTable1.getColumnModel().getColumn(5).setResizable(false);
jTable1.getColumnModel().getColumn(6).setResizable(false);
jTable1.getColumnModel().getColumn(7).setResizable(false);
jTable1.getColumnModel().getColumn(8).setResizable(false);
}
jButton1.setText("Skapa Anställd");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Uppdatera Anställd");
jButton3.setText("Tabort Anställd");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(224, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(297, 297, 297))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 788, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton3)
.addComponent(jButton2))
.addGap(29, 29, 29)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 495, Short.MAX_VALUE)
.addGap(26, 26, 26))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
JTextField field1 = new JTextField(10),
field2 = new JTextField(10),
field3 = new JTextField(10),
field4 = new JTextField(10),
field5 = new JTextField(10),
field6 = new JTextField(10),
field7 = new JTextField(10),
field8 = new JTextField(10),
field9 = new JTextField(10),
field10 = new JTextField(10);
JPanel myPanel = new JPanel();
myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.Y_AXIS));
myPanel.add(new JLabel("Förnamn:"));
myPanel.add(field1);
myPanel.add(Box.createHorizontalStrut(5));
myPanel.add(new JLabel("Efternamn:"));
myPanel.add(field2);
myPanel.add(Box.createHorizontalStrut(5));
myPanel.add(new JLabel("Personnummer:"));
myPanel.add(field3);
myPanel.add(Box.createHorizontalStrut(5));
myPanel.add(new JLabel("Adress:"));
myPanel.add(field4);
myPanel.add(Box.createHorizontalStrut(5));
myPanel.add(new JLabel("Ort:"));
myPanel.add(field5);
myPanel.add(Box.createHorizontalStrut(5));
myPanel.add(new JLabel("Postnummer:"));
myPanel.add(field6);
myPanel.add(Box.createHorizontalStrut(5));
myPanel.add(new JLabel("Användarnamn:"));
myPanel.add(field7);
myPanel.add(Box.createHorizontalStrut(5));
myPanel.add(new JLabel("Position:"));
myPanel.add(field8);
myPanel.add(Box.createHorizontalStrut(5));
myPanel.add(new JLabel("Kompetens:"));
myPanel.add(field9);
int result = JOptionPane.showConfirmDialog(null, myPanel, "Fyll i kunduppgifter:",
JOptionPane.OK_CANCEL_OPTION);
String fNamn, eNamn, prnr,adr,or,pstnr,telnr;
Scanner input = new Scanner(System.in);
JFrame frame = new JFrame();
int id =0;
fNamn = field1.getText();
eNamn = field2.getText();
prnr = field3.getText();
adr = field4.getText();
or = field5.getText();
pstnr = field6.getText();
String anvNamn = field7.getText();
String position = field8.getText();
String komp = field9.getText();
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AdminUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AdminUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AdminUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AdminUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AdminUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
}
|
UTF-8
|
Java
| 10,204 |
java
|
AdminUI.java
|
Java
|
[
{
"context": "\nimport javax.swing.JTextField;\n\n/**\n *\n * @author El Rey\n */\npublic class AdminUI extends javax.swing.JFra",
"end": 453,
"score": 0.9998605847358704,
"start": 447,
"tag": "NAME",
"value": "El Rey"
}
] | null |
[] |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gittest2;
import java.util.Scanner;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
*
* @author <NAME>
*/
public class AdminUI extends javax.swing.JFrame {
boolean boolLäggTillP = false;
public boolean isBoolLäggTillP() {
return boolLäggTillP;
}
public void setBoolLäggTillP(boolean boolLäggTillP) {
this.boolLäggTillP = boolLäggTillP;
}
public AdminUI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Förnamn", "Efternamn", "Personnummer", "Adress", "Postnummer", "Ort", "Användarnamn", "Position", "Kompetens"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
if (jTable1.getColumnModel().getColumnCount() > 0) {
jTable1.getColumnModel().getColumn(0).setResizable(false);
jTable1.getColumnModel().getColumn(1).setResizable(false);
jTable1.getColumnModel().getColumn(2).setResizable(false);
jTable1.getColumnModel().getColumn(3).setResizable(false);
jTable1.getColumnModel().getColumn(4).setResizable(false);
jTable1.getColumnModel().getColumn(5).setResizable(false);
jTable1.getColumnModel().getColumn(6).setResizable(false);
jTable1.getColumnModel().getColumn(7).setResizable(false);
jTable1.getColumnModel().getColumn(8).setResizable(false);
}
jButton1.setText("Skapa Anställd");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Uppdatera Anställd");
jButton3.setText("Tabort Anställd");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(224, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(297, 297, 297))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 788, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton3)
.addComponent(jButton2))
.addGap(29, 29, 29)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 495, Short.MAX_VALUE)
.addGap(26, 26, 26))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
JTextField field1 = new JTextField(10),
field2 = new JTextField(10),
field3 = new JTextField(10),
field4 = new JTextField(10),
field5 = new JTextField(10),
field6 = new JTextField(10),
field7 = new JTextField(10),
field8 = new JTextField(10),
field9 = new JTextField(10),
field10 = new JTextField(10);
JPanel myPanel = new JPanel();
myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.Y_AXIS));
myPanel.add(new JLabel("Förnamn:"));
myPanel.add(field1);
myPanel.add(Box.createHorizontalStrut(5));
myPanel.add(new JLabel("Efternamn:"));
myPanel.add(field2);
myPanel.add(Box.createHorizontalStrut(5));
myPanel.add(new JLabel("Personnummer:"));
myPanel.add(field3);
myPanel.add(Box.createHorizontalStrut(5));
myPanel.add(new JLabel("Adress:"));
myPanel.add(field4);
myPanel.add(Box.createHorizontalStrut(5));
myPanel.add(new JLabel("Ort:"));
myPanel.add(field5);
myPanel.add(Box.createHorizontalStrut(5));
myPanel.add(new JLabel("Postnummer:"));
myPanel.add(field6);
myPanel.add(Box.createHorizontalStrut(5));
myPanel.add(new JLabel("Användarnamn:"));
myPanel.add(field7);
myPanel.add(Box.createHorizontalStrut(5));
myPanel.add(new JLabel("Position:"));
myPanel.add(field8);
myPanel.add(Box.createHorizontalStrut(5));
myPanel.add(new JLabel("Kompetens:"));
myPanel.add(field9);
int result = JOptionPane.showConfirmDialog(null, myPanel, "Fyll i kunduppgifter:",
JOptionPane.OK_CANCEL_OPTION);
String fNamn, eNamn, prnr,adr,or,pstnr,telnr;
Scanner input = new Scanner(System.in);
JFrame frame = new JFrame();
int id =0;
fNamn = field1.getText();
eNamn = field2.getText();
prnr = field3.getText();
adr = field4.getText();
or = field5.getText();
pstnr = field6.getText();
String anvNamn = field7.getText();
String position = field8.getText();
String komp = field9.getText();
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AdminUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AdminUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AdminUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AdminUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AdminUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
}
| 10,204 | 0.602257 | 0.586555 | 267 | 37.164795 | 31.343855 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.659176 | false | false |
10
|
06635e4f0d3d947245542792e0dcf3d479da6965
| 10,539,849,810,587 |
dcfa3f8e6cd30c63dfda761fddc8bce15ac3c691
|
/app/src/main/java/com/demo/samt/parkdemo1/welecomeActivity.java
|
cc545ccc63108ae993ebaf76a3b2cdcca23772ad
|
[] |
no_license
|
PabloLema/24FINDCLIENTES
|
https://github.com/PabloLema/24FINDCLIENTES
|
e0f28c6795f218363083e68e9cf869dae3ee4411
|
216d48b01448797d59a71ebd15514e9301032184
|
refs/heads/master
| 2021-05-03T22:21:49.905000 | 2018-02-06T02:46:25 | 2018-02-06T02:46:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.demo.samt.parkdemo1;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
public class welecomeActivity extends AppCompatActivity implements View.OnClickListener {
LinearLayout l1,l2;
Button btntodos,btnparqueadero;
Animation uptodown,downtoup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welecome);
btntodos = (Button)findViewById(R.id.buttonsub);
btntodos.setOnClickListener(this);
btnparqueadero = (Button)findViewById(R.id.btnpar);
btnparqueadero.setOnClickListener(this);
l1 = (LinearLayout) findViewById(R.id.l1);
//l2 = (LinearLayout) findViewById(R.id.l2);
uptodown = AnimationUtils.loadAnimation(this,R.anim.uptodown);
downtoup = AnimationUtils.loadAnimation(this,R.anim.downtoup);
l1.setAnimation(uptodown);
// l2.setAnimation(downtoup);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.buttonsub:
Intent intent1 = new Intent(this,LoginLocales.class);
startActivity(intent1);
break;
case R.id.btnpar:
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
break;
default:
break;
}
}
}
|
UTF-8
|
Java
| 1,671 |
java
|
welecomeActivity.java
|
Java
|
[] | null |
[] |
package com.demo.samt.parkdemo1;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
public class welecomeActivity extends AppCompatActivity implements View.OnClickListener {
LinearLayout l1,l2;
Button btntodos,btnparqueadero;
Animation uptodown,downtoup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welecome);
btntodos = (Button)findViewById(R.id.buttonsub);
btntodos.setOnClickListener(this);
btnparqueadero = (Button)findViewById(R.id.btnpar);
btnparqueadero.setOnClickListener(this);
l1 = (LinearLayout) findViewById(R.id.l1);
//l2 = (LinearLayout) findViewById(R.id.l2);
uptodown = AnimationUtils.loadAnimation(this,R.anim.uptodown);
downtoup = AnimationUtils.loadAnimation(this,R.anim.downtoup);
l1.setAnimation(uptodown);
// l2.setAnimation(downtoup);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.buttonsub:
Intent intent1 = new Intent(this,LoginLocales.class);
startActivity(intent1);
break;
case R.id.btnpar:
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
break;
default:
break;
}
}
}
| 1,671 | 0.664273 | 0.657092 | 49 | 33.102039 | 21.313257 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.77551 | false | false |
10
|
b132afd849b1338502f2bb8502c09beeb998dcfb
| 28,003,186,829,864 |
3e3a8497675f80061602d23e4e79a96951cfa1fa
|
/src/main/java/com/fdmgroup/basket/FruitEntity.java
|
25c9c0fef357ac72f4e0cdbb00b8dcf0e7f20966
|
[] |
no_license
|
FahadBaig2016/BasketThirdAttempt
|
https://github.com/FahadBaig2016/BasketThirdAttempt
|
2a8f182bbbb8e823fe6db5e6322da90f37f1f628
|
5fbb2843e2f54ad58a1ee74a6b07e8e9608f6b97
|
refs/heads/master
| 2021-05-11T06:06:59.950000 | 2018-01-18T12:33:20 | 2018-01-18T12:33:20 | 117,979,803 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.fdmgroup.basket;
import java.util.ArrayList;
import java.util.List;
public class FruitEntity {
private double price;
private String name;
List<FruitEntity> fruitlist = new ArrayList<FruitEntity>();
public FruitEntity() {
}
public FruitEntity(String name, double price) {
this.name = name;
this.price = price;
fruitlist.add(this);
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
UTF-8
|
Java
| 618 |
java
|
FruitEntity.java
|
Java
|
[] | null |
[] |
package com.fdmgroup.basket;
import java.util.ArrayList;
import java.util.List;
public class FruitEntity {
private double price;
private String name;
List<FruitEntity> fruitlist = new ArrayList<FruitEntity>();
public FruitEntity() {
}
public FruitEntity(String name, double price) {
this.name = name;
this.price = price;
fruitlist.add(this);
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 618 | 0.660194 | 0.660194 | 36 | 15.166667 | 15.168498 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.194444 | false | false |
10
|
6defc4f4d147db4ea8276d7586bda654587d4c68
| 8,967,891,776,955 |
d6b6abe73a0c82656b04875135b4888c644d2557
|
/sources/com/google/android/gms/internal/ads/ahi.java
|
afaa7fee94d476a58bd18b7d8872f2036ded3edf
|
[] |
no_license
|
chanyaz/and_unimed
|
https://github.com/chanyaz/and_unimed
|
4344d1a8ce8cb13b6880ca86199de674d770304b
|
fb74c460f8c536c16cca4900da561c78c7035972
|
refs/heads/master
| 2020-03-29T09:07:09.224000 | 2018-08-30T06:29:32 | 2018-08-30T06:29:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.google.android.gms.internal.ads;
import com.mopub.volley.DefaultRetryPolicy;
public final class ahi implements zzab {
private int a;
private int b;
private final int c;
private final float d;
public ahi() {
this(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, 1, 1.0f);
}
private ahi(int i, int i2, float f) {
this.a = DefaultRetryPolicy.DEFAULT_TIMEOUT_MS;
this.c = 1;
this.d = 1.0f;
}
public final void zza(zzae zzae) {
this.b++;
this.a = (int) (((float) this.a) + (((float) this.a) * this.d));
if ((this.b <= this.c ? 1 : null) == null) {
throw zzae;
}
}
public final int zzc() {
return this.a;
}
public final int zzd() {
return this.b;
}
}
|
UTF-8
|
Java
| 802 |
java
|
ahi.java
|
Java
|
[] | null |
[] |
package com.google.android.gms.internal.ads;
import com.mopub.volley.DefaultRetryPolicy;
public final class ahi implements zzab {
private int a;
private int b;
private final int c;
private final float d;
public ahi() {
this(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, 1, 1.0f);
}
private ahi(int i, int i2, float f) {
this.a = DefaultRetryPolicy.DEFAULT_TIMEOUT_MS;
this.c = 1;
this.d = 1.0f;
}
public final void zza(zzae zzae) {
this.b++;
this.a = (int) (((float) this.a) + (((float) this.a) * this.d));
if ((this.b <= this.c ? 1 : null) == null) {
throw zzae;
}
}
public final int zzc() {
return this.a;
}
public final int zzd() {
return this.b;
}
}
| 802 | 0.552369 | 0.542394 | 36 | 21.277779 | 19.347137 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.527778 | false | false |
10
|
25429d698ab6ad1f7f068cf539db5e9654c2ca03
| 4,398,046,512,903 |
17856b68942cf9811463e8151610b8c6c7e564ab
|
/JavaIoExcie/src/Main.java
|
a8cc75a7313bd86bb95af13ceec8c027e97bb45d
|
[] |
no_license
|
killjas/GARIFULLIN_11_703
|
https://github.com/killjas/GARIFULLIN_11_703
|
178fc78ab05eae555f822b51a1500182ed1c749e
|
bdd16b06a237504dc861893fd931c42a49c8072b
|
refs/heads/master
| 2021-10-19T12:14:11.118000 | 2019-02-20T18:49:45 | 2019-02-20T18:49:45 | 105,008,730 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner();
int integer = scanner.nextInt();
System.out.println(integer);
integer = scanner.nextInt();
System.out.println(integer);
integer = scanner.nextInt();
System.out.println(integer);
}
}
|
UTF-8
|
Java
| 394 |
java
|
Main.java
|
Java
|
[] | null |
[] |
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner();
int integer = scanner.nextInt();
System.out.println(integer);
integer = scanner.nextInt();
System.out.println(integer);
integer = scanner.nextInt();
System.out.println(integer);
}
}
| 394 | 0.619289 | 0.619289 | 18 | 20.833334 | 19.653244 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false |
10
|
7a18760141a5c7680371b10f85ee232321b656e2
| 35,742,717,868,527 |
f634ac0e874e3147407a352e43403168b373875f
|
/src-intf/eayun-dashboard-intf/src/main/java/com/eayun/dashboard/ecmcservice/EcmcOverviewService.java
|
fe9b6009321088ea4f431923a336907d583c2b8f
|
[] |
no_license
|
yapengsong/business
|
https://github.com/yapengsong/business
|
82d49442c1d546029c3449909b37c772b17bbef1
|
f876cf82e1c08a91770ea58582719cda4e7927aa
|
refs/heads/master
| 2021-01-19T21:44:35.104000 | 2017-04-19T03:33:24 | 2017-04-19T03:33:24 | 88,695,172 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.eayun.dashboard.ecmcservice;
import java.util.Date;
import java.util.List;
import org.quartz.JobDataMap;
import com.alibaba.fastjson.JSONObject;
import com.eayun.common.dao.ParamsMap;
import com.eayun.common.dao.QueryMap;
import com.eayun.common.dao.support.Page;
import com.eayun.customer.model.BaseCustomer;
import com.eayun.dashboard.model.OverviewIncomeData;
import com.eayun.datacenter.model.DcDataCenter;
import com.eayun.sys.model.SysDataTree;
import com.eayun.virtualization.model.CloudProject;
import com.eayun.virtualization.model.CloudProjectType;
public interface EcmcOverviewService {
public List<SysDataTree> getResourceTypeList();
public List<DcDataCenter> getDcResourceList(String resourceType, String sortType);
public Page getListPrjResource(Page page,ParamsMap map,QueryMap queryMap) throws Exception;
public List<BaseCustomer> getAllCustomerList();
public List<CloudProject> getAllProjectList();
public List<CloudProject> getprojectListByCusId(String cusId);
public List<DcDataCenter> getAlldcList();
public List<CloudProject> getprojectListByDcId(String dcId);
public JSONObject getNowTime() throws Exception;
public CloudProjectType getAllProjectsType();
public CloudProjectType getNowCusToMonths(String type) throws Exception;
public List<String> getYears();
/**
* 查询总览收入统计数据
* @author bo.zeng@eayun.com
* @return
*/
public OverviewIncomeData getIncomeData(String periodType, String searchYear);
/**
* 采集总览收入统计数据(除图表数据以外的)
* @author bo.zeng@eayun.com
*/
public void gatherOverviewIncomeData();
/**
* 采集总览收入统计(图表数据)
* @author bo.zeng@eayun.com
*/
public void gatherOverviewIncomeChart();
}
|
UTF-8
|
Java
| 1,780 |
java
|
EcmcOverviewService.java
|
Java
|
[
{
"context": "ing> getYears();\n\t\n\t/**\n\t * 查询总览收入统计数据\n\t * @author bo.zeng@eayun.com\n\t * @return\n\t */\n\tpublic OverviewIncomeData getIn",
"end": 1381,
"score": 0.9999276399612427,
"start": 1364,
"tag": "EMAIL",
"value": "bo.zeng@eayun.com"
},
{
"context": "Year);\n\t\n\t/**\n\t * 采集总览收入统计数据(除图表数据以外的)\n\t * @author bo.zeng@eayun.com\n\t */\n\tpublic void gatherOverviewIncomeData();\n\t\n\t",
"end": 1540,
"score": 0.9999278783798218,
"start": 1523,
"tag": "EMAIL",
"value": "bo.zeng@eayun.com"
},
{
"context": "ncomeData();\n\t\n\t/**\n\t * 采集总览收入统计(图表数据)\n\t * @author bo.zeng@eayun.com\n\t */\n\tpublic void gatherOverviewInco",
"end": 1629,
"score": 0.9469356536865234,
"start": 1625,
"tag": "USERNAME",
"value": "bo.z"
},
{
"context": "Data();\n\t\n\t/**\n\t * 采集总览收入统计(图表数据)\n\t * @author bo.zeng@eayun.com\n\t */\n\tpublic void gatherOverviewIncomeChart();\n}\n",
"end": 1642,
"score": 0.9989590048789978,
"start": 1629,
"tag": "EMAIL",
"value": "eng@eayun.com"
}
] | null |
[] |
package com.eayun.dashboard.ecmcservice;
import java.util.Date;
import java.util.List;
import org.quartz.JobDataMap;
import com.alibaba.fastjson.JSONObject;
import com.eayun.common.dao.ParamsMap;
import com.eayun.common.dao.QueryMap;
import com.eayun.common.dao.support.Page;
import com.eayun.customer.model.BaseCustomer;
import com.eayun.dashboard.model.OverviewIncomeData;
import com.eayun.datacenter.model.DcDataCenter;
import com.eayun.sys.model.SysDataTree;
import com.eayun.virtualization.model.CloudProject;
import com.eayun.virtualization.model.CloudProjectType;
public interface EcmcOverviewService {
public List<SysDataTree> getResourceTypeList();
public List<DcDataCenter> getDcResourceList(String resourceType, String sortType);
public Page getListPrjResource(Page page,ParamsMap map,QueryMap queryMap) throws Exception;
public List<BaseCustomer> getAllCustomerList();
public List<CloudProject> getAllProjectList();
public List<CloudProject> getprojectListByCusId(String cusId);
public List<DcDataCenter> getAlldcList();
public List<CloudProject> getprojectListByDcId(String dcId);
public JSONObject getNowTime() throws Exception;
public CloudProjectType getAllProjectsType();
public CloudProjectType getNowCusToMonths(String type) throws Exception;
public List<String> getYears();
/**
* 查询总览收入统计数据
* @author <EMAIL>
* @return
*/
public OverviewIncomeData getIncomeData(String periodType, String searchYear);
/**
* 采集总览收入统计数据(除图表数据以外的)
* @author <EMAIL>
*/
public void gatherOverviewIncomeData();
/**
* 采集总览收入统计(图表数据)
* @author bo.z<EMAIL>
*/
public void gatherOverviewIncomeChart();
}
| 1,754 | 0.789598 | 0.789598 | 63 | 25.857143 | 24.81286 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.126984 | false | false |
10
|
ce04126bbe2f9e272ae8761e0de52e8d15b45d1e
| 36,197,984,404,368 |
9be9ad445372b76079094549cd3498d6d0dc607d
|
/spring-study/src/main/java/com/tron/spring/profile/Start.java
|
85929e15e68851a130d49fcd37a6c6c94d268daf
|
[] |
no_license
|
tronnort/tsc
|
https://github.com/tronnort/tsc
|
000c23b3e8ffb7198ec62804ccd1370a23066035
|
60eb45fda7184c45d9315b745b8a0c255e0e69ae
|
refs/heads/master
| 2022-07-12T23:22:28.259000 | 2019-12-01T17:19:06 | 2019-12-01T17:19:06 | 213,891,813 | 0 | 0 | null | false | 2022-06-29T17:43:10 | 2019-10-09T10:44:52 | 2019-12-01T17:25:24 | 2022-06-29T17:43:09 | 248 | 0 | 0 | 2 |
Java
| false | false |
package com.tron.spring.profile;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @description TODO
* @auther gaoli
* @create 2019-11-27
*/
public class Start {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
applicationContext.getEnvironment().setActiveProfiles("dev");
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
for (String name : beanDefinitionNames) {
System.out.println(name);
}
}
}
|
UTF-8
|
Java
| 631 |
java
|
Start.java
|
Java
|
[
{
"context": "ationContext;\n\n/**\n * @description TODO\n * @auther gaoli\n * @create 2019-11-27\n */\npublic class Start {\n ",
"end": 158,
"score": 0.9994609355926514,
"start": 153,
"tag": "USERNAME",
"value": "gaoli"
}
] | null |
[] |
package com.tron.spring.profile;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @description TODO
* @auther gaoli
* @create 2019-11-27
*/
public class Start {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
applicationContext.getEnvironment().setActiveProfiles("dev");
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
for (String name : beanDefinitionNames) {
System.out.println(name);
}
}
}
| 631 | 0.724247 | 0.711569 | 21 | 29.047619 | 32.756645 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false |
10
|
13fab09c5f1fe28f137930e8b4d9a855d87c0a20
| 1,717,986,958,501 |
bcd7fce9f6bc97083da9c23eba4bba1a4c3eb465
|
/android/mxYoutubeApp/tools/java2objc/src/main/java/com/google/code/java2objc/code/ObjcExpressionBinary.java
|
5f4af2c33d18edeea69bf4167ba3066c792782c8
|
[] |
no_license
|
wanghaogithub720/mxYoutube
|
https://github.com/wanghaogithub720/mxYoutube
|
d187254b00c9394a71c1e0c919e71a6014a0ee74
|
d5c99b8eb80e8939e502a5a99e562b644779f74b
|
refs/heads/master
| 2016-09-05T18:32:31.411000 | 2014-10-23T03:15:49 | 2014-10-23T03:15:49 | 23,252,766 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright (C) 2009 Inderjeet Singh
*
* 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.code.java2objc.code;
import japa.parser.ast.expr.BinaryExpr;
import com.googlecode.java2objc.objc.CompilationContext;
import com.googlecode.java2objc.objc.ObjcOperator;
import com.googlecode.java2objc.objc.SourceCodeWriter;
/**
* A binary expression in Objective C
*
* @author Inderjeet Singh
*/
public class ObjcExpressionBinary extends ObjcExpression {
private final ObjcOperator operator;
private final ObjcExpression left;
private final ObjcExpression right;
public ObjcExpressionBinary(CompilationContext context, BinaryExpr expr) {
this(new ObjcOperator(expr.getOperator()), context.getExpressionConverter().to(expr.getLeft()),
context.getExpressionConverter().to(expr.getRight()));
}
public ObjcExpressionBinary(ObjcOperator operator, ObjcExpression left, ObjcExpression right) {
super((ObjcType)null);
this.operator = operator;
this.left = left;
this.right = right;
}
public ObjcOperator getOperator() {
return operator;
}
public ObjcExpression getLeft() {
return left;
}
public ObjcExpression getRight() {
return right;
}
@Override
public void append(SourceCodeWriter writer) {
if ("+".equals(operator.getOperator()) && (isString(left) || isString(right))) {
writer.append('[').append(left).append(" stringByAppendingString:").append(right).append(']');
} else {
writer.append(left).append(" ");
writer.append(operator).append(" ");
writer.append(right);
}
}
private boolean isString(ObjcExpression expr) {
return expr.getType() != null && "NSString".equals(expr.getType().getName());
}
}
|
UTF-8
|
Java
| 2,248 |
java
|
ObjcExpressionBinary.java
|
Java
|
[
{
"context": "/*\n * Copyright (C) 2009 Inderjeet Singh\n *\n * Licensed under the Apache License, Version ",
"end": 40,
"score": 0.9998863339424133,
"start": 25,
"tag": "NAME",
"value": "Inderjeet Singh"
},
{
"context": " A binary expression in Objective C\n * \n * @author Inderjeet Singh\n */\npublic class ObjcExpressionBinary extends Obj",
"end": 917,
"score": 0.9998899102210999,
"start": 902,
"tag": "NAME",
"value": "Inderjeet Singh"
}
] | null |
[] |
/*
* Copyright (C) 2009 <NAME>
*
* 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.code.java2objc.code;
import japa.parser.ast.expr.BinaryExpr;
import com.googlecode.java2objc.objc.CompilationContext;
import com.googlecode.java2objc.objc.ObjcOperator;
import com.googlecode.java2objc.objc.SourceCodeWriter;
/**
* A binary expression in Objective C
*
* @author <NAME>
*/
public class ObjcExpressionBinary extends ObjcExpression {
private final ObjcOperator operator;
private final ObjcExpression left;
private final ObjcExpression right;
public ObjcExpressionBinary(CompilationContext context, BinaryExpr expr) {
this(new ObjcOperator(expr.getOperator()), context.getExpressionConverter().to(expr.getLeft()),
context.getExpressionConverter().to(expr.getRight()));
}
public ObjcExpressionBinary(ObjcOperator operator, ObjcExpression left, ObjcExpression right) {
super((ObjcType)null);
this.operator = operator;
this.left = left;
this.right = right;
}
public ObjcOperator getOperator() {
return operator;
}
public ObjcExpression getLeft() {
return left;
}
public ObjcExpression getRight() {
return right;
}
@Override
public void append(SourceCodeWriter writer) {
if ("+".equals(operator.getOperator()) && (isString(left) || isString(right))) {
writer.append('[').append(left).append(" stringByAppendingString:").append(right).append(']');
} else {
writer.append(left).append(" ");
writer.append(operator).append(" ");
writer.append(right);
}
}
private boolean isString(ObjcExpression expr) {
return expr.getType() != null && "NSString".equals(expr.getType().getName());
}
}
| 2,230 | 0.721975 | 0.716637 | 73 | 29.794521 | 28.710152 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.452055 | false | false |
10
|
a3583b9e47c7ef61ca67f7709804890c5ad165b5
| 34,179,349,788,285 |
141302bdd235602f64155fb70e13daa009e2a478
|
/spring-demo/src/pack/Identifier.java
|
f75991d088967d686dd8489f23bf067eb8a4303a
|
[] |
no_license
|
swathid20/eclipseexamples
|
https://github.com/swathid20/eclipseexamples
|
8bd6ffc7e5d1a8ba57171cb20ff7761aa770e05a
|
fd09cfea9ef14cc2bcde330e6d5f2667b54fd288
|
refs/heads/master
| 2021-04-15T13:43:35.390000 | 2018-03-26T03:09:36 | 2018-03-26T03:09:36 | 126,766,388 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pack;
public interface Identifier {
void display();
}
|
UTF-8
|
Java
| 63 |
java
|
Identifier.java
|
Java
|
[] | null |
[] |
package pack;
public interface Identifier {
void display();
}
| 63 | 0.746032 | 0.746032 | 5 | 11.6 | 10.613199 | 29 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
10
|
286c9779658851229ee2a0b4f02529c629e52892
| 18,734,647,406,081 |
8dc60c5709cfd1f4debaeeec2f3b82075f8c0eca
|
/laher-cloud-app/laher-cloud-school/laher-cloud-school-api/src/main/java/com/laher/school/api/StudentApi.java
|
167cb9248a07af1468784e9eff89ae66af0e2fdb
|
[] |
no_license
|
moutainhigh/laher-cloud
|
https://github.com/moutainhigh/laher-cloud
|
9cc077776d8c833599d91634dd6de6feaac6d899
|
680e0e749fc04559143d37f8b072ef23c7cc13b0
|
refs/heads/master
| 2020-09-29T10:01:25.139000 | 2019-12-09T08:14:50 | 2019-12-09T08:14:50 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.laher.school.api;
import com.laher.common.entity.ResultInfo;
import com.laher.school.fallback.factory.StudentFallbackFactory;
import com.laher.school.vo.StudentVo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.List;
/**
* 描述
* <p>
* hystrix熔断工厂后续需要统一处理
*
* @author 李亚男(laher)
* @version 1.0.0
* @date 2019/11/8
*/
/** hystrix 不填充fallbackFactory则走统一自定义熔断器 **/
// @FeignClient(value = "laher-school", path = "/student", fallbackFactory = StudentFallbackFactory.class)
@FeignClient(value = "laher-school", path = "/student")
public interface StudentApi {
/**
* 查询所有学生
*
* @return 结果
*/
@GetMapping("/findAll")
ResultInfo<List<StudentVo>> findAll();
}
|
UTF-8
|
Java
| 867 |
java
|
StudentApi.java
|
Java
|
[
{
"context": " * 描述\n * <p>\n * hystrix熔断工厂后续需要统一处理\n *\n * @author 李亚男(laher)\n * @version 1.0.0\n * @date 2019/11/8\n */\n\n",
"end": 374,
"score": 0.997868001461029,
"start": 371,
"tag": "NAME",
"value": "李亚男"
},
{
"context": "述\n * <p>\n * hystrix熔断工厂后续需要统一处理\n *\n * @author 李亚男(laher)\n * @version 1.0.0\n * @date 2019/11/8\n */\n\n/** hy",
"end": 380,
"score": 0.9993408918380737,
"start": 375,
"tag": "USERNAME",
"value": "laher"
}
] | null |
[] |
package com.laher.school.api;
import com.laher.common.entity.ResultInfo;
import com.laher.school.fallback.factory.StudentFallbackFactory;
import com.laher.school.vo.StudentVo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.List;
/**
* 描述
* <p>
* hystrix熔断工厂后续需要统一处理
*
* @author 李亚男(laher)
* @version 1.0.0
* @date 2019/11/8
*/
/** hystrix 不填充fallbackFactory则走统一自定义熔断器 **/
// @FeignClient(value = "laher-school", path = "/student", fallbackFactory = StudentFallbackFactory.class)
@FeignClient(value = "laher-school", path = "/student")
public interface StudentApi {
/**
* 查询所有学生
*
* @return 结果
*/
@GetMapping("/findAll")
ResultInfo<List<StudentVo>> findAll();
}
| 867 | 0.710493 | 0.697851 | 33 | 22.969696 | 24.169209 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
10
|
06cb4347d33d45caf0516b63e9d8d787cf30c5ea
| 8,014,409,002,662 |
a566a36c2da7d50cd197376d0c0e4c08121a9f59
|
/src/main/java/patryk/zadania/ex3/Uczen.java
|
6f7cef31d7037e907b79f5988fc2d12781fc5ed8
|
[] |
no_license
|
PatrykMarcisz/javakrk25-zaawansowana
|
https://github.com/PatrykMarcisz/javakrk25-zaawansowana
|
9300c0c1df6004beaf5fe38e27dcc6a42e79573b
|
f9bf09dd9f7fa442af3af2cef4cd867a0790ff4a
|
refs/heads/master
| 2021-01-01T11:59:38.037000 | 2020-04-19T11:46:37 | 2020-04-19T11:46:37 | 239,268,551 | 0 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package patryk.zadania.ex3;
//3. Utwórz klasę Uczen, dziedziczaca po klasie Osoba
public class Uczen extends Osoba {
public Uczen(String imie, String nazwisko, String pesel) {
super(imie, nazwisko, pesel);
}
public Uczen(Uczen uczen){
super(uczen);
}
public Uczen(Osoba osoba){
super(osoba);
}
}
|
UTF-8
|
Java
| 349 |
java
|
Uczen.java
|
Java
|
[] | null |
[] |
package patryk.zadania.ex3;
//3. Utwórz klasę Uczen, dziedziczaca po klasie Osoba
public class Uczen extends Osoba {
public Uczen(String imie, String nazwisko, String pesel) {
super(imie, nazwisko, pesel);
}
public Uczen(Uczen uczen){
super(uczen);
}
public Uczen(Osoba osoba){
super(osoba);
}
}
| 349 | 0.642651 | 0.636888 | 16 | 20.6875 | 19.068031 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5625 | false | false |
10
|
e0ea369635d0a630337085b17c09b4d9c8a3f7b1
| 32,573,031,977,023 |
cc4dfd27d781621d3ee261c9ad2924c532c43e95
|
/ltwclient_source.bak/client/src/main/java/org/evan/LeadTheWay/client/main.java
|
e4d10738e6bb527e3a8fcba1beaf0340e36ca2d6
|
[] |
no_license
|
evanritz/LeadTheWay
|
https://github.com/evanritz/LeadTheWay
|
41d6b5cdad1479c794ff7bd6b4c9b370ec03d7b8
|
d72ed458c11c409bf365990cce45aa317b72bb5a
|
refs/heads/master
| 2022-11-06T11:56:44.628000 | 2020-06-20T01:10:12 | 2020-06-20T01:10:12 | 273,614,674 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.evan.LeadTheWay.client;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import fi.iki.elonen.NanoHTTPD;
import fi.iki.elonen.NanoHTTPD.Method;
public class main extends NanoHTTPD{
private static responseservice responseservice = null;
private static requestservice requestservice = null;
private static hostname client_hostname = null;
private static server server = null;
public main(int httpport, String dir_name) throws IOException
{
super(httpport);
System.out.printf(" LTW CLIENT : STARTING UP.... \n");
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
System.out.printf(" -> Spawning http server on localhost. PORT=%d\n", httpport);
responseservice = new responseservice(client_hostname, server, dir_name);
requestservice = new requestservice(client_hostname, server);
if (server.firsttime) { requestservice.initServer(); server.firsttime = false; responseservice.saveServer(); }
System.out.printf(" LTW CLIENT : STARTUP COMPLETE!\n");
}
public static void main(String[] args)
{
int httpport = 0; String dir_name = null;
if (args.length == 2) { httpport = Integer.parseInt(args[0]); dir_name = args[1]; client_hostname = new hostname(); server = new server(); }
else if (args.length == 4) { httpport = Integer.parseInt(args[0]); dir_name = args[1]; client_hostname = new hostname(args[2]); server = new server(args[3]); }
else { System.out.printf(" LTW CLIENT : args -> httpport, serverdirectory, .onion hostname, .onion server hostname OR httpport, serverdirectory"); System.exit(0); }
try { new main(httpport, dir_name); } catch (IOException ioe) { ioe.printStackTrace(); }
}
public Response serve(IHTTPSession session)
{
HashMap<String, String> session_map = new HashMap<String, String>();
Map<String, String> params = session.getParms();
Method method = session.getMethod();
String uri = session.getUri();
try {
session.parseBody(session_map);
if (Method.GET.equals(method))
{
switch (uri)
{
case "/ping": requestservice.sendData(); return responseservice.ok();
default: return responseservice.not_found();
}
}
else if (Method.POST.equals(method))
{
switch (uri)
{
case "/updateserver": return responseservice.changeServerAddress(params);
default: return responseservice.not_found();
}
}
else
{
return responseservice.bad_request();
}
}
catch (IOException ioe) { ioe.printStackTrace(); }
catch (ResponseException re) { re.printStackTrace(); }
return responseservice.not_found();
}
}
|
UTF-8
|
Java
| 2,750 |
java
|
main.java
|
Java
|
[] | null |
[] |
package org.evan.LeadTheWay.client;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import fi.iki.elonen.NanoHTTPD;
import fi.iki.elonen.NanoHTTPD.Method;
public class main extends NanoHTTPD{
private static responseservice responseservice = null;
private static requestservice requestservice = null;
private static hostname client_hostname = null;
private static server server = null;
public main(int httpport, String dir_name) throws IOException
{
super(httpport);
System.out.printf(" LTW CLIENT : STARTING UP.... \n");
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
System.out.printf(" -> Spawning http server on localhost. PORT=%d\n", httpport);
responseservice = new responseservice(client_hostname, server, dir_name);
requestservice = new requestservice(client_hostname, server);
if (server.firsttime) { requestservice.initServer(); server.firsttime = false; responseservice.saveServer(); }
System.out.printf(" LTW CLIENT : STARTUP COMPLETE!\n");
}
public static void main(String[] args)
{
int httpport = 0; String dir_name = null;
if (args.length == 2) { httpport = Integer.parseInt(args[0]); dir_name = args[1]; client_hostname = new hostname(); server = new server(); }
else if (args.length == 4) { httpport = Integer.parseInt(args[0]); dir_name = args[1]; client_hostname = new hostname(args[2]); server = new server(args[3]); }
else { System.out.printf(" LTW CLIENT : args -> httpport, serverdirectory, .onion hostname, .onion server hostname OR httpport, serverdirectory"); System.exit(0); }
try { new main(httpport, dir_name); } catch (IOException ioe) { ioe.printStackTrace(); }
}
public Response serve(IHTTPSession session)
{
HashMap<String, String> session_map = new HashMap<String, String>();
Map<String, String> params = session.getParms();
Method method = session.getMethod();
String uri = session.getUri();
try {
session.parseBody(session_map);
if (Method.GET.equals(method))
{
switch (uri)
{
case "/ping": requestservice.sendData(); return responseservice.ok();
default: return responseservice.not_found();
}
}
else if (Method.POST.equals(method))
{
switch (uri)
{
case "/updateserver": return responseservice.changeServerAddress(params);
default: return responseservice.not_found();
}
}
else
{
return responseservice.bad_request();
}
}
catch (IOException ioe) { ioe.printStackTrace(); }
catch (ResponseException re) { re.printStackTrace(); }
return responseservice.not_found();
}
}
| 2,750 | 0.670182 | 0.666545 | 76 | 34.184212 | 36.617046 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.197368 | false | false |
10
|
4ba19081be50b21503a969491c020cd192796a97
| 9,543,417,389,272 |
fabc9b913e48de6555d559a26556d893856e6625
|
/src/FirstClass.java
|
8204d2baf5d08c1aed4c611841da4c9a628b5e7c
|
[] |
no_license
|
kamalkablan/Git-Project
|
https://github.com/kamalkablan/Git-Project
|
5d5eeeac44c120b536ce2572f01a7f7893ebd5b4
|
0fceefc02707ec6d96f4418849382084aac30e7a
|
refs/heads/master
| 2023-01-07T22:41:55.101000 | 2020-11-12T16:42:13 | 2020-11-12T16:42:13 | 312,320,509 | 0 | 0 | null | false | 2020-11-12T16:39:42 | 2020-11-12T15:39:09 | 2020-11-12T15:53:01 | 2020-11-12T16:35:58 | 2 | 0 | 0 | 1 |
Java
| false | false |
public class FirstClass {
public static void main(String[] args) {
System.out.println("let's do this thing");
int number1 =10;
int number2 = 19;
if (number1 == number2){
System.out.println("They are equal");
}else{
System.out.println("They are not equal");
//I am understanding this
//b21 I am back
//the head is where the last work is done
}
}
}
|
UTF-8
|
Java
| 463 |
java
|
FirstClass.java
|
Java
|
[] | null |
[] |
public class FirstClass {
public static void main(String[] args) {
System.out.println("let's do this thing");
int number1 =10;
int number2 = 19;
if (number1 == number2){
System.out.println("They are equal");
}else{
System.out.println("They are not equal");
//I am understanding this
//b21 I am back
//the head is where the last work is done
}
}
}
| 463 | 0.531317 | 0.509719 | 15 | 29.866667 | 16.981821 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
10
|
1ad7c1a19da7493bb38249c615357a463ede41a9
| 21,449,066,729,448 |
79b4bf7e86a7e9228d0582a3a51bfba9a7425b28
|
/UseCases/src/linkedHashMap/MyLinkedHashMap.java
|
ce7ca03961fcb697fc1a0309f184c95316b6d8d1
|
[] |
no_license
|
vaibhawj/workspace
|
https://github.com/vaibhawj/workspace
|
4061330152da19050fb7a46ce1b6091df20d918b
|
7d05c5550ee95fac5369fa8e3446a0898ae8cde8
|
refs/heads/master
| 2021-01-11T08:06:41.696000 | 2017-01-29T16:53:32 | 2017-01-29T16:53:32 | 72,841,966 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package linkedHashMap;
import java.util.AbstractMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
public class MyLinkedHashMap<K, V> extends AbstractMap<K, V> {
private LinkedList<LinkedList<Node<K, V>>> entryList;
private int capacity;
public MyLinkedHashMap() {
entryList = new LinkedList<>();
}
@Override
public V put(K key, V value) {
int index = getHashCode(key);
Node<K, V> node = new Node<K, V>(key, value);
LinkedList<Node<K, V>> list = entryList.get(index);
synchronized (list) {
if (list.contains(node)) {
list.remove(node);
}
list.add(node);
}
return node.v;
}
private int getHashCode(K key) {
return key.hashCode() % capacity;
}
@Override
public V get(Object key) {
int index = getHashCode((K) key);
LinkedList<Node<K, V>> list = entryList.get(index);
for (Node node : list) {
if (node.k.equals(((Node) key).k)) {
return (V) node.v;
}
}
return null;
}
static class Node<K, V> implements Map.Entry<K, V> {
private K k;
private V v;
public Node(K key, V value) {
this.k = key;
this.v = value;
}
@Override
public K getKey() {
return this.k;
}
@Override
public V getValue() {
return this.v;
}
@Override
public V setValue(V value) {
this.v = value;
return this.v;
}
@Override
public boolean equals(Object obj) {
Node o = (Node) obj;
return this.k.equals(o.k);
}
@Override
public String toString() {
return "{" + this.k + ", " + this.v + "}";
}
}
@Override
public Set<java.util.Map.Entry<K, V>> entrySet() {
HashSet<Entry<K, V>> entrySet = new HashSet<MyLinkedHashMap.Entry<K, V>>();
for (LinkedList<Node<K, V>> bucket : entryList) {
for (Node<K, V> node : bucket) {
entrySet.add(node);
}
}
return entrySet;
}
@Override
public String toString() {
Set<Entry<K, V>> entrySet = entrySet();
return entrySet.toString();
}
}
|
UTF-8
|
Java
| 1,963 |
java
|
MyLinkedHashMap.java
|
Java
|
[] | null |
[] |
package linkedHashMap;
import java.util.AbstractMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
public class MyLinkedHashMap<K, V> extends AbstractMap<K, V> {
private LinkedList<LinkedList<Node<K, V>>> entryList;
private int capacity;
public MyLinkedHashMap() {
entryList = new LinkedList<>();
}
@Override
public V put(K key, V value) {
int index = getHashCode(key);
Node<K, V> node = new Node<K, V>(key, value);
LinkedList<Node<K, V>> list = entryList.get(index);
synchronized (list) {
if (list.contains(node)) {
list.remove(node);
}
list.add(node);
}
return node.v;
}
private int getHashCode(K key) {
return key.hashCode() % capacity;
}
@Override
public V get(Object key) {
int index = getHashCode((K) key);
LinkedList<Node<K, V>> list = entryList.get(index);
for (Node node : list) {
if (node.k.equals(((Node) key).k)) {
return (V) node.v;
}
}
return null;
}
static class Node<K, V> implements Map.Entry<K, V> {
private K k;
private V v;
public Node(K key, V value) {
this.k = key;
this.v = value;
}
@Override
public K getKey() {
return this.k;
}
@Override
public V getValue() {
return this.v;
}
@Override
public V setValue(V value) {
this.v = value;
return this.v;
}
@Override
public boolean equals(Object obj) {
Node o = (Node) obj;
return this.k.equals(o.k);
}
@Override
public String toString() {
return "{" + this.k + ", " + this.v + "}";
}
}
@Override
public Set<java.util.Map.Entry<K, V>> entrySet() {
HashSet<Entry<K, V>> entrySet = new HashSet<MyLinkedHashMap.Entry<K, V>>();
for (LinkedList<Node<K, V>> bucket : entryList) {
for (Node<K, V> node : bucket) {
entrySet.add(node);
}
}
return entrySet;
}
@Override
public String toString() {
Set<Entry<K, V>> entrySet = entrySet();
return entrySet.toString();
}
}
| 1,963 | 0.626083 | 0.626083 | 113 | 16.371681 | 17.009209 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.867257 | false | false |
10
|
17f09ef36910d45d14d5077ba813ad1143f91b3f
| 12,455,405,200,355 |
40e146c89cc9f0c12a2a9d951aa6f23f92b80c81
|
/app/src/main/java/com/example/boti/neptunapp/list/DailyViewActivity.java
|
51be30388443392b051d202f6cd2811c6aac5f0c
|
[] |
no_license
|
RozDavid/Neptun_ebreszto
|
https://github.com/RozDavid/Neptun_ebreszto
|
f49ef4ced1f622361a92492a50bd84e5ae14df18
|
c6dc8a18678e5abb9979f24a500f650c9435e459
|
refs/heads/master
| 2020-02-22T23:17:12.666000 | 2017-02-23T14:43:33 | 2017-02-23T14:43:33 | 81,741,548 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.boti.neptunapp.list;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import com.data.Day;
import com.example.boti.neptunapp.R;
import com.example.boti.neptunapp.base.MainActivity;
import com.example.boti.neptunapp.base.NeptunApplication;
public class DailyViewActivity extends AppCompatActivity {
private ListView ListEvents;
private NeptunApplication neptunApplication;
private NeptunDataProvider neptunDataProvider;
Day day;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_view);
ListEvents=(ListView) this.findViewById(R.id.events);
neptunApplication= (NeptunApplication) getApplication();
neptunDataProvider=neptunApplication.getDataProvider();
Bundle dataPassed=getIntent().getExtras();
Integer symbolid=dataPassed.getInt(MainActivity.BUNDLE_SYMBOLID_KEY);
day=neptunDataProvider.getDays().get(symbolid);
this.setTitle(day.getName());
ListEvents.setAdapter(new EventAdapter(this, R.layout.event, day.getEvents()));
}
}
|
UTF-8
|
Java
| 1,226 |
java
|
DailyViewActivity.java
|
Java
|
[] | null |
[] |
package com.example.boti.neptunapp.list;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import com.data.Day;
import com.example.boti.neptunapp.R;
import com.example.boti.neptunapp.base.MainActivity;
import com.example.boti.neptunapp.base.NeptunApplication;
public class DailyViewActivity extends AppCompatActivity {
private ListView ListEvents;
private NeptunApplication neptunApplication;
private NeptunDataProvider neptunDataProvider;
Day day;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_view);
ListEvents=(ListView) this.findViewById(R.id.events);
neptunApplication= (NeptunApplication) getApplication();
neptunDataProvider=neptunApplication.getDataProvider();
Bundle dataPassed=getIntent().getExtras();
Integer symbolid=dataPassed.getInt(MainActivity.BUNDLE_SYMBOLID_KEY);
day=neptunDataProvider.getDays().get(symbolid);
this.setTitle(day.getName());
ListEvents.setAdapter(new EventAdapter(this, R.layout.event, day.getEvents()));
}
}
| 1,226 | 0.744698 | 0.743883 | 52 | 22.576923 | 26.361647 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false |
10
|
f3bc2f31932dd0eadeeac4c274cc96e699fd9ff4
| 4,629,974,767,364 |
8ea37c2cb42021bb73887fcfc65184492f0eb92e
|
/src/com/mojang/mojam/math/Mth.java
|
fa129d639ca8405bcb738089091c57b6aa6e53d6
|
[
"MIT"
] |
permissive
|
rekh127/Catacomb-Snatch-Reloaded
|
https://github.com/rekh127/Catacomb-Snatch-Reloaded
|
ea8616cbf799950e8b00903884aa1bb848cbc0b9
|
386f8dd4c073e0e7e0189807c34ff34d26d67ca8
|
refs/heads/master
| 2021-01-02T22:44:41.979000 | 2012-03-04T02:45:03 | 2012-03-04T02:45:03 | 3,596,503 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mojang.mojam.math;
public class Mth {
static public int clamp(int value, int low, int high) {
if (value < low)
return low;
return value > high ? high : value;
}
}
|
UTF-8
|
Java
| 194 |
java
|
Mth.java
|
Java
|
[] | null |
[] |
package com.mojang.mojam.math;
public class Mth {
static public int clamp(int value, int low, int high) {
if (value < low)
return low;
return value > high ? high : value;
}
}
| 194 | 0.634021 | 0.634021 | 9 | 19.555555 | 17.676796 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.555556 | false | false |
10
|
6e149e7ec7d33f70810ddfeeaf8a671828a88b14
| 1,992,864,844,845 |
15e319506fec4f9917ccbd4f9b73fea51675e237
|
/SoftwareTestApplication/app/src/androidTest/java/com/example/comp41670/COINPARE/RetrieveSuperValuPriceListTest.java
|
9da0c02dd44ca8118d7853a7091470a5e764ef89
|
[] |
no_license
|
parasgoel01/software_project
|
https://github.com/parasgoel01/software_project
|
2a7df083e443e2be35f6b84a885e15145d760cc2
|
adeccf9e2f7b91198584b3badc446f426ba23bc6
|
refs/heads/master
| 2020-06-19T18:38:11.468000 | 2016-12-23T14:56:35 | 2016-12-23T14:56:35 | 74,839,623 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.comp41670.COINPARE;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import static com.example.comp41670.COINPARE.MyValues.NO_PRICE_FOUND;
import static org.junit.Assert.*;
/**
* Created by seancasey on 19/12/2016.
*/
public class RetrieveSuperValuPriceListTest {
ArrayList<String> productNamesLongList;
ArrayList<String> expectedPriceLongList;
ArrayList<String> productNamesOneItemList;
ArrayList<String> expectedPriceOneItemList;
ArrayList<String> productNamesEmptyList;
ArrayList<String> expectedPriceEmptyList;
ArrayList<String> productNamesSpaceList;
ArrayList<String> expectedPriceSpaceList;
ArrayList<String> productNamesListWithInvalidItem;
ArrayList<String> expectedPriceListWithInvalidItem;
ArrayList<String> productNamesListOfNumbers;
ArrayList<String> expectedPriceListOfNumbers;
@Before
public void setUp() throws Exception {
productNamesLongList = new ArrayList<>();
productNamesLongList.add("milk");
productNamesLongList.add("ice cream");
productNamesLongList.add("strawberries");
productNamesLongList.add("pepsi");
productNamesLongList.add("chocolate ice cream");
productNamesLongList.add("raspberries");
productNamesLongList.add("bananas");
productNamesLongList.add("celebrations");
productNamesLongList.add("Corn Flakes");
expectedPriceLongList = new ArrayList<>();
expectedPriceLongList.add("1.18");
expectedPriceLongList.add("2.63");
expectedPriceLongList.add("1.49");
expectedPriceLongList.add("1.00");
expectedPriceLongList.add("2.00");
expectedPriceLongList.add("3.25");
expectedPriceLongList.add("0.65");
expectedPriceLongList.add("3.00");
expectedPriceLongList.add("3.70");
productNamesEmptyList = new ArrayList<>();
expectedPriceEmptyList = new ArrayList<>();
productNamesOneItemList = new ArrayList<>();
productNamesOneItemList.add("celebrations");
expectedPriceOneItemList = new ArrayList<>();
expectedPriceOneItemList.add("3.00");
productNamesSpaceList = new ArrayList<>();
productNamesSpaceList.add(" ");
expectedPriceSpaceList = new ArrayList<>();
expectedPriceSpaceList.add(NO_PRICE_FOUND);
productNamesListWithInvalidItem = productNamesLongList;
productNamesListWithInvalidItem.add("Lectures");
expectedPriceListWithInvalidItem = expectedPriceLongList;
expectedPriceListWithInvalidItem.add(NO_PRICE_FOUND);
productNamesListOfNumbers = new ArrayList<>();
productNamesListOfNumbers.add("12345");
productNamesListOfNumbers.add("67890");
productNamesListOfNumbers.add("24681");
expectedPriceListOfNumbers = new ArrayList<>();
expectedPriceListOfNumbers.add(NO_PRICE_FOUND);
expectedPriceListOfNumbers.add(NO_PRICE_FOUND);
expectedPriceListOfNumbers.add(NO_PRICE_FOUND);
}
//productPrices test cases
@Test
public void productPricesLongListTest() throws Exception {
assertEquals("Expect a list of prices for each item", expectedPriceLongList, new RetrieveSuperValuPriceList().productPrices(productNamesLongList));
}
@Test
public void productPricesOneItemListTest() throws Exception {
assertEquals("Expect price of celebrations to be £5", expectedPriceOneItemList,new RetrieveSuperValuPriceList().productPrices(productNamesOneItemList));
}
@Test
public void productPricesListWithInvalidItemTest() throws Exception {
assertEquals("Expect a list of prices for each valid item, and PRICE_NOT_FOUND for invalid item", expectedPriceListWithInvalidItem, new RetrieveSuperValuPriceList().productPrices(productNamesListWithInvalidItem));
}
@Test
public void productPricesEmptyListTest() throws Exception {
assertEquals("Expect an empty list", expectedPriceEmptyList, new RetrieveSuperValuPriceList().productPrices(productNamesEmptyList));
}
@Test
public void productPricesListOfNumbersTest() throws Exception {
assertEquals("Expect NO_PRICE_FOUND for each item", expectedPriceListOfNumbers, new RetrieveSuperValuPriceList().productPrices(productNamesListOfNumbers));
}
}
|
UTF-8
|
Java
| 4,364 |
java
|
RetrieveSuperValuPriceListTest.java
|
Java
|
[
{
"context": "port static org.junit.Assert.*;\n\n/**\n * Created by seancasey on 19/12/2016.\n */\npublic class RetrieveSuperValu",
"end": 251,
"score": 0.9994965195655823,
"start": 242,
"tag": "USERNAME",
"value": "seancasey"
}
] | null |
[] |
package com.example.comp41670.COINPARE;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import static com.example.comp41670.COINPARE.MyValues.NO_PRICE_FOUND;
import static org.junit.Assert.*;
/**
* Created by seancasey on 19/12/2016.
*/
public class RetrieveSuperValuPriceListTest {
ArrayList<String> productNamesLongList;
ArrayList<String> expectedPriceLongList;
ArrayList<String> productNamesOneItemList;
ArrayList<String> expectedPriceOneItemList;
ArrayList<String> productNamesEmptyList;
ArrayList<String> expectedPriceEmptyList;
ArrayList<String> productNamesSpaceList;
ArrayList<String> expectedPriceSpaceList;
ArrayList<String> productNamesListWithInvalidItem;
ArrayList<String> expectedPriceListWithInvalidItem;
ArrayList<String> productNamesListOfNumbers;
ArrayList<String> expectedPriceListOfNumbers;
@Before
public void setUp() throws Exception {
productNamesLongList = new ArrayList<>();
productNamesLongList.add("milk");
productNamesLongList.add("ice cream");
productNamesLongList.add("strawberries");
productNamesLongList.add("pepsi");
productNamesLongList.add("chocolate ice cream");
productNamesLongList.add("raspberries");
productNamesLongList.add("bananas");
productNamesLongList.add("celebrations");
productNamesLongList.add("Corn Flakes");
expectedPriceLongList = new ArrayList<>();
expectedPriceLongList.add("1.18");
expectedPriceLongList.add("2.63");
expectedPriceLongList.add("1.49");
expectedPriceLongList.add("1.00");
expectedPriceLongList.add("2.00");
expectedPriceLongList.add("3.25");
expectedPriceLongList.add("0.65");
expectedPriceLongList.add("3.00");
expectedPriceLongList.add("3.70");
productNamesEmptyList = new ArrayList<>();
expectedPriceEmptyList = new ArrayList<>();
productNamesOneItemList = new ArrayList<>();
productNamesOneItemList.add("celebrations");
expectedPriceOneItemList = new ArrayList<>();
expectedPriceOneItemList.add("3.00");
productNamesSpaceList = new ArrayList<>();
productNamesSpaceList.add(" ");
expectedPriceSpaceList = new ArrayList<>();
expectedPriceSpaceList.add(NO_PRICE_FOUND);
productNamesListWithInvalidItem = productNamesLongList;
productNamesListWithInvalidItem.add("Lectures");
expectedPriceListWithInvalidItem = expectedPriceLongList;
expectedPriceListWithInvalidItem.add(NO_PRICE_FOUND);
productNamesListOfNumbers = new ArrayList<>();
productNamesListOfNumbers.add("12345");
productNamesListOfNumbers.add("67890");
productNamesListOfNumbers.add("24681");
expectedPriceListOfNumbers = new ArrayList<>();
expectedPriceListOfNumbers.add(NO_PRICE_FOUND);
expectedPriceListOfNumbers.add(NO_PRICE_FOUND);
expectedPriceListOfNumbers.add(NO_PRICE_FOUND);
}
//productPrices test cases
@Test
public void productPricesLongListTest() throws Exception {
assertEquals("Expect a list of prices for each item", expectedPriceLongList, new RetrieveSuperValuPriceList().productPrices(productNamesLongList));
}
@Test
public void productPricesOneItemListTest() throws Exception {
assertEquals("Expect price of celebrations to be £5", expectedPriceOneItemList,new RetrieveSuperValuPriceList().productPrices(productNamesOneItemList));
}
@Test
public void productPricesListWithInvalidItemTest() throws Exception {
assertEquals("Expect a list of prices for each valid item, and PRICE_NOT_FOUND for invalid item", expectedPriceListWithInvalidItem, new RetrieveSuperValuPriceList().productPrices(productNamesListWithInvalidItem));
}
@Test
public void productPricesEmptyListTest() throws Exception {
assertEquals("Expect an empty list", expectedPriceEmptyList, new RetrieveSuperValuPriceList().productPrices(productNamesEmptyList));
}
@Test
public void productPricesListOfNumbersTest() throws Exception {
assertEquals("Expect NO_PRICE_FOUND for each item", expectedPriceListOfNumbers, new RetrieveSuperValuPriceList().productPrices(productNamesListOfNumbers));
}
}
| 4,364 | 0.727939 | 0.713271 | 115 | 36.947826 | 36.62331 | 221 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.66087 | false | false |
10
|
fefec89c5deee676e2994d52540c1efbb62b12d2
| 20,306,605,399,829 |
80ecf329ed25ae786863fb5c2658b9f375c16ae5
|
/app/src/main/java/com/fareway/activity/PurchaseHistoryDetail.java
|
e67226b3dde3482fac469b446e3aeed92ab1301d
|
[] |
no_license
|
IMiMineDigital/Fareway
|
https://github.com/IMiMineDigital/Fareway
|
83c5856489251400ca82a96b0a0d846e72558650
|
e1c16b7c5e3eee9b8ffe32b06d3b4ebd77c88462
|
refs/heads/master
| 2021-07-17T16:52:44.741000 | 2020-06-04T10:33:24 | 2020-06-04T10:33:24 | 175,552,466 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.fareway.activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
/*
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;*/
import android.os.Bundle;
/*
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;*/
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.fareway.R;
import com.fareway.adapter.PurchaseHistoryDetailAdapter;
import com.fareway.controller.FarewayApplication;
import com.fareway.model.PurchaseModelHistory;
import com.fareway.utility.AppUtilFw;
import com.fareway.utility.ConnectivityReceiver;
import com.fareway.utility.Constant;
import com.fareway.utility.DividerRVDecoration;
import com.fareway.utility.NetworkUtils;
import com.fareway.utility.UserAlertDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PurchaseHistoryDetail extends AppCompatActivity {
private ProgressDialog progressDialog;
private UserAlertDialog userAlertDialog;
AppUtilFw appUtil;
private Activity activity;
private AlertDialog alertDialog;
private RequestQueue mQueue;
private static RecyclerView rv_purchase_history;
private ArrayList<PurchaseModelHistory> purchaseArrayList;
private PurchaseHistoryDetailAdapter purchaseListAdapter;
public static JSONArray purchasemessage;
TextView tv_bottom_bar1,tv_bottom_bar2,tv_bottom_bar3,
tv_header_bar,tv_header_location,tv_header_total_price;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_purchase_history_detail);
activity=PurchaseHistoryDetail.this;
mQueue= FarewayApplication.getmInstance(this).getmRequestQueue();
appUtil=new AppUtilFw(activity);
userAlertDialog=new UserAlertDialog(activity);
tv_bottom_bar1=findViewById(R.id.tv_bottom_bar1);
tv_bottom_bar2=findViewById(R.id.tv_bottom_bar2);
tv_bottom_bar3=findViewById(R.id.tv_bottom_bar3);
tv_header_bar=findViewById(R.id.tv_header_bar);
tv_header_location=findViewById(R.id.tv_header_location);
tv_header_total_price=findViewById(R.id.tv_header_total_price);
/*String header_content = getIntent().getExtras().getString("PURCHASEDATE")+" Purchase \nLocation: "+
getIntent().getExtras().getString("PURCHASESTORELOCATION")+"\nTotal Price Paid: $"+
getIntent().getExtras().getString("PURCHASETOTALAMOUNT");*/
//String rate = getIntent().getExtras().getString("PURCHASESTORELOCATION");
//String rate = getIntent().getExtras().getString("PURCHASETOTALAMOUNT");
//tv_header_bar.setText(getIntent().getExtras().getString("PURCHASEDATE"));
tv_header_location.setText(getIntent().getExtras().getString("PURCHASESTORELOCATION"));
tv_header_total_price.setText("$"+getIntent().getExtras().getString("PURCHASETOTALAMOUNT"));
tv_bottom_bar2.setText("$"+getIntent().getExtras().getString("REMAINAMOUTNT"));
purchaseArrayList = new ArrayList<>();
rv_purchase_history = (RecyclerView) findViewById(R.id.rv_purchase_history);
purchaseListAdapter = new PurchaseHistoryDetailAdapter(this, purchaseArrayList);
RecyclerView.LayoutManager mLayoutManagerShoppingList = new LinearLayoutManager(activity);
rv_purchase_history.setLayoutManager(mLayoutManagerShoppingList);
rv_purchase_history.setAdapter(purchaseListAdapter);
/* Drawable dividerDrawableShoppingList = ContextCompat.getDrawable(activity, R.drawable.divider);
rv_purchase_history.addItemDecoration(new DividerRVDecoration(dividerDrawableShoppingList));*/
getSupportActionBar().setTitle("Purchase History");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
purchaseHistoryLoad();
}
private void purchaseHistoryLoad() {
if (ConnectivityReceiver.isConnected(activity) != NetworkUtils.TYPE_NOT_CONNECTED) {
try {
String purchaseId = getIntent().getExtras().getString("PURCHASEID");
progressDialog = new ProgressDialog(activity);
progressDialog.setMessage("Processing");
progressDialog.show();
StringRequest jsonObjectRequest = new StringRequest(Request.Method.GET, Constant.WEB_URL + Constant.PURCHASEDETAILHISTORY+purchaseId,
new Response.Listener<String>(){
@Override
public void onResponse(String response) {
Log.i("Purchase detail Data", response.toString());
try {
JSONObject root = new JSONObject(response);
root.getString("errorcode");
Log.i("errorcode", root.getString("errorcode"));
if (root.getString("errorcode").equals("0")){
progressDialog.dismiss();
purchasemessage= root.getJSONArray("purchasemessage");
for (int i = 0; i < 1; i++) {
tv_bottom_bar1.setText(purchasemessage.getJSONObject(i).getString("totalquantity"));
//tv_bottom_bar2.setText("$"+purchasemessage.getJSONObject(i).getString("remainamount"));
tv_bottom_bar3.setText(purchasemessage.getJSONObject(i).getString("totalamount"));
tv_header_bar.setText(purchasemessage.getJSONObject(i).getString("purchasedate")+" Purchase");
}
purchaseArrayList.clear();
List<PurchaseModelHistory> items = new Gson().fromJson(purchasemessage.toString(), new TypeToken<List<PurchaseModelHistory>>() {
}.getType());
purchaseArrayList.addAll(items);
purchaseListAdapter.notifyDataSetChanged();
progressDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
saveErrorLog("purchaseHistoryLoad", e.getLocalizedMessage());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley error resp", "error----" + error.getMessage());
error.printStackTrace();
saveErrorLog("purchaseHistoryLoad", String.valueOf(error.networkResponse.statusCode));
progressDialog.dismiss();
}
})
{
@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
// params.put("UserName", et_email.getText().toString().trim());
// params.put("password", et_pwd.getText().toString().trim());
//params.put("Device", "5");
return params;
}
//this is the part, that adds the header to the request
@Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
params.put("Authorization", appUtil.getPrefrence("token_type")+" "+appUtil.getPrefrence("access_token"));
return params;
}
};
RetryPolicy policy = new DefaultRetryPolicy
(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(policy);
try {
// FarewayApplication.getInstance().addToRequestQueue(jsonObjectRequest);
mQueue.add(jsonObjectRequest);
}
catch (Exception e)
{
e.printStackTrace();
saveErrorLog("purchaseHistoryLoad", e.getLocalizedMessage());
}
} catch (Exception e) {
e.printStackTrace();
saveErrorLog("purchaseHistoryLoad", e.getLocalizedMessage());
progressDialog.dismiss();
// displayAlert();
}
} else {
progressDialog.dismiss();
alertDialog=userAlertDialog.createPositiveAlert(getString(R.string.noInternet),
getString(R.string.ok),getString(R.string.alert));
alertDialog.show();
// Toast.makeText(activity, "No internet", Toast.LENGTH_LONG).show();
}
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
private void saveErrorLog(String FunctionName, String ErrorDetail) {
if (ConnectivityReceiver.isConnected(activity) != NetworkUtils.TYPE_NOT_CONNECTED) {
try {
StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, Constant.WEB_URL + Constant.ERRORLOG + "?FunctionName=" + FunctionName + "&ErrorSource=" + "android" + "&ErrorStatus=" + "fail" + "&ErrorDetail="+ErrorDetail + "&MemberId=" + appUtil.getPrefrence("MemberId") ,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("Fareway", response.toString());
try {
JSONObject root = new JSONObject(response);
root.getString("errorcode");
Log.i("errorcode", root.getString("errorcode"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley error resp", "error----" + error.getMessage());
error.printStackTrace();
if (error.networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
alertDialog = userAlertDialog.createPositiveAlert("Time out error",
getString(R.string.ok), "Fail");
alertDialog.show();
}
}
finish();
}
}) {
@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Device", "5");
return params;
}
//this is the part, that adds the header to the request
@Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
params.put("Authorization", appUtil.getPrefrence("token_type") + " " + appUtil.getPrefrence("access_token"));
return params;
}
};
RetryPolicy policy = new DefaultRetryPolicy
(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(policy);
try {
// FarewayApplication.getInstance().addToRequestQueue(jsonObjectRequest);
mQueue.add(jsonObjectRequest);
} catch (Exception e) {
finish();
e.printStackTrace();
}
} catch (Exception e) {
finish();
e.printStackTrace();
// progressDialog.dismiss();
// displayAlert();
}
} else {
finish();
alertDialog = userAlertDialog.createPositiveAlert(getString(R.string.noInternet),
getString(R.string.ok), getString(R.string.alert));
alertDialog.show();
// Toast.makeText(activity, "No internet", Toast.LENGTH_LONG).show();
}
}
}
|
UTF-8
|
Java
| 14,808 |
java
|
PurchaseHistoryDetail.java
|
Java
|
[
{
"context": "\n // params.put(\"password\", et_pwd.getText().toString().trim());\n //p",
"end": 8609,
"score": 0.9202302694320679,
"start": 8595,
"tag": "PASSWORD",
"value": "et_pwd.getText"
}
] | null |
[] |
package com.fareway.activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
/*
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;*/
import android.os.Bundle;
/*
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;*/
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.fareway.R;
import com.fareway.adapter.PurchaseHistoryDetailAdapter;
import com.fareway.controller.FarewayApplication;
import com.fareway.model.PurchaseModelHistory;
import com.fareway.utility.AppUtilFw;
import com.fareway.utility.ConnectivityReceiver;
import com.fareway.utility.Constant;
import com.fareway.utility.DividerRVDecoration;
import com.fareway.utility.NetworkUtils;
import com.fareway.utility.UserAlertDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PurchaseHistoryDetail extends AppCompatActivity {
private ProgressDialog progressDialog;
private UserAlertDialog userAlertDialog;
AppUtilFw appUtil;
private Activity activity;
private AlertDialog alertDialog;
private RequestQueue mQueue;
private static RecyclerView rv_purchase_history;
private ArrayList<PurchaseModelHistory> purchaseArrayList;
private PurchaseHistoryDetailAdapter purchaseListAdapter;
public static JSONArray purchasemessage;
TextView tv_bottom_bar1,tv_bottom_bar2,tv_bottom_bar3,
tv_header_bar,tv_header_location,tv_header_total_price;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_purchase_history_detail);
activity=PurchaseHistoryDetail.this;
mQueue= FarewayApplication.getmInstance(this).getmRequestQueue();
appUtil=new AppUtilFw(activity);
userAlertDialog=new UserAlertDialog(activity);
tv_bottom_bar1=findViewById(R.id.tv_bottom_bar1);
tv_bottom_bar2=findViewById(R.id.tv_bottom_bar2);
tv_bottom_bar3=findViewById(R.id.tv_bottom_bar3);
tv_header_bar=findViewById(R.id.tv_header_bar);
tv_header_location=findViewById(R.id.tv_header_location);
tv_header_total_price=findViewById(R.id.tv_header_total_price);
/*String header_content = getIntent().getExtras().getString("PURCHASEDATE")+" Purchase \nLocation: "+
getIntent().getExtras().getString("PURCHASESTORELOCATION")+"\nTotal Price Paid: $"+
getIntent().getExtras().getString("PURCHASETOTALAMOUNT");*/
//String rate = getIntent().getExtras().getString("PURCHASESTORELOCATION");
//String rate = getIntent().getExtras().getString("PURCHASETOTALAMOUNT");
//tv_header_bar.setText(getIntent().getExtras().getString("PURCHASEDATE"));
tv_header_location.setText(getIntent().getExtras().getString("PURCHASESTORELOCATION"));
tv_header_total_price.setText("$"+getIntent().getExtras().getString("PURCHASETOTALAMOUNT"));
tv_bottom_bar2.setText("$"+getIntent().getExtras().getString("REMAINAMOUTNT"));
purchaseArrayList = new ArrayList<>();
rv_purchase_history = (RecyclerView) findViewById(R.id.rv_purchase_history);
purchaseListAdapter = new PurchaseHistoryDetailAdapter(this, purchaseArrayList);
RecyclerView.LayoutManager mLayoutManagerShoppingList = new LinearLayoutManager(activity);
rv_purchase_history.setLayoutManager(mLayoutManagerShoppingList);
rv_purchase_history.setAdapter(purchaseListAdapter);
/* Drawable dividerDrawableShoppingList = ContextCompat.getDrawable(activity, R.drawable.divider);
rv_purchase_history.addItemDecoration(new DividerRVDecoration(dividerDrawableShoppingList));*/
getSupportActionBar().setTitle("Purchase History");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
purchaseHistoryLoad();
}
private void purchaseHistoryLoad() {
if (ConnectivityReceiver.isConnected(activity) != NetworkUtils.TYPE_NOT_CONNECTED) {
try {
String purchaseId = getIntent().getExtras().getString("PURCHASEID");
progressDialog = new ProgressDialog(activity);
progressDialog.setMessage("Processing");
progressDialog.show();
StringRequest jsonObjectRequest = new StringRequest(Request.Method.GET, Constant.WEB_URL + Constant.PURCHASEDETAILHISTORY+purchaseId,
new Response.Listener<String>(){
@Override
public void onResponse(String response) {
Log.i("Purchase detail Data", response.toString());
try {
JSONObject root = new JSONObject(response);
root.getString("errorcode");
Log.i("errorcode", root.getString("errorcode"));
if (root.getString("errorcode").equals("0")){
progressDialog.dismiss();
purchasemessage= root.getJSONArray("purchasemessage");
for (int i = 0; i < 1; i++) {
tv_bottom_bar1.setText(purchasemessage.getJSONObject(i).getString("totalquantity"));
//tv_bottom_bar2.setText("$"+purchasemessage.getJSONObject(i).getString("remainamount"));
tv_bottom_bar3.setText(purchasemessage.getJSONObject(i).getString("totalamount"));
tv_header_bar.setText(purchasemessage.getJSONObject(i).getString("purchasedate")+" Purchase");
}
purchaseArrayList.clear();
List<PurchaseModelHistory> items = new Gson().fromJson(purchasemessage.toString(), new TypeToken<List<PurchaseModelHistory>>() {
}.getType());
purchaseArrayList.addAll(items);
purchaseListAdapter.notifyDataSetChanged();
progressDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
saveErrorLog("purchaseHistoryLoad", e.getLocalizedMessage());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley error resp", "error----" + error.getMessage());
error.printStackTrace();
saveErrorLog("purchaseHistoryLoad", String.valueOf(error.networkResponse.statusCode));
progressDialog.dismiss();
}
})
{
@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
// params.put("UserName", et_email.getText().toString().trim());
// params.put("password", <PASSWORD>().toString().trim());
//params.put("Device", "5");
return params;
}
//this is the part, that adds the header to the request
@Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
params.put("Authorization", appUtil.getPrefrence("token_type")+" "+appUtil.getPrefrence("access_token"));
return params;
}
};
RetryPolicy policy = new DefaultRetryPolicy
(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(policy);
try {
// FarewayApplication.getInstance().addToRequestQueue(jsonObjectRequest);
mQueue.add(jsonObjectRequest);
}
catch (Exception e)
{
e.printStackTrace();
saveErrorLog("purchaseHistoryLoad", e.getLocalizedMessage());
}
} catch (Exception e) {
e.printStackTrace();
saveErrorLog("purchaseHistoryLoad", e.getLocalizedMessage());
progressDialog.dismiss();
// displayAlert();
}
} else {
progressDialog.dismiss();
alertDialog=userAlertDialog.createPositiveAlert(getString(R.string.noInternet),
getString(R.string.ok),getString(R.string.alert));
alertDialog.show();
// Toast.makeText(activity, "No internet", Toast.LENGTH_LONG).show();
}
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
private void saveErrorLog(String FunctionName, String ErrorDetail) {
if (ConnectivityReceiver.isConnected(activity) != NetworkUtils.TYPE_NOT_CONNECTED) {
try {
StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, Constant.WEB_URL + Constant.ERRORLOG + "?FunctionName=" + FunctionName + "&ErrorSource=" + "android" + "&ErrorStatus=" + "fail" + "&ErrorDetail="+ErrorDetail + "&MemberId=" + appUtil.getPrefrence("MemberId") ,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("Fareway", response.toString());
try {
JSONObject root = new JSONObject(response);
root.getString("errorcode");
Log.i("errorcode", root.getString("errorcode"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley error resp", "error----" + error.getMessage());
error.printStackTrace();
if (error.networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
alertDialog = userAlertDialog.createPositiveAlert("Time out error",
getString(R.string.ok), "Fail");
alertDialog.show();
}
}
finish();
}
}) {
@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Device", "5");
return params;
}
//this is the part, that adds the header to the request
@Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
params.put("Authorization", appUtil.getPrefrence("token_type") + " " + appUtil.getPrefrence("access_token"));
return params;
}
};
RetryPolicy policy = new DefaultRetryPolicy
(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(policy);
try {
// FarewayApplication.getInstance().addToRequestQueue(jsonObjectRequest);
mQueue.add(jsonObjectRequest);
} catch (Exception e) {
finish();
e.printStackTrace();
}
} catch (Exception e) {
finish();
e.printStackTrace();
// progressDialog.dismiss();
// displayAlert();
}
} else {
finish();
alertDialog = userAlertDialog.createPositiveAlert(getString(R.string.noInternet),
getString(R.string.ok), getString(R.string.alert));
alertDialog.show();
// Toast.makeText(activity, "No internet", Toast.LENGTH_LONG).show();
}
}
}
| 14,804 | 0.559562 | 0.557536 | 299 | 48.525085 | 34.477009 | 298 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.779264 | false | false |
10
|
f1937d0efe770719875697d27a23396335bc4fae
| 20,306,605,399,568 |
266803bcbeb8547387ab65e42d4cef1f6fee679e
|
/app/src/main/java/com/kazkazi/mytime/dbs/Converters.java
|
192dd0d2ce6b6846bf180f7ab441dee3331362db
|
[] |
no_license
|
egde/MyTime
|
https://github.com/egde/MyTime
|
cedb6d2b76640fb41c6221bde004cca6538c88e5
|
606564f3532a53dc436a9cd5b7e3ccb2a380448b
|
refs/heads/master
| 2020-03-28T16:28:56.650000 | 2018-09-15T20:26:19 | 2018-09-15T20:26:19 | 148,699,852 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.kazkazi.mytime.dbs;
import android.arch.persistence.room.TypeConverter;
import java.util.Date;
import java.util.UUID;
public class Converters {
@TypeConverter
public static Date fromTimestamp(Long value) {
return value == null ? null : new Date(value);
}
@TypeConverter
public static Long dateToTimestamp(Date date) {
return date == null ? null : date.getTime();
}
@TypeConverter
public static UUID stringToUUID(String uuidStr) {
return uuidStr == null ? null: UUID.fromString(uuidStr);
}
@TypeConverter
public static String fromUUID(UUID uuid) {
return uuid == null ? null: uuid.toString();
}
}
|
UTF-8
|
Java
| 692 |
java
|
Converters.java
|
Java
|
[] | null |
[] |
package com.kazkazi.mytime.dbs;
import android.arch.persistence.room.TypeConverter;
import java.util.Date;
import java.util.UUID;
public class Converters {
@TypeConverter
public static Date fromTimestamp(Long value) {
return value == null ? null : new Date(value);
}
@TypeConverter
public static Long dateToTimestamp(Date date) {
return date == null ? null : date.getTime();
}
@TypeConverter
public static UUID stringToUUID(String uuidStr) {
return uuidStr == null ? null: UUID.fromString(uuidStr);
}
@TypeConverter
public static String fromUUID(UUID uuid) {
return uuid == null ? null: uuid.toString();
}
}
| 692 | 0.67052 | 0.67052 | 28 | 23.714285 | 21.71875 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false |
10
|
cde9641c0bab0da2e892fad39f3813e556b67160
| 3,676,492,018,532 |
383203551093a356ad4c6c52b685c0876df1b277
|
/src/test/rmiObject/Server.java
|
983de2a43b690fc23470d8364f57e5ee3198a06f
|
[] |
no_license
|
fabienogli/TP-RPC
|
https://github.com/fabienogli/TP-RPC
|
5f95e7f30babe093ae83dd4b79c54042eb342f5e
|
ee4fdb2e63bf6ecfe07f95dfe9948ef657ec3b2b
|
refs/heads/master
| 2020-03-29T19:35:23.760000 | 2018-10-16T20:36:01 | 2018-10-16T20:36:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package test.rmiObject;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class Server implements Itest {
public Server() {
}
public String sayHello() {
return "Hello, world!";
}
public static void main(String args[]) {
Server server = new Server();
try {
System.out.println("ok");
Itest remote = (Itest) UnicastRemoteObject.exportObject(server, 10000);
System.out.println("ok");
Registry registry = LocateRegistry.getRegistry();
registry.bind("Hello", remote);
} catch (RemoteException e) {
e.printStackTrace();
} catch (AlreadyBoundException e) {
e.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 888 |
java
|
Server.java
|
Java
|
[] | null |
[] |
package test.rmiObject;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class Server implements Itest {
public Server() {
}
public String sayHello() {
return "Hello, world!";
}
public static void main(String args[]) {
Server server = new Server();
try {
System.out.println("ok");
Itest remote = (Itest) UnicastRemoteObject.exportObject(server, 10000);
System.out.println("ok");
Registry registry = LocateRegistry.getRegistry();
registry.bind("Hello", remote);
} catch (RemoteException e) {
e.printStackTrace();
} catch (AlreadyBoundException e) {
e.printStackTrace();
}
}
}
| 888 | 0.626126 | 0.620495 | 34 | 25.117647 | 20.285847 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.529412 | false | false |
10
|
9a18df698589f14d209f5b5225a9030d09031e49
| 927,712,972,328 |
1c6f09a16e7fd154f29c944b3fc59d8f85a688a8
|
/SupportTransitionDemos/src/com/example/android/support/transition/widget/BeginDelayedUsage.java
|
713e76dfda15412f2a82a06dece542b94399e99f
|
[] |
no_license
|
JWBlueLiu/AndroidOfficailDemo
|
https://github.com/JWBlueLiu/AndroidOfficailDemo
|
6c9afe46d95f862dfa01421c409b771e54c0df8c
|
83b9d66441b4618cd386be3e691ef2d0b65f3104
|
refs/heads/master
| 2021-09-23T15:37:05.999000 | 2018-09-25T10:13:26 | 2018-09-25T10:13:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* 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.example.android.support.transition.widget;
import android.os.Bundle;
import android.support.transition.TransitionManager;
import android.support.v4.view.GravityCompat;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import com.example.android.support.transition.R;
public class BeginDelayedUsage extends TransitionUsageBase {
private FrameLayout mRoot;
private Button mButton;
@Override
int getLayoutResId() {
return R.layout.begin_delayed;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRoot = (FrameLayout) findViewById(R.id.root);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toggle();
}
});
}
private void toggle() {
TransitionManager.beginDelayedTransition(mRoot);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mButton.getLayoutParams();
if ((params.gravity & GravityCompat.RELATIVE_HORIZONTAL_GRAVITY_MASK) == GravityCompat.END) {
params.gravity = params.gravity ^ GravityCompat.END | GravityCompat.START;
} else {
params.gravity = params.gravity ^ GravityCompat.START | GravityCompat.END;
}
mButton.setLayoutParams(params);
}
}
|
UTF-8
|
Java
| 2,100 |
java
|
BeginDelayedUsage.java
|
Java
|
[] | null |
[] |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* 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.example.android.support.transition.widget;
import android.os.Bundle;
import android.support.transition.TransitionManager;
import android.support.v4.view.GravityCompat;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import com.example.android.support.transition.R;
public class BeginDelayedUsage extends TransitionUsageBase {
private FrameLayout mRoot;
private Button mButton;
@Override
int getLayoutResId() {
return R.layout.begin_delayed;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRoot = (FrameLayout) findViewById(R.id.root);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toggle();
}
});
}
private void toggle() {
TransitionManager.beginDelayedTransition(mRoot);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mButton.getLayoutParams();
if ((params.gravity & GravityCompat.RELATIVE_HORIZONTAL_GRAVITY_MASK) == GravityCompat.END) {
params.gravity = params.gravity ^ GravityCompat.END | GravityCompat.START;
} else {
params.gravity = params.gravity ^ GravityCompat.START | GravityCompat.END;
}
mButton.setLayoutParams(params);
}
}
| 2,100 | 0.701905 | 0.697619 | 61 | 33.426231 | 27.956324 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.459016 | false | false |
10
|
da182b1c225b98ccb484015d15958bcca92ab640
| 9,053,791,064,028 |
408cd2cc7b40e55573b764bdd9c1ec921ccd2d58
|
/HomeWork/app/src/main/java/ryper/homeworkimprovement/Main/RecyclerViewHelper/MainTodoAdapter.java
|
e6d2c1c7077da4f162b0308e8487446474144544
|
[] |
no_license
|
RyperHUN/Android_BME_Labor
|
https://github.com/RyperHUN/Android_BME_Labor
|
137e45291cf23fd675a5fcb8c4a1eed40af0e4bc
|
770c54b645a2fcccd72d599ca6622c7f3d3a2050
|
refs/heads/master
| 2021-04-30T22:35:39.586000 | 2016-12-09T21:27:56 | 2016-12-09T21:27:56 | 68,892,684 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ryper.homeworkimprovement.Main.RecyclerViewHelper;
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.TextView;
import java.util.ArrayList;
import ryper.homeworkimprovement.DB.TodoHistory;
import ryper.homeworkimprovement.DB.TodoProgress;
import ryper.homeworkimprovement.R;
/**
* Created by Ryper on 2016. 11. 04..
*/
public class MainTodoAdapter extends RecyclerView.Adapter<MainTodoAdapter.ViewHolder>
implements OnListItemChangedNotifier {
ArrayList<TodoProgress> items;
public MainTodoAdapter ()
{
items = new ArrayList<TodoProgress> ();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate (R.layout.list_item_main_todo, parent, false);
return new ViewHolder (view, this);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
TodoProgress aktItem = items.get(position);
holder.nameTextView.setText(aktItem.getDesc());
holder.dateTextView.setText(aktItem.getFormatedStartDate());
}
@Override
public int getItemCount() {
return items.size();
}
@Override
public void ItemCompleted(int position) {
TodoProgress soonRemove = items.get(position);
TodoHistory todoHistory = new TodoHistory (soonRemove);
todoHistory.save (); // Write to DB
ItemRemoved (position);
}
@Override
public void ItemRemoved(int position) {
TodoProgress removed = items.remove(position);
removed.delete();
this.notifyDataSetChanged();
}
public void clear () {
items.clear();
}
public void add(TodoProgress item) {
items.add(item);
this.notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
int position;
TextView nameTextView;
TextView dateTextView;
Button completeButton;
Button removeButton;
OnListItemChangedNotifier myNotifier;
public ViewHolder (View itemView, OnListItemChangedNotifier notifier) {
super(itemView);
myNotifier = notifier;
nameTextView = (TextView) itemView.findViewById(R.id.TodoListItemDesc);
completeButton = (Button) itemView.findViewById(R.id.TodoListItemCompleteBtn);
removeButton = (Button) itemView.findViewById(R.id.TodoListItemRemovBtn);
dateTextView = (TextView) itemView.findViewById(R.id.TodoListItemStartDate);
removeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myNotifier.ItemRemoved (position);
//TODO Popup dialog biztos le akarja-e torolni
}
});
completeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myNotifier.ItemCompleted(position);
//TODO Popup dialog biztos le akarja-e torolni
}
});
}
}
}
|
UTF-8
|
Java
| 3,380 |
java
|
MainTodoAdapter.java
|
Java
|
[
{
"context": "rt ryper.homeworkimprovement.R;\n\n/**\n * Created by Ryper on 2016. 11. 04..\n */\npublic class MainTodoAdapte",
"end": 451,
"score": 0.8954795598983765,
"start": 446,
"tag": "USERNAME",
"value": "Ryper"
}
] | null |
[] |
package ryper.homeworkimprovement.Main.RecyclerViewHelper;
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.TextView;
import java.util.ArrayList;
import ryper.homeworkimprovement.DB.TodoHistory;
import ryper.homeworkimprovement.DB.TodoProgress;
import ryper.homeworkimprovement.R;
/**
* Created by Ryper on 2016. 11. 04..
*/
public class MainTodoAdapter extends RecyclerView.Adapter<MainTodoAdapter.ViewHolder>
implements OnListItemChangedNotifier {
ArrayList<TodoProgress> items;
public MainTodoAdapter ()
{
items = new ArrayList<TodoProgress> ();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate (R.layout.list_item_main_todo, parent, false);
return new ViewHolder (view, this);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
TodoProgress aktItem = items.get(position);
holder.nameTextView.setText(aktItem.getDesc());
holder.dateTextView.setText(aktItem.getFormatedStartDate());
}
@Override
public int getItemCount() {
return items.size();
}
@Override
public void ItemCompleted(int position) {
TodoProgress soonRemove = items.get(position);
TodoHistory todoHistory = new TodoHistory (soonRemove);
todoHistory.save (); // Write to DB
ItemRemoved (position);
}
@Override
public void ItemRemoved(int position) {
TodoProgress removed = items.remove(position);
removed.delete();
this.notifyDataSetChanged();
}
public void clear () {
items.clear();
}
public void add(TodoProgress item) {
items.add(item);
this.notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
int position;
TextView nameTextView;
TextView dateTextView;
Button completeButton;
Button removeButton;
OnListItemChangedNotifier myNotifier;
public ViewHolder (View itemView, OnListItemChangedNotifier notifier) {
super(itemView);
myNotifier = notifier;
nameTextView = (TextView) itemView.findViewById(R.id.TodoListItemDesc);
completeButton = (Button) itemView.findViewById(R.id.TodoListItemCompleteBtn);
removeButton = (Button) itemView.findViewById(R.id.TodoListItemRemovBtn);
dateTextView = (TextView) itemView.findViewById(R.id.TodoListItemStartDate);
removeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myNotifier.ItemRemoved (position);
//TODO Popup dialog biztos le akarja-e torolni
}
});
completeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myNotifier.ItemCompleted(position);
//TODO Popup dialog biztos le akarja-e torolni
}
});
}
}
}
| 3,380 | 0.654142 | 0.651479 | 108 | 30.296297 | 26.202297 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.481481 | false | false |
10
|
6098367c8e55c940f1de974ddf98936f1b7f2ad5
| 11,974,368,846,468 |
0fafe9068ebd98e55350d5d9d6d92272b6f12e29
|
/src/main/java/com/company/controller/adminController/AdminController.java
|
10ff744ca4adf32c69d79ceb95b9b7c195ecc626
|
[] |
no_license
|
OpreaMadalin/OpreaMadalin_FinalProject_API
|
https://github.com/OpreaMadalin/OpreaMadalin_FinalProject_API
|
55947c9daca7296ad36dc93403f8240f967982d0
|
3c2a37fbd8c928048c0e2a449f4fc7dbf231c2eb
|
refs/heads/main
| 2023-06-19T14:01:49.648000 | 2022-07-31T16:36:14 | 2022-07-31T16:36:14 | 374,677,943 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.company.controller.adminController;
import com.auth0.jwt.interfaces.Claim;
import com.company.controller.databaseController.MongoController;
import com.company.controller.tokenController.TokenManager;
import com.company.exception.NotFoundException;
import com.company.exception.UnauthorizedException;
import com.company.model.addAdmin.AddAdminRequestBody;
import com.company.model.addAdmin.AddAdminResponse;
import com.company.model.bannedUser.BannedUserRequestBody;
import com.company.model.bannedUser.BannedUserResponse;
import com.company.model.getAdmins.GetAdminsRequestBody;
import com.company.model.getAdmins.GetAdminsResponse;
import org.bson.Document;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RestController
public class AdminController {
@PostMapping("/addAdmin")
public AddAdminResponse addAdmin(@RequestHeader(name = "Authorization") String authHeader,
@RequestBody AddAdminRequestBody body) {
TokenManager tm = new TokenManager();
Map<String, Claim> claims = tm.verifyToken(authHeader);
if (claims == null) {
throw new UnauthorizedException();
}
MongoController mc = new MongoController();
String username = claims.get("username").asString();
if (!mc.isAdmin(username, body.getChatroomName())) {
throw new UnauthorizedException();
}
mc.addAdmin(body.getChatroomName(), body.getAdminName());
return new AddAdminResponse("");
}
@PostMapping("/getAdmins")
public GetAdminsResponse getAdmins(@RequestHeader(name = "Authorization") String authHeader,
@RequestBody GetAdminsRequestBody body) {
TokenManager tm = new TokenManager();
Map<String, Claim> claims = tm.verifyToken(authHeader);
if (claims == null) {
throw new UnauthorizedException();
}
MongoController mc = new MongoController();
String username = claims.get("username").asString();
if (!mc.isAdmin(username, body.getChatroomName())) {
throw new UnauthorizedException();
}
Document result = mc.getChatRoomWithName(body.getChatroomName());
if (result == null) {
throw new NotFoundException();
}
ArrayList<Document> chatrooms = mc.getChatroomWithName(body.getChatroomName());
ArrayList<String> chatroomAdmins = new ArrayList<>();
for (Document chatroom : chatrooms) {
List<String> admins = chatroom.getList("admins", String.class);
chatroomAdmins.addAll(admins);
}
return new GetAdminsResponse(chatroomAdmins);
}
@PostMapping("/banUser")
public BannedUserResponse addBannedUser(@RequestHeader(name = "Authorization") String authHeader,
@RequestBody BannedUserRequestBody body) {
TokenManager tm = new TokenManager();
Map<String, Claim> claims = tm.verifyToken(authHeader);
if (claims == null) {
throw new UnauthorizedException();
}
MongoController mc = new MongoController();
String username = claims.get("username").asString();
if (!mc.isAdmin(username, body.getChatroomName())) {
throw new UnauthorizedException();
}
mc.addBannedUser(body.getChatroomName(), body.getBannedUser());
return new BannedUserResponse("");
}
}
|
UTF-8
|
Java
| 3,752 |
java
|
AdminController.java
|
Java
|
[
{
"context": "ntroller();\n String username = claims.get(\"username\").asString();\n if (!mc.isAdmin(username, b",
"end": 1543,
"score": 0.996161162853241,
"start": 1535,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ntroller();\n String username = claims.get(\"username\").asString();\n if (!mc.isAdmin(username, b",
"end": 2298,
"score": 0.8795624375343323,
"start": 2290,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ntroller();\n String username = claims.get(\"username\").asString();\n if (!mc.isAdmin(username, b",
"end": 3493,
"score": 0.9230035543441772,
"start": 3485,
"tag": "USERNAME",
"value": "username"
}
] | null |
[] |
package com.company.controller.adminController;
import com.auth0.jwt.interfaces.Claim;
import com.company.controller.databaseController.MongoController;
import com.company.controller.tokenController.TokenManager;
import com.company.exception.NotFoundException;
import com.company.exception.UnauthorizedException;
import com.company.model.addAdmin.AddAdminRequestBody;
import com.company.model.addAdmin.AddAdminResponse;
import com.company.model.bannedUser.BannedUserRequestBody;
import com.company.model.bannedUser.BannedUserResponse;
import com.company.model.getAdmins.GetAdminsRequestBody;
import com.company.model.getAdmins.GetAdminsResponse;
import org.bson.Document;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RestController
public class AdminController {
@PostMapping("/addAdmin")
public AddAdminResponse addAdmin(@RequestHeader(name = "Authorization") String authHeader,
@RequestBody AddAdminRequestBody body) {
TokenManager tm = new TokenManager();
Map<String, Claim> claims = tm.verifyToken(authHeader);
if (claims == null) {
throw new UnauthorizedException();
}
MongoController mc = new MongoController();
String username = claims.get("username").asString();
if (!mc.isAdmin(username, body.getChatroomName())) {
throw new UnauthorizedException();
}
mc.addAdmin(body.getChatroomName(), body.getAdminName());
return new AddAdminResponse("");
}
@PostMapping("/getAdmins")
public GetAdminsResponse getAdmins(@RequestHeader(name = "Authorization") String authHeader,
@RequestBody GetAdminsRequestBody body) {
TokenManager tm = new TokenManager();
Map<String, Claim> claims = tm.verifyToken(authHeader);
if (claims == null) {
throw new UnauthorizedException();
}
MongoController mc = new MongoController();
String username = claims.get("username").asString();
if (!mc.isAdmin(username, body.getChatroomName())) {
throw new UnauthorizedException();
}
Document result = mc.getChatRoomWithName(body.getChatroomName());
if (result == null) {
throw new NotFoundException();
}
ArrayList<Document> chatrooms = mc.getChatroomWithName(body.getChatroomName());
ArrayList<String> chatroomAdmins = new ArrayList<>();
for (Document chatroom : chatrooms) {
List<String> admins = chatroom.getList("admins", String.class);
chatroomAdmins.addAll(admins);
}
return new GetAdminsResponse(chatroomAdmins);
}
@PostMapping("/banUser")
public BannedUserResponse addBannedUser(@RequestHeader(name = "Authorization") String authHeader,
@RequestBody BannedUserRequestBody body) {
TokenManager tm = new TokenManager();
Map<String, Claim> claims = tm.verifyToken(authHeader);
if (claims == null) {
throw new UnauthorizedException();
}
MongoController mc = new MongoController();
String username = claims.get("username").asString();
if (!mc.isAdmin(username, body.getChatroomName())) {
throw new UnauthorizedException();
}
mc.addBannedUser(body.getChatroomName(), body.getBannedUser());
return new BannedUserResponse("");
}
}
| 3,752 | 0.678571 | 0.678305 | 103 | 35.427185 | 27.971067 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.592233 | false | false |
10
|
44d27845f3a847e9195f7dd43335f8ab87353d5f
| 25,134,148,669,440 |
bc0d614addc3a90cc3834c15fc606bf36e549505
|
/src/HiJUtil/Generic/HiResult.java
|
0ab3ec375b9b34c57dc3ecfb4185dbd206cf5ca8
|
[] |
no_license
|
xumingxsh/hijdb
|
https://github.com/xumingxsh/hijdb
|
c650d4d3df0bddcb8ab98bde5d07a97172a55e6c
|
c88667c8723b2f0e8b8ec651238846dd7d4c643e
|
refs/heads/master
| 2020-12-31T07:43:54.644000 | 2016-05-28T23:31:40 | 2016-05-28T23:31:40 | 58,884,497 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package HiJUtil.Generic;
/**
* 在匿名类中调用局部变量并赋值处理
* @author XuminRong
*
* @param <T> 要访问局部变量的类型
*/
public class HiResult<T> implements IResult<T> {
@Override
public boolean GetIsSuccess() {
// TODO Auto-generated method stub
return isOK;
}
@Override
public void SetIsSuccess(boolean isSuccess) {
isOK = isSuccess;
}
@Override
public T Get() {
// TODO Auto-generated method stub
return t;
}
@Override
public void Set(T t) {
this.t = t;
}
boolean isOK = false;
T t;
}
|
GB18030
|
Java
| 554 |
java
|
HiResult.java
|
Java
|
[
{
"context": "JUtil.Generic;\n\n/**\n * 在匿名类中调用局部变量并赋值处理\n * @author XuminRong\n *\n * @param <T> 要访问局部变量的类型\n */\npublic class HiRe",
"end": 70,
"score": 0.9995379447937012,
"start": 61,
"tag": "NAME",
"value": "XuminRong"
}
] | null |
[] |
package HiJUtil.Generic;
/**
* 在匿名类中调用局部变量并赋值处理
* @author XuminRong
*
* @param <T> 要访问局部变量的类型
*/
public class HiResult<T> implements IResult<T> {
@Override
public boolean GetIsSuccess() {
// TODO Auto-generated method stub
return isOK;
}
@Override
public void SetIsSuccess(boolean isSuccess) {
isOK = isSuccess;
}
@Override
public T Get() {
// TODO Auto-generated method stub
return t;
}
@Override
public void Set(T t) {
this.t = t;
}
boolean isOK = false;
T t;
}
| 554 | 0.665339 | 0.665339 | 34 | 13.764706 | 13.503941 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.029412 | false | false |
10
|
ced180638734eb317f8bf32af287ab0403db0cf6
| 25,134,148,672,031 |
eb7d08009bac0abd4e23bc63141dc89b9a81ac14
|
/src/br/ufc/banco/conta/ContaAbstrata.java
|
85920263222392e2605e5fecac2282dd0c405fc2
|
[] |
no_license
|
TPII20152/SB01
|
https://github.com/TPII20152/SB01
|
e2095067cca600f232618f52f0f39debeb932143
|
d368ec55b2ee0dc0cbb44e61d509ceffad9bcd24
|
refs/heads/master
| 2021-01-10T15:08:40.239000 | 2015-12-16T01:38:02 | 2015-12-16T01:38:02 | 47,142,802 | 3 | 1 | null | false | 2015-12-05T17:29:19 | 2015-11-30T20:03:38 | 2015-12-01T11:43:59 | 2015-12-05T17:29:19 | 17 | 0 | 0 | 4 |
Java
| null | null |
package br.ufc.banco.conta;
import br.ufc.banco.conta.excecoes.SIException;
public abstract class ContaAbstrata {
protected String numero;
protected double saldo;
public ContaAbstrata(String numero) {
this.numero = numero;
saldo = 0;
}
public void creditar(double valor) {
if (valor >= 0){
saldo = saldo + valor;
}
}
public abstract void debitar(double valor) throws SIException;
public String obterNumero() {
return numero;
}
public double obterSaldo() {
return saldo;
}
}
|
UTF-8
|
Java
| 540 |
java
|
ContaAbstrata.java
|
Java
|
[] | null |
[] |
package br.ufc.banco.conta;
import br.ufc.banco.conta.excecoes.SIException;
public abstract class ContaAbstrata {
protected String numero;
protected double saldo;
public ContaAbstrata(String numero) {
this.numero = numero;
saldo = 0;
}
public void creditar(double valor) {
if (valor >= 0){
saldo = saldo + valor;
}
}
public abstract void debitar(double valor) throws SIException;
public String obterNumero() {
return numero;
}
public double obterSaldo() {
return saldo;
}
}
| 540 | 0.668519 | 0.664815 | 31 | 15.419354 | 16.838463 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.16129 | false | false |
10
|
bd3654aae81a8205aedd01ac53c860e970c980a9
| 25,134,148,671,705 |
533a5274133a9159f10761d19e7f9a441336de36
|
/DndCharacterCreator/src/db/DndDB.java
|
b129a8fd0e0aabfe9889fd257faa88bc42508b82
|
[] |
no_license
|
w4alf/java-instruction
|
https://github.com/w4alf/java-instruction
|
17ed4b3df683f4e446ced8afdffa55ecab21f3c2
|
342b405fa99f950d6b14896a51394c31849c3f17
|
refs/heads/master
| 2020-08-07T15:11:16.044000 | 2020-04-29T15:35:39 | 2020-04-29T15:35:39 | 213,500,463 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import business.DndCharacter;
//Dungeons and Dragons character sheet
public class DndDB {
private Connection getConnection() throws SQLException {
String dbURL="jdbc:mysql://localhost:3306/dnd_db?useSSL=false&allowPublicKeyRetrieval=true";
String username= "dnd_db_user";
String password = "sesame";
Connection connection = DriverManager.getConnection(dbURL, username, password);
return connection;
}
public DndCharacter get(int id) {
String sql = "Select * from dndcharacter where id=" + id;
DndCharacter c = null;
try (Statement stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(sql);){
boolean charExists = rs.next();
if(charExists) {
//result set has a dnd character
//process the result set
int id2= rs.getInt(1);
String name= rs.getString(2);
String dndClass= rs.getString(3);
int level= rs.getInt(4);
int strength= rs.getInt(5);
int intelligence= rs.getInt(6);
int wisdom= rs.getInt(7);
int dexterity= rs.getInt(8);
int constitution= rs.getInt(9);
int charisma= rs.getInt(10);
int goldPieces= rs.getInt(11);
int expPoints= rs.getInt(12);
int armorClass= rs.getInt(13);
String armor= rs.getString(14);
int hitPoints = rs.getInt(15);
c = new DndCharacter(id2, name, dndClass, level, strength, intelligence, wisdom,
dexterity, constitution, charisma, goldPieces, expPoints, armorClass, armor,hitPoints);
}
} catch (SQLException e) {
e.printStackTrace();
}
return c;
}
public int add(DndCharacter c) {
int rowCount = 0;
String sql = "INSERT INTO dndcharacter (name, dndClass, level, strength, intelligence, wisdom, dexterity, constitution, charisma, goldPieces, expPoints, armorClass, armor, hitPoints) " +
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
try (PreparedStatement ps = getConnection().prepareStatement(sql)) {
ps.setString(1, c.getName());
ps.setString(2, c.getDndClass());
ps.setInt(3, c.getLevel());
ps.setInt(4, c.getStrength());
ps.setInt(5, c.getIntelligence());
ps.setInt(6, c.getWisdom());
ps.setInt(7, c.getDexterity());
ps.setInt(8, c.getConstitution());
ps.setInt(9, c.getCharisma());
ps.setInt(10, c.getGoldPieces());
ps.setInt(11, c.getExpPoints());
ps.setInt(12, c.getArmorClass());
ps.setString(13, c.getArmor());
ps.setInt(14, c.getHitPoints());
rowCount = ps.executeUpdate();
}
catch (SQLException se) {
System.out.println(se);
}
return rowCount;
} // add DndCharacter ending bracket
public List<DndCharacter> getAll() {
String sql = "SELECT * FROM dndCharacter";
List<DndCharacter> characters = new ArrayList<>();
try (PreparedStatement ps = getConnection().prepareStatement(sql); ResultSet rs = ps.executeQuery();) {
while (rs.next()) {
int id= rs.getInt(1);
String name= rs.getString(2);
String dndClass= rs.getString(3);
int level= rs.getInt(4);
int strength= rs.getInt(5);
int intelligence= rs.getInt(6);
int wisdom= rs.getInt(7);
int dexterity= rs.getInt(8);
int constitution= rs.getInt(9);
int charisma= rs.getInt(10);
int goldPieces= rs.getInt(11);
int expPoints= rs.getInt(12);
int armorClass= rs.getInt(13);
String armor= rs.getString(14);
int hitPoints = rs.getInt(15);
DndCharacter c = new DndCharacter(id, name, dndClass, level, strength, intelligence, wisdom,
dexterity, constitution, charisma, goldPieces, expPoints, armorClass, armor,hitPoints);
characters.add(c);
}
return characters;
} catch (SQLException e){
System.out.println(e);
return null;
}
}
public int delete(DndCharacter c) {
int rowCount = 0;
if (!(c==null)) {
String sql = "DELETE FROM dndcharacter WHERE id = ?";
try (Connection connection = getConnection(); PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setInt(1, c.getId());
rowCount = ps.executeUpdate();
} catch (SQLException e) {
System.err.println(e);
}
}
return rowCount;
}
public int update(DndCharacter c ) {
int rowCount = 0;
if (!(c==null)) {
String sql = "UPDATE dndcharacter SET name = ?, dndClass = ?, level = ?, strength = ?, intelligence = ?, wisdom = ?, dexterity = ?, constitution = ?,"
+" charisma =?, goldPieces = ?, expPoints = ?, armorClass = ?, armor=?, hitPoints=? WHERE id= ?";
try (PreparedStatement ps = getConnection().prepareStatement(sql);) {
ps.setString(1, c.getName());
ps.setString(2, c.getDndClass());
ps.setInt(3, c.getLevel());
ps.setInt(4, c.getStrength());
ps.setInt(5, c.getIntelligence());
ps.setInt(6, c.getWisdom());
ps.setInt(7, c.getDexterity());
ps.setInt(8, c.getConstitution());
ps.setInt(9, c.getCharisma());
ps.setInt(10, c.getGoldPieces());
ps.setInt(11, c.getExpPoints());
ps.setInt(12, c.getArmorClass());
ps.setString(13, c.getArmor());
ps.setInt(14, c.getHitPoints());
ps.setInt(15, c.getId());
rowCount = ps.executeUpdate();
} catch (SQLException e) {
System.err.println(e);
}
}
return rowCount;
}
}
|
UTF-8
|
Java
| 6,497 |
java
|
DndDB.java
|
Java
|
[
{
"context": "licKeyRetrieval=true\";\r\n\t\tString username= \"dnd_db_user\";\r\n\t\tString password = \"sesame\";\r\n\t\t\r\n\t\tConnectio",
"end": 542,
"score": 0.5221691131591797,
"start": 538,
"tag": "USERNAME",
"value": "user"
},
{
"context": "ng username= \"dnd_db_user\";\r\n\t\tString password = \"sesame\";\r\n\t\t\r\n\t\tConnection connection = DriverManager.ge",
"end": 573,
"score": 0.9993190765380859,
"start": 567,
"tag": "PASSWORD",
"value": "sesame"
}
] | null |
[] |
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import business.DndCharacter;
//Dungeons and Dragons character sheet
public class DndDB {
private Connection getConnection() throws SQLException {
String dbURL="jdbc:mysql://localhost:3306/dnd_db?useSSL=false&allowPublicKeyRetrieval=true";
String username= "dnd_db_user";
String password = "<PASSWORD>";
Connection connection = DriverManager.getConnection(dbURL, username, password);
return connection;
}
public DndCharacter get(int id) {
String sql = "Select * from dndcharacter where id=" + id;
DndCharacter c = null;
try (Statement stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(sql);){
boolean charExists = rs.next();
if(charExists) {
//result set has a dnd character
//process the result set
int id2= rs.getInt(1);
String name= rs.getString(2);
String dndClass= rs.getString(3);
int level= rs.getInt(4);
int strength= rs.getInt(5);
int intelligence= rs.getInt(6);
int wisdom= rs.getInt(7);
int dexterity= rs.getInt(8);
int constitution= rs.getInt(9);
int charisma= rs.getInt(10);
int goldPieces= rs.getInt(11);
int expPoints= rs.getInt(12);
int armorClass= rs.getInt(13);
String armor= rs.getString(14);
int hitPoints = rs.getInt(15);
c = new DndCharacter(id2, name, dndClass, level, strength, intelligence, wisdom,
dexterity, constitution, charisma, goldPieces, expPoints, armorClass, armor,hitPoints);
}
} catch (SQLException e) {
e.printStackTrace();
}
return c;
}
public int add(DndCharacter c) {
int rowCount = 0;
String sql = "INSERT INTO dndcharacter (name, dndClass, level, strength, intelligence, wisdom, dexterity, constitution, charisma, goldPieces, expPoints, armorClass, armor, hitPoints) " +
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
try (PreparedStatement ps = getConnection().prepareStatement(sql)) {
ps.setString(1, c.getName());
ps.setString(2, c.getDndClass());
ps.setInt(3, c.getLevel());
ps.setInt(4, c.getStrength());
ps.setInt(5, c.getIntelligence());
ps.setInt(6, c.getWisdom());
ps.setInt(7, c.getDexterity());
ps.setInt(8, c.getConstitution());
ps.setInt(9, c.getCharisma());
ps.setInt(10, c.getGoldPieces());
ps.setInt(11, c.getExpPoints());
ps.setInt(12, c.getArmorClass());
ps.setString(13, c.getArmor());
ps.setInt(14, c.getHitPoints());
rowCount = ps.executeUpdate();
}
catch (SQLException se) {
System.out.println(se);
}
return rowCount;
} // add DndCharacter ending bracket
public List<DndCharacter> getAll() {
String sql = "SELECT * FROM dndCharacter";
List<DndCharacter> characters = new ArrayList<>();
try (PreparedStatement ps = getConnection().prepareStatement(sql); ResultSet rs = ps.executeQuery();) {
while (rs.next()) {
int id= rs.getInt(1);
String name= rs.getString(2);
String dndClass= rs.getString(3);
int level= rs.getInt(4);
int strength= rs.getInt(5);
int intelligence= rs.getInt(6);
int wisdom= rs.getInt(7);
int dexterity= rs.getInt(8);
int constitution= rs.getInt(9);
int charisma= rs.getInt(10);
int goldPieces= rs.getInt(11);
int expPoints= rs.getInt(12);
int armorClass= rs.getInt(13);
String armor= rs.getString(14);
int hitPoints = rs.getInt(15);
DndCharacter c = new DndCharacter(id, name, dndClass, level, strength, intelligence, wisdom,
dexterity, constitution, charisma, goldPieces, expPoints, armorClass, armor,hitPoints);
characters.add(c);
}
return characters;
} catch (SQLException e){
System.out.println(e);
return null;
}
}
public int delete(DndCharacter c) {
int rowCount = 0;
if (!(c==null)) {
String sql = "DELETE FROM dndcharacter WHERE id = ?";
try (Connection connection = getConnection(); PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setInt(1, c.getId());
rowCount = ps.executeUpdate();
} catch (SQLException e) {
System.err.println(e);
}
}
return rowCount;
}
public int update(DndCharacter c ) {
int rowCount = 0;
if (!(c==null)) {
String sql = "UPDATE dndcharacter SET name = ?, dndClass = ?, level = ?, strength = ?, intelligence = ?, wisdom = ?, dexterity = ?, constitution = ?,"
+" charisma =?, goldPieces = ?, expPoints = ?, armorClass = ?, armor=?, hitPoints=? WHERE id= ?";
try (PreparedStatement ps = getConnection().prepareStatement(sql);) {
ps.setString(1, c.getName());
ps.setString(2, c.getDndClass());
ps.setInt(3, c.getLevel());
ps.setInt(4, c.getStrength());
ps.setInt(5, c.getIntelligence());
ps.setInt(6, c.getWisdom());
ps.setInt(7, c.getDexterity());
ps.setInt(8, c.getConstitution());
ps.setInt(9, c.getCharisma());
ps.setInt(10, c.getGoldPieces());
ps.setInt(11, c.getExpPoints());
ps.setInt(12, c.getArmorClass());
ps.setString(13, c.getArmor());
ps.setInt(14, c.getHitPoints());
ps.setInt(15, c.getId());
rowCount = ps.executeUpdate();
} catch (SQLException e) {
System.err.println(e);
}
}
return rowCount;
}
}
| 6,501 | 0.545944 | 0.531784 | 224 | 27.004465 | 26.888245 | 194 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.647321 | false | false |
10
|
74b32c58df6eeecbd3cf26feca22ae6cdab0dbbc
| 16,131,897,192,030 |
f910f0395f939ea170bcde2f747a2a1e6ced915d
|
/src/cordys/java/com/boco/mss/workflow/_3rd/cordys/xfire/DefaultXFireClientRuntimeContext.java
|
b78cad85899b42a587d09c033bf4229e159c6f78
|
[] |
no_license
|
xuxiaowei007/workflow
|
https://github.com/xuxiaowei007/workflow
|
a64887a06c9b857a293c45d73517e84e7153c357
|
a57517db894d854e4d961d90b2c4745b41788b31
|
refs/heads/master
| 2020-02-29T11:47:44.961000 | 2010-01-15T06:41:18 | 2010-01-15T06:41:18 | 88,940,734 | 1 | 1 | null | true | 2017-04-21T04:37:45 | 2017-04-21T04:37:45 | 2016-06-29T08:16:10 | 2010-01-15T06:41:26 | 516 | 0 | 0 | 0 | null | null | null |
package com.boco.mss.workflow._3rd.cordys.xfire;
import com.boco.mss.framework.common.collection.AbstractProperties;
import com.boco.mss.workflow._3rd.cordys.authentication.CordysSubjectProvider;
import com.boco.mss.workflow._3rd.cordys.config.CordysServiceClientConfiguration;
public class DefaultXFireClientRuntimeContext extends AbstractProperties implements
XFireClientRuntimeContext {
private CordysServiceClientConfiguration config;
private CordysSubjectProvider subjectProvider;
public DefaultXFireClientRuntimeContext(CordysServiceClientConfiguration config,
CordysSubjectProvider subjectProvider) {
super();
this.config = config;
this.subjectProvider = subjectProvider;
}
@Override
public void initProperties() {
}
/*
* (non-Javadoc)
* @seecom.boco.mss.workflow._3rd.cordys.xfire.XFireClientRuntimeContext#
* getConfiguration()
*/
public CordysServiceClientConfiguration getConfiguration() {
return config;
}
/*
* (non-Javadoc)
* @seecom.boco.mss.workflow._3rd.cordys.xfire.XFireClientRuntimeContext#
* getSubjectProvider()
*/
public CordysSubjectProvider getSubjectProvider() {
return subjectProvider;
}
}
|
UTF-8
|
Java
| 1,410 |
java
|
DefaultXFireClientRuntimeContext.java
|
Java
|
[] | null |
[] |
package com.boco.mss.workflow._3rd.cordys.xfire;
import com.boco.mss.framework.common.collection.AbstractProperties;
import com.boco.mss.workflow._3rd.cordys.authentication.CordysSubjectProvider;
import com.boco.mss.workflow._3rd.cordys.config.CordysServiceClientConfiguration;
public class DefaultXFireClientRuntimeContext extends AbstractProperties implements
XFireClientRuntimeContext {
private CordysServiceClientConfiguration config;
private CordysSubjectProvider subjectProvider;
public DefaultXFireClientRuntimeContext(CordysServiceClientConfiguration config,
CordysSubjectProvider subjectProvider) {
super();
this.config = config;
this.subjectProvider = subjectProvider;
}
@Override
public void initProperties() {
}
/*
* (non-Javadoc)
* @seecom.boco.mss.workflow._3rd.cordys.xfire.XFireClientRuntimeContext#
* getConfiguration()
*/
public CordysServiceClientConfiguration getConfiguration() {
return config;
}
/*
* (non-Javadoc)
* @seecom.boco.mss.workflow._3rd.cordys.xfire.XFireClientRuntimeContext#
* getSubjectProvider()
*/
public CordysSubjectProvider getSubjectProvider() {
return subjectProvider;
}
}
| 1,410 | 0.661702 | 0.658156 | 44 | 31.045454 | 30.410789 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false |
10
|
220d9685596aa700416505e9f431f34d103283fa
| 8,392,366,136,268 |
9f745cd8e4175b91d8801c998022e64013fb4b85
|
/api/src/main/java/com/juggle/juggle/config/PrimaryConfig.java
|
a92b87077c73728857252f1e219026f26a7db891
|
[] |
no_license
|
cjp472/juggle_be
|
https://github.com/cjp472/juggle_be
|
a8570213215564607e1d8e97cd3fd7de735da76d
|
673ee53c4d78351c723c4ba2c6f54eda12494220
|
refs/heads/master
| 2020-08-26T16:06:49.860000 | 2019-09-15T17:59:14 | 2019-09-15T17:59:14 | 217,066,645 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.juggle.juggle.config;
import com.juggle.juggle.framework.data.repo.impl.DefaultEntityInterceptor;
import com.juggle.juggle.framework.data.repo.impl.EntityRepositoryFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactoryPrimary",
repositoryFactoryBeanClass = EntityRepositoryFactoryBean.class,
transactionManagerRef="transactionManagerPrimary",
basePackages= {"com.juggle.juggle.primary"})
public class PrimaryConfig {
/**
* 注入 mysql数据源
*/
@Resource(name = "primaryDataSource")
private DataSource primaryDataSource;
/**
* 注入JPA配置实体
*/
@Autowired
private JpaProperties jpaProperties;
@Autowired
private HibernateProperties hibernateProperties;
/**
* 配置EntityManagerFactory实体
*
* @param builder
* @return 实体管理工厂
* packages 扫描@Entity注释的软件包名称
* persistenceUnit 持久性单元的名称。 如果只建立一个EntityManagerFactory,你可以省略这个,但是如果在同一个应用程序中有多个,你应该给它们不同的名字
* properties 标准JPA或供应商特定配置的通用属性。 这些属性覆盖构造函数中提供的任何值。
*/
@Primary
@Bean(name = "entityManagerFactoryPrimary")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) {
Map<String, Object> properties = hibernateProperties.determineHibernateProperties(
jpaProperties.getProperties(), new HibernateSettings()
);
properties.put("hibernate.ejb.interceptor", new DefaultEntityInterceptor());
return builder
.dataSource(primaryDataSource)
.properties(properties)
.packages("com.juggle.juggle.primary")
.persistenceUnit("primaryPersistenceUnit")
.build();
}
/**
* 配置EntityManager实体
*
* @param builder
* @return 实体管理器
*/
@Primary
@Bean(name = "entityManagerPrimary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
}
/**
* 配置事务transactionManager
*
* @param builder
* @return 事务管理器
*/
@Primary
@Bean(name = "transactionManagerPrimary")
public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
}
|
UTF-8
|
Java
| 3,751 |
java
|
PrimaryConfig.java
|
Java
|
[] | null |
[] |
package com.juggle.juggle.config;
import com.juggle.juggle.framework.data.repo.impl.DefaultEntityInterceptor;
import com.juggle.juggle.framework.data.repo.impl.EntityRepositoryFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactoryPrimary",
repositoryFactoryBeanClass = EntityRepositoryFactoryBean.class,
transactionManagerRef="transactionManagerPrimary",
basePackages= {"com.juggle.juggle.primary"})
public class PrimaryConfig {
/**
* 注入 mysql数据源
*/
@Resource(name = "primaryDataSource")
private DataSource primaryDataSource;
/**
* 注入JPA配置实体
*/
@Autowired
private JpaProperties jpaProperties;
@Autowired
private HibernateProperties hibernateProperties;
/**
* 配置EntityManagerFactory实体
*
* @param builder
* @return 实体管理工厂
* packages 扫描@Entity注释的软件包名称
* persistenceUnit 持久性单元的名称。 如果只建立一个EntityManagerFactory,你可以省略这个,但是如果在同一个应用程序中有多个,你应该给它们不同的名字
* properties 标准JPA或供应商特定配置的通用属性。 这些属性覆盖构造函数中提供的任何值。
*/
@Primary
@Bean(name = "entityManagerFactoryPrimary")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) {
Map<String, Object> properties = hibernateProperties.determineHibernateProperties(
jpaProperties.getProperties(), new HibernateSettings()
);
properties.put("hibernate.ejb.interceptor", new DefaultEntityInterceptor());
return builder
.dataSource(primaryDataSource)
.properties(properties)
.packages("com.juggle.juggle.primary")
.persistenceUnit("primaryPersistenceUnit")
.build();
}
/**
* 配置EntityManager实体
*
* @param builder
* @return 实体管理器
*/
@Primary
@Bean(name = "entityManagerPrimary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
}
/**
* 配置事务transactionManager
*
* @param builder
* @return 事务管理器
*/
@Primary
@Bean(name = "transactionManagerPrimary")
public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
}
| 3,751 | 0.750503 | 0.750503 | 93 | 36.408604 | 29.401644 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.365591 | false | false |
10
|
77c504ae8f1b28f3cfd0c18dc1486772cdc2c749
| 16,913,581,253,399 |
c57202aa5a791dbb9b93c78b49eafaf9aef4ad93
|
/src/main/java/cpg/sr/security/config/GeneralFunction.java
|
b5600203cd5dfd6c65137a0cd53795fa968d0b04
|
[] |
no_license
|
cuongphuong/sercurity-with-springboot
|
https://github.com/cuongphuong/sercurity-with-springboot
|
c67514dee3a7568253ac009c67bfebbbc0ac4406
|
2bc82a150eb6f2290e66d3a7a48d82b856648934
|
refs/heads/master
| 2020-05-30T14:32:33.166000 | 2019-06-06T16:27:22 | 2019-06-06T16:27:22 | 189,793,197 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cpg.sr.security.config;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import cpg.sr.security.anotations.DefaultFunctionInfo;
import cpg.sr.security.anotations.DefaultModuleInfo;
import cpg.sr.security.commons.Utils;
import cpg.sr.security.entitys.Function;
import cpg.sr.security.entitys.Module;
@Configuration
public class GeneralFunction {
@Bean("CPG_GeneralFunction")
public void genaralFunction() {
// declare
Class<? extends Object>[] classes = Utils.getClassesInPackage("cpg.sr.controller");
List<Module> lstModule = new ArrayList<Module>();
List<Function> lstFunction = new ArrayList<Function>();
for (Class<? extends Object> c : classes) {
// Get module
Annotation[] moduleAnotations = c.getAnnotations();
Module module = new Module();
for (Annotation annotationElement : moduleAnotations) {
if (annotationElement instanceof RequestMapping) {
RequestMapping anotationRequestModule = (RequestMapping) annotationElement;
String moduleName[] = anotationRequestModule.value();
module.setModuleLable(moduleName[0]);
}
if (annotationElement instanceof DefaultModuleInfo) {
DefaultModuleInfo annotationInfoModule = (DefaultModuleInfo) annotationElement;
String moduleName = annotationInfoModule.name();
module.setModuleName(moduleName);
}
}
// add module to list
lstModule.add(module);
// Get function of class
Method[] methods = c.getMethods();
for (Method method : methods) {
Annotation[] methodAnnotation = method.getAnnotations();
Function function = null;
for (Annotation annotationElement : methodAnnotation) {
if (annotationElement instanceof DefaultFunctionInfo) {
DefaultFunctionInfo anotationRequestFunction = (DefaultFunctionInfo) annotationElement;
function.setFunctionName(anotationRequestFunction.name());
function.setIconType(anotationRequestFunction.icon());
function.setEnable(anotationRequestFunction.enable());
}
if (function != null) {
if (annotationElement instanceof GetMapping) {
GetMapping anotationRequestFunction = (GetMapping) annotationElement;
String name[] = anotationRequestFunction.value();
function.setFunctionLable(name[0]);
}
if (annotationElement instanceof PostMapping) {
PostMapping anotationRequestFunction = (PostMapping) annotationElement;
String name[] = anotationRequestFunction.value();
function.setFunctionLable(name[0]);
}
if (annotationElement instanceof PutMapping) {
PutMapping anotationRequestFunction = (PutMapping) annotationElement;
String name[] = anotationRequestFunction.value();
function.setFunctionLable(name[0]);
}
if (annotationElement instanceof DeleteMapping) {
DeleteMapping anotationRequestFunction = (DeleteMapping) annotationElement;
String name[] = anotationRequestFunction.value();
function.setFunctionLable(name[0]);
}
}
}
// add funtion
if (function != null) {
lstFunction.add(function);
}
}
}
System.err.println("Module General: " + lstModule.size());
System.err.println("Function General: " + lstFunction.size());
}
}
|
UTF-8
|
Java
| 3,721 |
java
|
GeneralFunction.java
|
Java
|
[] | null |
[] |
package cpg.sr.security.config;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import cpg.sr.security.anotations.DefaultFunctionInfo;
import cpg.sr.security.anotations.DefaultModuleInfo;
import cpg.sr.security.commons.Utils;
import cpg.sr.security.entitys.Function;
import cpg.sr.security.entitys.Module;
@Configuration
public class GeneralFunction {
@Bean("CPG_GeneralFunction")
public void genaralFunction() {
// declare
Class<? extends Object>[] classes = Utils.getClassesInPackage("cpg.sr.controller");
List<Module> lstModule = new ArrayList<Module>();
List<Function> lstFunction = new ArrayList<Function>();
for (Class<? extends Object> c : classes) {
// Get module
Annotation[] moduleAnotations = c.getAnnotations();
Module module = new Module();
for (Annotation annotationElement : moduleAnotations) {
if (annotationElement instanceof RequestMapping) {
RequestMapping anotationRequestModule = (RequestMapping) annotationElement;
String moduleName[] = anotationRequestModule.value();
module.setModuleLable(moduleName[0]);
}
if (annotationElement instanceof DefaultModuleInfo) {
DefaultModuleInfo annotationInfoModule = (DefaultModuleInfo) annotationElement;
String moduleName = annotationInfoModule.name();
module.setModuleName(moduleName);
}
}
// add module to list
lstModule.add(module);
// Get function of class
Method[] methods = c.getMethods();
for (Method method : methods) {
Annotation[] methodAnnotation = method.getAnnotations();
Function function = null;
for (Annotation annotationElement : methodAnnotation) {
if (annotationElement instanceof DefaultFunctionInfo) {
DefaultFunctionInfo anotationRequestFunction = (DefaultFunctionInfo) annotationElement;
function.setFunctionName(anotationRequestFunction.name());
function.setIconType(anotationRequestFunction.icon());
function.setEnable(anotationRequestFunction.enable());
}
if (function != null) {
if (annotationElement instanceof GetMapping) {
GetMapping anotationRequestFunction = (GetMapping) annotationElement;
String name[] = anotationRequestFunction.value();
function.setFunctionLable(name[0]);
}
if (annotationElement instanceof PostMapping) {
PostMapping anotationRequestFunction = (PostMapping) annotationElement;
String name[] = anotationRequestFunction.value();
function.setFunctionLable(name[0]);
}
if (annotationElement instanceof PutMapping) {
PutMapping anotationRequestFunction = (PutMapping) annotationElement;
String name[] = anotationRequestFunction.value();
function.setFunctionLable(name[0]);
}
if (annotationElement instanceof DeleteMapping) {
DeleteMapping anotationRequestFunction = (DeleteMapping) annotationElement;
String name[] = anotationRequestFunction.value();
function.setFunctionLable(name[0]);
}
}
}
// add funtion
if (function != null) {
lstFunction.add(function);
}
}
}
System.err.println("Module General: " + lstModule.size());
System.err.println("Function General: " + lstFunction.size());
}
}
| 3,721 | 0.738242 | 0.736899 | 103 | 35.126213 | 25.783895 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.533981 | false | false |
10
|
00f3e915ea260dd608494269d97f68b6c3d40da4
| 33,028,298,507,763 |
a7ba366c188061a3c36efa7dd16519d0c8f51408
|
/src/test/java/fr/ing/interview/Service/TestTransactionService.java
|
30b24653764f62030927ee3700f47b602224cc29
|
[] |
no_license
|
saipranathi/Hackathon
|
https://github.com/saipranathi/Hackathon
|
2a221d5ec3bdf783ad37fd3de86ddfc989ef3e4e
|
6a2f0b86617142eb153ef22e8740522123637d07
|
refs/heads/master
| 2022-12-30T09:30:54.550000 | 2020-05-21T06:13:13 | 2020-05-21T06:13:13 | 265,272,254 | 0 | 0 | null | false | 2020-10-13T22:07:29 | 2020-05-19T14:35:28 | 2020-05-21T06:13:31 | 2020-10-13T22:07:28 | 64,309 | 0 | 0 | 1 |
Java
| false | false |
package fr.ing.interview.Service;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import fr.ing.interview.Model.Transaction;
import static fr.ing.interview.Constants.*;
@RunWith(MockitoJUnitRunner.class)
public class TestTransactionService {
@InjectMocks
static
TransactionService transactionService;
private static Transaction txn1;
private static Transaction txn2;
static Date date = new Date();
static Timestamp timestamp = new Timestamp(date.getTime());
private static List<Transaction> txnList= new ArrayList<Transaction>();
@BeforeClass
public static void setUp() throws Exception {
transactionService = mock(TransactionService.class);
txn1=new Transaction(1L,"400",credited, minAmt);
txn2=new Transaction(2L,"300",credited, minAmt);
txnList.add(txn1);
txnList.add(txn2);
when(transactionService.displayTransactions("400")).thenReturn(txnList);
}
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@Test
public void displayTransactions() throws Exception{
List<Transaction> txnList = transactionService.displayTransactions("400");
assertEquals(2, txnList.size());
Transaction tx = txnList.get(0);
assertEquals(new Long(1),tx.getTransactionId());
assertEquals("400", tx.getAccountNumber());
assertEquals(credited, tx.getType());
assertEquals(minAmt, tx.getTransactionAmount());
}
}
|
UTF-8
|
Java
| 1,788 |
java
|
TestTransactionService.java
|
Java
|
[] | null |
[] |
package fr.ing.interview.Service;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import fr.ing.interview.Model.Transaction;
import static fr.ing.interview.Constants.*;
@RunWith(MockitoJUnitRunner.class)
public class TestTransactionService {
@InjectMocks
static
TransactionService transactionService;
private static Transaction txn1;
private static Transaction txn2;
static Date date = new Date();
static Timestamp timestamp = new Timestamp(date.getTime());
private static List<Transaction> txnList= new ArrayList<Transaction>();
@BeforeClass
public static void setUp() throws Exception {
transactionService = mock(TransactionService.class);
txn1=new Transaction(1L,"400",credited, minAmt);
txn2=new Transaction(2L,"300",credited, minAmt);
txnList.add(txn1);
txnList.add(txn2);
when(transactionService.displayTransactions("400")).thenReturn(txnList);
}
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@Test
public void displayTransactions() throws Exception{
List<Transaction> txnList = transactionService.displayTransactions("400");
assertEquals(2, txnList.size());
Transaction tx = txnList.get(0);
assertEquals(new Long(1),tx.getTransactionId());
assertEquals("400", tx.getAccountNumber());
assertEquals(credited, tx.getType());
assertEquals(minAmt, tx.getTransactionAmount());
}
}
| 1,788 | 0.748881 | 0.73434 | 67 | 25.686567 | 21.669987 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.223881 | false | false |
10
|
f789556cc03d4ffc7564ec87f2220298c7a87a9e
| 33,603,824,176,073 |
416b755c0dc1f6305c8e1278edc26817473c6720
|
/src/main/java/com/leetcode/slidingwindow/LongestSubstringWithAtLeastKDistinctChars.java
|
57640f95e93a1ce3a4a94624c336f38f946dc3dd
|
[] |
no_license
|
unrealwork/algo-problems
|
https://github.com/unrealwork/algo-problems
|
147d2529fe1560401d3ae4be2d5c77daf81cb571
|
7e89280f7e791f4017c0e1fd4d574d408e746141
|
refs/heads/master
| 2022-08-01T18:01:47.991000 | 2022-07-13T05:44:41 | 2022-07-13T05:44:41 | 103,003,039 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.leetcode.slidingwindow;
import scala.Char;
import java.util.Arrays;
import java.util.Map;
class LongestSubstringWithAtLeastKDistinctChars {
private LongestSubstringWithAtLeastKDistinctChars() {
}
public static int longestSubstring(String s, int k) {
int windowStart = 0;
int curCount = 0;
int best = 0;
int[] dict = new int['z' + 1];
return best;
}
private static boolean isFilled(int[] dict, int k) {
for (int i = 'a'; i < dict.length; i++) {
if (dict[i] > 0 && dict[i] < k) {
return false;
}
}
return true;
}
}
|
UTF-8
|
Java
| 659 |
java
|
LongestSubstringWithAtLeastKDistinctChars.java
|
Java
|
[] | null |
[] |
package com.leetcode.slidingwindow;
import scala.Char;
import java.util.Arrays;
import java.util.Map;
class LongestSubstringWithAtLeastKDistinctChars {
private LongestSubstringWithAtLeastKDistinctChars() {
}
public static int longestSubstring(String s, int k) {
int windowStart = 0;
int curCount = 0;
int best = 0;
int[] dict = new int['z' + 1];
return best;
}
private static boolean isFilled(int[] dict, int k) {
for (int i = 'a'; i < dict.length; i++) {
if (dict[i] > 0 && dict[i] < k) {
return false;
}
}
return true;
}
}
| 659 | 0.566009 | 0.558422 | 29 | 21.724138 | 19.120123 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.517241 | false | false |
10
|
725ddd296868270a88715cb4055c41accd058654
| 12,945,031,436,947 |
2b07a1e08f1e6b0a5c48133ac0a7755e0958811f
|
/app/src/main/java/com/tema7/tema7ejemplo2/Fragments/InfoFragment.java
|
5a90f3bbc1f25c725d7b1b0740a02f3ae43b39fa
|
[] |
no_license
|
marto30/TFG-GYM
|
https://github.com/marto30/TFG-GYM
|
5d24509799f520bd09e6e433faa1879f56a7efe3
|
5db8524cd32068598b27fb37238ec3c4db203e17
|
refs/heads/main
| 2023-04-29T19:31:39.146000 | 2021-04-30T09:04:40 | 2021-04-30T09:04:40 | 352,054,948 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.tema7.tema7ejemplo2.Fragments;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.tema7.tema7ejemplo2.R;
public class InfoFragment extends Fragment {
private FloatingActionButton btnInfo;
public InfoFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_info, container, false);
btnInfo = (FloatingActionButton) view.findViewById(R.id.botonInfo);
btnInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final AlertDialog.Builder alerta = new AlertDialog.Builder(getContext());
alerta.setMessage("Este dialogo de alerta es solo para mostrar un mensaje informativo normal al usuario,nada con lo que interartuar")
.setCancelable(true)
.setPositiveButton("Entendido", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
InfoFragment.this.finalize();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
});
AlertDialog titulo = alerta.create();
titulo.setTitle("Información");
titulo.show();
}
});
return view;
}
}
|
UTF-8
|
Java
| 2,069 |
java
|
InfoFragment.java
|
Java
|
[] | null |
[] |
package com.tema7.tema7ejemplo2.Fragments;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.tema7.tema7ejemplo2.R;
public class InfoFragment extends Fragment {
private FloatingActionButton btnInfo;
public InfoFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_info, container, false);
btnInfo = (FloatingActionButton) view.findViewById(R.id.botonInfo);
btnInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final AlertDialog.Builder alerta = new AlertDialog.Builder(getContext());
alerta.setMessage("Este dialogo de alerta es solo para mostrar un mensaje informativo normal al usuario,nada con lo que interartuar")
.setCancelable(true)
.setPositiveButton("Entendido", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
InfoFragment.this.finalize();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
});
AlertDialog titulo = alerta.create();
titulo.setTitle("Información");
titulo.show();
}
});
return view;
}
}
| 2,069 | 0.588975 | 0.586074 | 59 | 34.067795 | 30.96026 | 149 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.491525 | false | false |
11
|
394151ea16d342f4794ba32dc7316f55a3d02ab8
| 163,208,767,652 |
838fe57287c222529328a042c68a5c80c6afb150
|
/app/src/main/java/danchokoe/co/za/smartreadings/sync/SmartCitizenAuthenticatorService.java
|
b0a427741ab9c3112a5367af65d8c27f36ae4839
|
[] |
no_license
|
DannySpecial1/meterreader
|
https://github.com/DannySpecial1/meterreader
|
e9adcaafb04681bb2736af4256fc98a8ba604ee1
|
a9d56fc56a2882f718a629e8287cd5c25df60020
|
refs/heads/master
| 2020-04-26T17:01:53.332000 | 2019-03-04T07:58:18 | 2019-03-04T07:58:18 | 173,699,488 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package danchokoe.co.za.smartreadings.sync;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class SmartCitizenAuthenticatorService extends Service {
private SmartCitizenAuthenticator mAuthenticator;
@Override
public void onCreate() {
mAuthenticator = new SmartCitizenAuthenticator(this);
}
@Override
public IBinder onBind(Intent intent) {
return mAuthenticator.getIBinder();
}
}
|
UTF-8
|
Java
| 473 |
java
|
SmartCitizenAuthenticatorService.java
|
Java
|
[] | null |
[] |
package danchokoe.co.za.smartreadings.sync;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class SmartCitizenAuthenticatorService extends Service {
private SmartCitizenAuthenticator mAuthenticator;
@Override
public void onCreate() {
mAuthenticator = new SmartCitizenAuthenticator(this);
}
@Override
public IBinder onBind(Intent intent) {
return mAuthenticator.getIBinder();
}
}
| 473 | 0.744186 | 0.744186 | 20 | 22.65 | 21.422594 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.35 | false | false |
11
|
f213e25b4f3a47906aad8391f3f97c72b171f72e
| 163,208,771,066 |
f8f35bc8c8145408bbc18912f8f8c1ee3f37a580
|
/src/com/demo/creational/test/PrototypingTest.java
|
5b66d43619a2215fe43b12eca735358e31962469
|
[] |
no_license
|
amnope2811/Design-Pattern-Example
|
https://github.com/amnope2811/Design-Pattern-Example
|
51989386ed0f1cd16441efe4b01da65b4021e9f5
|
d4c978f501d195f1cbe1bf15df0a2a35433954d2
|
refs/heads/main
| 2023-04-26T06:48:20.027000 | 2021-05-04T16:05:11 | 2021-05-04T16:05:11 | 364,280,821 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.demo.creational.test;
import org.junit.After;
import org.junit.Test;
import com.demo.creational.prototyping.ClothesProtoSingle;
import com.demo.creational.prototyping.ClothesPrototyping;
import com.demo.creational.singleton.ClothesSingleton;
public class PrototypingTest {
@Test
public void protyping() {
ClothesPrototyping clothes1 = new ClothesPrototyping();
ClothesPrototyping clothes2 = clothes1.deepClone();
System.out.println(clothes1);
System.out.println(clothes2);
clothes1.turnMachine();
clothes2.turnMachine();
}
@Test
public void protypingAndSingleton() {
ClothesProtoSingle clothes1 = ClothesProtoSingle.getInstance();
ClothesProtoSingle clothes2 = clothes1.deepClone();
System.out.println(clothes1);
System.out.println(clothes2);
clothes1.turnMachine();
clothes2.turnMachine();
}
@After
public void tearDown() {
int i =0;
while (i<20) {
try {
Thread.sleep(1000);
i++;
} catch (InterruptedException e) {
e.printStackTrace();
i=20;
}
}
}
}
|
UTF-8
|
Java
| 1,060 |
java
|
PrototypingTest.java
|
Java
|
[] | null |
[] |
package com.demo.creational.test;
import org.junit.After;
import org.junit.Test;
import com.demo.creational.prototyping.ClothesProtoSingle;
import com.demo.creational.prototyping.ClothesPrototyping;
import com.demo.creational.singleton.ClothesSingleton;
public class PrototypingTest {
@Test
public void protyping() {
ClothesPrototyping clothes1 = new ClothesPrototyping();
ClothesPrototyping clothes2 = clothes1.deepClone();
System.out.println(clothes1);
System.out.println(clothes2);
clothes1.turnMachine();
clothes2.turnMachine();
}
@Test
public void protypingAndSingleton() {
ClothesProtoSingle clothes1 = ClothesProtoSingle.getInstance();
ClothesProtoSingle clothes2 = clothes1.deepClone();
System.out.println(clothes1);
System.out.println(clothes2);
clothes1.turnMachine();
clothes2.turnMachine();
}
@After
public void tearDown() {
int i =0;
while (i<20) {
try {
Thread.sleep(1000);
i++;
} catch (InterruptedException e) {
e.printStackTrace();
i=20;
}
}
}
}
| 1,060 | 0.717925 | 0.696226 | 45 | 22.555555 | 18.847404 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.8 | false | false |
11
|
e3b9f62afbe7b053d46b1cd627c018b6e58eeebb
| 10,849,087,403,421 |
d0bffe491f356190ca4eeb711660257d2016d1a7
|
/src/main/java/logic/NumbersVariableContainer.java
|
6d663bb7324751e627bd33c6d449388f159143e7
|
[] |
no_license
|
Kondziu1999/Compiler
|
https://github.com/Kondziu1999/Compiler
|
42a54bb942384f30949841a2fd4338e37b7b65ab
|
2e53886461775769cd52e38c44b9f1035a2fdad2
|
refs/heads/master
| 2023-06-04T06:08:40.838000 | 2021-06-16T09:47:28 | 2021-06-16T09:47:28 | 368,900,792 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package logic;
import java.util.HashMap;
public class NumbersVariableContainer {
private static HashMap<String, Double> variables = new HashMap<>();
public static boolean containsVariable(String name){
return variables.containsKey(name);
}
public static void setVariable(NumberVariable numberVariable){
if (variables.containsKey(numberVariable.name)){
variables.replace(numberVariable.name,numberVariable.value);
return;
}
variables.put(numberVariable.name, numberVariable.value);
}
public static Double getValue(String varName){
if (variables.containsKey(varName)) {
return variables.get(varName);
}
return null;
}
}
|
UTF-8
|
Java
| 752 |
java
|
NumbersVariableContainer.java
|
Java
|
[] | null |
[] |
package logic;
import java.util.HashMap;
public class NumbersVariableContainer {
private static HashMap<String, Double> variables = new HashMap<>();
public static boolean containsVariable(String name){
return variables.containsKey(name);
}
public static void setVariable(NumberVariable numberVariable){
if (variables.containsKey(numberVariable.name)){
variables.replace(numberVariable.name,numberVariable.value);
return;
}
variables.put(numberVariable.name, numberVariable.value);
}
public static Double getValue(String varName){
if (variables.containsKey(varName)) {
return variables.get(varName);
}
return null;
}
}
| 752 | 0.664894 | 0.664894 | 28 | 25.892857 | 25.247828 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false |
11
|
13f7ffee78fd58abb86f4048c05fb7adcf78993a
| 24,558,623,008,357 |
86563f3983fc102a9932be3826aa5f4d30e5da93
|
/hw5-podocarp/src/test/java/misc/TestSorter.java
|
9b5df480175c01238f1b0e434f941d916b6ea58c
|
[] |
no_license
|
Anthony2018/CSE373
|
https://github.com/Anthony2018/CSE373
|
fa571d2d494b6fa47b831497da93681c8c9fd2fb
|
66fdf531cff26dccc92ebd5d8a5f5d631ec4a641
|
refs/heads/master
| 2020-05-09T10:35:58.710000 | 2019-06-14T10:02:05 | 2019-06-14T10:02:05 | 181,049,231 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package misc;
import datastructures.concrete.DoubleLinkedList;
import datastructures.interfaces.IList;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
/**
* See spec for details on what kinds of tests this class should include.
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestSorter extends BaseTest {
@Test(timeout=SECOND)
public void testSimpleUsage() {
IList<Integer> list = new DoubleLinkedList<>();
for (int i = 0; i < 20; i++) {
list.add(i);
}
IList<Integer> top = Sorter.topKSort(5, list);
assertEquals(5, top.size());
for (int i = 0; i < top.size(); i++) {
assertEquals(15 + i, top.get(i));
}
}
@Test(timeout=SECOND)
public void testSortLessThanK() {
IList<Integer> list = new DoubleLinkedList<>();
list.add(3);
list.add(8);
list.add(2);
IList<Integer> top = Sorter.topKSort(5, list);
assertEquals(3, top.size());
assertEquals(2, top.get(0));
assertEquals(3, top.get(1));
assertEquals(8, top.get(2));
}
@Test(timeout=SECOND)
public void testSortMoreThanK() {
IList<Integer> list = new DoubleLinkedList<>();
list.add(3);
list.add(8);
list.add(2);
list.add(11);
list.add(23);
list.add(5);
IList<Integer> top = Sorter.topKSort(4, list);
assertEquals(4, top.size());
assertEquals(5, top.get(0));
assertEquals(8, top.get(1));
assertEquals(11, top.get(2));
assertEquals(23, top.get(3));
}
@Test(timeout=SECOND)
public void testZeroK() {
IList<Integer> list = new DoubleLinkedList<>();
list.add(3);
list.add(8);
list.add(2);
IList<Integer> top = Sorter.topKSort(0, list);
assertEquals(0, top.size());
}
@Test(timeout=SECOND)
public void testWithLargeData() {
IList<Integer> list = new DoubleLinkedList<>();
for (int i = 0; i < 1000; i++) {
list.add(i);
}
IList<Integer> top = Sorter.topKSort(5, list);
assertEquals(5, top.size());
for (int i = 0; i < top.size(); i++) {
assertEquals(995 + i, top.get(i));
}
IList<Integer> top2 = Sorter.topKSort(1000, list);
assertEquals(1000, top2.size());
for (int i = 0; i < top2.size(); i++) {
assertEquals(i, top2.get(i));
}
}
}
|
UTF-8
|
Java
| 2,539 |
java
|
TestSorter.java
|
Java
|
[] | null |
[] |
package misc;
import datastructures.concrete.DoubleLinkedList;
import datastructures.interfaces.IList;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
/**
* See spec for details on what kinds of tests this class should include.
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestSorter extends BaseTest {
@Test(timeout=SECOND)
public void testSimpleUsage() {
IList<Integer> list = new DoubleLinkedList<>();
for (int i = 0; i < 20; i++) {
list.add(i);
}
IList<Integer> top = Sorter.topKSort(5, list);
assertEquals(5, top.size());
for (int i = 0; i < top.size(); i++) {
assertEquals(15 + i, top.get(i));
}
}
@Test(timeout=SECOND)
public void testSortLessThanK() {
IList<Integer> list = new DoubleLinkedList<>();
list.add(3);
list.add(8);
list.add(2);
IList<Integer> top = Sorter.topKSort(5, list);
assertEquals(3, top.size());
assertEquals(2, top.get(0));
assertEquals(3, top.get(1));
assertEquals(8, top.get(2));
}
@Test(timeout=SECOND)
public void testSortMoreThanK() {
IList<Integer> list = new DoubleLinkedList<>();
list.add(3);
list.add(8);
list.add(2);
list.add(11);
list.add(23);
list.add(5);
IList<Integer> top = Sorter.topKSort(4, list);
assertEquals(4, top.size());
assertEquals(5, top.get(0));
assertEquals(8, top.get(1));
assertEquals(11, top.get(2));
assertEquals(23, top.get(3));
}
@Test(timeout=SECOND)
public void testZeroK() {
IList<Integer> list = new DoubleLinkedList<>();
list.add(3);
list.add(8);
list.add(2);
IList<Integer> top = Sorter.topKSort(0, list);
assertEquals(0, top.size());
}
@Test(timeout=SECOND)
public void testWithLargeData() {
IList<Integer> list = new DoubleLinkedList<>();
for (int i = 0; i < 1000; i++) {
list.add(i);
}
IList<Integer> top = Sorter.topKSort(5, list);
assertEquals(5, top.size());
for (int i = 0; i < top.size(); i++) {
assertEquals(995 + i, top.get(i));
}
IList<Integer> top2 = Sorter.topKSort(1000, list);
assertEquals(1000, top2.size());
for (int i = 0; i < top2.size(); i++) {
assertEquals(i, top2.get(i));
}
}
}
| 2,539 | 0.559275 | 0.532493 | 93 | 26.301075 | 18.940645 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.849462 | false | false |
11
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.