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
sequence | 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
sequence | 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8410be086c4e3192542310fa40b021b95bc8686b | 14,216,341,756,718 | edc9062911be0aec0c970a472c1ebcece39c589c | /src/homework_5/Vendor.java | 083316bcee53583226ea221754b31fed91b9658e | [] | no_license | kristjard/Kodutood_Innale | https://github.com/kristjard/Kodutood_Innale | 3d7f0d305b6c021fb8536a82197151f38fea6b77 | 0fbf1f79186cf6407485a25a12d0f6890bd6a20a | refs/heads/master | 2023-01-24T14:33:12.241000 | 2020-12-13T17:47:14 | 2020-12-13T17:47:14 | 256,307,186 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package homework_5;
public class Vendor {
private String companyName;
private String address;
private String repName;
private int phoneNr;
public Vendor(String companyName, String address, String repName, int phoneNr) {
this.companyName = companyName;
this.address = address;
this.repName = repName;
this.phoneNr = phoneNr;
}
public Vendor(){
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getRepName() {
return repName;
}
public void setRepName(String repName) {
this.repName = repName;
}
public int getPhoneNr() {
return phoneNr;
}
public void setPhoneNr(int phoneNr) {
this.phoneNr = phoneNr;
}
@Override
public String toString() {
return companyName + '\'' +
", address='" + address + '\'' +
", rep_name='" + repName + '\'' +
", phone_nr=" + phoneNr +
'}';
}
}
| UTF-8 | Java | 1,274 | java | Vendor.java | Java | [
{
"context": " address + '\\'' +\n \", rep_name='\" + repName + '\\'' +\n \", phone_nr=\" + phon",
"end": 1189,
"score": 0.537028968334198,
"start": 1186,
"tag": "NAME",
"value": "rep"
}
] | null | [] | package homework_5;
public class Vendor {
private String companyName;
private String address;
private String repName;
private int phoneNr;
public Vendor(String companyName, String address, String repName, int phoneNr) {
this.companyName = companyName;
this.address = address;
this.repName = repName;
this.phoneNr = phoneNr;
}
public Vendor(){
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getRepName() {
return repName;
}
public void setRepName(String repName) {
this.repName = repName;
}
public int getPhoneNr() {
return phoneNr;
}
public void setPhoneNr(int phoneNr) {
this.phoneNr = phoneNr;
}
@Override
public String toString() {
return companyName + '\'' +
", address='" + address + '\'' +
", rep_name='" + repName + '\'' +
", phone_nr=" + phoneNr +
'}';
}
}
| 1,274 | 0.565149 | 0.564364 | 59 | 20.59322 | 18.017994 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.40678 | false | false | 4 |
4ce13ad7717730d7fd986bd52fdc8538a12a48e1 | 16,887,811,470,935 | b1bbbe9b11a257a42295032cb47163faf3bfe6e1 | /src/main/java/com/itsubedibesh/walmart/controllers/api/Inventory/Products/ProductsApi.java | 1a77d5e74f2ede934db3e2de9fef456ddea8b3c5 | [] | no_license | itSubeDibesh/Inventory_Management | https://github.com/itSubeDibesh/Inventory_Management | cdd911bf77e0984f6c6d552ec039b92f07cb95db | 8e33d3d40a70d8cfc6571cd5ae721faf30c335f3 | refs/heads/master | 2023-04-13T01:04:51.500000 | 2021-04-13T16:46:21 | 2021-04-13T16:46:21 | 348,314,625 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.itsubedibesh.walmart.controllers.api.Inventory.Products;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/api")
public class ProductsApi {
@Autowired
ProductsRepo productsRepo;
@GetMapping("/products")
public ResponseEntity<List<Products>> getAllProducts() {
try {
List<Products> products = new ArrayList<Products>();
productsRepo.findAll().forEach(products::add);
if (products.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(products, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping("/productsOfVendor/{vendorName}")
public ResponseEntity<List<Products>> getAllProductsOfVendor(@PathVariable() String vendorName) {
try {
List<Products> products = new ArrayList<Products>();
productsRepo.findAllByVendorName(vendorName).forEach(products::add);
if (products.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(products, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping("/vendors")
public ResponseEntity<List<Products>> getAllVendors(){
try{
List<Products> vendors = new ArrayList<Products>();
productsRepo.findAllGroupByVendorName().forEach(vendors::add);
if (vendors.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(vendors, HttpStatus.OK);
}
catch (Exception e){
return new ResponseEntity<>(null,HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
| UTF-8 | Java | 2,370 | java | ProductsApi.java | Java | [] | null | [] | package com.itsubedibesh.walmart.controllers.api.Inventory.Products;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/api")
public class ProductsApi {
@Autowired
ProductsRepo productsRepo;
@GetMapping("/products")
public ResponseEntity<List<Products>> getAllProducts() {
try {
List<Products> products = new ArrayList<Products>();
productsRepo.findAll().forEach(products::add);
if (products.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(products, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping("/productsOfVendor/{vendorName}")
public ResponseEntity<List<Products>> getAllProductsOfVendor(@PathVariable() String vendorName) {
try {
List<Products> products = new ArrayList<Products>();
productsRepo.findAllByVendorName(vendorName).forEach(products::add);
if (products.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(products, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping("/vendors")
public ResponseEntity<List<Products>> getAllVendors(){
try{
List<Products> vendors = new ArrayList<Products>();
productsRepo.findAllGroupByVendorName().forEach(vendors::add);
if (vendors.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(vendors, HttpStatus.OK);
}
catch (Exception e){
return new ResponseEntity<>(null,HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
| 2,370 | 0.664135 | 0.664135 | 63 | 36.619049 | 27.603443 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.507937 | false | false | 4 |
26bb51e95ce1b64756a9d9b9ebf41b46b6b1219e | 30,751,965,874,074 | 0e05b0503b933a2da9c275fa75c417d06e6a2666 | /app/src/main/java/vn/thientf/iwaiter/Interface/ItemClickListener.java | 0390082730f88909e183a7820a522fcb51237bc1 | [] | no_license | Sinchana27-M/iWaiter | https://github.com/Sinchana27-M/iWaiter | 0d7f9bbb522e3eb0b107414bc79d09c2563192df | 5b4444d8b53197b2715d69b4eaf4fb985d3fee70 | refs/heads/master | 2023-06-28T08:25:27.987000 | 2018-07-10T02:13:24 | 2018-07-10T02:13:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package vn.thientf.iwaiter.Interface;
import android.view.View;
/**
* Created by ASUS on 22/06/2018.
*/
public interface ItemClickListener {
public void onClick(View view, int pos);
}
| UTF-8 | Java | 193 | java | ItemClickListener.java | Java | [
{
"context": "ace;\n\nimport android.view.View;\n\n/**\n * Created by ASUS on 22/06/2018.\n */\n\npublic interface ItemClickLis",
"end": 88,
"score": 0.93476402759552,
"start": 84,
"tag": "NAME",
"value": "ASUS"
}
] | null | [] | package vn.thientf.iwaiter.Interface;
import android.view.View;
/**
* Created by ASUS on 22/06/2018.
*/
public interface ItemClickListener {
public void onClick(View view, int pos);
}
| 193 | 0.720207 | 0.678756 | 11 | 16.545454 | 17.380049 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 4 |
66b200e2cc4e71d9895bfaddb1d574a17672543b | 4,904,852,677,224 | 892602da84e5798e40b0af1af04df1bc274d8fd6 | /prep/src/test/java/com/john/Nov2022/leetcode/q500_599/Question560Test.java | f597d06b437cf252437d0f12ced32524f3e005bc | [] | no_license | deviantthread/InterviewPrepQuestions | https://github.com/deviantthread/InterviewPrepQuestions | f6002e3cbf4c6ace099a8ae6f734fc2e1c3d5023 | d93077dad611dce8e86e483de36ba6e8704166f5 | refs/heads/master | 2023-04-13T04:29:34.114000 | 2023-04-04T21:36:44 | 2023-04-04T21:36:44 | 37,752,719 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.john.Nov2022.leetcode.q500_599;
import com.john.leetcode.inputhelp.CollectionCreator;
import org.junit.Assert;
import org.junit.Test;
public class Question560Test {
private final Question560 classUnderTest = new Question560();
@Test
public void testExample1() {
int[] nums = CollectionCreator.createArrayInt("[1,1,1]");
int k = 2;
int expected = 2;
Assert.assertEquals(expected, classUnderTest.subarraySum(nums, k));
}
@Test
public void testExample2() {
int[] nums = CollectionCreator.createArrayInt("[1,2,3]");
int k = 3;
int expected = 2;
Assert.assertEquals(expected, classUnderTest.subarraySum(nums, k));
}
}
| UTF-8 | Java | 721 | java | Question560Test.java | Java | [] | null | [] | package com.john.Nov2022.leetcode.q500_599;
import com.john.leetcode.inputhelp.CollectionCreator;
import org.junit.Assert;
import org.junit.Test;
public class Question560Test {
private final Question560 classUnderTest = new Question560();
@Test
public void testExample1() {
int[] nums = CollectionCreator.createArrayInt("[1,1,1]");
int k = 2;
int expected = 2;
Assert.assertEquals(expected, classUnderTest.subarraySum(nums, k));
}
@Test
public void testExample2() {
int[] nums = CollectionCreator.createArrayInt("[1,2,3]");
int k = 3;
int expected = 2;
Assert.assertEquals(expected, classUnderTest.subarraySum(nums, k));
}
}
| 721 | 0.662968 | 0.619972 | 25 | 27.84 | 24.759127 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.84 | false | false | 4 |
92c63a2141107f7f8c010ff6a93b136b8131aaa8 | 1,005,022,372,930 | b9fb025dac8ab1337d8514ed759a268b6b3d02fb | /app/src/main/java/com/example/apptest/DataBase/DBHelper.java | b25508e1a1e83b81b4b5dc159f61c86c01312f2c | [] | no_license | abhi8422/InterviewAssignment | https://github.com/abhi8422/InterviewAssignment | 987958dde2574876d27131e39cce568b6cfc6df5 | c3f0d10d4f69ae1aabbb59613f1bf275ad3c5529 | refs/heads/master | 2020-04-26T14:13:13.581000 | 2019-03-03T17:17:26 | 2019-03-03T17:17:26 | 173,605,429 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.apptest.DataBase;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import com.example.apptest.model.Results;
public class DBHelper extends SQLiteOpenHelper {
private static final String DB_NAME="meetup_db";
private static int DB_VERSION=1;
public static final String MEETUP_TABLE="EMPLOYEE";
public static final String ID="id";
public static final String NAME="name";
public static final String DESCRIPTION="description";
public static final String COUNT="membercount";
public static final String LON="longitude";
public static final String LAT="latitude";
SQLiteDatabase db = getWritableDatabase();
Results results1;
public DBHelper(Context context) {
super(context, DB_NAME, null , DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String DB_CREATE= " create table " + MEETUP_TABLE + " ( " + ID + " integer primary key ," + NAME +
" text , " + DESCRIPTION + " text ," + COUNT + " integer , " + LON + " double , " + LAT + " double ) ";
db.execSQL(DB_CREATE);
}
public void insertData(Results[] results, Context context){
ContentValues cv = new ContentValues();
for(int i = 0; i == results.length; i++) {
results1 = results[i];
int id=Integer.parseInt(results1.getId());
cv.put(ID,id);
cv.put(NAME, results1.getName());
cv.put(DESCRIPTION, results1.getDescription());
cv.put(COUNT, results1.getMembers());
cv.put(LON, results1.getLon());
cv.put(LAT, results1.getLat());
long insert = db.insert(MEETUP_TABLE, null, cv);
if (insert == 0) {
Toast.makeText(context, "Data Is Not Stored", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Data Is Stored", Toast.LENGTH_SHORT).show();
}
}
db.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
| UTF-8 | Java | 2,231 | java | DBHelper.java | Java | [] | null | [] | package com.example.apptest.DataBase;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import com.example.apptest.model.Results;
public class DBHelper extends SQLiteOpenHelper {
private static final String DB_NAME="meetup_db";
private static int DB_VERSION=1;
public static final String MEETUP_TABLE="EMPLOYEE";
public static final String ID="id";
public static final String NAME="name";
public static final String DESCRIPTION="description";
public static final String COUNT="membercount";
public static final String LON="longitude";
public static final String LAT="latitude";
SQLiteDatabase db = getWritableDatabase();
Results results1;
public DBHelper(Context context) {
super(context, DB_NAME, null , DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String DB_CREATE= " create table " + MEETUP_TABLE + " ( " + ID + " integer primary key ," + NAME +
" text , " + DESCRIPTION + " text ," + COUNT + " integer , " + LON + " double , " + LAT + " double ) ";
db.execSQL(DB_CREATE);
}
public void insertData(Results[] results, Context context){
ContentValues cv = new ContentValues();
for(int i = 0; i == results.length; i++) {
results1 = results[i];
int id=Integer.parseInt(results1.getId());
cv.put(ID,id);
cv.put(NAME, results1.getName());
cv.put(DESCRIPTION, results1.getDescription());
cv.put(COUNT, results1.getMembers());
cv.put(LON, results1.getLon());
cv.put(LAT, results1.getLat());
long insert = db.insert(MEETUP_TABLE, null, cv);
if (insert == 0) {
Toast.makeText(context, "Data Is Not Stored", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Data Is Stored", Toast.LENGTH_SHORT).show();
}
}
db.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
| 2,231 | 0.62528 | 0.62035 | 65 | 33.323078 | 27.447353 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.907692 | false | false | 4 |
5fcaacd8dc7e566d56636e6472e0eec0ecbb1099 | 28,209,345,246,052 | 294ce33df0e67cb3bf686983bf19d76004b658bf | /examples/test2/java_source/com/tencent/wxop/stat/ak.java | abce03cb4d8b0a042ced4e2364a3e74ad44b40a5 | [] | no_license | flyDream123/script | https://github.com/flyDream123/script | b5fd3308264fb4ac4cc09428aa062ae83b8be3d7 | 6607aa81002b4fe5044a0ade1b8898a55c31205c | refs/heads/master | 2021-01-22T12:43:56.478000 | 2017-09-04T11:22:44 | 2017-09-04T11:22:44 | 102,352,318 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tencent.wxop.stat;
import android.content.Context;
import com.tencent.wxop.stat.common.StatLogger;
final class ak
implements Runnable
{
ak(String paramString, Context paramContext, StatSpecifyReportedInfo paramStatSpecifyReportedInfo) {}
public final void run()
{
if ((a == null) || (a.trim().length() == 0))
{
StatServiceImpl.f().w("qq num is null or empty.");
return;
}
StatConfig.f = a;
StatServiceImpl.a(b, new StatAccount(a), c);
}
}
| UTF-8 | Java | 498 | java | ak.java | Java | [] | null | [] | package com.tencent.wxop.stat;
import android.content.Context;
import com.tencent.wxop.stat.common.StatLogger;
final class ak
implements Runnable
{
ak(String paramString, Context paramContext, StatSpecifyReportedInfo paramStatSpecifyReportedInfo) {}
public final void run()
{
if ((a == null) || (a.trim().length() == 0))
{
StatServiceImpl.f().w("qq num is null or empty.");
return;
}
StatConfig.f = a;
StatServiceImpl.a(b, new StatAccount(a), c);
}
}
| 498 | 0.670683 | 0.668675 | 21 | 22.714285 | 25.386803 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.619048 | false | false | 4 |
964742aa37740825615ed1a41da2a49c75188864 | 28,209,345,246,967 | 742b8a21cbf5d21b6880b58fef367cc0b17bf87b | /src/me/coolade/monstersplus/monsters/monsterevents/SpiderSpawnEvent.java | c62acef074eeac88b9a68f56fa94bdb764fc6b42 | [] | no_license | nathank33/MonstersPlus | https://github.com/nathank33/MonstersPlus | 0b1d92789a309eda8a37e4719902c19b14c6a42a | 5d91cc42615335ca3ec4192cd26478ad45472d9b | refs/heads/master | 2021-07-03T19:43:52.694000 | 2016-11-03T06:13:14 | 2016-11-03T06:13:14 | 24,926,272 | 3 | 6 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.coolade.monstersplus.monsters.monsterevents;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.MagmaCube;
import org.bukkit.entity.Slime;
import org.bukkit.entity.Wolf;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import me.coolade.monstersplus.MonstersPlus;
import me.coolade.monstersplus.monsters.MonsterList;
import me.coolade.monstersplus.monsters.MonsterListener;
public class SpiderSpawnEvent {
/*
* Instead of using a field lent, we want to directly pass the lent that was
* sent to us, that way if it came through a command it would be able to
* modify the original lent, not a copy reference.
*/
LivingEntity lent;
String mobName;
public SpiderSpawnEvent(LivingEntity lent, String mobName) {
this.lent = lent;
this.mobName = mobName;
createMonster();
}
public SpiderSpawnEvent(LivingEntity lent) {
this(lent, MonsterList.generateMonster(EntityType.SPIDER, lent.getLocation().getBlock().getBiome()));
}
public LivingEntity getLent() {
return lent;
}
public String getMobName() {
return mobName;
}
public void setLent(LivingEntity lent) {
this.lent = lent;
}
public void setMobName(String mobName) {
this.mobName = mobName;
}
public void createMonster() {
// EntityEquipment ee = lent.getEquipment();
if (mobName == null) {
return;
}
/** Black Widow EASY **/
if (mobName.equalsIgnoreCase("Black Widow")) {
lent.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, MonsterListener.POTION_DURATION, 1));
} else if (mobName.equalsIgnoreCase("Mountain Pincer")) {
MonstersPlus.setSpeed(lent, 0.40);
} else if (mobName.equalsIgnoreCase("Witch Apprentice")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.WITCH);
}
/** Scorpion Medium **/
else if (mobName.equalsIgnoreCase("Scorpion")) {
Location loc = lent.getLocation();
lent.remove();
LivingEntity scorp = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.SILVERFISH);
lent = scorp;
}
/** Rock Scorpion Medium **/
else if (mobName.equalsIgnoreCase("Rock Scorpion")) {
Location loc = lent.getLocation();
lent.remove();
LivingEntity scorp = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.SILVERFISH);
lent = scorp;
}
/** Stinger MEDIUM **/
else if (mobName.equalsIgnoreCase("Stinger")) {
lent.addPotionEffect(
new PotionEffect(PotionEffectType.INCREASE_DAMAGE, MonsterListener.POTION_DURATION, 1));
lent.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, MonsterListener.POTION_DURATION, 1));
} else if (mobName.equalsIgnoreCase("Desert Scorpion")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.SILVERFISH);
lent.addPotionEffect(
new PotionEffect(PotionEffectType.FIRE_RESISTANCE, MonsterListener.POTION_DURATION, 100));
lent.setFireTicks(MonsterListener.POTION_DURATION);
} else if (mobName.equalsIgnoreCase("Witch of the East")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.WITCH);
} else if (mobName.equalsIgnoreCase("Tarantula")) {
lent.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, MonsterListener.POTION_DURATION, 5));
lent.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, MonsterListener.POTION_DURATION, 2));
} else if (mobName.equalsIgnoreCase("Ice Spider")) {
lent.addPotionEffect(
new PotionEffect(PotionEffectType.INCREASE_DAMAGE, MonsterListener.POTION_DURATION, 1));
} else if (mobName.equalsIgnoreCase("Warlock")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.WITCH);
}
/** BROWN RECLUSE Hard **/
else if (mobName.equalsIgnoreCase("Brown Recluse")) {
lent.addPotionEffect(
new PotionEffect(PotionEffectType.INCREASE_DAMAGE, MonsterListener.POTION_DURATION, 1));
} else if (mobName.equalsIgnoreCase("Witch of the West")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.WITCH);
} else if (mobName.equalsIgnoreCase("Dark Mage")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.WITCH);
} else if (mobName.equalsIgnoreCase("Water Stinger")) {
lent.addPotionEffect(
new PotionEffect(PotionEffectType.INCREASE_DAMAGE, MonsterListener.POTION_DURATION, 1));
lent.addPotionEffect(
new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, MonsterListener.POTION_DURATION, 1));
} else if (mobName.equalsIgnoreCase("Filth Purch")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.SILVERFISH);
} else if (mobName.equalsIgnoreCase("Swamp Witch")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.WITCH);
}
/** Infearno Legendary **/
else if (mobName.equalsIgnoreCase("Infearno")) {
Location loc = lent.getLocation();
lent.remove();
LivingEntity newLent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.MAGMA_CUBE);
((MagmaCube) newLent).setSize(7);
newLent.addPotionEffect(
new PotionEffect(PotionEffectType.FIRE_RESISTANCE, MonsterListener.POTION_DURATION, 50));
lent = newLent;
}
/** Hadamard Legendary **/
else if (mobName.equalsIgnoreCase("Hadamard")) {
Location loc = lent.getLocation();
lent.remove();
LivingEntity newLent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.SLIME);
((Slime) newLent).setSize(5);
newLent.addPotionEffect(
new PotionEffect(PotionEffectType.FIRE_RESISTANCE, MonsterListener.POTION_DURATION, 50));
lent = newLent;
}
/** Lesath Legendary **/
else if (mobName.equalsIgnoreCase("Lesath")) {
lent.addPotionEffect(
new PotionEffect(PotionEffectType.FIRE_RESISTANCE, MonsterListener.POTION_DURATION, 50));
lent.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, MonsterListener.POTION_DURATION, 2));
}
/** Shelob Legendary **/
else if (mobName.equalsIgnoreCase("Shelob")) {
lent.addPotionEffect(
new PotionEffect(PotionEffectType.FIRE_RESISTANCE, MonsterListener.POTION_DURATION, 2));
lent.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, MonsterListener.POTION_DURATION, 1));
}
/** Arachne Legendary **/
else if (mobName.equalsIgnoreCase("Arachne")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.CAVE_SPIDER);
lent.addPotionEffect(
new PotionEffect(PotionEffectType.FIRE_RESISTANCE, MonsterListener.POTION_DURATION, 2));
lent.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, MonsterListener.POTION_DURATION, 1));
}
/** Charlotte Legendary **/
else if (mobName.equalsIgnoreCase("Charlotte")) {
lent.setMaxHealth(MonsterList.getMaxHealth("Charlotte"));
lent.setHealth(lent.getMaxHealth());
lent.addPotionEffect(
new PotionEffect(PotionEffectType.INCREASE_DAMAGE, MonsterListener.POTION_DURATION, 2));
lent.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, MonsterListener.POTION_DURATION, 3));
lent.setCustomName(ChatColor.DARK_PURPLE + "Charlotte");
}
/** Raikou Legendary **/
else if (mobName.equalsIgnoreCase("Raikou")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.WOLF);
((Wolf) lent).setAngry(true);
lent.addPotionEffect(
new PotionEffect(PotionEffectType.FIRE_RESISTANCE, MonsterListener.POTION_DURATION, 50));
lent.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, MonsterListener.POTION_DURATION, 1));
}
/** Entei Legendary **/
else if (mobName.equalsIgnoreCase("Entei")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.WOLF);
((Wolf) lent).setAngry(true);
lent.addPotionEffect(
new PotionEffect(PotionEffectType.FIRE_RESISTANCE, MonsterListener.POTION_DURATION, 100));
lent.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, MonsterListener.POTION_DURATION, 1));
lent.setFireTicks(MonsterListener.POTION_DURATION);
}
/** Suicune Legendary **/
else if (mobName.equalsIgnoreCase("Suicune")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.WOLF);
((Wolf) lent).setAngry(true);
lent.addPotionEffect(
new PotionEffect(PotionEffectType.FIRE_RESISTANCE, MonsterListener.POTION_DURATION, 100));
lent.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, MonsterListener.POTION_DURATION, 1));
}
/** Barkira Legendary **/
else if (mobName.equalsIgnoreCase("Barkira")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.WOLF);
((Wolf) lent).setAngry(true);
lent.addPotionEffect(
new PotionEffect(PotionEffectType.FIRE_RESISTANCE, MonsterListener.POTION_DURATION, 100));
lent.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, MonsterListener.POTION_DURATION, 1));
}
double health = MonsterList.getMaxHealth(mobName);
if (health > 0) {
lent.setMaxHealth(health);
lent.setHealth(health);
lent.setCustomName(MonsterList.getColoredMobName(mobName));
}
}
}
| UTF-8 | Java | 9,669 | java | SpiderSpawnEvent.java | Java | [
{
"context": "t, 0.40);\n\t\t} else if (mobName.equalsIgnoreCase(\"Witch Apprentice\")) {\n\t\t\tLocation loc = lent.getLocatio",
"end": 1778,
"score": 0.5067849159240723,
"start": 1774,
"tag": "NAME",
"value": "itch"
},
{
"context": ";\n\t\t} else if (mobName.equalsIgnoreCase(\"Witch Apprentice\")) {\n\t\t\tLocation loc = lent.getLocation();\n\t\t\t",
"end": 1786,
"score": 0.5456534624099731,
"start": 1782,
"tag": "NAME",
"value": "rent"
},
{
"context": "TION, 1));\n\t\t} else if (mobName.equalsIgnoreCase(\"Desert Scorpion\")) {\n\t\t\tLocation loc = lent.getLocation(",
"end": 2781,
"score": 0.571144700050354,
"start": 2775,
"tag": "NAME",
"value": "Desert"
},
{
"context": ");\n\t\t} else if (mobName.equalsIgnoreCase(\"Desert Scorpion\")) {\n\t\t\tLocation loc = lent.getLocation();\n\t\t\t",
"end": 2787,
"score": 0.621021568775177,
"start": 2783,
"tag": "NAME",
"value": "corp"
},
{
"context": "TION, 1));\n\t\t} else if (mobName.equalsIgnoreCase(\"Filth Purch\")) {\n\t\t\tLocation loc = lent.getLocation();\n\t\t\tlen",
"end": 4863,
"score": 0.996709942817688,
"start": 4852,
"tag": "NAME",
"value": "Filth Purch"
},
{
"context": "LVERFISH);\n\t\t} else if (mobName.equalsIgnoreCase(\"Swamp Witch\")) {\n\t\t\tLocation loc = lent.getLocation();\n\t\t\tlen",
"end": 5056,
"score": 0.9807595610618591,
"start": 5045,
"tag": "NAME",
"value": "Swamp Witch"
},
{
"context": "egendary **/\n\t\telse if (mobName.equalsIgnoreCase(\"Infearno\")) {\n\t\t\tLocation loc = lent.getLocation();\n\t\t\tlen",
"end": 5273,
"score": 0.9370973706245422,
"start": 5265,
"tag": "NAME",
"value": "Infearno"
},
{
"context": "egendary **/\n\t\telse if (mobName.equalsIgnoreCase(\"Hadamard\")) {\n\t\t\tLocation loc = lent.getLocation();\n\t\t\tlen",
"end": 5689,
"score": 0.9633978009223938,
"start": 5681,
"tag": "NAME",
"value": "Hadamard"
},
{
"context": "egendary **/\n\t\telse if (mobName.equalsIgnoreCase(\"Lesath\")) {\n\t\t\tlent.addPotionEffect(\n\t\t\t\t\tnew PotionEffe",
"end": 6092,
"score": 0.856436014175415,
"start": 6086,
"tag": "NAME",
"value": "Lesath"
}
] | null | [] | package me.coolade.monstersplus.monsters.monsterevents;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.MagmaCube;
import org.bukkit.entity.Slime;
import org.bukkit.entity.Wolf;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import me.coolade.monstersplus.MonstersPlus;
import me.coolade.monstersplus.monsters.MonsterList;
import me.coolade.monstersplus.monsters.MonsterListener;
public class SpiderSpawnEvent {
/*
* Instead of using a field lent, we want to directly pass the lent that was
* sent to us, that way if it came through a command it would be able to
* modify the original lent, not a copy reference.
*/
LivingEntity lent;
String mobName;
public SpiderSpawnEvent(LivingEntity lent, String mobName) {
this.lent = lent;
this.mobName = mobName;
createMonster();
}
public SpiderSpawnEvent(LivingEntity lent) {
this(lent, MonsterList.generateMonster(EntityType.SPIDER, lent.getLocation().getBlock().getBiome()));
}
public LivingEntity getLent() {
return lent;
}
public String getMobName() {
return mobName;
}
public void setLent(LivingEntity lent) {
this.lent = lent;
}
public void setMobName(String mobName) {
this.mobName = mobName;
}
public void createMonster() {
// EntityEquipment ee = lent.getEquipment();
if (mobName == null) {
return;
}
/** Black Widow EASY **/
if (mobName.equalsIgnoreCase("Black Widow")) {
lent.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, MonsterListener.POTION_DURATION, 1));
} else if (mobName.equalsIgnoreCase("Mountain Pincer")) {
MonstersPlus.setSpeed(lent, 0.40);
} else if (mobName.equalsIgnoreCase("Witch Apprentice")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.WITCH);
}
/** Scorpion Medium **/
else if (mobName.equalsIgnoreCase("Scorpion")) {
Location loc = lent.getLocation();
lent.remove();
LivingEntity scorp = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.SILVERFISH);
lent = scorp;
}
/** Rock Scorpion Medium **/
else if (mobName.equalsIgnoreCase("Rock Scorpion")) {
Location loc = lent.getLocation();
lent.remove();
LivingEntity scorp = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.SILVERFISH);
lent = scorp;
}
/** Stinger MEDIUM **/
else if (mobName.equalsIgnoreCase("Stinger")) {
lent.addPotionEffect(
new PotionEffect(PotionEffectType.INCREASE_DAMAGE, MonsterListener.POTION_DURATION, 1));
lent.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, MonsterListener.POTION_DURATION, 1));
} else if (mobName.equalsIgnoreCase("Desert Scorpion")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.SILVERFISH);
lent.addPotionEffect(
new PotionEffect(PotionEffectType.FIRE_RESISTANCE, MonsterListener.POTION_DURATION, 100));
lent.setFireTicks(MonsterListener.POTION_DURATION);
} else if (mobName.equalsIgnoreCase("Witch of the East")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.WITCH);
} else if (mobName.equalsIgnoreCase("Tarantula")) {
lent.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, MonsterListener.POTION_DURATION, 5));
lent.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, MonsterListener.POTION_DURATION, 2));
} else if (mobName.equalsIgnoreCase("Ice Spider")) {
lent.addPotionEffect(
new PotionEffect(PotionEffectType.INCREASE_DAMAGE, MonsterListener.POTION_DURATION, 1));
} else if (mobName.equalsIgnoreCase("Warlock")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.WITCH);
}
/** BROWN RECLUSE Hard **/
else if (mobName.equalsIgnoreCase("Brown Recluse")) {
lent.addPotionEffect(
new PotionEffect(PotionEffectType.INCREASE_DAMAGE, MonsterListener.POTION_DURATION, 1));
} else if (mobName.equalsIgnoreCase("Witch of the West")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.WITCH);
} else if (mobName.equalsIgnoreCase("Dark Mage")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.WITCH);
} else if (mobName.equalsIgnoreCase("Water Stinger")) {
lent.addPotionEffect(
new PotionEffect(PotionEffectType.INCREASE_DAMAGE, MonsterListener.POTION_DURATION, 1));
lent.addPotionEffect(
new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, MonsterListener.POTION_DURATION, 1));
} else if (mobName.equalsIgnoreCase("<NAME>")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.SILVERFISH);
} else if (mobName.equalsIgnoreCase("<NAME>")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.WITCH);
}
/** Infearno Legendary **/
else if (mobName.equalsIgnoreCase("Infearno")) {
Location loc = lent.getLocation();
lent.remove();
LivingEntity newLent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.MAGMA_CUBE);
((MagmaCube) newLent).setSize(7);
newLent.addPotionEffect(
new PotionEffect(PotionEffectType.FIRE_RESISTANCE, MonsterListener.POTION_DURATION, 50));
lent = newLent;
}
/** Hadamard Legendary **/
else if (mobName.equalsIgnoreCase("Hadamard")) {
Location loc = lent.getLocation();
lent.remove();
LivingEntity newLent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.SLIME);
((Slime) newLent).setSize(5);
newLent.addPotionEffect(
new PotionEffect(PotionEffectType.FIRE_RESISTANCE, MonsterListener.POTION_DURATION, 50));
lent = newLent;
}
/** Lesath Legendary **/
else if (mobName.equalsIgnoreCase("Lesath")) {
lent.addPotionEffect(
new PotionEffect(PotionEffectType.FIRE_RESISTANCE, MonsterListener.POTION_DURATION, 50));
lent.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, MonsterListener.POTION_DURATION, 2));
}
/** Shelob Legendary **/
else if (mobName.equalsIgnoreCase("Shelob")) {
lent.addPotionEffect(
new PotionEffect(PotionEffectType.FIRE_RESISTANCE, MonsterListener.POTION_DURATION, 2));
lent.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, MonsterListener.POTION_DURATION, 1));
}
/** Arachne Legendary **/
else if (mobName.equalsIgnoreCase("Arachne")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.CAVE_SPIDER);
lent.addPotionEffect(
new PotionEffect(PotionEffectType.FIRE_RESISTANCE, MonsterListener.POTION_DURATION, 2));
lent.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, MonsterListener.POTION_DURATION, 1));
}
/** Charlotte Legendary **/
else if (mobName.equalsIgnoreCase("Charlotte")) {
lent.setMaxHealth(MonsterList.getMaxHealth("Charlotte"));
lent.setHealth(lent.getMaxHealth());
lent.addPotionEffect(
new PotionEffect(PotionEffectType.INCREASE_DAMAGE, MonsterListener.POTION_DURATION, 2));
lent.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, MonsterListener.POTION_DURATION, 3));
lent.setCustomName(ChatColor.DARK_PURPLE + "Charlotte");
}
/** Raikou Legendary **/
else if (mobName.equalsIgnoreCase("Raikou")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.WOLF);
((Wolf) lent).setAngry(true);
lent.addPotionEffect(
new PotionEffect(PotionEffectType.FIRE_RESISTANCE, MonsterListener.POTION_DURATION, 50));
lent.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, MonsterListener.POTION_DURATION, 1));
}
/** Entei Legendary **/
else if (mobName.equalsIgnoreCase("Entei")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.WOLF);
((Wolf) lent).setAngry(true);
lent.addPotionEffect(
new PotionEffect(PotionEffectType.FIRE_RESISTANCE, MonsterListener.POTION_DURATION, 100));
lent.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, MonsterListener.POTION_DURATION, 1));
lent.setFireTicks(MonsterListener.POTION_DURATION);
}
/** Suicune Legendary **/
else if (mobName.equalsIgnoreCase("Suicune")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.WOLF);
((Wolf) lent).setAngry(true);
lent.addPotionEffect(
new PotionEffect(PotionEffectType.FIRE_RESISTANCE, MonsterListener.POTION_DURATION, 100));
lent.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, MonsterListener.POTION_DURATION, 1));
}
/** Barkira Legendary **/
else if (mobName.equalsIgnoreCase("Barkira")) {
Location loc = lent.getLocation();
lent.remove();
lent = (LivingEntity) loc.getWorld().spawnEntity(loc, EntityType.WOLF);
((Wolf) lent).setAngry(true);
lent.addPotionEffect(
new PotionEffect(PotionEffectType.FIRE_RESISTANCE, MonsterListener.POTION_DURATION, 100));
lent.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, MonsterListener.POTION_DURATION, 1));
}
double health = MonsterList.getMaxHealth(mobName);
if (health > 0) {
lent.setMaxHealth(health);
lent.setHealth(health);
lent.setCustomName(MonsterList.getColoredMobName(mobName));
}
}
}
| 9,659 | 0.735753 | 0.730996 | 235 | 40.14468 | 30.567755 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.165957 | false | false | 4 |
bf81c0be67b9d76fea42d714ef8069fd9b89ef81 | 34,041,910,794,947 | 781386210ec1c318a5085822444e6f570079874e | /0.UML/src/implement/PrintClass.java | d333d6cef0bb217b48cba93c0b0a743efe7472a2 | [] | no_license | guoyu07/DesignPattern-84 | https://github.com/guoyu07/DesignPattern-84 | 0b24a6c723dd54b21354e319ab0efa5b23cc26d5 | f5d5c7d4c7813bbcdfa2f10fc8d3fb6a503c7e1f | refs/heads/master | 2021-01-01T06:53:34.142000 | 2016-12-16T08:18:10 | 2016-12-16T08:18:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package implement;
class PrintClass implements Printable {
public void print(){
}
public void newPage(){
}
} | UTF-8 | Java | 124 | java | PrintClass.java | Java | [] | null | [] | package implement;
class PrintClass implements Printable {
public void print(){
}
public void newPage(){
}
} | 124 | 0.66129 | 0.66129 | 10 | 10.6 | 13.039939 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
0661a14a4c73e085fe68d991ff02148138428eba | 14,912,126,463,012 | bdae74528cbc0ce7dd6b5b6bbef8142c264e8216 | /Aroha_programs/src/Aroha_first_floor/eight.java | 38bdb00501024818d887ac22687e458d71c94842 | [] | no_license | SandeepAroha07/Aroha_java_codes | https://github.com/SandeepAroha07/Aroha_java_codes | 683b611730ba4bb8195111323c23f2ceaa6379dd | 898ee59433009fa9a2df17ee6f1ec9d5f30626fe | refs/heads/master | 2020-07-29T10:08:46.921000 | 2019-09-20T09:47:01 | 2019-09-20T09:47:01 | 209,757,746 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Aroha_first_floor;
public class eight {
public static void main(String[] args) {
// TODO Auto-generated method stub
char ch='a';
char charr=('m'+7);
{
for(;ch<='m';ch++)
System.out.println(ch);
}
{
for(;charr<='z';charr++)
System.out.println(charr);
}
}
}
| UTF-8 | Java | 318 | java | eight.java | Java | [] | null | [] | package Aroha_first_floor;
public class eight {
public static void main(String[] args) {
// TODO Auto-generated method stub
char ch='a';
char charr=('m'+7);
{
for(;ch<='m';ch++)
System.out.println(ch);
}
{
for(;charr<='z';charr++)
System.out.println(charr);
}
}
}
| 318 | 0.54717 | 0.544025 | 22 | 12.454545 | 13.337327 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.590909 | false | false | 4 |
0ba64ecfeb7dcaf3d32ddfcc33de4d9be306bea2 | 22,677,427,361,688 | 9cfb35f9d543e01c4ad36eed51d892cc39f13b68 | /telegram-spring/src/main/java/eddy/bot/telegram/core/ContentDetails.java | aae52b32b6ea285ba5700cb4c839f5716bde1fed | [] | no_license | sieunkr/bot | https://github.com/sieunkr/bot | 7158c091e2e1025818445ea99580aa12074c12c5 | 0e9cd8ec6e228ce3ce0e0bfd822b99078c16c820 | refs/heads/master | 2020-04-27T00:44:02.765000 | 2019-09-24T13:20:55 | 2019-09-24T13:20:55 | 173,943,876 | 8 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null | package eddy.bot.telegram.core;
import reactor.core.publisher.Mono;
public interface ContentDetails {
Mono<Content> findByName(String name);
Mono<Content> searchByKeyword(String keyword);
Mono<Void> syncOne(String name);
Mono<?> template(Content content);
} | UTF-8 | Java | 275 | java | ContentDetails.java | Java | [] | null | [] | package eddy.bot.telegram.core;
import reactor.core.publisher.Mono;
public interface ContentDetails {
Mono<Content> findByName(String name);
Mono<Content> searchByKeyword(String keyword);
Mono<Void> syncOne(String name);
Mono<?> template(Content content);
} | 275 | 0.749091 | 0.749091 | 10 | 26.6 | 17.900839 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 4 |
e75c30fb4387e309ea8d996b6ef6589629640c69 | 22,677,427,365,701 | f4bd840f1d45733cfb8fc4b3eda03e06f790ad38 | /FoodOrderingWebApp/src/main/java/com/fdmgroup/food/Dish.java | a77a57ac086b53e18d6c6bfd76222f269b9ae5f1 | [] | no_license | southpaw93/Java-Practice | https://github.com/southpaw93/Java-Practice | 9b96b3ae190fde5c2a933b06f6370618112a212e | d8321657212c5e7097a9d02cf9cc7926d4cd565e | refs/heads/master | 2020-04-30T20:35:41.719000 | 2019-03-23T05:02:58 | 2019-03-23T05:02:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fdmgroup.food;
public class Dish {
private String dishName;
private double dishPrice;
public Dish(String dishName, double dishPrice) {
this.dishName = dishName;
this.dishPrice = dishPrice;
}
public String getDishName() {
return dishName;
}
public void setDishName(String dishName) {
this.dishName = dishName;
}
public double getDishPrice() {
return dishPrice;
}
public void setDishPrice(double dishPrice) {
this.dishPrice = dishPrice;
}
public String toString(){
return dishName;
}
}
| UTF-8 | Java | 531 | java | Dish.java | Java | [] | null | [] | package com.fdmgroup.food;
public class Dish {
private String dishName;
private double dishPrice;
public Dish(String dishName, double dishPrice) {
this.dishName = dishName;
this.dishPrice = dishPrice;
}
public String getDishName() {
return dishName;
}
public void setDishName(String dishName) {
this.dishName = dishName;
}
public double getDishPrice() {
return dishPrice;
}
public void setDishPrice(double dishPrice) {
this.dishPrice = dishPrice;
}
public String toString(){
return dishName;
}
}
| 531 | 0.725047 | 0.725047 | 28 | 17.964285 | 14.98924 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5 | false | false | 4 |
1d8b9763bffeae984d4d4cc9fc87d8ce55cc6d57 | 24,300,925,025,224 | 5bddf06d8768eea29ab72e65b8ea79d5cbf5a2cd | /sonar-xml-plugin/src/main/java/org/sonar/plugins/xml/parsers/DetectSchemaParser.java | 4596780696c39fd67ba43b4a36b5432a133f4b26 | [] | no_license | iveslandrieu/sonar-xml | https://github.com/iveslandrieu/sonar-xml | d8bdbf6b528f24c4ad3defff33188dc5b6823b7e | 1542b9e19f340e85f2da7abf3066d6ee0b0b655d | refs/heads/master | 2020-04-08T20:16:27.449000 | 2016-01-26T13:32:15 | 2016-01-26T13:32:15 | 50,430,109 | 5 | 0 | null | true | 2016-01-26T13:25:56 | 2016-01-26T13:25:56 | 2015-11-23T12:28:43 | 2015-12-11T08:29:16 | 819 | 0 | 0 | 0 | null | null | null | /*
* SonarQube XML Plugin
* Copyright (C) 2010 SonarSource
* sonarqube@googlegroups.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sonar.plugins.xml.parsers;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.SAXParser;
import org.apache.commons.io.IOUtils;
import org.apache.xerces.impl.Constants;
import org.sonar.api.utils.SonarException;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.DefaultHandler;
/**
* Parse the file quickly only to detect the sDTD or Schema.
*
* @author Matthijs Galesloot
*/
public final class DetectSchemaParser extends AbstractParser {
/**
* Doctype declaration in a Document.
*/
public static class Doctype {
private String dtd;
private String namespace;
public String getDtd() {
return dtd;
}
public String getNamespace() {
return namespace;
}
}
/**
* Exception to stop the parser from further processing.
*/
private static class StopParserException extends SAXException {
private static final long serialVersionUID = 1L;
}
private static class Handler extends DefaultHandler implements LexicalHandler {
private Doctype doctype = new Doctype();
public void comment(char[] arg0, int arg1, int arg2) throws SAXException {
// empty
}
public void endCDATA() throws SAXException {
// empty
}
public void endDTD() throws SAXException {
// empty
}
public void endEntity(String name) throws SAXException {
// empty
}
@Override
public void fatalError(SAXParseException e) throws SAXException {
// ignore
}
public void startCDATA() throws SAXException {
// empty
}
public void startDTD(String name, String publicId, String systemId) throws SAXException {
doctype.dtd = publicId;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
doctype.namespace = attributes.getValue("xmlns");
// we are done, cause the parser to stop
throw new StopParserException();
}
public void startEntity(String name) throws SAXException {
// empty
}
}
/**
* Find the Doctype (DTD or schema).
*/
public Doctype findDoctype(InputStream input) {
Handler handler = new Handler();
try {
SAXParser parser = newSaxParser(false);
XMLReader xmlReader = parser.getXMLReader();
xmlReader.setFeature(Constants.XERCES_FEATURE_PREFIX + "continue-after-fatal-error", true);
xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
parser.parse(input, handler);
return handler.doctype;
} catch (IOException e) {
throw new SonarException(e);
} catch (StopParserException e) {
return handler.doctype;
} catch (SAXException e) {
throw new SonarException(e);
} finally {
IOUtils.closeQuietly(input);
}
}
}
| UTF-8 | Java | 3,641 | java | DetectSchemaParser.java | Java | [
{
"context": "be XML Plugin\n * Copyright (C) 2010 SonarSource\n * sonarqube@googlegroups.com\n *\n * Licensed under the Apache License, Version ",
"end": 90,
"score": 0.999924898147583,
"start": 64,
"tag": "EMAIL",
"value": "sonarqube@googlegroups.com"
},
{
"context": "y only to detect the sDTD or Schema.\n *\n * @author Matthijs Galesloot\n */\npublic final class DetectSchemaParser extends",
"end": 1217,
"score": 0.9998884797096252,
"start": 1199,
"tag": "NAME",
"value": "Matthijs Galesloot"
}
] | null | [] | /*
* SonarQube XML Plugin
* Copyright (C) 2010 SonarSource
* <EMAIL>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sonar.plugins.xml.parsers;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.SAXParser;
import org.apache.commons.io.IOUtils;
import org.apache.xerces.impl.Constants;
import org.sonar.api.utils.SonarException;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.DefaultHandler;
/**
* Parse the file quickly only to detect the sDTD or Schema.
*
* @author <NAME>
*/
public final class DetectSchemaParser extends AbstractParser {
/**
* Doctype declaration in a Document.
*/
public static class Doctype {
private String dtd;
private String namespace;
public String getDtd() {
return dtd;
}
public String getNamespace() {
return namespace;
}
}
/**
* Exception to stop the parser from further processing.
*/
private static class StopParserException extends SAXException {
private static final long serialVersionUID = 1L;
}
private static class Handler extends DefaultHandler implements LexicalHandler {
private Doctype doctype = new Doctype();
public void comment(char[] arg0, int arg1, int arg2) throws SAXException {
// empty
}
public void endCDATA() throws SAXException {
// empty
}
public void endDTD() throws SAXException {
// empty
}
public void endEntity(String name) throws SAXException {
// empty
}
@Override
public void fatalError(SAXParseException e) throws SAXException {
// ignore
}
public void startCDATA() throws SAXException {
// empty
}
public void startDTD(String name, String publicId, String systemId) throws SAXException {
doctype.dtd = publicId;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
doctype.namespace = attributes.getValue("xmlns");
// we are done, cause the parser to stop
throw new StopParserException();
}
public void startEntity(String name) throws SAXException {
// empty
}
}
/**
* Find the Doctype (DTD or schema).
*/
public Doctype findDoctype(InputStream input) {
Handler handler = new Handler();
try {
SAXParser parser = newSaxParser(false);
XMLReader xmlReader = parser.getXMLReader();
xmlReader.setFeature(Constants.XERCES_FEATURE_PREFIX + "continue-after-fatal-error", true);
xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
parser.parse(input, handler);
return handler.doctype;
} catch (IOException e) {
throw new SonarException(e);
} catch (StopParserException e) {
return handler.doctype;
} catch (SAXException e) {
throw new SonarException(e);
} finally {
IOUtils.closeQuietly(input);
}
}
}
| 3,610 | 0.697611 | 0.694315 | 137 | 25.576643 | 25.631506 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357664 | false | false | 4 |
df3a72e4a24a5a6fc1aa35e13bc3551b8ad93c52 | 23,691,039,621,795 | 2ed3a30e4e2729b066c99deb909b85d84ac9462f | /src/main/java/sw/praktikum/risk5/GUI/StatisticsPanelController.java | c607a0cff447f595dd056b955f16ecccbedbb41f | [] | no_license | lvschenck/risiko | https://github.com/lvschenck/risiko | b47a9b77d6f30096cb4eefd19e75197879d3a60e | 46eda04175e668d2e8074f365781071530e5ec7b | refs/heads/master | 2020-05-21T17:11:10.779000 | 2019-05-12T21:55:52 | 2019-05-12T21:55:52 | 186,119,096 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sw.praktikum.risk5.GUI;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import sw.praktikum.risk5.GUI.*;
import sw.praktikum.risk5.App.RiskMain;
import sw.praktikum.risk5.Database.Database;
public class StatisticsPanelController implements Initializable{
Database db;
@FXML
private Label playedGames;
@FXML
private Label totalAmountTroops;
@FXML
private Label winRate;
@FXML
private Label averagePeakEmpire;
@FXML
private Label successfullAttacks;
@FXML
private Label successfullDefenses;
@FXML
private TableView<String> table;
@FXML
private void openMenu(ActionEvent actionEvent) {
Parent newContent = null;
try {
newContent = FXMLLoader.load(RiskMain.class.getResource("/view/MainMenu.fxml"));
} catch (IOException e) {
e.printStackTrace();
}
Stage primaryStage = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow();
primaryStage.getScene().setRoot(newContent);
}
@Override
public void initialize(URL location, ResourceBundle resources) {
List<org.jdom2.Attribute> attribute = db.getStatisticsLobby(Integer.toString(db.getUserId(RiskMain.getInstance().getDomain().getPlayerName())));
for(int i=0; i<attribute.size(); i++) {
switch(attribute.get(i).getName()) {
case "placement":
}
}
}
}
| UTF-8 | Java | 1,694 | java | StatisticsPanelController.java | Java | [] | null | [] | package sw.praktikum.risk5.GUI;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import sw.praktikum.risk5.GUI.*;
import sw.praktikum.risk5.App.RiskMain;
import sw.praktikum.risk5.Database.Database;
public class StatisticsPanelController implements Initializable{
Database db;
@FXML
private Label playedGames;
@FXML
private Label totalAmountTroops;
@FXML
private Label winRate;
@FXML
private Label averagePeakEmpire;
@FXML
private Label successfullAttacks;
@FXML
private Label successfullDefenses;
@FXML
private TableView<String> table;
@FXML
private void openMenu(ActionEvent actionEvent) {
Parent newContent = null;
try {
newContent = FXMLLoader.load(RiskMain.class.getResource("/view/MainMenu.fxml"));
} catch (IOException e) {
e.printStackTrace();
}
Stage primaryStage = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow();
primaryStage.getScene().setRoot(newContent);
}
@Override
public void initialize(URL location, ResourceBundle resources) {
List<org.jdom2.Attribute> attribute = db.getStatisticsLobby(Integer.toString(db.getUserId(RiskMain.getInstance().getDomain().getPlayerName())));
for(int i=0; i<attribute.size(); i++) {
switch(attribute.get(i).getName()) {
case "placement":
}
}
}
}
| 1,694 | 0.753247 | 0.749705 | 68 | 23.911764 | 24.964525 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.088235 | false | false | 4 |
4a8eeb73a04d07b5fe44cd8cf9f1305fd32cb7fd | 35,201,551,959,804 | 3995ae1333198fc31f9ba2fdae640ec9fcd9d2cb | /app/src/main/java/com/ccsuper/snailshop/adapter/FosterCareTaskAdapter.java | 299fe9f67e6e669e80d3b7d29ed6fac82a34ba40 | [] | no_license | ChenChao-Android/SnailShop | https://github.com/ChenChao-Android/SnailShop | 01a1a12e868d061a52ecf2e8faf21beda26688bf | 6a6336f70cd9f1d493c26798dd7948bbc58010e8 | refs/heads/master | 2018-01-02T01:49:14.679000 | 2017-03-31T09:49:23 | 2017-03-31T09:49:23 | 71,782,524 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ccsuper.snailshop.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.ccsuper.snailshop.CustomApp;
import com.ccsuper.snailshop.R;
import com.ccsuper.snailshop.customview.RemindDialog;
import com.ccsuper.snailshop.dataBean.FosterTaskMsg;
import com.ccsuper.snailshop.http.ReListener;
import com.ccsuper.snailshop.http.TaskHttp;
import com.ccsuper.snailshop.utils.DataUtils;
import com.daimajia.swipe.SwipeLayout;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;
import java.text.ParseException;
import java.util.ArrayList;
/**
* 寄养任务适配
* Created by super on 2017/1/21.
*/
public class FosterCareTaskAdapter extends RecyclerView.Adapter<FosterCareTaskAdapter.ViewHolder> implements RemindDialog.RemindDialogCallBack {
private ArrayList<FosterTaskMsg> fosterTaskMsgList;
private Context context;
private OnMyItemClickListener listener;
private LayoutInflater mInflater;
private SwipeLayout swipeLayout;
private int choosePositon;
public FosterCareTaskAdapter(ArrayList<FosterTaskMsg> fosterTaskMsgList, Context context) {
this.context = context;
this.fosterTaskMsgList = fosterTaskMsgList;
this.mInflater = LayoutInflater.from(context);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_foster_care_task,
parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final FosterTaskMsg fosterTaskMsg = fosterTaskMsgList.get(position);
String sex = fosterTaskMsg.getCustomer_pet_sex();
String customer_pet_kind = fosterTaskMsg.getCustomer_pet_kind();
if (sex != null) {
if (sex.equals("1")) {
if (customer_pet_kind != null) {
if (customer_pet_kind.contains("cat")) {
holder.iv_itemFosterCareTask_header.setImageDrawable(context.getResources().getDrawable(R.drawable.male_cat));
} else {
holder.iv_itemFosterCareTask_header.setImageDrawable(context.getResources().getDrawable(R.drawable.male_dog));
}
} else {
holder.iv_itemFosterCareTask_header.setImageDrawable(context.getResources().getDrawable(R.drawable.male_dog));
}
} else {
if (customer_pet_kind != null) {
if (customer_pet_kind.contains("Dog")) {
holder.iv_itemFosterCareTask_header.setImageDrawable(context.getResources().getDrawable(R.drawable.female_dog));
} else {
holder.iv_itemFosterCareTask_header.setImageDrawable(context.getResources().getDrawable(R.drawable.female_cat));
}
} else {
holder.iv_itemFosterCareTask_header.setImageDrawable(context.getResources().getDrawable(R.drawable.female_dog));
}
}
} else {
holder.iv_itemFosterCareTask_header.setImageDrawable(context.getResources().getDrawable(R.drawable.male_dog));
}
String name = fosterTaskMsg.getCustomer_pet_name();
if (name != null) {
holder.tv_itemFosterCareTask_name.setText(name);
} else {
holder.tv_itemFosterCareTask_name.setText("--");
}
String type = fosterTaskMsg.getCustomer_pet_species();
if (type != null) {
holder.tv_itemFosterCareTask_type.setText(type);
} else {
holder.tv_itemFosterCareTask_type.setText("--");
}
String action_time = DataUtils.stampToDate("yyyy/MM/dd", fosterTaskMsg.getAction_time());
int end = Integer.parseInt(fosterTaskMsg.getEnd_time());
String end_time = DataUtils.stampToDate("yyyy/MM/dd", fosterTaskMsg.getEnd_time());
holder.tv_itemFosterCareTask_start.setText(action_time);
holder.tv_itemFosterCareTask_end.setText(end_time);
String now_time = DataUtils.getTime("yyyy/MM/dd HH:mm:ss");
try {
int now = Integer.parseInt(DataUtils.dateToStamp("yyyy/MM/dd HH:mm:ss", now_time));
if (end < now) {
holder.tv_itemFosterCareTask_time.setText("(已过期)");
} else {
String day = DataUtils.daysBetween(end, now);
holder.tv_itemFosterCareTask_time.setText("(还有" + day + "过期)");
fosterTaskMsgList.get(position).setDayTime(day);
}
} catch (ParseException e) {
e.printStackTrace();
}
if (fosterTaskMsg.getOpt_user_id().equals("-1")) {
holder.ll_itemFosterCareTask_small.setVisibility(View.VISIBLE);
} else {
holder.ll_itemFosterCareTask_small.setVisibility(View.GONE);
}
holder.ll_itemFosterCareTask.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.onMyItemClick(position, fosterTaskMsgList.get(position));
}
});
holder.tv_delete_care.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
choosePositon = position;
new RemindDialog(context, "删除")
.setTitle("温馨提示")
.setTv_entry_dialog_text("确认删除")
.setTv_cancel_dialog_text("取消")
.setEntryColor(R.color.white_background)
.setCancelColor(R.color.white_background)
.setMid("是否删除 " + fosterTaskMsg.getCustomer_name() + " 的 " + fosterTaskMsg.getCustomer_pet_name() + "的寄养任务?")
.setCallBack(FosterCareTaskAdapter.this)
.showDialog();
holder.swipe_foster_care.quickClose();
}
});
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemCount() {
return fosterTaskMsgList.size();
}
@Override
public void cancelCallBack(String tag) {
}
@Override
public void entryCallBack(String tag) {
switch (tag) {
case "删除":
deleteTask();
break;
}
}
private void deleteTask() {
TaskHttp.updateStatus(CustomApp.shopId, "3", fosterTaskMsgList.get(choosePositon).getTask_id(), new ReListener(context) {
@Override
public void result(int code, Object result) {
super.result(code, result);
if (code == 0) {
fosterTaskMsgList.remove(choosePositon);
notifyItemRemoved(choosePositon);
notifyDataSetChanged();
// if(choosePositon != (getList().size())){ // 如果移除的是最后一个,忽略
// notifyItemRangeChanged(choosePositon, getList().size() - choosePositon);
// }
}
}
});
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView iv_itemFosterCareTask_header;
private TextView tv_itemFosterCareTask_name;
private TextView tv_itemFosterCareTask_type;
private TextView tv_itemFosterCareTask_start;
private TextView tv_itemFosterCareTask_end;
private TextView tv_itemFosterCareTask_time;
private LinearLayout ll_itemFosterCareTask;
private TextView tv_delete_care;
private SwipeMenuLayout swipe_foster_care;
private LinearLayout ll_itemFosterCareTask_small;
public ViewHolder(View itemView) {
super(itemView);
iv_itemFosterCareTask_header = (ImageView) itemView.findViewById(R.id.iv_itemFosterCareTask_header);
tv_itemFosterCareTask_name = (TextView) itemView.findViewById(R.id.tv_itemFosterCareTask_name);
tv_delete_care = (TextView) itemView.findViewById(R.id.tv_delete_care);
tv_itemFosterCareTask_type = (TextView) itemView.findViewById(R.id.tv_itemFosterCareTask_type);
tv_itemFosterCareTask_start = (TextView) itemView.findViewById(R.id.tv_itemFosterCareTask_start);
tv_itemFosterCareTask_end = (TextView) itemView.findViewById(R.id.tv_itemFosterCareTask_end);
tv_itemFosterCareTask_time = (TextView) itemView.findViewById(R.id.tv_itemFosterCareTask_time);
ll_itemFosterCareTask = (LinearLayout) itemView.findViewById(R.id.ll_itemFosterCareTask);
ll_itemFosterCareTask_small = (LinearLayout) itemView.findViewById(R.id.ll_itemFosterCareTask_small);
swipe_foster_care = (SwipeMenuLayout) itemView.findViewById(R.id.swipe_foster_care);
}
}
public interface OnMyItemClickListener {
void onMyItemClick(int position, FosterTaskMsg fosterTaskMsg);
}
public void setOnMyItemClickListener(OnMyItemClickListener listener) {
this.listener = listener;
}
public ArrayList<FosterTaskMsg> getList() {
return this.fosterTaskMsgList;
}
}
| UTF-8 | Java | 9,590 | java | FosterCareTaskAdapter.java | Java | [
{
"context": " java.util.ArrayList;\n\n/**\n * 寄养任务适配\n * Created by super on 2017/1/21.\n */\npublic class FosterCareTaskAdap",
"end": 815,
"score": 0.9932399988174438,
"start": 810,
"tag": "USERNAME",
"value": "super"
}
] | null | [] | package com.ccsuper.snailshop.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.ccsuper.snailshop.CustomApp;
import com.ccsuper.snailshop.R;
import com.ccsuper.snailshop.customview.RemindDialog;
import com.ccsuper.snailshop.dataBean.FosterTaskMsg;
import com.ccsuper.snailshop.http.ReListener;
import com.ccsuper.snailshop.http.TaskHttp;
import com.ccsuper.snailshop.utils.DataUtils;
import com.daimajia.swipe.SwipeLayout;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;
import java.text.ParseException;
import java.util.ArrayList;
/**
* 寄养任务适配
* Created by super on 2017/1/21.
*/
public class FosterCareTaskAdapter extends RecyclerView.Adapter<FosterCareTaskAdapter.ViewHolder> implements RemindDialog.RemindDialogCallBack {
private ArrayList<FosterTaskMsg> fosterTaskMsgList;
private Context context;
private OnMyItemClickListener listener;
private LayoutInflater mInflater;
private SwipeLayout swipeLayout;
private int choosePositon;
public FosterCareTaskAdapter(ArrayList<FosterTaskMsg> fosterTaskMsgList, Context context) {
this.context = context;
this.fosterTaskMsgList = fosterTaskMsgList;
this.mInflater = LayoutInflater.from(context);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_foster_care_task,
parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final FosterTaskMsg fosterTaskMsg = fosterTaskMsgList.get(position);
String sex = fosterTaskMsg.getCustomer_pet_sex();
String customer_pet_kind = fosterTaskMsg.getCustomer_pet_kind();
if (sex != null) {
if (sex.equals("1")) {
if (customer_pet_kind != null) {
if (customer_pet_kind.contains("cat")) {
holder.iv_itemFosterCareTask_header.setImageDrawable(context.getResources().getDrawable(R.drawable.male_cat));
} else {
holder.iv_itemFosterCareTask_header.setImageDrawable(context.getResources().getDrawable(R.drawable.male_dog));
}
} else {
holder.iv_itemFosterCareTask_header.setImageDrawable(context.getResources().getDrawable(R.drawable.male_dog));
}
} else {
if (customer_pet_kind != null) {
if (customer_pet_kind.contains("Dog")) {
holder.iv_itemFosterCareTask_header.setImageDrawable(context.getResources().getDrawable(R.drawable.female_dog));
} else {
holder.iv_itemFosterCareTask_header.setImageDrawable(context.getResources().getDrawable(R.drawable.female_cat));
}
} else {
holder.iv_itemFosterCareTask_header.setImageDrawable(context.getResources().getDrawable(R.drawable.female_dog));
}
}
} else {
holder.iv_itemFosterCareTask_header.setImageDrawable(context.getResources().getDrawable(R.drawable.male_dog));
}
String name = fosterTaskMsg.getCustomer_pet_name();
if (name != null) {
holder.tv_itemFosterCareTask_name.setText(name);
} else {
holder.tv_itemFosterCareTask_name.setText("--");
}
String type = fosterTaskMsg.getCustomer_pet_species();
if (type != null) {
holder.tv_itemFosterCareTask_type.setText(type);
} else {
holder.tv_itemFosterCareTask_type.setText("--");
}
String action_time = DataUtils.stampToDate("yyyy/MM/dd", fosterTaskMsg.getAction_time());
int end = Integer.parseInt(fosterTaskMsg.getEnd_time());
String end_time = DataUtils.stampToDate("yyyy/MM/dd", fosterTaskMsg.getEnd_time());
holder.tv_itemFosterCareTask_start.setText(action_time);
holder.tv_itemFosterCareTask_end.setText(end_time);
String now_time = DataUtils.getTime("yyyy/MM/dd HH:mm:ss");
try {
int now = Integer.parseInt(DataUtils.dateToStamp("yyyy/MM/dd HH:mm:ss", now_time));
if (end < now) {
holder.tv_itemFosterCareTask_time.setText("(已过期)");
} else {
String day = DataUtils.daysBetween(end, now);
holder.tv_itemFosterCareTask_time.setText("(还有" + day + "过期)");
fosterTaskMsgList.get(position).setDayTime(day);
}
} catch (ParseException e) {
e.printStackTrace();
}
if (fosterTaskMsg.getOpt_user_id().equals("-1")) {
holder.ll_itemFosterCareTask_small.setVisibility(View.VISIBLE);
} else {
holder.ll_itemFosterCareTask_small.setVisibility(View.GONE);
}
holder.ll_itemFosterCareTask.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.onMyItemClick(position, fosterTaskMsgList.get(position));
}
});
holder.tv_delete_care.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
choosePositon = position;
new RemindDialog(context, "删除")
.setTitle("温馨提示")
.setTv_entry_dialog_text("确认删除")
.setTv_cancel_dialog_text("取消")
.setEntryColor(R.color.white_background)
.setCancelColor(R.color.white_background)
.setMid("是否删除 " + fosterTaskMsg.getCustomer_name() + " 的 " + fosterTaskMsg.getCustomer_pet_name() + "的寄养任务?")
.setCallBack(FosterCareTaskAdapter.this)
.showDialog();
holder.swipe_foster_care.quickClose();
}
});
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemCount() {
return fosterTaskMsgList.size();
}
@Override
public void cancelCallBack(String tag) {
}
@Override
public void entryCallBack(String tag) {
switch (tag) {
case "删除":
deleteTask();
break;
}
}
private void deleteTask() {
TaskHttp.updateStatus(CustomApp.shopId, "3", fosterTaskMsgList.get(choosePositon).getTask_id(), new ReListener(context) {
@Override
public void result(int code, Object result) {
super.result(code, result);
if (code == 0) {
fosterTaskMsgList.remove(choosePositon);
notifyItemRemoved(choosePositon);
notifyDataSetChanged();
// if(choosePositon != (getList().size())){ // 如果移除的是最后一个,忽略
// notifyItemRangeChanged(choosePositon, getList().size() - choosePositon);
// }
}
}
});
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView iv_itemFosterCareTask_header;
private TextView tv_itemFosterCareTask_name;
private TextView tv_itemFosterCareTask_type;
private TextView tv_itemFosterCareTask_start;
private TextView tv_itemFosterCareTask_end;
private TextView tv_itemFosterCareTask_time;
private LinearLayout ll_itemFosterCareTask;
private TextView tv_delete_care;
private SwipeMenuLayout swipe_foster_care;
private LinearLayout ll_itemFosterCareTask_small;
public ViewHolder(View itemView) {
super(itemView);
iv_itemFosterCareTask_header = (ImageView) itemView.findViewById(R.id.iv_itemFosterCareTask_header);
tv_itemFosterCareTask_name = (TextView) itemView.findViewById(R.id.tv_itemFosterCareTask_name);
tv_delete_care = (TextView) itemView.findViewById(R.id.tv_delete_care);
tv_itemFosterCareTask_type = (TextView) itemView.findViewById(R.id.tv_itemFosterCareTask_type);
tv_itemFosterCareTask_start = (TextView) itemView.findViewById(R.id.tv_itemFosterCareTask_start);
tv_itemFosterCareTask_end = (TextView) itemView.findViewById(R.id.tv_itemFosterCareTask_end);
tv_itemFosterCareTask_time = (TextView) itemView.findViewById(R.id.tv_itemFosterCareTask_time);
ll_itemFosterCareTask = (LinearLayout) itemView.findViewById(R.id.ll_itemFosterCareTask);
ll_itemFosterCareTask_small = (LinearLayout) itemView.findViewById(R.id.ll_itemFosterCareTask_small);
swipe_foster_care = (SwipeMenuLayout) itemView.findViewById(R.id.swipe_foster_care);
}
}
public interface OnMyItemClickListener {
void onMyItemClick(int position, FosterTaskMsg fosterTaskMsg);
}
public void setOnMyItemClickListener(OnMyItemClickListener listener) {
this.listener = listener;
}
public ArrayList<FosterTaskMsg> getList() {
return this.fosterTaskMsgList;
}
}
| 9,590 | 0.632799 | 0.631535 | 225 | 41.168888 | 34.44968 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.528889 | false | false | 4 |
b06d118c79d5dff24da494663fb4ed5770d22dfc | 33,191,507,299,994 | d8afa6ce0c34a154f6868fb934048b1725551622 | /StudyTest/src/com/lyx/IO/demo6_tryfinally.java | aff69d040c1c30fde176449d34b64bafe1219e1a | [] | no_license | reasunLiang/name | https://github.com/reasunLiang/name | cb876cfc732e4e33cd05915b00e4487f82b458c1 | a946046ac0fab862db5a11e4372b2ed09602a8b2 | refs/heads/master | 2022-12-30T18:09:57.319000 | 2020-10-22T01:40:18 | 2020-10-22T01:40:45 | 287,437,602 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lyx.IO;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @Package: com.lyx.IO
* @ClassName: demo6_tryCatch
* @Author: LYX
* @CreateTime: 2020/8/17 11:42
* @Description:
*/
public class demo6_tryfinally {
public static void main(String[] args) throws IOException {
//作用域,如果不赋值null;下面try中没有创建,fis就会出错
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("yyy.txt");
fos = new FileOutputStream("zzz.txt");
int b;
while ((b = fis.read())!= -1){
fos.write(b);
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
//嵌套try
try {
if (fis != null)
fis.close();
}
finally {
if(fos != null)
fos.close();
}
}
}
}
| UTF-8 | Java | 1,053 | java | demo6_tryfinally.java | Java | [
{
"context": "m.lyx.IO\n * @ClassName: demo6_tryCatch\n * @Author: LYX\n * @CreateTime: 2020/8/17 11:42\n * @Description:\n",
"end": 188,
"score": 0.9990677833557129,
"start": 185,
"tag": "USERNAME",
"value": "LYX"
}
] | null | [] | package com.lyx.IO;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @Package: com.lyx.IO
* @ClassName: demo6_tryCatch
* @Author: LYX
* @CreateTime: 2020/8/17 11:42
* @Description:
*/
public class demo6_tryfinally {
public static void main(String[] args) throws IOException {
//作用域,如果不赋值null;下面try中没有创建,fis就会出错
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("yyy.txt");
fos = new FileOutputStream("zzz.txt");
int b;
while ((b = fis.read())!= -1){
fos.write(b);
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
//嵌套try
try {
if (fis != null)
fis.close();
}
finally {
if(fos != null)
fos.close();
}
}
}
}
| 1,053 | 0.48858 | 0.474677 | 41 | 23.560976 | 14.46619 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.341463 | false | false | 4 |
a129f9359e9cc853c540d53aee5c3eff6818941e | 20,718,922,278,409 | 692eedcebb07cfdf7c6e9ebeb719303a476ffd25 | /UserAPI/web/src/main/java/com/userapi/web/AdminAPI/AdminController.java | a8f05515fa55b3513080a5c8d015152e2671a56c | [] | no_license | IT19085968/UserAPI | https://github.com/IT19085968/UserAPI | 5d84c57eca08fbbddf0b6a55b1ee035fcb2bb4e6 | 84bb5b4c4b2fd3b7b54987f299d193a235b812bb | refs/heads/master | 2023-06-19T16:07:59.190000 | 2021-07-06T06:09:54 | 2021-07-06T06:09:54 | 380,539,429 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.userapi.web.AdminAPI;
import com.userapi.web.EditorAPI.Editor;
import com.userapi.web.EditorAPI.EditorService;
import com.userapi.web.ReviewerAPI.Reviewer;
import com.userapi.web.ReviewerAPI.ReviewerService;
import com.userapi.web.models.Activity;
import com.userapi.web.models.EditorChanges;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(path = "adminapi")
@CrossOrigin
public class AdminController {
@Autowired
private final AdminService adminService;
@Autowired
private final EditorService editorService;
@Autowired
private final ReviewerService reviewerService;
@Autowired
private final ActivityService activityService;
public AdminController(AdminService adminService, EditorService editorService, ReviewerService reviewerService, ActivityService activityService) {
this.adminService = adminService;
this.editorService = editorService;
this.reviewerService = reviewerService;
this.activityService = activityService;
}
@PostMapping("/addEditor")
public void addEditor(@RequestBody Editor editor) {
editorService.addNewEditor(editor);
}
@PostMapping("/addReviewer")
public void addReviewer(@RequestBody Reviewer reviewer) {
reviewerService.addNewReviewer(reviewer);
}
@PostMapping("/addAdmin")
public void addAdmin(@RequestBody Admin admin) {
adminService.addAdmin(admin);
}
@GetMapping(path = "/EditorChangesList")
public List<EditorChanges> getEditorChangesList() {
return adminService.getAllEditorChanges();
}
@PostMapping("/ApproveDeclineEdit")
public void approveOrDeclineEdit(@RequestBody EditorChanges editorChanges) {
activityService.addActivity("Approve/Decline edit",editorChanges.toString());
adminService.approveOrDeclineEdit(editorChanges);
}
@GetMapping(path = "/viewAllActivities")
public List<Activity> viewAllActivities() {
return adminService.viewAllActivities();
}
@GetMapping(path = "/getActivityDetails")
public Activity getActivityDetails(@RequestParam String id) {
return adminService.getActivityDetails(id);
}
}
| UTF-8 | Java | 2,309 | java | AdminController.java | Java | [] | null | [] | package com.userapi.web.AdminAPI;
import com.userapi.web.EditorAPI.Editor;
import com.userapi.web.EditorAPI.EditorService;
import com.userapi.web.ReviewerAPI.Reviewer;
import com.userapi.web.ReviewerAPI.ReviewerService;
import com.userapi.web.models.Activity;
import com.userapi.web.models.EditorChanges;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(path = "adminapi")
@CrossOrigin
public class AdminController {
@Autowired
private final AdminService adminService;
@Autowired
private final EditorService editorService;
@Autowired
private final ReviewerService reviewerService;
@Autowired
private final ActivityService activityService;
public AdminController(AdminService adminService, EditorService editorService, ReviewerService reviewerService, ActivityService activityService) {
this.adminService = adminService;
this.editorService = editorService;
this.reviewerService = reviewerService;
this.activityService = activityService;
}
@PostMapping("/addEditor")
public void addEditor(@RequestBody Editor editor) {
editorService.addNewEditor(editor);
}
@PostMapping("/addReviewer")
public void addReviewer(@RequestBody Reviewer reviewer) {
reviewerService.addNewReviewer(reviewer);
}
@PostMapping("/addAdmin")
public void addAdmin(@RequestBody Admin admin) {
adminService.addAdmin(admin);
}
@GetMapping(path = "/EditorChangesList")
public List<EditorChanges> getEditorChangesList() {
return adminService.getAllEditorChanges();
}
@PostMapping("/ApproveDeclineEdit")
public void approveOrDeclineEdit(@RequestBody EditorChanges editorChanges) {
activityService.addActivity("Approve/Decline edit",editorChanges.toString());
adminService.approveOrDeclineEdit(editorChanges);
}
@GetMapping(path = "/viewAllActivities")
public List<Activity> viewAllActivities() {
return adminService.viewAllActivities();
}
@GetMapping(path = "/getActivityDetails")
public Activity getActivityDetails(@RequestParam String id) {
return adminService.getActivityDetails(id);
}
}
| 2,309 | 0.745777 | 0.745777 | 74 | 30.202703 | 27.018002 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.405405 | false | false | 4 |
dfd643ab9ad6f129de623812cdd89a77b9b300c1 | 35,167,192,224,545 | 04b66a26d276e5bbcae644e3843dc1a5de81ef2c | /RichClientDemoTest/src/com/redheap/selenium/pages/NoteWindowDemoPage.java | 2a7132191410bed91f3f77d2646c56d72413eb78 | [
"Apache-2.0"
] | permissive | tolis-e/adf-selenium | https://github.com/tolis-e/adf-selenium | 9aaa9e2483395f63945398383daaf53ec2aa00b3 | a66b0b65ff7bea36296b8de37956a257ef62a454 | refs/heads/master | 2021-01-22T19:30:28.679000 | 2016-04-01T09:06:48 | 2016-04-01T09:06:48 | 85,202,900 | 0 | 1 | null | true | 2017-03-16T14:07:06 | 2017-03-16T14:07:06 | 2017-03-08T09:49:58 | 2017-02-20T10:02:27 | 57,892 | 0 | 0 | 0 | null | null | null | package com.redheap.selenium.pages;
import com.redheap.selenium.component.AdfCommandLink;
import com.redheap.selenium.component.AdfNoteWindow;
import com.redheap.selenium.component.AdfPopup;
import com.redheap.selenium.page.Page;
import org.openqa.selenium.WebDriver;
public class NoteWindowDemoPage extends Page {
private final String scavengingLink = "dmoTpl:scavenger";
private final String scavengingPopup = "dmoTpl:popupScavenger";
private final String scavengingNoteWindow = "dmoTpl:nw1";
public NoteWindowDemoPage(WebDriver webDriver) {
super(webDriver);
}
@Override
protected String getExpectedTitle() {
return "noteWindow Demo";
}
public AdfCommandLink findScavengingLink() {
return findAdfComponent(scavengingLink);
}
public AdfPopup findScavengingPopup() {
return findAdfComponent(scavengingPopup);
}
public AdfNoteWindow findScavengingNoteWindow() {
return findAdfComponent(scavengingNoteWindow);
}
}
| UTF-8 | Java | 1,019 | java | NoteWindowDemoPage.java | Java | [] | null | [] | package com.redheap.selenium.pages;
import com.redheap.selenium.component.AdfCommandLink;
import com.redheap.selenium.component.AdfNoteWindow;
import com.redheap.selenium.component.AdfPopup;
import com.redheap.selenium.page.Page;
import org.openqa.selenium.WebDriver;
public class NoteWindowDemoPage extends Page {
private final String scavengingLink = "dmoTpl:scavenger";
private final String scavengingPopup = "dmoTpl:popupScavenger";
private final String scavengingNoteWindow = "dmoTpl:nw1";
public NoteWindowDemoPage(WebDriver webDriver) {
super(webDriver);
}
@Override
protected String getExpectedTitle() {
return "noteWindow Demo";
}
public AdfCommandLink findScavengingLink() {
return findAdfComponent(scavengingLink);
}
public AdfPopup findScavengingPopup() {
return findAdfComponent(scavengingPopup);
}
public AdfNoteWindow findScavengingNoteWindow() {
return findAdfComponent(scavengingNoteWindow);
}
}
| 1,019 | 0.744848 | 0.743867 | 37 | 26.540541 | 23.664999 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.378378 | false | false | 4 |
198c19f3d7c8d0c0b57d7e8d6dfc2ad8ae167588 | 36,292,473,676,785 | f5e7044a8a5610741e090c1dca4fe0a36b79104c | /PrettyPrintXML.java | fe911bf2b9e963743a5c00cf1012ed1017c48609 | [] | no_license | akhil31415/Tools | https://github.com/akhil31415/Tools | af945e02735207a3e1a7a0a7e5c29fb6ec9416f6 | e2137b326c814c351be2d90e2a508fa9e7d972e5 | refs/heads/master | 2020-05-17T05:19:37.374000 | 2019-05-28T04:03:49 | 2019-05-28T04:03:49 | 183,529,318 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import com.iflex.fcr.app.service.command.MessageHelper;
import com.iflex.fcr.infra.error.ErrorManager;
import com.iflex.fcr.infra.exception.FatalException;
import com.iflex.fcr.infra.xml.FCRJXMLParser;
public class Test {
/**
* @param args
*/
public static String inputXml = "";
public static String responseXml;
public static String requestXml = "";
public static String path1 = "D://TranXML//RequestAutoChrg.xml";
public static void main(String[] args) {
// System.setProperty("file.encoding", "Shift-JIS");
// System.out.println(System.getProperty("user.home"));
System.setProperty("user.home", "D://FLEXCUBE_HOST//flexcube//host//runarea//env//");
FCRJXMLParser inputData = null;
FileReader file = null;
try {
file = new FileReader(path1);
BufferedReader buf = new BufferedReader(file);
while ((inputXml = buf.readLine()) != null) {
//System.out.println(inputXml);
requestXml = requestXml.concat(inputXml).trim();
System.out.println("\n RequestXml : ");
prettyPrintXML(requestXml);
}
if (requestXml != null) {
inputData = FCRJXMLParser.getInstance();
inputData.parse(requestXml);
} else {
try {
ErrorManager.throwFatalException(
"Failed to execute service", null);
} catch (FatalException e) {
e.printStackTrace();
}
}
MessageHelper mesg = new MessageHelper();
//System.out.println(requestXml);
try {
responseXml = mesg.executeMessage(requestXml);
} catch (FatalException e) {
e.printStackTrace();
}
//System.out.println("responseXml Thread 1-->" + responseXml);
System.out.println("\n ResponseXml : ");
prettyPrintXML(responseXml);
buf.close();
/* while (true)
{
Thread thread1 =new Thread(){
public void run()
{ MessageHelper mesg1 = new MessageHelper();
System.out.println(requestXml);
try {
responseXml = mesg1.executeMessage(requestXml);
} catch (FatalException e) {
e.printStackTrace();
}
System.out.println("responseXml Thread 1-->" + responseXml);
};
};
thread1.run();
}
*/
/* Thread thread2 =new Thread(){
public void run()
{ MessageHelper mesg2 = new MessageHelper();
System.out.println(requestXml);
try {
responseXml = mesg2.executeMessage(requestXml);
} catch (FatalException e) {
e.printStackTrace();
}
System.out.println("responseXml Thread 2-->" + responseXml);
};
};
*/
//thread1.start();
//thread2.start();
/*thread1.run();
thread2.run();
*/
/* System.out.println("responseXml-->" + responseXml); */
// }
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void prettyPrintXML(String input) {
try {
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
DocumentBuilder builder= factory.newDocumentBuilder();
Document doc= builder.parse(new InputSource(new StringReader(input)));
Transformer tform=TransformerFactory.newInstance().newTransformer();
tform.setOutputProperty(OutputKeys.ENCODING, "SJIS");
tform.setOutputProperty(OutputKeys.INDENT, "yes");
tform.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
tform.transform(new DOMSource(doc), new StreamResult(System.out));
}catch (Exception e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 4,126 | java | PrettyPrintXML.java | Java | [] | null | [] |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import com.iflex.fcr.app.service.command.MessageHelper;
import com.iflex.fcr.infra.error.ErrorManager;
import com.iflex.fcr.infra.exception.FatalException;
import com.iflex.fcr.infra.xml.FCRJXMLParser;
public class Test {
/**
* @param args
*/
public static String inputXml = "";
public static String responseXml;
public static String requestXml = "";
public static String path1 = "D://TranXML//RequestAutoChrg.xml";
public static void main(String[] args) {
// System.setProperty("file.encoding", "Shift-JIS");
// System.out.println(System.getProperty("user.home"));
System.setProperty("user.home", "D://FLEXCUBE_HOST//flexcube//host//runarea//env//");
FCRJXMLParser inputData = null;
FileReader file = null;
try {
file = new FileReader(path1);
BufferedReader buf = new BufferedReader(file);
while ((inputXml = buf.readLine()) != null) {
//System.out.println(inputXml);
requestXml = requestXml.concat(inputXml).trim();
System.out.println("\n RequestXml : ");
prettyPrintXML(requestXml);
}
if (requestXml != null) {
inputData = FCRJXMLParser.getInstance();
inputData.parse(requestXml);
} else {
try {
ErrorManager.throwFatalException(
"Failed to execute service", null);
} catch (FatalException e) {
e.printStackTrace();
}
}
MessageHelper mesg = new MessageHelper();
//System.out.println(requestXml);
try {
responseXml = mesg.executeMessage(requestXml);
} catch (FatalException e) {
e.printStackTrace();
}
//System.out.println("responseXml Thread 1-->" + responseXml);
System.out.println("\n ResponseXml : ");
prettyPrintXML(responseXml);
buf.close();
/* while (true)
{
Thread thread1 =new Thread(){
public void run()
{ MessageHelper mesg1 = new MessageHelper();
System.out.println(requestXml);
try {
responseXml = mesg1.executeMessage(requestXml);
} catch (FatalException e) {
e.printStackTrace();
}
System.out.println("responseXml Thread 1-->" + responseXml);
};
};
thread1.run();
}
*/
/* Thread thread2 =new Thread(){
public void run()
{ MessageHelper mesg2 = new MessageHelper();
System.out.println(requestXml);
try {
responseXml = mesg2.executeMessage(requestXml);
} catch (FatalException e) {
e.printStackTrace();
}
System.out.println("responseXml Thread 2-->" + responseXml);
};
};
*/
//thread1.start();
//thread2.start();
/*thread1.run();
thread2.run();
*/
/* System.out.println("responseXml-->" + responseXml); */
// }
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void prettyPrintXML(String input) {
try {
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
DocumentBuilder builder= factory.newDocumentBuilder();
Document doc= builder.parse(new InputSource(new StringReader(input)));
Transformer tform=TransformerFactory.newInstance().newTransformer();
tform.setOutputProperty(OutputKeys.ENCODING, "SJIS");
tform.setOutputProperty(OutputKeys.INDENT, "yes");
tform.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
tform.transform(new DOMSource(doc), new StreamResult(System.out));
}catch (Exception e) {
e.printStackTrace();
}
}
}
| 4,126 | 0.655599 | 0.651236 | 138 | 27.884058 | 21.3552 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.23913 | false | false | 4 |
9aa9e32aaa1f77eec3cbda9c9e1cc1cd8ae0316b | 34,136,400,109,905 | 2a977a592e092fb71c924378c220fd9689e64c3f | /src/main/java/advent/year2015/day10/LookAndSay.java | 11ea7269c8d63145e2083f108eedc51c1dc09d9b | [] | no_license | samlindsaylevine/advent | https://github.com/samlindsaylevine/advent | ff14d3853a4a457ec1b3ee7af354e1c8099b995a | feaa93c0590b32cf798644ca4a9bfad3767cc3eb | refs/heads/master | 2023-01-28T21:45:31.379000 | 2023-01-09T23:00:27 | 2023-01-09T23:00:27 | 58,000,923 | 4 | 0 | null | false | 2023-01-09T23:02:26 | 2016-05-03T20:52:49 | 2022-12-14T22:36:35 | 2023-01-09T23:01:54 | 14,617 | 2 | 0 | 0 | Kotlin | false | false | package advent.year2015.day10;
/**
* --- Day 10: Elves Look, Elves Say ---
* Today, the Elves are playing a game called look-and-say. They take turns making sequences by reading aloud the
* previous sequence and using that reading as the next sequence. For example, 211 is read as "one two, two ones",
* which becomes 1221 (1 2, 2 1s).
* Look-and-say sequences are generated iteratively, using the previous value as input for the next step. For each
* step, take the previous value, and replace each run of digits (like 111) with the number of digits (3) followed by
* the digit itself (1).
* For example:
*
* 1 becomes 11 (1 copy of digit 1).
* 11 becomes 21 (2 copies of digit 1).
* 21 becomes 1211 (one 2 followed by one 1).
* 1211 becomes 111221 (one 1, one 2, and two 1s).
* 111221 becomes 312211 (three 1s, two 2s, and one 1).
*
* Starting with the digits in your puzzle input, apply this process 40 times. What is the length of the result?
*
* --- Part Two ---
* Neat, right? You might also enjoy hearing John Conway talking about this sequence (that's Conway of Conway's Game of
* Life fame).
* Now, starting again with the digits in your puzzle input, apply this process 50 times. What is the length of the
* new result?
*
*/
public class LookAndSay {
public static String lookAndSay(String input) {
if (input.isEmpty()) {
return "";
}
StringBuilder output = new StringBuilder();
String currentDigit = input.substring(0, 1);
int count = 1;
for (int i = 1; i < input.length(); i++) {
String digit = input.substring(i, i + 1);
if (currentDigit.equals(digit)) {
count++;
} else {
output.append(count + currentDigit);
currentDigit = digit;
count = 1;
}
}
output.append(count + currentDigit);
return output.toString();
}
public static String lookAndSay(String input, int times) {
String value = input;
for (int i = 0; i < times; i++) {
value = lookAndSay(value);
}
return value;
}
public static void main(String[] args) {
System.out.println(lookAndSay("1321131112", 50).length());
}
} | UTF-8 | Java | 2,103 | java | LookAndSay.java | Java | [] | null | [] | package advent.year2015.day10;
/**
* --- Day 10: Elves Look, Elves Say ---
* Today, the Elves are playing a game called look-and-say. They take turns making sequences by reading aloud the
* previous sequence and using that reading as the next sequence. For example, 211 is read as "one two, two ones",
* which becomes 1221 (1 2, 2 1s).
* Look-and-say sequences are generated iteratively, using the previous value as input for the next step. For each
* step, take the previous value, and replace each run of digits (like 111) with the number of digits (3) followed by
* the digit itself (1).
* For example:
*
* 1 becomes 11 (1 copy of digit 1).
* 11 becomes 21 (2 copies of digit 1).
* 21 becomes 1211 (one 2 followed by one 1).
* 1211 becomes 111221 (one 1, one 2, and two 1s).
* 111221 becomes 312211 (three 1s, two 2s, and one 1).
*
* Starting with the digits in your puzzle input, apply this process 40 times. What is the length of the result?
*
* --- Part Two ---
* Neat, right? You might also enjoy hearing John Conway talking about this sequence (that's Conway of Conway's Game of
* Life fame).
* Now, starting again with the digits in your puzzle input, apply this process 50 times. What is the length of the
* new result?
*
*/
public class LookAndSay {
public static String lookAndSay(String input) {
if (input.isEmpty()) {
return "";
}
StringBuilder output = new StringBuilder();
String currentDigit = input.substring(0, 1);
int count = 1;
for (int i = 1; i < input.length(); i++) {
String digit = input.substring(i, i + 1);
if (currentDigit.equals(digit)) {
count++;
} else {
output.append(count + currentDigit);
currentDigit = digit;
count = 1;
}
}
output.append(count + currentDigit);
return output.toString();
}
public static String lookAndSay(String input, int times) {
String value = input;
for (int i = 0; i < times; i++) {
value = lookAndSay(value);
}
return value;
}
public static void main(String[] args) {
System.out.println(lookAndSay("1321131112", 50).length());
}
} | 2,103 | 0.673799 | 0.629101 | 72 | 28.222221 | 33.652729 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.513889 | false | false | 4 |
fc7dee43040f2d14f20091826119f53ed490eddc | 37,666,863,199,694 | df820611adc44a856d2b8ab243a85a02f38c02ff | /util/src/main/java/de/kessel/HibernateUtil.java | 97b8d9f826d51ccc423135d2e20dd0a500eeace1 | [] | no_license | kesselm/ClientApplications | https://github.com/kesselm/ClientApplications | 8c23790c2393ee4625f0f9125b4bdfee79d9aaf4 | a39007838292bce20a40fe9f31d467c8a94969dc | refs/heads/master | 2020-03-26T19:14:14.749000 | 2018-08-26T21:56:39 | 2018-08-26T21:56:39 | 145,254,766 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.kessel;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import java.util.Properties;
/**
* @project ClientApplication
*/
public class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
Properties prop= new Properties();
prop.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/finance?useSSL=false&serverTimezone=UTC");
prop.setProperty("hibernate.connection.username", "finance");
prop.setProperty("hibernate.connection.password", "finance");
prop.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
sessionFactory = new AnnotationConfiguration()
.addPackage("com.concretepage.persistence")
.addProperties(prop)
.addAnnotatedClass(Transaction.class)
.buildSessionFactory();
}
return sessionFactory;
}
}
| UTF-8 | Java | 1,107 | java | HibernateUtil.java | Java | [
{
"context": "rop.setProperty(\"hibernate.connection.password\", \"finance\");\n prop.setProperty(\"dialect\", \"org.h",
"end": 708,
"score": 0.9992592930793762,
"start": 701,
"tag": "PASSWORD",
"value": "finance"
}
] | null | [] | package de.kessel;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import java.util.Properties;
/**
* @project ClientApplication
*/
public class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
Properties prop= new Properties();
prop.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/finance?useSSL=false&serverTimezone=UTC");
prop.setProperty("hibernate.connection.username", "finance");
prop.setProperty("hibernate.connection.password", "<PASSWORD>");
prop.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
sessionFactory = new AnnotationConfiguration()
.addPackage("com.concretepage.persistence")
.addProperties(prop)
.addAnnotatedClass(Transaction.class)
.buildSessionFactory();
}
return sessionFactory;
}
}
| 1,110 | 0.66486 | 0.661247 | 32 | 33.59375 | 30.326204 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5625 | false | false | 4 |
b147f7f339a95f561e96012f0eaeb843c996a946 | 37,666,863,198,253 | 2b93506f8e38236bc44213bc39c10719fed924b4 | /app/src/main/java/com/example/sofra/ui/fragment/userCycle/userHome/userRestaurantMenu/restaurantDetails/UserRestaurantInformationFragment.java | 62698ff13dc556442d37833b190b0ee55eb98526 | [] | no_license | ahmednasser74/Sofra_Ah | https://github.com/ahmednasser74/Sofra_Ah | 5686253b7c18cbc94ca476084e45e7c91183c4da | 8d068642f8ecacbb5bf1ceadb67a036d23db1a97 | refs/heads/master | 2021-01-06T12:52:47.371000 | 2020-11-24T01:32:35 | 2020-11-24T01:32:35 | 241,331,772 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.sofra.ui.fragment.userCycle.userHome.userRestaurantMenu.restaurantDetails;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.sofra.R;
import com.example.sofra.data.model.restaurantLogin.Restaurant;
import com.example.sofra.ui.fragment.untitledFolder.BaseFragment;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import static com.example.sofra.data.api.ApiClient.getClient;
public class UserRestaurantInformationFragment extends BaseFragment {
@BindView(R.id.restaurant_information_fragment_tv_case)
TextView restaurantInformationFragmentTvCase;
@BindView(R.id.restaurant_information_fragment_tv_city)
TextView restaurantInformationFragmentTvCity;
@BindView(R.id.restaurant_information_fragment_tv_town)
TextView restaurantInformationFragmentTvTown;
@BindView(R.id.restaurant_information_fragment_tv_minimum_cost)
TextView restaurantInformationFragmentTvMinimumCost;
@BindView(R.id.restaurant_information_fragment_tv_delivery_cost)
TextView restaurantInformationFragmentTvDeliveryCost;
public Restaurant restaurantData;
public UserRestaurantInformationFragment() {
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
setUpActivity();
View view = inflater.inflate(R.layout.fragment_user_restaurant_information, container, false);
ButterKnife.bind(this, view);
getClient();
init();
return view;
}
private void init() {
restaurantInformationFragmentTvCase.setText(restaurantData.getAvailability());
restaurantInformationFragmentTvTown.setText(restaurantData.getRegion().getName());
restaurantInformationFragmentTvCity.setText(restaurantData.getRegion().getCity().getName());
restaurantInformationFragmentTvMinimumCost.setText(restaurantData.getMinimumCharger());
restaurantInformationFragmentTvDeliveryCost.setText(restaurantData.getDeliveryCost());
}
@Override
public void onBack() {
super.onBack();
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
| UTF-8 | Java | 2,602 | java | UserRestaurantInformationFragment.java | Java | [] | null | [] | package com.example.sofra.ui.fragment.userCycle.userHome.userRestaurantMenu.restaurantDetails;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.sofra.R;
import com.example.sofra.data.model.restaurantLogin.Restaurant;
import com.example.sofra.ui.fragment.untitledFolder.BaseFragment;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import static com.example.sofra.data.api.ApiClient.getClient;
public class UserRestaurantInformationFragment extends BaseFragment {
@BindView(R.id.restaurant_information_fragment_tv_case)
TextView restaurantInformationFragmentTvCase;
@BindView(R.id.restaurant_information_fragment_tv_city)
TextView restaurantInformationFragmentTvCity;
@BindView(R.id.restaurant_information_fragment_tv_town)
TextView restaurantInformationFragmentTvTown;
@BindView(R.id.restaurant_information_fragment_tv_minimum_cost)
TextView restaurantInformationFragmentTvMinimumCost;
@BindView(R.id.restaurant_information_fragment_tv_delivery_cost)
TextView restaurantInformationFragmentTvDeliveryCost;
public Restaurant restaurantData;
public UserRestaurantInformationFragment() {
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
setUpActivity();
View view = inflater.inflate(R.layout.fragment_user_restaurant_information, container, false);
ButterKnife.bind(this, view);
getClient();
init();
return view;
}
private void init() {
restaurantInformationFragmentTvCase.setText(restaurantData.getAvailability());
restaurantInformationFragmentTvTown.setText(restaurantData.getRegion().getName());
restaurantInformationFragmentTvCity.setText(restaurantData.getRegion().getCity().getName());
restaurantInformationFragmentTvMinimumCost.setText(restaurantData.getMinimumCharger());
restaurantInformationFragmentTvDeliveryCost.setText(restaurantData.getDeliveryCost());
}
@Override
public void onBack() {
super.onBack();
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
| 2,602 | 0.758647 | 0.758647 | 80 | 31.525 | 30.254742 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5125 | false | false | 4 |
34ca12295d54818cc23c98116eafde6876cc3d8a | 8,641,474,220,250 | 4187ee0f313d0dc7176f924488831a4406204425 | /app/src/main/java/com/nit/demo/User.java | dd6dd57417cde923bf81ab0a207341160ada4b8c | [] | no_license | ripulagrawal98/demo | https://github.com/ripulagrawal98/demo | 589b1ca2ea7a6220055449fa349561ad61c86ecd | 6becc35a54de0a5fc4a6b5b632e47695b68b8628 | refs/heads/master | 2022-07-28T01:41:16.466000 | 2020-05-21T08:36:57 | 2020-05-21T08:36:57 | 264,922,679 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nit.demo;
import android.os.Parcel;
import android.os.Parcelable;
public class User implements Parcelable {
private String name;
private String time;
public User()
{
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public User(String name, String time)
{
this.name = name;
this.time = time;
}
public String getName(){
return name;
}
public void setName(String Name)
{
name = Name;
}
public String getTime(){
return time;
}
public void setTime(String Time){
time = Time;
}
public User(Parcel parcel)
{
name = parcel.readString();
time = parcel.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeString(name);
parcel.writeString(time);
}
public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>()
{
public User createFromParcel(Parcel in)
{
return new User(in);
}
public User[] newArray(int size)
{
return new User[size];
}
};
}
| UTF-8 | Java | 1,293 | java | User.java | Java | [] | null | [] | package com.nit.demo;
import android.os.Parcel;
import android.os.Parcelable;
public class User implements Parcelable {
private String name;
private String time;
public User()
{
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public User(String name, String time)
{
this.name = name;
this.time = time;
}
public String getName(){
return name;
}
public void setName(String Name)
{
name = Name;
}
public String getTime(){
return time;
}
public void setTime(String Time){
time = Time;
}
public User(Parcel parcel)
{
name = parcel.readString();
time = parcel.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeString(name);
parcel.writeString(time);
}
public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>()
{
public User createFromParcel(Parcel in)
{
return new User(in);
}
public User[] newArray(int size)
{
return new User[size];
}
};
}
| 1,293 | 0.575406 | 0.574633 | 70 | 17.471428 | 18.925207 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 4 |
22316032d6a366c6b5695d3f3463d0ba5fcffe2e | 25,022,479,481,728 | 7b8151f911d163e979393cfbc793510a67efe5bb | /src/main/java/com/talool/website/marketing/pages/mobile/MobileFaqPage.java | 3e960002b83dedddb3d2c06ba861634bb56cee55 | [] | no_license | talool/talool-website | https://github.com/talool/talool-website | 5e0aaa63c4f1367bf4e4fb9c472b9920e12d9782 | 4319439c090349905fc69ca9e46dc15657b18551 | refs/heads/master | 2020-04-11T04:18:53.794000 | 2015-03-31T15:38:43 | 2015-03-31T15:38:43 | 8,697,887 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.talool.website.marketing.pages.mobile;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import com.talool.website.marketing.panel.FaqPanel;
public class MobileFaqPage extends MobilePage {
private static final long serialVersionUID = 1L;
public MobileFaqPage(PageParameters parameters)
{
super(parameters);
}
@Override
protected void onInitialize()
{
super.onInitialize();
add(new FaqPanel("content"));
}
}
| UTF-8 | Java | 459 | java | MobileFaqPage.java | Java | [] | null | [] | package com.talool.website.marketing.pages.mobile;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import com.talool.website.marketing.panel.FaqPanel;
public class MobileFaqPage extends MobilePage {
private static final long serialVersionUID = 1L;
public MobileFaqPage(PageParameters parameters)
{
super(parameters);
}
@Override
protected void onInitialize()
{
super.onInitialize();
add(new FaqPanel("content"));
}
}
| 459 | 0.771242 | 0.769063 | 23 | 18.956522 | 21.756516 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.043478 | false | false | 4 |
58e7c2d24617ac947e0b39dae9f0a7676128a480 | 22,093,311,783,086 | 76dbfcd4a6de236aaa7efd00f21744de85c814bd | /fg-common/src/main/java/com/ws/jg/common/model/TableStat.java | cdfbf280b1c385dee7138856845e07bbaf8e92bd | [] | no_license | sudiptasish/flash-game | https://github.com/sudiptasish/flash-game | a442a3b3c31bcc7cb9d138400326c8c7b4200b2f | 2e846e411032e0be3f1914f98978d5d2b4ce695c | refs/heads/master | 2021-04-04T05:40:33.481000 | 2020-03-19T08:30:47 | 2020-03-19T08:30:47 | 248,428,599 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ws.jg.common.model;
/**
*
* @author Sudiptasish Chanda
*/
public enum TableStat {
WAITING_FOR_PLAYERS ("Waiting for players"),
IN_GAME ("Game started");
private final String description;
/**
*
*/
TableStat(String description) {
this.description = description;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
}
| UTF-8 | Java | 487 | java | TableStat.java | Java | [
{
"context": "ge com.ws.jg.common.model;\r\n\r\n/**\r\n * \r\n * @author Sudiptasish Chanda\r\n */\r\npublic enum TableStat {\r\n\r\n WAITING_FOR_",
"end": 74,
"score": 0.9998356699943542,
"start": 56,
"tag": "NAME",
"value": "Sudiptasish Chanda"
}
] | null | [] | package com.ws.jg.common.model;
/**
*
* @author <NAME>
*/
public enum TableStat {
WAITING_FOR_PLAYERS ("Waiting for players"),
IN_GAME ("Game started");
private final String description;
/**
*
*/
TableStat(String description) {
this.description = description;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
}
| 475 | 0.537988 | 0.537988 | 28 | 15.392858 | 14.943559 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.214286 | false | false | 4 |
6046319449305db28868f3b8611acbb683f15a39 | 33,775,622,828,087 | 2719d784bcfd328858728db39bc364ca33b7f8e0 | /NSA/app/src/main/java/net/tomoddy/nsa/MainActivity.java | c45e03bfe67828ce218464de9b204caca76a7944 | [] | no_license | tomoddy/AndroidStudioProjects | https://github.com/tomoddy/AndroidStudioProjects | e2825b26bac1343a2dc5ee11c57729ec7f00ff35 | e702f3af8c5fcf9f30b118e935b8f6a16d7f8422 | refs/heads/master | 2016-09-14T20:46:17.991000 | 2016-05-04T07:58:22 | 2016-05-04T07:58:22 | 57,061,400 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.tomoddy.nsa;
import android.graphics.drawable.Animatable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);}
final ImageView ct (ImageView) findViewById(R.id.imageView1);
final ImageView t (ImageView) findViewById(R.id.imageView2);
final Button clickMe = (Button) findViewById(R.id.side_button);
final Animation fade = new AlphaAnimation(1,0);
fade.setStartOffset(1000);
fade.setDuration(1000);
ct.setAnimation(fade);
t.setAnimation(fade);
}
}
| UTF-8 | Java | 931 | java | MainActivity.java | Java | [] | null | [] | package net.tomoddy.nsa;
import android.graphics.drawable.Animatable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);}
final ImageView ct (ImageView) findViewById(R.id.imageView1);
final ImageView t (ImageView) findViewById(R.id.imageView2);
final Button clickMe = (Button) findViewById(R.id.side_button);
final Animation fade = new AlphaAnimation(1,0);
fade.setStartOffset(1000);
fade.setDuration(1000);
ct.setAnimation(fade);
t.setAnimation(fade);
}
}
| 931 | 0.725027 | 0.711063 | 38 | 23.5 | 23.812592 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
f7a092340368be69a3043a6fadd33d054d17040e | 33,045,478,399,394 | a0cea8207e48b9b537a336dd2a173ec33395f349 | /app/src/main/java/net/glouz/myapp/model/api/request/product/BaseRequestListener.java | 663c0d4508f80ba131174ccadfcb0ef1a166a5f0 | [] | no_license | glouzaille/AndroidAppSample | https://github.com/glouzaille/AndroidAppSample | b35989a05a3df2baf5b98fb3a5869b16a1af7a0d | c4b951eca1e9c24d4fd0ad2c7142e742baa4de45 | refs/heads/master | 2020-04-16T01:01:16.719000 | 2015-07-30T15:01:08 | 2015-07-30T15:01:08 | 39,956,183 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.glouz.myapp.model.api.request.product;
import com.octo.android.robospice.exception.NoNetworkException;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.request.listener.RequestListener;
import net.glouz.myapp.R;
import net.glouz.myapp.SampleApplication;
import net.glouz.myapp.event.ErrorEvent;
import de.greenrobot.event.EventBus;
/**
* Handles generic request listener logic.
*
* @author glouzonf
*
* @param <T>
*/
public class BaseRequestListener<T> implements RequestListener<T> {
protected EventBus mEventBus = EventBus.getDefault();
private ErrorEvent mErrorEvent = null;
@Override
public void onRequestFailure(SpiceException spiceException) {
if (spiceException != null) {
if (spiceException instanceof NoNetworkException) {
mErrorEvent = new ErrorEvent(SampleApplication.getInstance()
.getString(R.string.connectivity_error));
mEventBus.post(mErrorEvent);
return;
}
}
}
@Override
public void onRequestSuccess(T resultSuccess) {
}
}
| UTF-8 | Java | 1,062 | java | BaseRequestListener.java | Java | [
{
"context": "les generic request listener logic.\n * \n * @author glouzonf\n *\n * @param <T>\n */\npublic class BaseRequestList",
"end": 475,
"score": 0.9994605779647827,
"start": 467,
"tag": "USERNAME",
"value": "glouzonf"
}
] | null | [] | package net.glouz.myapp.model.api.request.product;
import com.octo.android.robospice.exception.NoNetworkException;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.request.listener.RequestListener;
import net.glouz.myapp.R;
import net.glouz.myapp.SampleApplication;
import net.glouz.myapp.event.ErrorEvent;
import de.greenrobot.event.EventBus;
/**
* Handles generic request listener logic.
*
* @author glouzonf
*
* @param <T>
*/
public class BaseRequestListener<T> implements RequestListener<T> {
protected EventBus mEventBus = EventBus.getDefault();
private ErrorEvent mErrorEvent = null;
@Override
public void onRequestFailure(SpiceException spiceException) {
if (spiceException != null) {
if (spiceException instanceof NoNetworkException) {
mErrorEvent = new ErrorEvent(SampleApplication.getInstance()
.getString(R.string.connectivity_error));
mEventBus.post(mErrorEvent);
return;
}
}
}
@Override
public void onRequestSuccess(T resultSuccess) {
}
}
| 1,062 | 0.769303 | 0.769303 | 43 | 23.697674 | 24.595835 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.139535 | false | false | 4 |
bd780766c6b149f87abbc7fc60d8dd607afa1ce9 | 34,634,616,286,895 | 8d7e76fab2101a0d2a3c0075b52f0b98e581a2b6 | /src/main/java/net/webstructor/al/AL.java | 3096a6e7a91fbeafa4149876d45eeb67f18ef4ce | [
"MIT"
] | permissive | aigents/aigents-java | https://github.com/aigents/aigents-java | f28a2f3d3e13d0104fd086aa592c5587c63ea9e8 | 52b66faa3641e6ff57d0f7742bcd1be6f1684cdc | refs/heads/master | 2022-11-01T18:44:02.018000 | 2022-10-22T18:10:31 | 2022-10-22T18:10:31 | 157,051,431 | 26 | 12 | MIT | false | 2021-11-22T10:13:42 | 2018-11-11T05:47:25 | 2021-11-20T05:13:25 | 2021-11-22T10:13:42 | 9,042 | 20 | 10 | 37 | Java | false | false | /*
* MIT License
*
* Copyright (c) 2005-2020 by Anton Kolonin, Aigents®
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.webstructor.al;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import net.webstructor.agent.Body;
import net.webstructor.agent.Schema;
import net.webstructor.core.Storager;
import net.webstructor.util.Array;
public class AL {
public static final int declaration = 0, direction = 1, confirmation = 2, interrogation = 3;
//TODO: move out to Lexicon/Schema
//values
public final static String _true = "true";
public final static String _false = "false";
public final static String id = "id";
public final static String is = "is";
public final static String has = "has";
public final static String name = "name";
public final static String does = "does";
public final static String times = "times";
public final static String trust = "trust";
public final static String trusts = "trusts";
public final static String ignore = "ignore";
public final static String ignores = "ignores";
public final static String share = "share";
public final static String shares = "shares";
public final static String friend = "friend";
public final static String friends = "friends";
public final static String _new = "new";
public final static String news = "news";
public final static String things = "things";
//public final static String sessions = "sessions";
public final static String sites = "sites";
public final static String areas = "areas";
public final static String sources = "sources";
public final static String categories = "categories";
public final static String patterns = "patterns";
public final static String responses = "responses";
public final static String member = "member";
public final static String members = "members";
public final static String group = "group";
public final static String groups = "groups";
public final static String network = "network";
public final static String networks = "networks";
public final static String authors = "authors";
public final static String parents = "parents";
public final static String topic = "topic";
public final static String topics = "topics";
public final static String query = "query";
public final static String queries = "queries";
public final static String click = "click";
public final static String clicks = "clicks";
public final static String selection = "selection";
public final static String selections = "selections";
public final static String copypaste = "copypaste";
public final static String copypastes = "copypastes";
public final static String image = "image";
public final static String path = "path";
public final static String text = "text"; // TODO: move this out to name?
public final static String version = "version";
public final static String format = "format";
public final static String conversation = "conversation";
public final static String context = "context";
public final static String reputation = "reputation";//global reputaion
public final static String title = "title";
public final static String positive = "positive";
public final static String negative = "negative";
public final static String sentiment = "sentiment";//(positive-negative)/max(positive,negative)
//things
public final static String number = "number";//integer or floating point
public final static String currency = "currency";
public final static String money = "money";//currency+number
//public final static String value = "value";// not used?
public final static String date = "date";//year,monh,day
public final static String daytime = "daytime";//hour,minute,second
public final static String time = "time";//date and daytime
public final static String word = "word";//single token
public final static String email = "email";//email address
public final static String address = "address";//physical address
public final static String[] foundation = new String[]{ //TODO have this in Schema, not here and in Thing
id,name,is,has,does,times,trust,trusts,ignores,share,shares,friend,friends,_new,news,things,topics,sites,areas,sources,patterns,responses,text
,query,queries,click,clicks,selection,selections,copypaste,copypastes
,members,groups
};
//synsets
public final static String[] what = new String[] {"what"};
public final static String[] iff = new String[] {"if"};
public final static String[] doo = new String[] {"do"};
//TODO: decide what to do with true/false if appears as property value and breaks parsing as negation
//public final static String[] not = new String[] {"not","no","false","~"};
public final static String[] no = new String[] {"no","not","~"};
public final static String[] ok = new String[] {"ok","yes","true"};
public final static String[] i_my = new String[] {"my","i","we","our","me"};
public final static String[] you = new String[] {"your","you"};
public final static String[] there = new String[] {"there","it","here","this","that","a","the"};
public final static String[] lister = new String[] {",",";","and","or"};//TODO: have either AL.lister or AL.commas!
public final static String[][] grammar = new String[][]{what,iff,doo,no,ok,i_my,you,there,lister};
public static final String period = ".";
public static final String space = " ";
public static final String spaces = space+"\t\r\n";
public static final String brackets_open = "{([";
public static final String brackets_close = "})]";
public static final String brackets = brackets_open + brackets_close;
public static final String commas = ",;";//TODO: union with 'separators' below
public static final String periods = ".!?";
public static final String delimiters = commas+periods;
public static final String negation = "~";
public static final String punctuation = brackets + commas + periods + negation;
public static final String separators = ".,:";//like decimal separators inside a word or colon in time
public static final String dashes = "-—";//word separators allowed only inside a word
public static final String quotes = "\'\"";
public static final String trimmers = separators + dashes;
//https://stackoverflow.com/questions/1856785/characters-allowed-in-a-url
public static final String urls = "?$-_.+!*'";//()";TODO fix hack excluding parentheses for MD: [I'm an inline-style link](https://www.google.com)
public static final String[] https = {"http://", "https://"};
public static final String[] imgs = {".png", ".svg", ".jpeg", ".jpg", ".bmp", ".tiff", ".gif"};
protected Body body;
//private int recursion = 0;//TODO: need to consider current recursion level?
public AL(Body body) {
this.body = body;
}
public static boolean empty(String string) {
return string == null || string.isEmpty();//string.length() == 0;
}
public static boolean empty(StringBuilder sb) {
return sb == null || sb.length() == 0;
}
public static boolean empty(Object[] objects) {
return objects == null || objects.length == 0;
}
public static boolean single(Object[] collection) {
return collection != null && collection.length == 1;
}
public static boolean empty(Collection collection) {
return collection == null || collection.isEmpty();
}
public static boolean single(Collection collection) {
return collection != null && collection.size() == 1;
}
public static boolean empty(Set set) {
return set == null || set.size() == 0;
}
public static boolean single(Set collection) {
return collection != null && collection.size() == 1;
}
public static boolean empty(Map set) {
return set == null || set.isEmpty();
}
public static String unquote(String string) {
int len;
if (!AL.empty(string) && (len = string.length()) > 2)
if ((string.startsWith("\'") && string.endsWith("\'")) || (string.startsWith("\"") && string.endsWith("\"")))
return string.substring(1, len - 1);
return string;
}
//TODO: move out somewhere!?
//TODO: optimization to avoid extra lowercasing!
public static boolean isURL(String str) {
return Array.prefix(https,str.toLowerCase()) != null && str.indexOf(' ') == -1;
}
public static boolean isIMG(String str) {
return isURL(str) && Array.suffix(imgs,str.toLowerCase()) != null;
}
public static boolean isVariable(String term) {
return term != null && term.length() > 1 && term.charAt(0) == '$';
}
public static int integer(String s, int def) {
try {
return Integer.valueOf(s).intValue();
} catch (Exception e) {
return def;
}
}
public static long integer(String s, long def) {
try {
return Long.valueOf(s).intValue();
} catch (Exception e) {
return def;
}
}
public static String toString(Object o) {
return o == null || o instanceof String ? (String)o : o.toString();
}
public Storager getStorager() {
return body.storager;
}
public static Object[][] parseToGrid(String input, String[] columns, String listSeparator) {
ArrayList rows = new ArrayList();
Parser parser = new Parser(input);
Object[] o = new Object[columns.length];
while (!parser.end()) {
String name = parser.parseAny(columns,true);
if (name == null)
break;
String delimiter = null;
StringBuilder sb = new StringBuilder();
while (!parser.end()) {
String token = parser.parse();
if (AL.punctuation.indexOf(token) != -1) {
delimiter = token;
break;
}
if (sb.length() > 0)
sb.append(' ');
sb.append(token);
}
int column = Array.index(columns,name,true);//TODO: should be sensitive=false!?
if (column < 0 || column >= o.length)
;//throw new Exception("ddd");//TODO:throw exception
else
if (name.equals(AL.trust) || name.equals(AL.share) || name.equals(AL.friend))//TODO: fair Schema-unary properties!
o[column] = Boolean.valueOf(sb.toString());
else
o[column] = sb.toString();
if (delimiter == null || !delimiter.equals(listSeparator)) {
rows.add(o);
o = new Object[columns.length];
}
}
return (Object[][])rows.toArray(new Object[][]{});
}
//TODO:optimize and move all AL-parsing into separate "linguistic" framework
public static Object[][] parseToSheet(String input, String[] names, String listSeparator) {
String[] sorted = Array.sortedByLength(names, false);
HashMap props = new HashMap();
Parser parser = new Parser(input);
while (!parser.end()) {
String n = parser.parseAny(sorted,true);
if (n == null) {
parser.parse();
continue;//skip for tolerance?
//break;
}
String delimiter = null;
StringBuilder sb = new StringBuilder();
while (!parser.end()) {
String token = parser.parse();
if (AL.punctuation.indexOf(token) != -1) {
delimiter = token;
break;
}
if (sb.length() > 0)
sb.append(' ');
sb.append(token);
}
props.put(n, sb.toString());
if (delimiter == null || !delimiter.equals(listSeparator))
break; //ignore objects other than first one?
}
Object[][] o = new Object[names.length][2];
for (int i = 0; i < names.length; i++) {
String str = (String)props.get(names[i]);
o[i][0] = names[i];
o[i][1] = str == null ? "" : str;
}
return o;
}
public static String[] parseToFields(String input) {
ArrayList list = new ArrayList();
Parser p = new Parser(input);
while (!p.end()) {
StringBuilder name = new StringBuilder();
String s = null;
while (!p.end()) { // glueing multi-word names from multiple tokens
s = p.parse();
if (AL.empty(s) || AL.punctuation.indexOf(s) != -1) // break field formation on any delimiter
break;
if (name.length() > 0)
name.append(' ');
name.append(s);
}
if (name.length() > 0)
list.add(name.toString());
if (AL.empty(s) || AL.periods.indexOf(s) !=-1) //break list formation on period
break;
}
return AL.empty(list) ? null : (String[]) list.toArray(new String[]{});
}
public static String propList(String[] names) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < names.length; i++) {
if (i > 0)
b.append(", ");
String val = names[i];
b.append(Writer.needsQuoting(val) ? Writer.quote(val) : val);
}
return b.toString();
}
private static void buildQualifier(StringBuilder b, String name, Object val) {
if (val != null) {
if (b.length() > 0)
b.append(", ");//TODO: consider " and " ?
Writer.toString(b,name);
b.append(' ');
if (val instanceof String)
Writer.toString(b,(String)val,Schema.quotable(name));
else
Writer.toString(b,val);
}
}
public static String buildQualifier(String names[], Object[] values, int fromPos) {
StringBuilder b = new StringBuilder();
for (int i = fromPos; i < names.length; i++)
if (i < values.length && values[i] != null && values[i] instanceof String) {
buildQualifier(b,names[i],values[i]);
}
return b.toString();
}
public static String buildQualifier(String names[], Object[] values) {
return buildQualifier(names,values,0);
}
public static String buildQualifier(Map map) {
StringBuilder b = new StringBuilder();
for (Iterator it = map.keySet().iterator(); it.hasNext();) {
String name = (String) it.next();
buildQualifier(b,name,map.get(name));
}
return b.toString();
}
public static String buildQualifier(String names[], Map map) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < names.length; i++) {
String name = names[i];
buildQualifier(b,name,map.get(name));
}
return b.toString();
}
public static String error(String message) {
if (message.startsWith("Error") || message.startsWith("No"))
return message;
//TODO: get rid of java.lang.Exception on error - on backend!!!
if (message.startsWith("Java.lang.Exception: "))
return Writer.capitalize(message.substring("Java.lang.Exception: ".length()));
return null;
}
}
| UTF-8 | Java | 15,128 | java | AL.java | Java | [
{
"context": "*\n * MIT License\n * \n * Copyright (c) 2005-2020 by Anton Kolonin, Aigents®\n *\n * Permission is hereby granted, fre",
"end": 65,
"score": 0.999840497970581,
"start": 52,
"tag": "NAME",
"value": "Anton Kolonin"
}
] | null | [] | /*
* MIT License
*
* Copyright (c) 2005-2020 by <NAME>, Aigents®
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.webstructor.al;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import net.webstructor.agent.Body;
import net.webstructor.agent.Schema;
import net.webstructor.core.Storager;
import net.webstructor.util.Array;
public class AL {
public static final int declaration = 0, direction = 1, confirmation = 2, interrogation = 3;
//TODO: move out to Lexicon/Schema
//values
public final static String _true = "true";
public final static String _false = "false";
public final static String id = "id";
public final static String is = "is";
public final static String has = "has";
public final static String name = "name";
public final static String does = "does";
public final static String times = "times";
public final static String trust = "trust";
public final static String trusts = "trusts";
public final static String ignore = "ignore";
public final static String ignores = "ignores";
public final static String share = "share";
public final static String shares = "shares";
public final static String friend = "friend";
public final static String friends = "friends";
public final static String _new = "new";
public final static String news = "news";
public final static String things = "things";
//public final static String sessions = "sessions";
public final static String sites = "sites";
public final static String areas = "areas";
public final static String sources = "sources";
public final static String categories = "categories";
public final static String patterns = "patterns";
public final static String responses = "responses";
public final static String member = "member";
public final static String members = "members";
public final static String group = "group";
public final static String groups = "groups";
public final static String network = "network";
public final static String networks = "networks";
public final static String authors = "authors";
public final static String parents = "parents";
public final static String topic = "topic";
public final static String topics = "topics";
public final static String query = "query";
public final static String queries = "queries";
public final static String click = "click";
public final static String clicks = "clicks";
public final static String selection = "selection";
public final static String selections = "selections";
public final static String copypaste = "copypaste";
public final static String copypastes = "copypastes";
public final static String image = "image";
public final static String path = "path";
public final static String text = "text"; // TODO: move this out to name?
public final static String version = "version";
public final static String format = "format";
public final static String conversation = "conversation";
public final static String context = "context";
public final static String reputation = "reputation";//global reputaion
public final static String title = "title";
public final static String positive = "positive";
public final static String negative = "negative";
public final static String sentiment = "sentiment";//(positive-negative)/max(positive,negative)
//things
public final static String number = "number";//integer or floating point
public final static String currency = "currency";
public final static String money = "money";//currency+number
//public final static String value = "value";// not used?
public final static String date = "date";//year,monh,day
public final static String daytime = "daytime";//hour,minute,second
public final static String time = "time";//date and daytime
public final static String word = "word";//single token
public final static String email = "email";//email address
public final static String address = "address";//physical address
public final static String[] foundation = new String[]{ //TODO have this in Schema, not here and in Thing
id,name,is,has,does,times,trust,trusts,ignores,share,shares,friend,friends,_new,news,things,topics,sites,areas,sources,patterns,responses,text
,query,queries,click,clicks,selection,selections,copypaste,copypastes
,members,groups
};
//synsets
public final static String[] what = new String[] {"what"};
public final static String[] iff = new String[] {"if"};
public final static String[] doo = new String[] {"do"};
//TODO: decide what to do with true/false if appears as property value and breaks parsing as negation
//public final static String[] not = new String[] {"not","no","false","~"};
public final static String[] no = new String[] {"no","not","~"};
public final static String[] ok = new String[] {"ok","yes","true"};
public final static String[] i_my = new String[] {"my","i","we","our","me"};
public final static String[] you = new String[] {"your","you"};
public final static String[] there = new String[] {"there","it","here","this","that","a","the"};
public final static String[] lister = new String[] {",",";","and","or"};//TODO: have either AL.lister or AL.commas!
public final static String[][] grammar = new String[][]{what,iff,doo,no,ok,i_my,you,there,lister};
public static final String period = ".";
public static final String space = " ";
public static final String spaces = space+"\t\r\n";
public static final String brackets_open = "{([";
public static final String brackets_close = "})]";
public static final String brackets = brackets_open + brackets_close;
public static final String commas = ",;";//TODO: union with 'separators' below
public static final String periods = ".!?";
public static final String delimiters = commas+periods;
public static final String negation = "~";
public static final String punctuation = brackets + commas + periods + negation;
public static final String separators = ".,:";//like decimal separators inside a word or colon in time
public static final String dashes = "-—";//word separators allowed only inside a word
public static final String quotes = "\'\"";
public static final String trimmers = separators + dashes;
//https://stackoverflow.com/questions/1856785/characters-allowed-in-a-url
public static final String urls = "?$-_.+!*'";//()";TODO fix hack excluding parentheses for MD: [I'm an inline-style link](https://www.google.com)
public static final String[] https = {"http://", "https://"};
public static final String[] imgs = {".png", ".svg", ".jpeg", ".jpg", ".bmp", ".tiff", ".gif"};
protected Body body;
//private int recursion = 0;//TODO: need to consider current recursion level?
public AL(Body body) {
this.body = body;
}
public static boolean empty(String string) {
return string == null || string.isEmpty();//string.length() == 0;
}
public static boolean empty(StringBuilder sb) {
return sb == null || sb.length() == 0;
}
public static boolean empty(Object[] objects) {
return objects == null || objects.length == 0;
}
public static boolean single(Object[] collection) {
return collection != null && collection.length == 1;
}
public static boolean empty(Collection collection) {
return collection == null || collection.isEmpty();
}
public static boolean single(Collection collection) {
return collection != null && collection.size() == 1;
}
public static boolean empty(Set set) {
return set == null || set.size() == 0;
}
public static boolean single(Set collection) {
return collection != null && collection.size() == 1;
}
public static boolean empty(Map set) {
return set == null || set.isEmpty();
}
public static String unquote(String string) {
int len;
if (!AL.empty(string) && (len = string.length()) > 2)
if ((string.startsWith("\'") && string.endsWith("\'")) || (string.startsWith("\"") && string.endsWith("\"")))
return string.substring(1, len - 1);
return string;
}
//TODO: move out somewhere!?
//TODO: optimization to avoid extra lowercasing!
public static boolean isURL(String str) {
return Array.prefix(https,str.toLowerCase()) != null && str.indexOf(' ') == -1;
}
public static boolean isIMG(String str) {
return isURL(str) && Array.suffix(imgs,str.toLowerCase()) != null;
}
public static boolean isVariable(String term) {
return term != null && term.length() > 1 && term.charAt(0) == '$';
}
public static int integer(String s, int def) {
try {
return Integer.valueOf(s).intValue();
} catch (Exception e) {
return def;
}
}
public static long integer(String s, long def) {
try {
return Long.valueOf(s).intValue();
} catch (Exception e) {
return def;
}
}
public static String toString(Object o) {
return o == null || o instanceof String ? (String)o : o.toString();
}
public Storager getStorager() {
return body.storager;
}
public static Object[][] parseToGrid(String input, String[] columns, String listSeparator) {
ArrayList rows = new ArrayList();
Parser parser = new Parser(input);
Object[] o = new Object[columns.length];
while (!parser.end()) {
String name = parser.parseAny(columns,true);
if (name == null)
break;
String delimiter = null;
StringBuilder sb = new StringBuilder();
while (!parser.end()) {
String token = parser.parse();
if (AL.punctuation.indexOf(token) != -1) {
delimiter = token;
break;
}
if (sb.length() > 0)
sb.append(' ');
sb.append(token);
}
int column = Array.index(columns,name,true);//TODO: should be sensitive=false!?
if (column < 0 || column >= o.length)
;//throw new Exception("ddd");//TODO:throw exception
else
if (name.equals(AL.trust) || name.equals(AL.share) || name.equals(AL.friend))//TODO: fair Schema-unary properties!
o[column] = Boolean.valueOf(sb.toString());
else
o[column] = sb.toString();
if (delimiter == null || !delimiter.equals(listSeparator)) {
rows.add(o);
o = new Object[columns.length];
}
}
return (Object[][])rows.toArray(new Object[][]{});
}
//TODO:optimize and move all AL-parsing into separate "linguistic" framework
public static Object[][] parseToSheet(String input, String[] names, String listSeparator) {
String[] sorted = Array.sortedByLength(names, false);
HashMap props = new HashMap();
Parser parser = new Parser(input);
while (!parser.end()) {
String n = parser.parseAny(sorted,true);
if (n == null) {
parser.parse();
continue;//skip for tolerance?
//break;
}
String delimiter = null;
StringBuilder sb = new StringBuilder();
while (!parser.end()) {
String token = parser.parse();
if (AL.punctuation.indexOf(token) != -1) {
delimiter = token;
break;
}
if (sb.length() > 0)
sb.append(' ');
sb.append(token);
}
props.put(n, sb.toString());
if (delimiter == null || !delimiter.equals(listSeparator))
break; //ignore objects other than first one?
}
Object[][] o = new Object[names.length][2];
for (int i = 0; i < names.length; i++) {
String str = (String)props.get(names[i]);
o[i][0] = names[i];
o[i][1] = str == null ? "" : str;
}
return o;
}
public static String[] parseToFields(String input) {
ArrayList list = new ArrayList();
Parser p = new Parser(input);
while (!p.end()) {
StringBuilder name = new StringBuilder();
String s = null;
while (!p.end()) { // glueing multi-word names from multiple tokens
s = p.parse();
if (AL.empty(s) || AL.punctuation.indexOf(s) != -1) // break field formation on any delimiter
break;
if (name.length() > 0)
name.append(' ');
name.append(s);
}
if (name.length() > 0)
list.add(name.toString());
if (AL.empty(s) || AL.periods.indexOf(s) !=-1) //break list formation on period
break;
}
return AL.empty(list) ? null : (String[]) list.toArray(new String[]{});
}
public static String propList(String[] names) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < names.length; i++) {
if (i > 0)
b.append(", ");
String val = names[i];
b.append(Writer.needsQuoting(val) ? Writer.quote(val) : val);
}
return b.toString();
}
private static void buildQualifier(StringBuilder b, String name, Object val) {
if (val != null) {
if (b.length() > 0)
b.append(", ");//TODO: consider " and " ?
Writer.toString(b,name);
b.append(' ');
if (val instanceof String)
Writer.toString(b,(String)val,Schema.quotable(name));
else
Writer.toString(b,val);
}
}
public static String buildQualifier(String names[], Object[] values, int fromPos) {
StringBuilder b = new StringBuilder();
for (int i = fromPos; i < names.length; i++)
if (i < values.length && values[i] != null && values[i] instanceof String) {
buildQualifier(b,names[i],values[i]);
}
return b.toString();
}
public static String buildQualifier(String names[], Object[] values) {
return buildQualifier(names,values,0);
}
public static String buildQualifier(Map map) {
StringBuilder b = new StringBuilder();
for (Iterator it = map.keySet().iterator(); it.hasNext();) {
String name = (String) it.next();
buildQualifier(b,name,map.get(name));
}
return b.toString();
}
public static String buildQualifier(String names[], Map map) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < names.length; i++) {
String name = names[i];
buildQualifier(b,name,map.get(name));
}
return b.toString();
}
public static String error(String message) {
if (message.startsWith("Error") || message.startsWith("No"))
return message;
//TODO: get rid of java.lang.Exception on error - on backend!!!
if (message.startsWith("Java.lang.Exception: "))
return Writer.capitalize(message.substring("Java.lang.Exception: ".length()));
return null;
}
}
| 15,121 | 0.675107 | 0.671736 | 403 | 36.531017 | 28.187178 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.679901 | false | false | 4 |
1b54a75d0beade3d4fee80c21906d5ba1a5446f7 | 20,555,713,509,640 | 5e40b252b039e27c897a3ecaa1230286cc7c6c90 | /Project/src/main/java/com/codegym/project/service/EmployeeService.java | 084df3bccf00157ec57cb4cf250aaff48cb3e350 | [] | no_license | duongdonguyen96/Music_Instruments | https://github.com/duongdonguyen96/Music_Instruments | e0b0f0c9a564c3cda8273b3ef6e96c1c351bc7ff | adadb1570b3ec75b6ccf0ca5e2e79e6e0f46563f | refs/heads/main | 2023-01-23T18:58:36.378000 | 2020-12-09T06:42:44 | 2020-12-09T06:42:44 | 318,393,807 | 0 | 0 | null | false | 2020-12-09T06:42:45 | 2020-12-04T03:38:43 | 2020-12-09T04:15:30 | 2020-12-09T06:42:45 | 1,427 | 0 | 0 | 2 | HTML | false | false | package com.codegym.project.service;
import com.codegym.project.model.Employee;
public interface EmployeeService extends BaseService<Employee>{
}
| UTF-8 | Java | 148 | java | EmployeeService.java | Java | [] | null | [] | package com.codegym.project.service;
import com.codegym.project.model.Employee;
public interface EmployeeService extends BaseService<Employee>{
}
| 148 | 0.831081 | 0.831081 | 6 | 23.666666 | 24.729649 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 4 |
bba2ab8134a0895036dc05ec6c39e67893f03e93 | 1,537,598,297,335 | ee00e94d07631fab54d67342d74d5b7bb702e4f9 | /Set 03/LAB09/Driver.java | 1c1477bca64f37a2ac481e7a3716439b9e35c265 | [] | no_license | sami0055/CSE215-Programming-Language-II | https://github.com/sami0055/CSE215-Programming-Language-II | 761f888a41a0fea176f8a62f2887876d1d907b90 | 1be454dd506b3ea639c0ec95dd48ae7e679cd4ea | refs/heads/main | 2023-08-24T14:45:34.999000 | 2021-10-03T15:25:34 | 2021-10-03T15:25:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Driver {
public static void main(String[] args) {
// creating an object of circle
Circle c1 = new Circle();
c1.setRadius(5.0); // set radius to 5.5
System.out.println(c1.toString()); // display output
System.out.printf("Area: %.2f\n",c1.getArea()); //area
// creating an object of rectangle
Rectangle r1 = new Rectangle();
r1.setSide1(3.5);
r1.setSide2(4.5);
System.out.println();
System.out.println(r1.toString()); // display output
System.out.printf("Area: %.2f\n",r1.getArea()); //area
// creating an object of circle
Circle c2 = new Circle();
c2.setRadius(10.0); // set radius to 10
System.out.println();
System.out.println(c2.toString()); // display output
System.out.printf("Area: %.2f\n",c2.getArea()); //area
// creating an object of rectangle
Rectangle r2 = new Rectangle();
r2.setSide1(12.5);
r2.setSide2(13.0);
System.out.println();
System.out.println(r2.toString()); // display output
System.out.printf("Area: %.2f\n",r2.getArea()); //area
}
}
| UTF-8 | Java | 1,030 | java | Driver.java | Java | [] | null | [] |
public class Driver {
public static void main(String[] args) {
// creating an object of circle
Circle c1 = new Circle();
c1.setRadius(5.0); // set radius to 5.5
System.out.println(c1.toString()); // display output
System.out.printf("Area: %.2f\n",c1.getArea()); //area
// creating an object of rectangle
Rectangle r1 = new Rectangle();
r1.setSide1(3.5);
r1.setSide2(4.5);
System.out.println();
System.out.println(r1.toString()); // display output
System.out.printf("Area: %.2f\n",r1.getArea()); //area
// creating an object of circle
Circle c2 = new Circle();
c2.setRadius(10.0); // set radius to 10
System.out.println();
System.out.println(c2.toString()); // display output
System.out.printf("Area: %.2f\n",c2.getArea()); //area
// creating an object of rectangle
Rectangle r2 = new Rectangle();
r2.setSide1(12.5);
r2.setSide2(13.0);
System.out.println();
System.out.println(r2.toString()); // display output
System.out.printf("Area: %.2f\n",r2.getArea()); //area
}
}
| 1,030 | 0.656311 | 0.612621 | 36 | 27.555555 | 19.633368 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.138889 | false | false | 4 |
07bb20ce8e717bc4fce821b59ffe77d41e643033 | 18,098,992,237,311 | 85ac8e4d9de189277c39e6b2b32433931284a37c | /jahnstatusbyuser/src/main/java/cse/uprm/bigdataproject1/statusbyuser/StatusByUserReducer.java | 83e63a18849a4e53282a6c40f27c6c5bc8ea20c7 | [] | no_license | JahnCarlo/bigdataanalytics_p1 | https://github.com/JahnCarlo/bigdataanalytics_p1 | 7f2e66d450eb179a45acae6920df6d98beb2d1c2 | da7a560186892b716395d0a4bc408862947950c6 | refs/heads/master | 2020-03-31T14:50:07.877000 | 2018-10-23T22:15:01 | 2018-10-23T22:15:01 | 152,311,222 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cse.uprm.bigdataproject1.statusbyuser;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
public class StatusByUserReducer extends Reducer<Text, Text, Text, Text> {
@Override
protected void reduce(Text key, Iterable<Text> values, Context context)
throws IOException, InterruptedException {
String tweets = "";
for (Text value : values){
tweets += value.toString()+" ";
}
context.write(key, new Text(tweets));
}
} | UTF-8 | Java | 548 | java | StatusByUserReducer.java | Java | [] | null | [] | package cse.uprm.bigdataproject1.statusbyuser;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
public class StatusByUserReducer extends Reducer<Text, Text, Text, Text> {
@Override
protected void reduce(Text key, Iterable<Text> values, Context context)
throws IOException, InterruptedException {
String tweets = "";
for (Text value : values){
tweets += value.toString()+" ";
}
context.write(key, new Text(tweets));
}
} | 548 | 0.671533 | 0.669708 | 20 | 26.450001 | 24.334082 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.7 | false | false | 4 |
2d45bb9f8a3d0e5b8abbeba89fc00e106bf5b5ed | 29,480,655,568,596 | f800206889d8e4663e07c2e513d78d17666641c3 | /src/main/java/org/springframework/extensions/workflow/NoStartStateException.java | 4a3a107a49e8ffb02aa176c42b727ee6911f4535 | [
"Apache-2.0"
] | permissive | VijayEluri/spring-workflow | https://github.com/VijayEluri/spring-workflow | ea51f7d73057b452540975ed4d2f2adc4fa33148 | 633a06733241c26f06ebd912f5cd641b43c94fe6 | refs/heads/master | 2020-05-20T11:09:34.462000 | 2012-04-14T19:55:11 | 2012-04-14T19:55:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.springframework.extensions.workflow;
/**
* @author janm
*/
public class NoStartStateException extends FlowRuntimeException {
private static final long serialVersionUID = -6374994671991595343L;
public NoStartStateException(String msg) {
super(msg);
}
}
| UTF-8 | Java | 288 | java | NoStartStateException.java | Java | [
{
"context": "ringframework.extensions.workflow;\n\n/**\n * @author janm\n */\npublic class NoStartStateException extends Fl",
"end": 69,
"score": 0.9994730949401855,
"start": 65,
"tag": "USERNAME",
"value": "janm"
}
] | null | [] | package org.springframework.extensions.workflow;
/**
* @author janm
*/
public class NoStartStateException extends FlowRuntimeException {
private static final long serialVersionUID = -6374994671991595343L;
public NoStartStateException(String msg) {
super(msg);
}
}
| 288 | 0.743056 | 0.677083 | 12 | 23 | 25.768198 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 4 |
8512f2d57ff25ffa627c4dd23ec7e2d0adec957e | 9,380,208,575,667 | a904c66d4ccefe063086b65c82c0fdb33f0b45a5 | /ew.levr.base/src/main/java/com/eduworks/cruncher/file/CruncherFileHash.java | 485a3f3513e27d795b52b8d1cd6a4357fbe49c3c | [
"Apache-2.0"
] | permissive | sohail288/ew | https://github.com/sohail288/ew | 7df8c3fb22f3a5ae537c284a06dbc98db8848ff8 | 9226acc501d811e6529b958ebb00ed2e15cce5a1 | refs/heads/master | 2017-10-18T07:07:26.184000 | 2017-02-16T01:14:55 | 2017-02-16T01:14:55 | 68,891,041 | 0 | 0 | null | true | 2016-09-28T01:14:45 | 2016-09-22T06:21:30 | 2016-09-22T06:21:32 | 2016-09-28T01:14:45 | 913 | 0 | 0 | 0 | Java | null | null | package com.eduworks.cruncher.file;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.eduworks.resolver.Context;
import com.eduworks.resolver.Cruncher;
import com.eduworks.util.io.InMemoryFile;
public class CruncherFileHash extends Cruncher
{
@Override
public Object resolve(Context c, Map<String, String[]> parameters, Map<String, InputStream> dataStreams) throws JSONException
{
Object obj = getObj(c, parameters, dataStreams);
if(obj instanceof InMemoryFile){
InMemoryFile file = (InMemoryFile) obj;
MessageDigest md = null;
try
{
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
DigestInputStream dis = new DigestInputStream(file.getInputStream(), md);
int numRead;
byte[] buffer = new byte[1024];
try {
do{
numRead = dis.read(buffer);
}while(numRead != -1);
} catch (IOException e) {
e.printStackTrace();
}
return md.digest();
}
return null;
}
@Override
public String getDescription()
{
return "Converts an in memory file to a string.";
}
@Override
public String getReturn()
{
return "String";
}
@Override
public String getAttribution()
{
return ATTRIB_NONE;
}
@Override
public JSONObject getParameters() throws JSONException
{
return jo("obj", "InMemoryFile");
}
}
| UTF-8 | Java | 1,656 | java | CruncherFileHash.java | Java | [] | null | [] | package com.eduworks.cruncher.file;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.eduworks.resolver.Context;
import com.eduworks.resolver.Cruncher;
import com.eduworks.util.io.InMemoryFile;
public class CruncherFileHash extends Cruncher
{
@Override
public Object resolve(Context c, Map<String, String[]> parameters, Map<String, InputStream> dataStreams) throws JSONException
{
Object obj = getObj(c, parameters, dataStreams);
if(obj instanceof InMemoryFile){
InMemoryFile file = (InMemoryFile) obj;
MessageDigest md = null;
try
{
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
DigestInputStream dis = new DigestInputStream(file.getInputStream(), md);
int numRead;
byte[] buffer = new byte[1024];
try {
do{
numRead = dis.read(buffer);
}while(numRead != -1);
} catch (IOException e) {
e.printStackTrace();
}
return md.digest();
}
return null;
}
@Override
public String getDescription()
{
return "Converts an in memory file to a string.";
}
@Override
public String getReturn()
{
return "String";
}
@Override
public String getAttribution()
{
return ATTRIB_NONE;
}
@Override
public JSONObject getParameters() throws JSONException
{
return jo("obj", "InMemoryFile");
}
}
| 1,656 | 0.676932 | 0.673309 | 78 | 19.23077 | 21.313847 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.974359 | false | false | 4 |
775b1da198c66d19319980a507314508ab08fee6 | 6,416,681,202,232 | a51431ac0d7e103c3f8780930dacdd3304c4e093 | /src/main/java/com/mg2/lda/security/BasicConfiguration.java | 2c79ddeec447ed3c367b6f66e6f57fa8e9224455 | [] | no_license | yassinecheggar/MG2-LDA-BACK | https://github.com/yassinecheggar/MG2-LDA-BACK | 9e374b9f598305ef3a96c93d303b794540fd8a24 | f83fb0ccac413baa1a403fd1a57cf01017e3420a | refs/heads/main | 2023-06-18T23:55:53.958000 | 2021-07-15T15:57:14 | 2021-07-15T15:57:14 | 376,750,362 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mg2.lda.security;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
//@Configuration
//@EnableWebSecurity
public class BasicConfiguration extends WebSecurityConfigurerAdapter
{
@Autowired
DataSource dataSource;
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.cors().and()
.authorizeRequests()
.antMatchers("/**/Delete/*").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.httpBasic()
.and().csrf().disable()
;
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception
{
PasswordEncoder encoder =
PasswordEncoderFactories.createDelegatingPasswordEncoder();
/* auth
.inMemoryAuthentication()
.withUser("user")
.password(encoder.encode("password"))
.roles("USER")
.and()
.withUser("admin")
.password(encoder.encode("admin"))
.roles("USER", "ADMIN");*/
auth.jdbcAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.dataSource(dataSource).usersByUsernameQuery("select username , password , enabled from lda.user where username=?")
.authoritiesByUsernameQuery(
"select user.username , roles.role from lda.users_roles "
+ "inner join lda.user on user.id = users_roles.id "
+ "inner join lda.roles on roles.role_id = users_roles.role_id where username =?");
}
} | UTF-8 | Java | 2,670 | java | BasicConfiguration.java | Java | [
{
"context": "(\"user\")\n \t .password(encoder.encode(\"password\"))\n \t .roles(\"USER\")\n \t .",
"end": 2014,
"score": 0.9928395748138428,
"start": 2006,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "\"admin\")\n \t .password(encoder.encode(\"admin\"))\n \t .roles(\"USER\", \"ADMIN\");*/\n ",
"end": 2150,
"score": 0.9970220923423767,
"start": 2145,
"tag": "PASSWORD",
"value": "admin"
}
] | null | [] | package com.mg2.lda.security;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
//@Configuration
//@EnableWebSecurity
public class BasicConfiguration extends WebSecurityConfigurerAdapter
{
@Autowired
DataSource dataSource;
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.cors().and()
.authorizeRequests()
.antMatchers("/**/Delete/*").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.httpBasic()
.and().csrf().disable()
;
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception
{
PasswordEncoder encoder =
PasswordEncoderFactories.createDelegatingPasswordEncoder();
/* auth
.inMemoryAuthentication()
.withUser("user")
.password(encoder.encode("<PASSWORD>"))
.roles("USER")
.and()
.withUser("admin")
.password(encoder.encode("<PASSWORD>"))
.roles("USER", "ADMIN");*/
auth.jdbcAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.dataSource(dataSource).usersByUsernameQuery("select username , password , enabled from lda.user where username=?")
.authoritiesByUsernameQuery(
"select user.username , roles.role from lda.users_roles "
+ "inner join lda.user on user.id = users_roles.id "
+ "inner join lda.roles on roles.role_id = users_roles.role_id where username =?");
}
} | 2,677 | 0.719101 | 0.718727 | 72 | 36.097221 | 31.814636 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.055556 | false | false | 4 |
78b9c5b17a9b6780682fd4f6f5afcb2c139fb982 | 18,854,906,494,061 | 7e81d1c7e5f2aa8641bdf2c034405fd28947d487 | /contrib/axismora/src/org/apache/axismora/wsdl2ws/cpp/ClassLoader.java | 7ef04f0d8c79d6e80eb3436c9d15b86711c756e3 | [] | no_license | apache/axis1 | https://github.com/apache/axis1 | bf35d1bfbc0ca192f00100b7bd9173236780d4f4 | 02c3393b06ce4e973b89ff43fa7cf8f3eed59ff8 | HEAD | 2016-09-16T14:06:18.862000 | 2013-03-07T20:47:29 | 2013-03-07T20:47:29 | 206,460 | 5 | 10 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.apache.axismora.wsdl2ws.cpp;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import org.apache.axismora.wsdl2ws.SourceWriter;
import org.apache.axismora.wsdl2ws.WrapperFault;
import org.apache.axismora.wsdl2ws.WrapperUtils;
import org.apache.axismora.wsdl2ws.info.WebServiceContext;
/**
* @author Srinath Perera(hemapani@openource.lk)
*/
public class ClassLoader implements SourceWriter{
private Writer writer;
private WebServiceContext wscontext;
private String classname;
public ClassLoader(WebServiceContext wscontext) throws WrapperFault {
this.wscontext = wscontext;
this.classname = WrapperUtils.getClassNameFromFullyQualifiedName(wscontext.getSerInfo().getQualifiedServiceName());
}
public void writeSource() throws WrapperFault {
String wrappername = classname + CPPUtils.WRAPPER_NAME_APPENDER;
try{
this.writer = new BufferedWriter(new FileWriter(getFilePath(), false));
writer.write("// This file is automatically generated by the Axis C++ Wrapper Class Generator\n");
writer.write("// Service file containing the two export functions of the Web service Library\n");
writer.write("#ifdef WIN32\n");
writer.write("#define STORAGE_CLASS_INFO __declspec(dllexport)\n");
writer.write("#else\n");
writer.write("#define STORAGE_CLASS_INFO \n");
writer.write("#endif\n");
writer.write("#include \""+wrappername+".h\" \n");
writer.write("extern \"C\" {\n");
writer.write("STORAGE_CLASS_INFO\n");
writer.write("int GetClassInstance(BasicHandler **inst)\n");
writer.write("{\n");
writer.write("\tWrapperClassHandler* pWCH = new "+wrappername+"();\n");
writer.write("\tif (pWCH)\n");
writer.write("\t{\n");
writer.write("\t\tpWCH->Init();\n");
writer.write("\t\t*inst = pWCH;\n");
writer.write("\t\treturn SUCCESS;\n");
writer.write("\t}\n");
writer.write("\treturn FAIL;\n");
writer.write("}\n");
writer.write("STORAGE_CLASS_INFO \n");
writer.write("int DestroyInstance(BasicHandler *inst)\n");
writer.write("{\n");
writer.write("\tif (inst)\n");
writer.write("\t{\n");
writer.write("\t\tWrapperClassHandler* pWCH = static_cast<WrapperClassHandler*>(inst);\n");
writer.write("\t\tpWCH->Fini();\n");
writer.write("\t\tdelete pWCH;\n");
writer.write("\t\treturn SUCCESS;\n");
writer.write("\t}\n");
writer.write("\treturn FAIL;\n");
writer.write("}\n");
writer.write("}\n");
writer.flush();
writer.close();
}catch(IOException e){
throw new WrapperFault(e);
}
}
protected File getFilePath() throws WrapperFault {
String targetOutputLocation = this.wscontext.getWrapInfo().getTargetOutputLocation();
if(targetOutputLocation.endsWith("/"))
targetOutputLocation = targetOutputLocation.substring(0, targetOutputLocation.length() - 1);
new File(targetOutputLocation).mkdirs();
String fileName = targetOutputLocation + "/" + classname + CPPUtils.CLASS_LODER_APPENDER + ".cpp";
return new File(fileName);
}
}
| UTF-8 | Java | 3,057 | java | ClassLoader.java | Java | [
{
"context": "ra.wsdl2ws.info.WebServiceContext;\n\n/**\n * @author Srinath Perera(hemapani@openource.lk)\n */\npublic class ClassLoad",
"end": 409,
"score": 0.9998679161071777,
"start": 395,
"tag": "NAME",
"value": "Srinath Perera"
},
{
"context": "WebServiceContext;\n\n/**\n * @author Srinath Perera(hemapani@openource.lk)\n */\npublic class ClassLoader implements SourceWr",
"end": 431,
"score": 0.9999327659606934,
"start": 410,
"tag": "EMAIL",
"value": "hemapani@openource.lk"
}
] | null | [] | package org.apache.axismora.wsdl2ws.cpp;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import org.apache.axismora.wsdl2ws.SourceWriter;
import org.apache.axismora.wsdl2ws.WrapperFault;
import org.apache.axismora.wsdl2ws.WrapperUtils;
import org.apache.axismora.wsdl2ws.info.WebServiceContext;
/**
* @author <NAME>(<EMAIL>)
*/
public class ClassLoader implements SourceWriter{
private Writer writer;
private WebServiceContext wscontext;
private String classname;
public ClassLoader(WebServiceContext wscontext) throws WrapperFault {
this.wscontext = wscontext;
this.classname = WrapperUtils.getClassNameFromFullyQualifiedName(wscontext.getSerInfo().getQualifiedServiceName());
}
public void writeSource() throws WrapperFault {
String wrappername = classname + CPPUtils.WRAPPER_NAME_APPENDER;
try{
this.writer = new BufferedWriter(new FileWriter(getFilePath(), false));
writer.write("// This file is automatically generated by the Axis C++ Wrapper Class Generator\n");
writer.write("// Service file containing the two export functions of the Web service Library\n");
writer.write("#ifdef WIN32\n");
writer.write("#define STORAGE_CLASS_INFO __declspec(dllexport)\n");
writer.write("#else\n");
writer.write("#define STORAGE_CLASS_INFO \n");
writer.write("#endif\n");
writer.write("#include \""+wrappername+".h\" \n");
writer.write("extern \"C\" {\n");
writer.write("STORAGE_CLASS_INFO\n");
writer.write("int GetClassInstance(BasicHandler **inst)\n");
writer.write("{\n");
writer.write("\tWrapperClassHandler* pWCH = new "+wrappername+"();\n");
writer.write("\tif (pWCH)\n");
writer.write("\t{\n");
writer.write("\t\tpWCH->Init();\n");
writer.write("\t\t*inst = pWCH;\n");
writer.write("\t\treturn SUCCESS;\n");
writer.write("\t}\n");
writer.write("\treturn FAIL;\n");
writer.write("}\n");
writer.write("STORAGE_CLASS_INFO \n");
writer.write("int DestroyInstance(BasicHandler *inst)\n");
writer.write("{\n");
writer.write("\tif (inst)\n");
writer.write("\t{\n");
writer.write("\t\tWrapperClassHandler* pWCH = static_cast<WrapperClassHandler*>(inst);\n");
writer.write("\t\tpWCH->Fini();\n");
writer.write("\t\tdelete pWCH;\n");
writer.write("\t\treturn SUCCESS;\n");
writer.write("\t}\n");
writer.write("\treturn FAIL;\n");
writer.write("}\n");
writer.write("}\n");
writer.flush();
writer.close();
}catch(IOException e){
throw new WrapperFault(e);
}
}
protected File getFilePath() throws WrapperFault {
String targetOutputLocation = this.wscontext.getWrapInfo().getTargetOutputLocation();
if(targetOutputLocation.endsWith("/"))
targetOutputLocation = targetOutputLocation.substring(0, targetOutputLocation.length() - 1);
new File(targetOutputLocation).mkdirs();
String fileName = targetOutputLocation + "/" + classname + CPPUtils.CLASS_LODER_APPENDER + ".cpp";
return new File(fileName);
}
}
| 3,035 | 0.708211 | 0.705267 | 84 | 35.392857 | 27.47987 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.761905 | false | false | 4 |
8ccc407bc637426891287978a3c38033255dcde2 | 30,786,325,637,988 | 9885c60e37a23887c04627ddd4647f63d42101fb | /CSC2015/src/Vendingmachine.java | 1ffefcf2ea3a30712ac8425af0791c214c7d6afb | [] | no_license | NonFatPat/Assignment-2-Diving | https://github.com/NonFatPat/Assignment-2-Diving | d93170516327156783f34a085e83da5e943d5150 | 019cc8ec28015ef44da56f49c3a28aafb08d5fa1 | refs/heads/master | 2021-01-10T21:26:13.253000 | 2015-02-21T14:29:18 | 2015-02-21T14:29:18 | 31,127,882 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
public class Vendingmachine {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Change out = new Change();
double ammount = 0;
double nis = 1.46;
double hon = 1.55;
double mit = 2.67;
double sub = 3.75;
double bmw = 4.89;
double change;
int x;
int Quarters;
int Dimes;
int Nickels;
int Penny;
System.out.println("Keychain Vending machine");
System.out.println("1) Nissan Emblem\t 1.46 \n2) Honda Emblem\t\t 1.55 \n3) Mitsubishi Emblem\t 2.67 \n4) Subaru Emblem\t 3.75 \n5) BMW Emblem\t\t 4.89 \n ");
System.out.println("Insert Amount, only takes 1 & 5");
System.out.println("Press 0 when finished");
double money = 5;
while (money != 0){
money = in.nextDouble();
if (money !=0 &&money != 1 && money != 5&& money !=.25&& money !=.1&& money !=.05&& money !=.01){
System.out.println("error in bills");
}
else
ammount = ammount + money;
}
System.out.println("Current ammount is: " + ammount);
if (money < 5 )
{
// switch case to choose the product and out put the change
System.out.println("select your choice");
x = in.nextInt();
switch ( x){
case 0: change = ammount;
if (change < 0){
System.out.println("Bro your broke");
}
else{
Quarters = (int) (change / .25);
double OneChange=change - ( Quarters * .25);
Dimes = (int) (OneChange / .10);
double TwoChange = OneChange - (Dimes *.10);
Nickels= (int) (TwoChange / .05);
double ThreeChange= TwoChange - (Nickels * .05);
Penny = (int) (ThreeChange / .01);
System.out.println ("Your change is:" + "\nQuarter: "+ Quarters + "\nDimes: " + Dimes + "\nNickel: " + Nickels + "\nPenny: " + Penny); // replace with method which give out exact change in quarters dimes nickles and pennies
}
break;
case 1: change = ammount - nis;
out.setChange(change);
if(change < 0){
System.out.println("Insufficent funds");
}
else{
Quarters = (int) (change / .25);
double OneChange=change - ( Quarters * .25);
Dimes = (int) (OneChange / .10);
double TwoChange = OneChange - (Dimes *.10);
Nickels= (int) (TwoChange / .05);
double ThreeChange= TwoChange - (Nickels * .05);
Penny = (int) (ThreeChange / .01);
System.out.println ("Your change is:" + "\nQuarter: "+ Quarters + "\nDimes: " + Dimes + "\nNickel: " + Nickels + "\nPenny: " + Penny); // replace with method which give out exact change in quarters dimes nickles and pennies
}
break;
case 2: change = ammount - hon;
out.setChange(change);
if(change < 0){
System.out.println("Insufficent funds");
}
else{
Quarters = (int) (change / .25);
double OneChange=change - ( Quarters * .25);
Dimes = (int) (OneChange / .10);
double TwoChange = OneChange - (Dimes *.10);
Nickels= (int) (TwoChange / .05);
double ThreeChange= TwoChange - (Nickels * .05);
Penny = (int) (ThreeChange / .01);
System.out.println ("Your change is:" + "\nQuarter: "+ Quarters + "\nDimes: " + Dimes + "\nNickel: " + Nickels + "\nPenny: " + Penny); // replace with method which give out exact change in quarters dimes nickles and pennies
}
break;
case 3: change = money - mit;
out.setChange(change);
if(change < 0){
System.out.println("Insufficent funds");
}
else{
Quarters = (int) (change / .25);
double OneChange=change - ( Quarters * .25);
Dimes = (int) (OneChange / .10);
double TwoChange = OneChange - (Dimes *.10);
Nickels= (int) (TwoChange / .05);
double ThreeChange= TwoChange - (Nickels * .05);
Penny = (int) (ThreeChange / .01);
System.out.println ("Your change is:" + "\nQuarter: "+ Quarters + "\nDimes: " + Dimes + "\nNickel: " + Nickels + "\nPenny: " + Penny); // replace with method which give out exact change in quarters dimes nickles and pennies
}
break;
case 4: change = ammount - sub;
out.setChange(change);
if(change < 0){
System.out.println("Insufficent funds");
}
else{
Quarters = (int) (change / .25);
double OneChange=change - ( Quarters * .25);
Dimes = (int) (OneChange / .10);
double TwoChange = OneChange - (Dimes *.10);
Nickels= (int) (TwoChange / .05);
double ThreeChange= TwoChange - (Nickels * .05);
Penny = (int) (ThreeChange / .01);
System.out.println ("Your change is:" + "\nQuarter: "+ Quarters + "\nDimes: " + Dimes + "\nNickel: " + Nickels + "\nPenny: " + Penny); // replace with method which give out exact change in quarters dimes nickles and pennies
}
break;
case 5: change = ammount - bmw;
out.setChange(change);
if(change < 0){
System.out.println("Insufficent funds");
}
else{
Quarters = (int) (change / .25);
double OneChange=change - ( Quarters * .25);
Dimes = (int) (OneChange / .10);
double TwoChange = OneChange - (Dimes *.10);
Nickels= (int) (TwoChange / .05);
double ThreeChange= TwoChange - (Nickels * .05);
Penny = (int) (ThreeChange / .01);
System.out.println ("Your change is:" + "\nQuarter: "+ Quarters + "\nDimes: " + Dimes + "\nNickel: " + Nickels + "\nPenny: " + Penny); // replace with method which give out exact change in quarters dimes nickles and pennies
}
break;
default: System.out.println("error wrong selection");
}
}
else{
System.out.println("Incorrect Bill");
in.close();
}
}
} | UTF-8 | Java | 5,554 | java | Vendingmachine.java | Java | [
{
"context": "ssan Emblem\\t 1.46 \\n2) Honda Emblem\\t\\t 1.55 \\n3) Mitsubishi Emblem\\t 2.67 \\n4) Subaru Emblem\\t 3.75 \\n",
"end": 516,
"score": 0.5360532402992249,
"start": 513,
"tag": "NAME",
"value": "Mit"
},
{
"context": "\" + Dimes + \"\\nNickel: \" + Nickels + \"\\nPenny: \" + Penny); // replace with method which give out exact c",
"end": 4579,
"score": 0.5438001155853271,
"start": 4576,
"tag": "NAME",
"value": "Pen"
}
] | null | [] | import java.util.*;
public class Vendingmachine {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Change out = new Change();
double ammount = 0;
double nis = 1.46;
double hon = 1.55;
double mit = 2.67;
double sub = 3.75;
double bmw = 4.89;
double change;
int x;
int Quarters;
int Dimes;
int Nickels;
int Penny;
System.out.println("Keychain Vending machine");
System.out.println("1) Nissan Emblem\t 1.46 \n2) Honda Emblem\t\t 1.55 \n3) Mitsubishi Emblem\t 2.67 \n4) Subaru Emblem\t 3.75 \n5) BMW Emblem\t\t 4.89 \n ");
System.out.println("Insert Amount, only takes 1 & 5");
System.out.println("Press 0 when finished");
double money = 5;
while (money != 0){
money = in.nextDouble();
if (money !=0 &&money != 1 && money != 5&& money !=.25&& money !=.1&& money !=.05&& money !=.01){
System.out.println("error in bills");
}
else
ammount = ammount + money;
}
System.out.println("Current ammount is: " + ammount);
if (money < 5 )
{
// switch case to choose the product and out put the change
System.out.println("select your choice");
x = in.nextInt();
switch ( x){
case 0: change = ammount;
if (change < 0){
System.out.println("Bro your broke");
}
else{
Quarters = (int) (change / .25);
double OneChange=change - ( Quarters * .25);
Dimes = (int) (OneChange / .10);
double TwoChange = OneChange - (Dimes *.10);
Nickels= (int) (TwoChange / .05);
double ThreeChange= TwoChange - (Nickels * .05);
Penny = (int) (ThreeChange / .01);
System.out.println ("Your change is:" + "\nQuarter: "+ Quarters + "\nDimes: " + Dimes + "\nNickel: " + Nickels + "\nPenny: " + Penny); // replace with method which give out exact change in quarters dimes nickles and pennies
}
break;
case 1: change = ammount - nis;
out.setChange(change);
if(change < 0){
System.out.println("Insufficent funds");
}
else{
Quarters = (int) (change / .25);
double OneChange=change - ( Quarters * .25);
Dimes = (int) (OneChange / .10);
double TwoChange = OneChange - (Dimes *.10);
Nickels= (int) (TwoChange / .05);
double ThreeChange= TwoChange - (Nickels * .05);
Penny = (int) (ThreeChange / .01);
System.out.println ("Your change is:" + "\nQuarter: "+ Quarters + "\nDimes: " + Dimes + "\nNickel: " + Nickels + "\nPenny: " + Penny); // replace with method which give out exact change in quarters dimes nickles and pennies
}
break;
case 2: change = ammount - hon;
out.setChange(change);
if(change < 0){
System.out.println("Insufficent funds");
}
else{
Quarters = (int) (change / .25);
double OneChange=change - ( Quarters * .25);
Dimes = (int) (OneChange / .10);
double TwoChange = OneChange - (Dimes *.10);
Nickels= (int) (TwoChange / .05);
double ThreeChange= TwoChange - (Nickels * .05);
Penny = (int) (ThreeChange / .01);
System.out.println ("Your change is:" + "\nQuarter: "+ Quarters + "\nDimes: " + Dimes + "\nNickel: " + Nickels + "\nPenny: " + Penny); // replace with method which give out exact change in quarters dimes nickles and pennies
}
break;
case 3: change = money - mit;
out.setChange(change);
if(change < 0){
System.out.println("Insufficent funds");
}
else{
Quarters = (int) (change / .25);
double OneChange=change - ( Quarters * .25);
Dimes = (int) (OneChange / .10);
double TwoChange = OneChange - (Dimes *.10);
Nickels= (int) (TwoChange / .05);
double ThreeChange= TwoChange - (Nickels * .05);
Penny = (int) (ThreeChange / .01);
System.out.println ("Your change is:" + "\nQuarter: "+ Quarters + "\nDimes: " + Dimes + "\nNickel: " + Nickels + "\nPenny: " + Penny); // replace with method which give out exact change in quarters dimes nickles and pennies
}
break;
case 4: change = ammount - sub;
out.setChange(change);
if(change < 0){
System.out.println("Insufficent funds");
}
else{
Quarters = (int) (change / .25);
double OneChange=change - ( Quarters * .25);
Dimes = (int) (OneChange / .10);
double TwoChange = OneChange - (Dimes *.10);
Nickels= (int) (TwoChange / .05);
double ThreeChange= TwoChange - (Nickels * .05);
Penny = (int) (ThreeChange / .01);
System.out.println ("Your change is:" + "\nQuarter: "+ Quarters + "\nDimes: " + Dimes + "\nNickel: " + Nickels + "\nPenny: " + Penny); // replace with method which give out exact change in quarters dimes nickles and pennies
}
break;
case 5: change = ammount - bmw;
out.setChange(change);
if(change < 0){
System.out.println("Insufficent funds");
}
else{
Quarters = (int) (change / .25);
double OneChange=change - ( Quarters * .25);
Dimes = (int) (OneChange / .10);
double TwoChange = OneChange - (Dimes *.10);
Nickels= (int) (TwoChange / .05);
double ThreeChange= TwoChange - (Nickels * .05);
Penny = (int) (ThreeChange / .01);
System.out.println ("Your change is:" + "\nQuarter: "+ Quarters + "\nDimes: " + Dimes + "\nNickel: " + Nickels + "\nPenny: " + Penny); // replace with method which give out exact change in quarters dimes nickles and pennies
}
break;
default: System.out.println("error wrong selection");
}
}
else{
System.out.println("Incorrect Bill");
in.close();
}
}
} | 5,554 | 0.594707 | 0.568059 | 180 | 29.861111 | 42.651791 | 229 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.705555 | false | false | 4 |
efe0b9aaff2d1dcf2666952abae16153302a2c8d | 9,835,475,126,092 | 18ba89d8233bc91e013f20b5a6b2d1a186787075 | /src/com/example/snapsound/SnapSoundApplication.java | 5a8b681c60ce9993b2eb3cfc7f290f30f9befc9e | [] | no_license | dahisdaniel/SnapSound | https://github.com/dahisdaniel/SnapSound | 4c63ed7f157e8e2a9beb551304eb59093fab92fd | 9ec469198f77de1d10cf984d0eb1e4f3fa5eefdb | refs/heads/master | 2021-03-12T23:54:03.035000 | 2014-12-09T14:25:32 | 2014-12-09T14:25:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.snapsound;
import android.app.Application;
import com.parse.Parse;
import com.parse.ParseObject;
public class SnapSoundApplication extends Application {
public void onCreate() {
Parse.initialize(this, "9s7onecmVBfemhPNfnmRHyPLsJt2OrIzUs3oRYT2", "PVUvjVRUTXxcAfSu288QURSn4CxScr2bjLhELsDD");
}
}
| UTF-8 | Java | 334 | java | SnapSoundApplication.java | Java | [
{
"context": " void onCreate() {\n\t\t\n\t\t Parse.initialize(this, \"9s7onecmVBfemhPNfnmRHyPLsJt2OrIzUs3oRYT2\", \"PVUvjVRUTXxcAfSu288QURSn4CxScr2bjLhELsDD\");\n\t\t",
"end": 275,
"score": 0.6857732534408569,
"start": 235,
"tag": "KEY",
"value": "9s7onecmVBfemhPNfnmRHyPLsJt2OrIzUs3oRYT2"
},
{
"context": "his, \"9s7onecmVBfemhPNfnmRHyPLsJt2OrIzUs3oRYT2\", \"PVUvjVRUTXxcAfSu288QURSn4CxScr2bjLhELsDD\");\n\t\t\n\t\n\t}\n\n}\n",
"end": 319,
"score": 0.9782788157463074,
"start": 279,
"tag": "KEY",
"value": "PVUvjVRUTXxcAfSu288QURSn4CxScr2bjLhELsDD"
}
] | null | [] | package com.example.snapsound;
import android.app.Application;
import com.parse.Parse;
import com.parse.ParseObject;
public class SnapSoundApplication extends Application {
public void onCreate() {
Parse.initialize(this, "<KEY>", "<KEY>");
}
}
| 264 | 0.787425 | 0.757485 | 17 | 18.647058 | 28.91151 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 4 |
5f1647060d726b71eb339c6edab0b784903e9e0c | 7,962,869,422,243 | 4f81938351c01feb4bc2d3a3b45eb969bc58596d | /Wechat-Mall-Parent/wechat-mall-api/wechat-mall-pay-api/src/main/java/pay/entity/PaymentInfo.java | cad626a8b0b65cad917704e86615002085f4087d | [] | no_license | lpcwqj/Linpengcheng | https://github.com/lpcwqj/Linpengcheng | da226fed3811de3966ceecc533ee9ae4a2f18bce | bc6f418c42dfada3d55431d253330f4dddc5dee6 | refs/heads/master | 2022-12-08T23:58:33.317000 | 2020-02-23T04:13:15 | 2020-02-23T04:13:15 | 237,629,816 | 3 | 0 | null | false | 2022-06-17T02:52:12 | 2020-02-01T14:52:28 | 2022-04-01T07:25:21 | 2022-06-17T02:52:12 | 84,179 | 2 | 0 | 2 | JavaScript | false | false | package pay.entity;
import com.lpc.entity.BaseEntity;
import lombok.Data;
import java.io.Serializable;
/**
* 支付信息表
*/
@Data
public class PaymentInfo extends BaseEntity implements Serializable {
/**
* 支付类型id
*/
private Long typeId;
/**
* 订单编号
*/
private String orderId;
/**
* 第三方平台支付id
*/
private String plantformorderId;
/**
* 订单总价格 以分为单位
*/
private Long price;
/**
* 支付状态 0未支付 1已支付2已失效
*/
private Integer state;
/**
* 支付报文
*/
private String payMessage;
}
| UTF-8 | Java | 593 | java | PaymentInfo.java | Java | [] | null | [] | package pay.entity;
import com.lpc.entity.BaseEntity;
import lombok.Data;
import java.io.Serializable;
/**
* 支付信息表
*/
@Data
public class PaymentInfo extends BaseEntity implements Serializable {
/**
* 支付类型id
*/
private Long typeId;
/**
* 订单编号
*/
private String orderId;
/**
* 第三方平台支付id
*/
private String plantformorderId;
/**
* 订单总价格 以分为单位
*/
private Long price;
/**
* 支付状态 0未支付 1已支付2已失效
*/
private Integer state;
/**
* 支付报文
*/
private String payMessage;
}
| 593 | 0.655311 | 0.649299 | 39 | 11.794871 | 13.492979 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.871795 | false | false | 4 |
397fa9ed62cab6def0c34806bf83918fe375f2b4 | 19,267,223,340,920 | b0bf701671f7222cf49a2824e6c76129bcf8f4c9 | /src/main/java/com/example/shoppingcart/service/ProductService.java | f215719c786f1536db26b0286e6d67bcfc2598fc | [] | no_license | menes-t/shopping-cart | https://github.com/menes-t/shopping-cart | 92c9f6cfafddd6b8001fd9c33593dc41e32108a6 | 8ea9484fffdc2fbeac96936d8dc0a83f6aea3d82 | refs/heads/master | 2020-12-21T04:16:26.064000 | 2020-01-29T18:05:10 | 2020-01-29T18:05:10 | 236,303,410 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.shoppingcart.service;
import com.example.shoppingcart.exception.CartException;
import com.example.shoppingcart.data.dto.ProductDTO;
import com.example.shoppingcart.data.entity.category.Category;
import com.example.shoppingcart.data.entity.product.Product;
import com.example.shoppingcart.repository.CategoryRepository;
import com.example.shoppingcart.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class ProductService {
private final CategoryRepository categoryRepository;
private final ProductRepository productRepository;
@Autowired
public ProductService(CategoryRepository categoryRepository, ProductRepository productRepository) {
this.categoryRepository = categoryRepository;
this.productRepository = productRepository;
}
public ProductDTO createProduct(ProductDTO product){
if (product.getProductId() != null) {
throw new CartException("Cannot give id while create");
}
Product entity = dtoToEntity(product);
Product savedEntity = productRepository.save(entity);
return entityToDto(savedEntity);
}
public ProductDTO getProduct(String productId){
if (productId == null) {
throw new CartException("product id cannot be null");
}
Optional<Product> optionalProduct = productRepository.findById(productId);
Product entity = optionalProduct.orElseThrow(() -> new CartException("Given product id does not exist"));
return entityToDto(entity);
}
Product getProductByTitle(String productTitle){
if (productTitle == null) {
throw new CartException("product title cannot be null");
}
Optional<Product> optionalProduct = productRepository.findByTitle(productTitle);
return optionalProduct.orElseThrow(() -> new CartException("Given product title does not exist"));
}
public void deleteProduct(String productId){
if (productId == null) {
throw new CartException("product id cannot be null");
}
productRepository.deleteById(productId);
}
public ProductDTO updateProduct(ProductDTO product, String productId){
if (productId == null) {
throw new CartException("product id cannot be null");
}
Optional<Product> optionalProduct = productRepository.findById(productId);
if (optionalProduct.isEmpty()) {
throw new CartException("Given product id does not exist");
}
Product toBeSaved = dtoToEntity(product);
toBeSaved.setId(productId);
productRepository.save(toBeSaved);
return product;
}
private Product dtoToEntity(ProductDTO product) {
Product entity = new Product();
entity.setTitle(product.getTitle());
entity.setPrice(product.getPrice());
Optional<Category> category = categoryRepository.findById(product.getCategoryId());
entity.setCategory(category.orElseThrow(() -> new CartException("Given category id does not exist")));
return entity;
}
ProductDTO entityToDto(Product entity) {
ProductDTO dto = new ProductDTO();
dto.setProductId(entity.getId());
dto.setPrice(entity.getPrice());
dto.setTitle(entity.getTitle());
dto.setCategoryId(entity.getCategory().getId());
return dto;
}
}
| UTF-8 | Java | 3,521 | java | ProductService.java | Java | [] | null | [] | package com.example.shoppingcart.service;
import com.example.shoppingcart.exception.CartException;
import com.example.shoppingcart.data.dto.ProductDTO;
import com.example.shoppingcart.data.entity.category.Category;
import com.example.shoppingcart.data.entity.product.Product;
import com.example.shoppingcart.repository.CategoryRepository;
import com.example.shoppingcart.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class ProductService {
private final CategoryRepository categoryRepository;
private final ProductRepository productRepository;
@Autowired
public ProductService(CategoryRepository categoryRepository, ProductRepository productRepository) {
this.categoryRepository = categoryRepository;
this.productRepository = productRepository;
}
public ProductDTO createProduct(ProductDTO product){
if (product.getProductId() != null) {
throw new CartException("Cannot give id while create");
}
Product entity = dtoToEntity(product);
Product savedEntity = productRepository.save(entity);
return entityToDto(savedEntity);
}
public ProductDTO getProduct(String productId){
if (productId == null) {
throw new CartException("product id cannot be null");
}
Optional<Product> optionalProduct = productRepository.findById(productId);
Product entity = optionalProduct.orElseThrow(() -> new CartException("Given product id does not exist"));
return entityToDto(entity);
}
Product getProductByTitle(String productTitle){
if (productTitle == null) {
throw new CartException("product title cannot be null");
}
Optional<Product> optionalProduct = productRepository.findByTitle(productTitle);
return optionalProduct.orElseThrow(() -> new CartException("Given product title does not exist"));
}
public void deleteProduct(String productId){
if (productId == null) {
throw new CartException("product id cannot be null");
}
productRepository.deleteById(productId);
}
public ProductDTO updateProduct(ProductDTO product, String productId){
if (productId == null) {
throw new CartException("product id cannot be null");
}
Optional<Product> optionalProduct = productRepository.findById(productId);
if (optionalProduct.isEmpty()) {
throw new CartException("Given product id does not exist");
}
Product toBeSaved = dtoToEntity(product);
toBeSaved.setId(productId);
productRepository.save(toBeSaved);
return product;
}
private Product dtoToEntity(ProductDTO product) {
Product entity = new Product();
entity.setTitle(product.getTitle());
entity.setPrice(product.getPrice());
Optional<Category> category = categoryRepository.findById(product.getCategoryId());
entity.setCategory(category.orElseThrow(() -> new CartException("Given category id does not exist")));
return entity;
}
ProductDTO entityToDto(Product entity) {
ProductDTO dto = new ProductDTO();
dto.setProductId(entity.getId());
dto.setPrice(entity.getPrice());
dto.setTitle(entity.getTitle());
dto.setCategoryId(entity.getCategory().getId());
return dto;
}
}
| 3,521 | 0.697813 | 0.697813 | 98 | 34.92857 | 29.891043 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.489796 | false | false | 4 |
b0f3bc4e2d54670b4343541a9541e1665f340e96 | 17,849,884,132,791 | fe5d86481efdfe242d90398ecb98986286d55e17 | /data/search/APIzator19936269.java | df4995e5ffb557d0447eb0636335bb518c9a74f9 | [
"CC-BY-4.0"
] | permissive | pasqualesalza/apization | https://github.com/pasqualesalza/apization | 0923a438ac3b963d6efa8d779cce614e04bc0193 | 941ae03b2a9177875d00feec651dd27e7bdd5e29 | refs/heads/main | 2022-07-30T04:33:10.078000 | 2021-08-23T14:08:35 | 2021-08-23T14:08:35 | 399,110,560 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.stackoverflow.api;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* java JPanel How to fixed sizes
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/19936269">https://stackoverflow.com/a/19936269</a>
*/
public class APIzator19936269 extends JFrame {
public static void fixSize() {
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new BorderLayout());
JPanel green = new JPanel();
green.setPreferredSize(new Dimension(80, 150));
green.setBackground(Color.GREEN);
JPanel yellow = new JPanel();
yellow.setBackground(Color.YELLOW);
frame.getContentPane().add(green, BorderLayout.PAGE_START);
frame.getContentPane().add(yellow, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
| UTF-8 | Java | 925 | java | APIzator19936269.java | Java | [
{
"context": "**\n * java JPanel How to fixed sizes\n *\n * @author APIzator\n * @see <a href=\"https://stackoverflow.com/a",
"end": 222,
"score": 0.5380957722663879,
"start": 219,
"tag": "USERNAME",
"value": "API"
},
{
"context": "* java JPanel How to fixed sizes\n *\n * @author APIzator\n * @see <a href=\"https://stackoverflow.com/a/1993",
"end": 227,
"score": 0.8094200491905212,
"start": 222,
"tag": "NAME",
"value": "zator"
}
] | null | [] | package com.stackoverflow.api;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* java JPanel How to fixed sizes
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/19936269">https://stackoverflow.com/a/19936269</a>
*/
public class APIzator19936269 extends JFrame {
public static void fixSize() {
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new BorderLayout());
JPanel green = new JPanel();
green.setPreferredSize(new Dimension(80, 150));
green.setBackground(Color.GREEN);
JPanel yellow = new JPanel();
yellow.setBackground(Color.YELLOW);
frame.getContentPane().add(green, BorderLayout.PAGE_START);
frame.getContentPane().add(yellow, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
| 925 | 0.722162 | 0.690811 | 31 | 28.838709 | 22.057253 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.677419 | false | false | 4 |
33578413a15dd99f55f29cd123f6f3e64da36a61 | 6,502,580,493,673 | 4fa2d6070b55b1405fe2ceff80be424f299d2c23 | /school/cpe103/Lab5B/Lab5B.java | f9ed0d715505f52144e3d0f4d1007d34e86e83f2 | [] | no_license | jared-spadaro/hello-world | https://github.com/jared-spadaro/hello-world | 9fa6e8c39f3ca91698e2891307c851bbe567e840 | 541fab381127684a2dc1daacf2d835850dbf4054 | refs/heads/master | 2021-01-23T01:50:12.811000 | 2020-11-30T22:36:37 | 2020-11-30T22:36:37 | 92,885,685 | 0 | 0 | null | false | 2020-11-13T00:37:04 | 2017-05-30T23:44:36 | 2020-11-12T05:53:10 | 2020-11-13T00:37:04 | 2 | 0 | 0 | 0 | JavaScript | false | false | public class Lab5B
{
private static int[] data = {5,2,1,8,4,3,7,10,0,6,11,12,9};
private static boolean[] answer =
{true,true,false,true,true,false,true,true,true,true,true,false,true};
private static int failures = 0;
public static void main(String[] args)
{
int i;
if (data.length != answer.length)
throw new RuntimeException("Initialization error in driver.");
System.out.println("Begin creating tree A");
MyBST t = new MyBST();
for(i=0;i<data.length;++i)
{
t.insert(new Integer(data[i]));
reportTest("A"+i,t.isBalanced()==answer[i]);
}
System.out.println("Begin creating tree B");
t = new MyBST();
reportTest("B",t.isBalanced());
for(i=0;i<=2;++i)
{
t.insert(new Integer(i));
t.insert(new Integer(-i));
reportTest("B"+i,t.isBalanced());
}
for(i=3;i<=5;++i)
{
t.insert(new Integer(i));
t.insert(new Integer(-i));
reportTest("B"+i,!t.isBalanced());
}
System.out.println();
if (failures == 0)
System.out.println("All test cases were passed.");
else
System.out.println("Failed " + failures + " test cases.");
}
private static void reportTest(String ID,boolean passed)
{
if (passed)
System.out.println("Passed test " + ID);
else
{
++failures;
System.out.println("FAILED test " + ID);
}
}
}
| UTF-8 | Java | 1,545 | java | Lab5B.java | Java | [] | null | [] | public class Lab5B
{
private static int[] data = {5,2,1,8,4,3,7,10,0,6,11,12,9};
private static boolean[] answer =
{true,true,false,true,true,false,true,true,true,true,true,false,true};
private static int failures = 0;
public static void main(String[] args)
{
int i;
if (data.length != answer.length)
throw new RuntimeException("Initialization error in driver.");
System.out.println("Begin creating tree A");
MyBST t = new MyBST();
for(i=0;i<data.length;++i)
{
t.insert(new Integer(data[i]));
reportTest("A"+i,t.isBalanced()==answer[i]);
}
System.out.println("Begin creating tree B");
t = new MyBST();
reportTest("B",t.isBalanced());
for(i=0;i<=2;++i)
{
t.insert(new Integer(i));
t.insert(new Integer(-i));
reportTest("B"+i,t.isBalanced());
}
for(i=3;i<=5;++i)
{
t.insert(new Integer(i));
t.insert(new Integer(-i));
reportTest("B"+i,!t.isBalanced());
}
System.out.println();
if (failures == 0)
System.out.println("All test cases were passed.");
else
System.out.println("Failed " + failures + " test cases.");
}
private static void reportTest(String ID,boolean passed)
{
if (passed)
System.out.println("Passed test " + ID);
else
{
++failures;
System.out.println("FAILED test " + ID);
}
}
}
| 1,545 | 0.527508 | 0.511974 | 54 | 26.611111 | 21.122585 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.092593 | false | false | 4 |
7179ff5146a32446daa089c47869e4266ec37fd7 | 1,632,087,576,623 | 7df093bfff8a57ad27ae52005624eded4ca8a537 | /app/src/main/java/com/campusbooksinc/campusbooks/Fragments/MessageDialogFragment.java | 5642fea431c2c41dc4fc28996e61c068cadc7732 | [
"Apache-2.0"
] | permissive | vector-solutions/CampusBooks | https://github.com/vector-solutions/CampusBooks | 1605014031ec914af5b289847b9efad7c27bc212 | 9e5687381c1f823ce5593f081692698b5db2cf0e | refs/heads/master | 2016-03-30T03:25:10.798000 | 2015-09-10T17:28:23 | 2015-09-10T17:28:23 | 37,321,837 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.campusbooksinc.campusbooks.Fragments;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import com.campusbooksinc.campusbooks.BaseActivity;
import com.campusbooksinc.campusbooks.R;
public class MessageDialogFragment extends DialogFragment {
public interface MessageDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
}
private String mTitle;
private String mMessage;
private String mContent;
private MessageDialogListener mListener;
public void onCreate(Bundle state) {
super.onCreate(state);
setRetainInstance(true);
}
public static MessageDialogFragment newInstance(String title, String message, String content, String format, MessageDialogListener listener) {
MessageDialogFragment fragment = new MessageDialogFragment();
fragment.mTitle = title;
fragment.mContent = content;
fragment.mMessage = message;
fragment.mListener = listener;
return fragment;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(mMessage)
.setTitle(mTitle);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if(mListener != null) {
mListener.onDialogPositiveClick(MessageDialogFragment.this);
}
BaseActivity.act.getSupportFragmentManager().popBackStack();
BaseActivity.act.getSupportFragmentManager().beginTransaction()
.replace(R.id.base_container, new FragmentBuyRent()
.newInstance(mContent))
.addToBackStack(null).commit();
}
});
return builder.create();
}
}
| UTF-8 | Java | 2,059 | java | MessageDialogFragment.java | Java | [] | null | [] | package com.campusbooksinc.campusbooks.Fragments;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import com.campusbooksinc.campusbooks.BaseActivity;
import com.campusbooksinc.campusbooks.R;
public class MessageDialogFragment extends DialogFragment {
public interface MessageDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
}
private String mTitle;
private String mMessage;
private String mContent;
private MessageDialogListener mListener;
public void onCreate(Bundle state) {
super.onCreate(state);
setRetainInstance(true);
}
public static MessageDialogFragment newInstance(String title, String message, String content, String format, MessageDialogListener listener) {
MessageDialogFragment fragment = new MessageDialogFragment();
fragment.mTitle = title;
fragment.mContent = content;
fragment.mMessage = message;
fragment.mListener = listener;
return fragment;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(mMessage)
.setTitle(mTitle);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if(mListener != null) {
mListener.onDialogPositiveClick(MessageDialogFragment.this);
}
BaseActivity.act.getSupportFragmentManager().popBackStack();
BaseActivity.act.getSupportFragmentManager().beginTransaction()
.replace(R.id.base_container, new FragmentBuyRent()
.newInstance(mContent))
.addToBackStack(null).commit();
}
});
return builder.create();
}
}
| 2,059 | 0.675571 | 0.675085 | 58 | 34.5 | 28.913815 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.603448 | false | false | 4 |
bc5df534af1d54392f16c7a078d361345209e4c1 | 21,818,433,895,610 | 1c69384ccb96ab69fed77f97dd96bfd62517a659 | /java/src/main/java/sandbox/SqlBuilder.java | f012426c18a72deaa23dfc9a54b0dcc2712670be | [] | no_license | r0perice/golang-sandbox | https://github.com/r0perice/golang-sandbox | 5d4e1a7cd319b441314b1a59f141f5cfdfe4f6b5 | a0ba8b9242e23c6d7a68e6f04b6729a043d73479 | refs/heads/master | 2019-07-19T01:07:59.415000 | 2018-10-16T08:32:19 | 2018-10-16T08:32:19 | 54,901,421 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Author: Robin Péricé (2018)
*/
package sandbox;
import ca.krasnay.sqlbuilder.InsertBuilder;
public class SqlBuilder {
public static void main(final String[] args) {
new InsertBuilder("aa").set("", "");
}
}
| UTF-8 | Java | 223 | java | SqlBuilder.java | Java | [
{
"context": "/*\n * Author: Robin Péricé (2018)\n */\npackage sandbox;\n\nimport ca.krasnay.sq",
"end": 26,
"score": 0.9998607039451599,
"start": 14,
"tag": "NAME",
"value": "Robin Péricé"
}
] | null | [] | /*
* Author: <NAME> (2018)
*/
package sandbox;
import ca.krasnay.sqlbuilder.InsertBuilder;
public class SqlBuilder {
public static void main(final String[] args) {
new InsertBuilder("aa").set("", "");
}
}
| 215 | 0.678733 | 0.660634 | 14 | 14.785714 | 17.403524 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 4 |
865c8ed517b862fc8cc6ed56d96d02a123ea97e2 | 33,380,485,839,871 | 03534de0a6cf69ad221b9c9094ff3cc0e7684c6f | /backend/src/main/java/retailshop/config/SwaggerConfiguration.java | 443e1d86f3458c57e46ffc125d1359d0cb6b7ef9 | [] | no_license | masoomeg/myRetailShop | https://github.com/masoomeg/myRetailShop | b6c79df66a96b33700ff349dc8ca0abde9d55b81 | f4b51651a19b1b529972bbead9d3ac3531ce76b0 | refs/heads/master | 2020-04-12T22:14:01.057000 | 2018-12-26T16:37:25 | 2018-12-26T16:37:25 | 162,785,268 | 0 | 0 | null | false | 2018-12-26T16:37:26 | 2018-12-22T05:47:12 | 2018-12-25T18:48:46 | 2018-12-26T16:37:26 | 3,225 | 0 | 0 | 0 | Java | false | null | package retailshop.config;
import static com.google.common.base.Predicates.not;
import static springfox.documentation.builders.RequestHandlerSelectors.withClassAnnotation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.swagger.models.auth.In;
import springfox.documentation.annotations.ApiIgnore;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.schema.TypeNameExtractor;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.Contact;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket swaggerSpringMvcPlugin() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("administration-api")
.select()
.apis(not(withClassAnnotation(ApiIgnore.class)))
.paths(PathSelectors.ant("/api/**"))
.build()
.apiInfo(apiInfo())
;
}
//http://localhost:7080/swagger-ui.html
private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo("MyRetailShop Administration API", "REST API for Product's crud oprations",
"API", "Terms of service",
"",
"", "");
return apiInfo;
}
}
| UTF-8 | Java | 1,619 | java | SwaggerConfiguration.java | Java | [] | null | [] | package retailshop.config;
import static com.google.common.base.Predicates.not;
import static springfox.documentation.builders.RequestHandlerSelectors.withClassAnnotation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.swagger.models.auth.In;
import springfox.documentation.annotations.ApiIgnore;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.schema.TypeNameExtractor;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.Contact;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket swaggerSpringMvcPlugin() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("administration-api")
.select()
.apis(not(withClassAnnotation(ApiIgnore.class)))
.paths(PathSelectors.ant("/api/**"))
.build()
.apiInfo(apiInfo())
;
}
//http://localhost:7080/swagger-ui.html
private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo("MyRetailShop Administration API", "REST API for Product's crud oprations",
"API", "Terms of service",
"",
"", "");
return apiInfo;
}
}
| 1,619 | 0.797406 | 0.792464 | 49 | 32.040817 | 26.233612 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.77551 | false | false | 4 |
ea04bdac843a2686cdb6cd112c506b87ea989067 | 17,763,984,742,124 | 564695f046e062bb630c2b3765f03894aa14d539 | /app/src/main/java/com/bosc/leave/BienvenidoActivity.java | de6715c63b6a3147a33e8f69af7f0cb6a5bf67b2 | [] | no_license | dramirezm/LEAVE | https://github.com/dramirezm/LEAVE | 4517e75fc15ab3d499796b17439e33d87522bb11 | 32275ee41b9f9597957c6d2eca27ea36b9b00d2d | refs/heads/master | 2018-01-08T23:48:35.847000 | 2015-12-08T23:44:49 | 2015-12-08T23:44:49 | 45,489,540 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bosc.leave;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class BienvenidoActivity extends Activity {
private TextView nombre;
private Button btn_listo;
private TextView consecutivos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bienvenido);
nombre = (TextView)findViewById(R.id.textView2);
nombre.setText("Hola " + RegistroDatosActivity.nombre_obtenido+" preparate para");
btn_listo = (Button)findViewById(R.id.listo);
consecutivos = (TextView)findViewById(R.id.consecutivos);
btn_listo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(BienvenidoActivity.this,LeerCardActivity.class);
startActivity(i);
}
});
for (int i =0; i< ColorCodeActivity.colores.size();i++)
{
Log.e("Posicion "+"["+i+"]",""+ColorCodeActivity.colores.get(i));
}
}
}
| UTF-8 | Java | 1,369 | java | BienvenidoActivity.java | Java | [] | null | [] | package com.bosc.leave;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class BienvenidoActivity extends Activity {
private TextView nombre;
private Button btn_listo;
private TextView consecutivos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bienvenido);
nombre = (TextView)findViewById(R.id.textView2);
nombre.setText("Hola " + RegistroDatosActivity.nombre_obtenido+" preparate para");
btn_listo = (Button)findViewById(R.id.listo);
consecutivos = (TextView)findViewById(R.id.consecutivos);
btn_listo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(BienvenidoActivity.this,LeerCardActivity.class);
startActivity(i);
}
});
for (int i =0; i< ColorCodeActivity.colores.size();i++)
{
Log.e("Posicion "+"["+i+"]",""+ColorCodeActivity.colores.get(i));
}
}
}
| 1,369 | 0.672754 | 0.670562 | 48 | 27.520834 | 24.990824 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 4 |
25c1acb2aa396294ff5f01a8659959a068fbbb5f | 16,037,407,935,276 | d46a97779c6644d32f2cb2d94eecb6f5225c2158 | /src/main/java/com/basquiat/app/web3j/common/util/BlockMapper.java | a2a35e0a02961bcc01c46ae73050c25ebeb4cdc7 | [] | no_license | zoops/middle-web3j | https://github.com/zoops/middle-web3j | 1799b44e3ea9b16d63c331eb2b2ca10561cd947e | 09a751e76f949753fd8d7647987ec34c09f526a3 | refs/heads/master | 2023-03-15T19:53:38.933000 | 2018-04-24T01:09:16 | 2018-04-24T01:09:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.basquiat.app.web3j.common.util;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.ReportingPolicy;
import org.mapstruct.factory.Mappers;
import org.web3j.protocol.core.methods.response.EthBlock.Block;
import com.basquiat.app.web3j.service.block.vo.BlockVO;
/**
* It's BlockMapper using Map Struct
*
* create by basquiat 2018.04.19
*
*/
@Mapper(componentModel="spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface BlockMapper {
BlockMapper mapper = Mappers.getMapper(BlockMapper.class);
@Mappings({
@Mapping(source="number", target="number"),
@Mapping(source="hash", target="hash"),
@Mapping(source="parentHash", target="parentHash"),
@Mapping(source="nonce", target="nonce"),
@Mapping(source="sha3Uncles", target="sha3Uncles"),
@Mapping(source="logsBloom", target="logsBloom"),
@Mapping(source="transactionsRoot", target="transactionsRoot"),
@Mapping(source="stateRoot", target="stateRoot"),
@Mapping(source="receiptsRoot", target="receiptsRoot"),
@Mapping(source="author", target="author"),
@Mapping(source="miner", target="miner"),
@Mapping(source="mixHash", target="mixHash"),
@Mapping(source="difficulty", target="difficulty"),
@Mapping(source="totalDifficulty", target="totalDifficulty"),
@Mapping(source="extraData", target="extraData"),
@Mapping(source="size", target="size"),
@Mapping(source="gasLimit", target="gasLimit"),
@Mapping(source="gasUsed", target="gasUsed"),
@Mapping(source="timestamp", target="timestamp")
})
BlockVO mappingFrom(Block block);
}
| UTF-8 | Java | 1,760 | java | BlockMapper.java | Java | [
{
"context": "'s BlockMapper using Map Struct\r\n * \r\n * create by basquiat 2018.04.19\r\n *\r\n */\r\n@Mapper(componentModel=\"spri",
"end": 413,
"score": 0.9996687769889832,
"start": 405,
"tag": "USERNAME",
"value": "basquiat"
}
] | null | [] | package com.basquiat.app.web3j.common.util;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.ReportingPolicy;
import org.mapstruct.factory.Mappers;
import org.web3j.protocol.core.methods.response.EthBlock.Block;
import com.basquiat.app.web3j.service.block.vo.BlockVO;
/**
* It's BlockMapper using Map Struct
*
* create by basquiat 2018.04.19
*
*/
@Mapper(componentModel="spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface BlockMapper {
BlockMapper mapper = Mappers.getMapper(BlockMapper.class);
@Mappings({
@Mapping(source="number", target="number"),
@Mapping(source="hash", target="hash"),
@Mapping(source="parentHash", target="parentHash"),
@Mapping(source="nonce", target="nonce"),
@Mapping(source="sha3Uncles", target="sha3Uncles"),
@Mapping(source="logsBloom", target="logsBloom"),
@Mapping(source="transactionsRoot", target="transactionsRoot"),
@Mapping(source="stateRoot", target="stateRoot"),
@Mapping(source="receiptsRoot", target="receiptsRoot"),
@Mapping(source="author", target="author"),
@Mapping(source="miner", target="miner"),
@Mapping(source="mixHash", target="mixHash"),
@Mapping(source="difficulty", target="difficulty"),
@Mapping(source="totalDifficulty", target="totalDifficulty"),
@Mapping(source="extraData", target="extraData"),
@Mapping(source="size", target="size"),
@Mapping(source="gasLimit", target="gasLimit"),
@Mapping(source="gasUsed", target="gasUsed"),
@Mapping(source="timestamp", target="timestamp")
})
BlockVO mappingFrom(Block block);
}
| 1,760 | 0.675568 | 0.668182 | 46 | 36.260868 | 23.771955 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.565217 | false | false | 4 |
2ab746a7041d481bcc93ffd0892cff9446cf3ec2 | 17,600,776,037,312 | 244ae1ad4dccae1b15620fa66320c38733d8a6b5 | /DOM Tree/Tree.java | 02e7bd7feb4d6175d76093ccc6933ea864989e18 | [] | no_license | Endand/Data-Structures | https://github.com/Endand/Data-Structures | 7235c95622ee97f4e1b02d0bb00057510cb075d8 | fcfa357544099dfcdfffbc4ef59946b7eb982ba5 | refs/heads/master | 2020-12-29T12:25:40.593000 | 2020-02-07T20:07:32 | 2020-02-07T20:07:32 | 238,606,728 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package structures;
import java.util.*;
/**
* This class implements an HTML DOM Tree. Each node of the tree is a TagNode, with fields for
* tag/text, first child and sibling.
*
*/
public class Tree {
/**
* Root node
*/
TagNode root=null;
/**
* Scanner used to read input HTML file when building the tree
*/
Scanner sc;
/**
* Initializes this tree object with scanner for input HTML file
*
* @param sc Scanner for input HTML file
*/
public Tree(Scanner sc) {
this.sc = sc;
root = null;
}
/**
* Builds the DOM tree from input HTML file, through scanner passed
* in to the constructor and stored in the sc field of this object.
*
* The root of the tree that is built is referenced by the root field of this object.
*/
public void build() {
Stack<TagNode> tagstack = new Stack<TagNode>();
String html= sc.nextLine();
root=new TagNode(html.substring(1,html.length()-1), null, null);
tagstack.push(root); //to have an item in the stack to peek
boolean startTag=false;
while(sc.hasNextLine()) {
startTag=false;
String next= sc.nextLine();
if(next.charAt(0)=='<') {
if(next.charAt(1)=='/') {
tagstack.pop();
continue;
}
else {
next=next.substring(1, next.length()-1); //get brackets off
startTag=true;
}
} // if it's a tag
TagNode element= new TagNode(next, null, null);
if(tagstack.peek().firstChild==null) {
tagstack.peek().firstChild = element;
}
else { //if there is firstChild
TagNode fcCopy = tagstack.peek().firstChild;
while(fcCopy.sibling != null) {
fcCopy = fcCopy.sibling;
}
fcCopy.sibling = element;
}
if(startTag) {
tagstack.push(element);
}
}
}
/**
* Replaces all occurrences of an old tag in the DOM tree with a new tag
*
* @param oldTag Old tag
* @param newTag Replacement tag
*/
public void replaceTag(String oldTag, String newTag) {
if(oldTag!=null || newTag!=null) {
replacetag (oldTag, newTag, root);}
else return;
}
private void replacetag(String oldTag, String newTag, TagNode root){
if(root==null) {
return;
}
if(root.tag.equals(oldTag)) {
root.tag=newTag;
}
replacetag( oldTag, newTag, root.firstChild);
replacetag( oldTag, newTag, root.sibling);
return;
}
/**
* Boldfaces every column of the given row of the table in the DOM tree. The boldface (b)
* tag appears directly under the td tag of every column of this row.
*
* @param row Row to bold, first row is numbered 1 (not 0).
*/
public void boldRow(int row) {
boldRow(root, row);
}
private void boldRow(TagNode root, int row){
if(row<1) {return;}
if(root == null)
return;
if(root.tag.equals("table")){
TagNode fc= root.firstChild;
for(int i=1;i!=row;i++) {
fc = fc.sibling;
}
TagNode fam;
TagNode bold;
for(fam = fc.firstChild; fam != null; fam = fam.sibling){
bold = new TagNode("b",fam.firstChild,null);
fam.firstChild = bold;
}
}
boldRow(root.sibling, row);
boldRow(root.firstChild, row);
}
/**
* Remove all occurrences of a tag from the DOM tree. If the tag is p, em, or b, all occurrences of the tag
* are removed. If the tag is ol or ul, then All occurrences of such a tag are removed from the tree, and,
* in addition, all the li tags immediately under the removed tag are converted to p tags.
*
* @param tag Tag to be removed, can be p, em, b, ol, or ul
*/
public void removeTag(String tag) {
if(tag.equals("p")||tag.equals("em")||tag.equals("b")) {
removepemb(root,tag);
}
if(tag.equals("ol")||tag.equals("ul")) {
removeList(root, tag);
}
}
private void removepemb(TagNode root, String tag) {
if(root==null) {
return;
}
if(root.tag.equals(tag)) {
TagNode temp= root.sibling; //save sibling
root.tag=root.firstChild.tag; //transfer data
root.sibling= root.firstChild.sibling; //change pointer
root.firstChild=root.firstChild.firstChild;
TagNode ptr= root.sibling;
if(ptr!=null) {
while(ptr.sibling!=null) {
ptr=ptr.sibling;
}
ptr.sibling=temp;
}
else {
root.sibling=temp;
}
}
removepemb(root.firstChild, tag);
removepemb(root.sibling, tag);
}
private void removeList(TagNode root, String tag) {
if(root==null) {
return;
}
if(root.tag.equals(tag)&&root.firstChild != null) {
TagNode temp= root.sibling; //save sibling
TagNode liPtr = null;
for(liPtr = root.firstChild; liPtr!= null; liPtr = liPtr.sibling){ //change all li to p
liPtr.tag = "p";
}
root.tag=root.firstChild.tag; //transfer data
root.sibling= root.firstChild.sibling; //change pointer
root.firstChild=root.firstChild.firstChild;
TagNode ptr= root.sibling;
if(ptr!=null) {
while(ptr.sibling!=null) {
ptr=ptr.sibling;
}
ptr.sibling=temp;
}
else {
root.sibling=temp;
}
}
removeList(root.firstChild, tag);
removeList(root.sibling, tag);
}
/**
* Adds a tag around all occurrences of a word in the DOM tree.
*
* @param word Word around which tag is to be added
* @param tag Tag to be added
*/
public void addTag(String word, String tag) {
if(tag.equals("em") || tag.equals("b")) {
addTag( root, word.toLowerCase(), tag);}
}
private void addTag(TagNode root, String word, String tag) {
if(root == null){
return;
}
addTag(root.firstChild, word, tag);
addTag(root.sibling, word, tag);
boolean isTarget=false;
if(root.firstChild == null){ //if it's a text node
if(root.tag.toLowerCase().contains(word)) {
String before="";
String after="";
StringTokenizer str = new StringTokenizer(root.tag, " ", true);
while(str.hasMoreTokens()) {
isTarget=false;
String token= str.nextToken();
if(!str.hasMoreTokens()) {//if it's last token
if(token.toLowerCase().contains(word.toLowerCase())){
if(token.toLowerCase().charAt(0)==word.toLowerCase().charAt(0)) {//if first char matches to ensure it starts with word
String temp= token.toLowerCase().replace(word.toLowerCase(), "");
if(temp.equals("!") ||temp.equals("?")||temp.equals(".")||temp.equals(":")||temp.equals(";")||temp.equals("")) {
isTarget=true;
}
}
}
}
if(token.equalsIgnoreCase(word)) {isTarget=true;}
if(!isTarget) {
before+=token;
}
if(isTarget) { //time to add the tag
root.tag=before;
while(str.hasMoreTokens()) {
after+=str.nextToken();
}
TagNode tokenNode = new TagNode(token, null, null); //node of the token(target) to be put as the firstChild of TagNode adding
TagNode afterNode= new TagNode(after, null,null); //
if(after.equals("")) {
afterNode=null;
}
TagNode adding= new TagNode(tag, tokenNode, null);
if(root.tag.equals("")||root.tag.equals(" ")) {
root.tag=tag;
root.firstChild=tokenNode;
root.sibling=afterNode;
}
else {
root.sibling=adding;
adding.sibling=afterNode;
}
addTag(afterNode, word, tag);
}
}//while
}
}
}
/**
* Gets the HTML represented by this DOM tree. The returned string includes
* new lines, so that when it is printed, it will be identical to the
* input file from which the DOM tree was built.
*
* @return HTML string, including new lines.
*/
public String getHTML() {
StringBuilder sb = new StringBuilder();
getHTML(root, sb);
return sb.toString();
}
private void getHTML(TagNode root, StringBuilder sb) {
for (TagNode ptr=root; ptr != null;ptr=ptr.sibling) {
if (ptr.firstChild == null) {
sb.append(ptr.tag);
sb.append("\n");
} else {
sb.append("<");
sb.append(ptr.tag);
sb.append(">\n");
getHTML(ptr.firstChild, sb);
sb.append("</");
sb.append(ptr.tag);
sb.append(">\n");
}
}
}
/**
* Prints the DOM tree.
*
*/
public void print() {
print(root, 1);
}
private void print(TagNode root, int level) {
for (TagNode ptr=root; ptr != null;ptr=ptr.sibling) {
for (int i=0; i < level-1; i++) {
System.out.print(" ");
};
if (root != this.root) {
System.out.print("|----");
} else {
System.out.print(" ");
}
System.out.println(ptr.tag);
if (ptr.firstChild != null) {
print(ptr.firstChild, level+1);
}
}
}
} | UTF-8 | Java | 8,703 | java | Tree.java | Java | [] | null | [] | package structures;
import java.util.*;
/**
* This class implements an HTML DOM Tree. Each node of the tree is a TagNode, with fields for
* tag/text, first child and sibling.
*
*/
public class Tree {
/**
* Root node
*/
TagNode root=null;
/**
* Scanner used to read input HTML file when building the tree
*/
Scanner sc;
/**
* Initializes this tree object with scanner for input HTML file
*
* @param sc Scanner for input HTML file
*/
public Tree(Scanner sc) {
this.sc = sc;
root = null;
}
/**
* Builds the DOM tree from input HTML file, through scanner passed
* in to the constructor and stored in the sc field of this object.
*
* The root of the tree that is built is referenced by the root field of this object.
*/
public void build() {
Stack<TagNode> tagstack = new Stack<TagNode>();
String html= sc.nextLine();
root=new TagNode(html.substring(1,html.length()-1), null, null);
tagstack.push(root); //to have an item in the stack to peek
boolean startTag=false;
while(sc.hasNextLine()) {
startTag=false;
String next= sc.nextLine();
if(next.charAt(0)=='<') {
if(next.charAt(1)=='/') {
tagstack.pop();
continue;
}
else {
next=next.substring(1, next.length()-1); //get brackets off
startTag=true;
}
} // if it's a tag
TagNode element= new TagNode(next, null, null);
if(tagstack.peek().firstChild==null) {
tagstack.peek().firstChild = element;
}
else { //if there is firstChild
TagNode fcCopy = tagstack.peek().firstChild;
while(fcCopy.sibling != null) {
fcCopy = fcCopy.sibling;
}
fcCopy.sibling = element;
}
if(startTag) {
tagstack.push(element);
}
}
}
/**
* Replaces all occurrences of an old tag in the DOM tree with a new tag
*
* @param oldTag Old tag
* @param newTag Replacement tag
*/
public void replaceTag(String oldTag, String newTag) {
if(oldTag!=null || newTag!=null) {
replacetag (oldTag, newTag, root);}
else return;
}
private void replacetag(String oldTag, String newTag, TagNode root){
if(root==null) {
return;
}
if(root.tag.equals(oldTag)) {
root.tag=newTag;
}
replacetag( oldTag, newTag, root.firstChild);
replacetag( oldTag, newTag, root.sibling);
return;
}
/**
* Boldfaces every column of the given row of the table in the DOM tree. The boldface (b)
* tag appears directly under the td tag of every column of this row.
*
* @param row Row to bold, first row is numbered 1 (not 0).
*/
public void boldRow(int row) {
boldRow(root, row);
}
private void boldRow(TagNode root, int row){
if(row<1) {return;}
if(root == null)
return;
if(root.tag.equals("table")){
TagNode fc= root.firstChild;
for(int i=1;i!=row;i++) {
fc = fc.sibling;
}
TagNode fam;
TagNode bold;
for(fam = fc.firstChild; fam != null; fam = fam.sibling){
bold = new TagNode("b",fam.firstChild,null);
fam.firstChild = bold;
}
}
boldRow(root.sibling, row);
boldRow(root.firstChild, row);
}
/**
* Remove all occurrences of a tag from the DOM tree. If the tag is p, em, or b, all occurrences of the tag
* are removed. If the tag is ol or ul, then All occurrences of such a tag are removed from the tree, and,
* in addition, all the li tags immediately under the removed tag are converted to p tags.
*
* @param tag Tag to be removed, can be p, em, b, ol, or ul
*/
public void removeTag(String tag) {
if(tag.equals("p")||tag.equals("em")||tag.equals("b")) {
removepemb(root,tag);
}
if(tag.equals("ol")||tag.equals("ul")) {
removeList(root, tag);
}
}
private void removepemb(TagNode root, String tag) {
if(root==null) {
return;
}
if(root.tag.equals(tag)) {
TagNode temp= root.sibling; //save sibling
root.tag=root.firstChild.tag; //transfer data
root.sibling= root.firstChild.sibling; //change pointer
root.firstChild=root.firstChild.firstChild;
TagNode ptr= root.sibling;
if(ptr!=null) {
while(ptr.sibling!=null) {
ptr=ptr.sibling;
}
ptr.sibling=temp;
}
else {
root.sibling=temp;
}
}
removepemb(root.firstChild, tag);
removepemb(root.sibling, tag);
}
private void removeList(TagNode root, String tag) {
if(root==null) {
return;
}
if(root.tag.equals(tag)&&root.firstChild != null) {
TagNode temp= root.sibling; //save sibling
TagNode liPtr = null;
for(liPtr = root.firstChild; liPtr!= null; liPtr = liPtr.sibling){ //change all li to p
liPtr.tag = "p";
}
root.tag=root.firstChild.tag; //transfer data
root.sibling= root.firstChild.sibling; //change pointer
root.firstChild=root.firstChild.firstChild;
TagNode ptr= root.sibling;
if(ptr!=null) {
while(ptr.sibling!=null) {
ptr=ptr.sibling;
}
ptr.sibling=temp;
}
else {
root.sibling=temp;
}
}
removeList(root.firstChild, tag);
removeList(root.sibling, tag);
}
/**
* Adds a tag around all occurrences of a word in the DOM tree.
*
* @param word Word around which tag is to be added
* @param tag Tag to be added
*/
public void addTag(String word, String tag) {
if(tag.equals("em") || tag.equals("b")) {
addTag( root, word.toLowerCase(), tag);}
}
private void addTag(TagNode root, String word, String tag) {
if(root == null){
return;
}
addTag(root.firstChild, word, tag);
addTag(root.sibling, word, tag);
boolean isTarget=false;
if(root.firstChild == null){ //if it's a text node
if(root.tag.toLowerCase().contains(word)) {
String before="";
String after="";
StringTokenizer str = new StringTokenizer(root.tag, " ", true);
while(str.hasMoreTokens()) {
isTarget=false;
String token= str.nextToken();
if(!str.hasMoreTokens()) {//if it's last token
if(token.toLowerCase().contains(word.toLowerCase())){
if(token.toLowerCase().charAt(0)==word.toLowerCase().charAt(0)) {//if first char matches to ensure it starts with word
String temp= token.toLowerCase().replace(word.toLowerCase(), "");
if(temp.equals("!") ||temp.equals("?")||temp.equals(".")||temp.equals(":")||temp.equals(";")||temp.equals("")) {
isTarget=true;
}
}
}
}
if(token.equalsIgnoreCase(word)) {isTarget=true;}
if(!isTarget) {
before+=token;
}
if(isTarget) { //time to add the tag
root.tag=before;
while(str.hasMoreTokens()) {
after+=str.nextToken();
}
TagNode tokenNode = new TagNode(token, null, null); //node of the token(target) to be put as the firstChild of TagNode adding
TagNode afterNode= new TagNode(after, null,null); //
if(after.equals("")) {
afterNode=null;
}
TagNode adding= new TagNode(tag, tokenNode, null);
if(root.tag.equals("")||root.tag.equals(" ")) {
root.tag=tag;
root.firstChild=tokenNode;
root.sibling=afterNode;
}
else {
root.sibling=adding;
adding.sibling=afterNode;
}
addTag(afterNode, word, tag);
}
}//while
}
}
}
/**
* Gets the HTML represented by this DOM tree. The returned string includes
* new lines, so that when it is printed, it will be identical to the
* input file from which the DOM tree was built.
*
* @return HTML string, including new lines.
*/
public String getHTML() {
StringBuilder sb = new StringBuilder();
getHTML(root, sb);
return sb.toString();
}
private void getHTML(TagNode root, StringBuilder sb) {
for (TagNode ptr=root; ptr != null;ptr=ptr.sibling) {
if (ptr.firstChild == null) {
sb.append(ptr.tag);
sb.append("\n");
} else {
sb.append("<");
sb.append(ptr.tag);
sb.append(">\n");
getHTML(ptr.firstChild, sb);
sb.append("</");
sb.append(ptr.tag);
sb.append(">\n");
}
}
}
/**
* Prints the DOM tree.
*
*/
public void print() {
print(root, 1);
}
private void print(TagNode root, int level) {
for (TagNode ptr=root; ptr != null;ptr=ptr.sibling) {
for (int i=0; i < level-1; i++) {
System.out.print(" ");
};
if (root != this.root) {
System.out.print("|----");
} else {
System.out.print(" ");
}
System.out.println(ptr.tag);
if (ptr.firstChild != null) {
print(ptr.firstChild, level+1);
}
}
}
} | 8,703 | 0.597955 | 0.596116 | 323 | 24.950464 | 24.080566 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.817338 | false | false | 4 |
4c1121b06482df5866a8ab38ac9b1db93a369ef0 | 5,411,658,843,451 | 1894e54ed4d38c6afe08df96c096cbe0097a3cd5 | /E-Commerce_DAL/trunk/E-Commerce_DAL/src/main/java/com/ecommerce/dal/entity/Client.java | 69e0701d4813b144b5df532c301aa4282680c3a9 | [] | no_license | vsanth/eshtery-ecommerce-project | https://github.com/vsanth/eshtery-ecommerce-project | ffd97b8df2a0c65637bf78e0247c0b01fad957f7 | d9731206d5e2b72ac1872f0257e560bcc5983410 | refs/heads/master | 2018-01-11T23:22:23.753000 | 2013-11-26T07:05:38 | 2013-11-26T07:05:38 | 36,601,262 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ecommerce.dal.entity;
// Generated May 3, 2013 3:35:49 PM by Hibernate Tools 3.6.0
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
/**
* Client generated by hbm2java
*/
@Entity
@Table(name = "client", uniqueConstraints = @UniqueConstraint(columnNames = "MEMBERSHIP_CARD_ID"))
@PrimaryKeyJoinColumn(name="CLIENT_ID")
public class Client extends User implements java.io.Serializable {
private long clientId;
private MembershipCard membershipCard;
private Company company;
private Rank rank;
private User user;
private int state;
private boolean sponsor;
private boolean verified;
private Set<ClientHistory> clientHistories = new HashSet<ClientHistory>(0);
private Set<Item> items = new HashSet<Item>(0);
private Set<Category> categories = new HashSet<Category>(0);
public Client() {
}
public Client(Company company, Rank rank, User user, int state,
boolean sponsor, boolean verified) {
this.company = company;
this.rank = rank;
this.user = user;
this.state = state;
this.sponsor = sponsor;
this.verified = verified;
}
public Client(MembershipCard membershipCard, Company company, Rank rank,
User user, int state, boolean sponsor, boolean verified,
Set<ClientHistory> clientHistories, Set<Item> items,
Set<Category> categories) {
this.membershipCard = membershipCard;
this.company = company;
this.rank = rank;
this.user = user;
this.state = state;
this.sponsor = sponsor;
this.verified = verified;
this.clientHistories = clientHistories;
this.items = items;
this.categories = categories;
}
// @GenericGenerator(name = "generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "user"))
// @Id
// @GeneratedValue(generator = "generator")
// @Column(name = "CLIENT_ID", unique = true, nullable = false)
// public long getClientId() {
// return this.clientId;
// }
//
// public void setClientId(long clientId) {
// this.clientId = clientId;
// }
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "MEMBERSHIP_CARD_ID", unique = true)
public MembershipCard getMembershipCard() {
return this.membershipCard;
}
public void setMembershipCard(MembershipCard membershipCard) {
this.membershipCard = membershipCard;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "COMPANY_ID", nullable = false)
public Company getCompany() {
return this.company;
}
public void setCompany(Company company) {
this.company = company;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "RANK_RANK_ID", nullable = false)
public Rank getRank() {
return this.rank;
}
public void setRank(Rank rank) {
this.rank = rank;
}
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
@Column(name = "STATE", nullable = false)
public int getState() {
return this.state;
}
public void setState(int state) {
this.state = state;
}
@Column(name = "SPONSOR", nullable = false)
public boolean isSponsor() {
return this.sponsor;
}
public void setSponsor(boolean sponsor) {
this.sponsor = sponsor;
}
@Column(name = "VERIFIED", nullable = false)
public boolean isVerified() {
return this.verified;
}
public void setVerified(boolean verified) {
this.verified = verified;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "client")
public Set<ClientHistory> getClientHistories() {
return this.clientHistories;
}
public void setClientHistories(Set<ClientHistory> clientHistories) {
this.clientHistories = clientHistories;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "client")
public Set<Item> getItems() {
return this.items;
}
public void setItems(Set<Item> items) {
this.items = items;
}
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "client_category", joinColumns = { @JoinColumn(name = "CLIENT_ID", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "CATEGORY_ID", nullable = false, updatable = false) })
public Set<Category> getCategories() {
return this.categories;
}
public void setCategories(Set<Category> categories) {
this.categories = categories;
}
}
| UTF-8 | Java | 4,972 | java | Client.java | Java | [
{
"context": "any = company;\r\n\t\tthis.rank = rank;\r\n\t\tthis.user = user;\r\n\t\tthis.state = state;\r\n\t\tthis.sponsor = sponsor",
"end": 2060,
"score": 0.9398986101150513,
"start": 2056,
"tag": "USERNAME",
"value": "user"
}
] | null | [] | package com.ecommerce.dal.entity;
// Generated May 3, 2013 3:35:49 PM by Hibernate Tools 3.6.0
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
/**
* Client generated by hbm2java
*/
@Entity
@Table(name = "client", uniqueConstraints = @UniqueConstraint(columnNames = "MEMBERSHIP_CARD_ID"))
@PrimaryKeyJoinColumn(name="CLIENT_ID")
public class Client extends User implements java.io.Serializable {
private long clientId;
private MembershipCard membershipCard;
private Company company;
private Rank rank;
private User user;
private int state;
private boolean sponsor;
private boolean verified;
private Set<ClientHistory> clientHistories = new HashSet<ClientHistory>(0);
private Set<Item> items = new HashSet<Item>(0);
private Set<Category> categories = new HashSet<Category>(0);
public Client() {
}
public Client(Company company, Rank rank, User user, int state,
boolean sponsor, boolean verified) {
this.company = company;
this.rank = rank;
this.user = user;
this.state = state;
this.sponsor = sponsor;
this.verified = verified;
}
public Client(MembershipCard membershipCard, Company company, Rank rank,
User user, int state, boolean sponsor, boolean verified,
Set<ClientHistory> clientHistories, Set<Item> items,
Set<Category> categories) {
this.membershipCard = membershipCard;
this.company = company;
this.rank = rank;
this.user = user;
this.state = state;
this.sponsor = sponsor;
this.verified = verified;
this.clientHistories = clientHistories;
this.items = items;
this.categories = categories;
}
// @GenericGenerator(name = "generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "user"))
// @Id
// @GeneratedValue(generator = "generator")
// @Column(name = "CLIENT_ID", unique = true, nullable = false)
// public long getClientId() {
// return this.clientId;
// }
//
// public void setClientId(long clientId) {
// this.clientId = clientId;
// }
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "MEMBERSHIP_CARD_ID", unique = true)
public MembershipCard getMembershipCard() {
return this.membershipCard;
}
public void setMembershipCard(MembershipCard membershipCard) {
this.membershipCard = membershipCard;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "COMPANY_ID", nullable = false)
public Company getCompany() {
return this.company;
}
public void setCompany(Company company) {
this.company = company;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "RANK_RANK_ID", nullable = false)
public Rank getRank() {
return this.rank;
}
public void setRank(Rank rank) {
this.rank = rank;
}
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
@Column(name = "STATE", nullable = false)
public int getState() {
return this.state;
}
public void setState(int state) {
this.state = state;
}
@Column(name = "SPONSOR", nullable = false)
public boolean isSponsor() {
return this.sponsor;
}
public void setSponsor(boolean sponsor) {
this.sponsor = sponsor;
}
@Column(name = "VERIFIED", nullable = false)
public boolean isVerified() {
return this.verified;
}
public void setVerified(boolean verified) {
this.verified = verified;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "client")
public Set<ClientHistory> getClientHistories() {
return this.clientHistories;
}
public void setClientHistories(Set<ClientHistory> clientHistories) {
this.clientHistories = clientHistories;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "client")
public Set<Item> getItems() {
return this.items;
}
public void setItems(Set<Item> items) {
this.items = items;
}
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "client_category", joinColumns = { @JoinColumn(name = "CLIENT_ID", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "CATEGORY_ID", nullable = false, updatable = false) })
public Set<Category> getCategories() {
return this.categories;
}
public void setCategories(Set<Category> categories) {
this.categories = categories;
}
}
| 4,972 | 0.70897 | 0.705551 | 179 | 25.776537 | 25.944618 | 223 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.513966 | false | false | 4 |
c393505e60c7ee6c1ce1eacf9a8be179817c8340 | 25,056,839,231,989 | ff4ee1713d5dede68d4f9121219a803ab14c800b | /src/com/knowology/km/bll/AnalyzeDAO.java | 1c47084415288b80f07aa56d6313dd6b2d3f19f4 | [] | no_license | mjpln/QueryManage | https://github.com/mjpln/QueryManage | 187c028232ff7d80b955badf849086a63b120427 | 13abfac5f2ce08b3369a0b3f39471fd7521242f5 | refs/heads/master | 2020-09-20T03:04:30.071000 | 2019-11-18T02:11:04 | 2019-11-18T02:11:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.knowology.km.bll;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.jstl.sql.Result;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.knowology.Bean.User;
import com.knowology.bll.CommonLibKbDataDAO;
import com.knowology.bll.CommonLibMetafieldmappingDAO;
import com.knowology.bll.CommonLibQueryManageDAO;
import com.knowology.km.NLPCallerWS.NLPCaller4WSDelegate;
import com.knowology.km.entity.InsertOrUpdateParam;
import com.knowology.km.util.Check;
import com.knowology.km.util.GetLoadbalancingConfig;
import com.knowology.km.util.GetSession;
import com.knowology.km.util.MyUtil;
import com.knowology.km.util.ReadExcel;
import com.knowology.km.util.SimpleString;
import com.knowology.km.util.getServiceClient;
/**
* 语义训练业务
*
* @author cwy-pc
*
*/
public class AnalyzeDAO {
public static Logger logger = Logger.getLogger("querymanage");
public static Map<String, Set<String>> optionWordMap = new ConcurrentHashMap<>();
public static Map<String, List<String>> replaceWordMap = new ConcurrentHashMap<>();
/**
* @description 生成词模
* @param combition
* @param request
* @return
* @returnType Object
*/
public static Object produceWordpat(String combition, HttpServletRequest request) {
return produceWordpat(combition, "5", request);
}
/**
* @description 生成词模
* @param combition
* @param removeFlag
* 排除问题-是否严格排除标识
* @param request
* @return
* @returnType Object
*/
public static Object produceWordpat(String combition, String wordpattype, HttpServletRequest request) {
JSONObject jsonObj = new JSONObject();
Object sre = GetSession.getSessionByKey("accessUser");
User user = (User) sre;
String userid = user.getUserID();
// 获取行业
String servicetype = user.getIndustryOrganizationApplication();
String combitionArray[] = combition.split("@@");
List<List<String>> list = new ArrayList<List<String>>();// 待插入的词模数据
List<List<String>> text = new ArrayList<List<String>>();// 错误报告数据
int filterCount = 0;// 过滤的自学习词模数量
if (StringUtils.isEmpty(wordpattype)) {
wordpattype = "5";
}
// String wordpattype = "5";//词模类型
String autoWordpatRule = "默认方式";// 客户问自学习规则
// 读取自学习规则配置,商家默认配置
Result configValue = CommonLibMetafieldmappingDAO.getConfigValue("客户问自学习规则", servicetype);
if (configValue != null && configValue.getRowCount() > 0) {
autoWordpatRule = Objects.toString(configValue.getRows()[0].get("name"), "");
if ("分词学习".equals(autoWordpatRule)) {
wordpattype = "0";
}
}
// 可选词配置
Set<String> set = optionWordMap.get(servicetype);
if (CollectionUtils.isEmpty(set)) {
set = new HashSet<>();
Result optionWordRs = CommonLibMetafieldmappingDAO.getConfigValue("文法学习可选词类配置", servicetype);
if (optionWordRs != null && optionWordRs.getRowCount() > 0) {
for (int i = 0; i < optionWordRs.getRowCount(); i++) {
String optionWord = Objects.toString(optionWordRs.getRows()[i].get("name"), "");
set.add(optionWord);
}
}
optionWordMap.put(servicetype, set);
}
// 可选词配置
List<String> replaceList = replaceWordMap.get(servicetype);
if (CollectionUtils.isEmpty(replaceList)) {
replaceList = new ArrayList<>();
Result option = CommonLibMetafieldmappingDAO.getConfigValue("文法学习词类替换配置", servicetype);
if (option != null && option.getRowCount() > 0) {
for (int i = 0; i < option.getRowCount(); i++) {
String s = Objects.toString(option.getRows()[i].get("name"), "");
replaceList.add(s);
}
}
replaceWordMap.put(servicetype, replaceList);
}
// 获取摘要
List<String> kbIdList = new ArrayList<String>();
for (int i = 0; i < combitionArray.length; i++) {
String queryArray[] = combitionArray[i].split("@#@");
kbIdList.add(queryArray[2]);
}
// 生成客户问和对应的自学习词模 <客户问,词模>,一个客户问会包含两个词模,普通词模,精准词模,中间##分隔
Map<String, String> wordpatMap = getAutoWordpatMap(kbIdList, wordpattype);
List<String> oovWordList = new ArrayList<String>();
List<String> wordpatResultList = new ArrayList<String>();
//包含OOV词的扩展问
List<String> oovWordQueryList = new ArrayList<String>();
//包含OOV词的原分词
List<String> segmentWordList = new ArrayList<String>();
for (int i = 0; i < combitionArray.length; i++) {
String queryArray[] = combitionArray[i].split("@#@");
String queryCityCode = queryArray[0];
String query = queryArray[1];
String kbdataid = queryArray[2];
String queryid = queryArray[3];
// 排除问题的严格排除状态
String isstrictexclusion = "";
if (queryArray.length > 4) {
isstrictexclusion = queryArray[4];
}
List<String> wordpatList = new ArrayList<String>();
String wordpat = null;
// 调用高析接口生成词模
if ("0".equals(wordpattype) || "2".equals(wordpattype)) {
JSONObject jsonObject = getWordpat2(servicetype, query, queryCityCode);
if (jsonObject.getBooleanValue("success")) {
// 将简单词模转化为普通词模,并返回转换结果
wordpat = SimpleString.SimpleWordPatToWordPat(jsonObject.getString("wordpat"));
wordpatList.add(wordpat);
wordpat = SimpleString.SimpleWordPatToWordPat(jsonObject.getString("lockWordpat"));
wordpatList.add(wordpat);
JSONArray oovWord = jsonObject.getJSONArray("OOVWord");
JSONArray segmentWord = jsonObject.getJSONArray("segmentWord");
if (!CollectionUtils.isEmpty(oovWord)) {
oovWordList.add(StringUtils.join(oovWord, "$_$"));// 放入OOV分词
oovWordQueryList.add(combitionArray[i]);
segmentWordList.add(StringUtils.join(segmentWord,"##"));
}
}
} else {
// 调用自学习生成词模的接口生成词模,可能是多个,以@_@分隔
wordpat = callKAnalyze(servicetype, query, queryCityCode);
wordpatList.add(wordpat);
}
for (int j = 0; j < wordpatList.size(); j++) {
wordpat = wordpatList.get(j);
// 替换词模
for (String rep : replaceList) {
if (rep.contains("=>")) {
String[] split = rep.split("=>");
wordpat.replaceAll(split[0], split[1]);
}
}
List<String> rows = new ArrayList<String>();// 生成词模失败报告
// logger.info("问题库自学习词模:" + wordpat);
if (wordpat != null && !"".equals(wordpat)) {
// 判断词模是否含有@_@
if (wordpat.contains("@_@")) {
// 有的话,按照@_@进行拆分,并只取第一个
wordpat = wordpat.split("@_@")[0];
}
// 获取词模中@前面的词模题,在加上@2#编者="问题库"&来源="(当前问题)"
// wordpat = wordpat.split("@")[0] + "@2#编者=\"问题库\"&来源=\""
// + query.replace("&", "\\and") + "\"";
// 保留自学习词模返回值,并替换 编者=\"自学习\""=>编者="问题库"&来源="(当前问题)" --->
// modify 2017-05-24
wordpat = wordpat.replace("编者=\"自学习\"", "编者=\"问题库\"&来源=\"" + query.replace("&", "\\and") + "\"");
// 校验自动生成的词模是否符合规范
if (Check.CheckWordpat(wordpat, request)) {
// 获取客户问对应的旧词模
String oldWordpat = wordpatMap.get(query);
// 存在旧词模
if (oldWordpat != null && !"".equals(oldWordpat)) {
String newWordpat = wordpat.split("@2#")[0];
logger.info("新旧词模比较 ----新词模:\"" + newWordpat + "\",旧词模:\"" + oldWordpat + "\",针对问题:\""
+ query + "\"");
// 新旧词模不相同,执行插入
if (!oldWordpat.equals(newWordpat)) {
List<String> tempList = new ArrayList<String>();
tempList.add(wordpat);
tempList.add(queryCityCode);
tempList.add(query);
tempList.add(kbdataid);
tempList.add(queryid);
list.add(tempList);
wordpatResultList.add(wordpat);
} else {// 新旧词模相同,不进行插入操作
filterCount++;// 记录过滤的词模数量
}
} else {// 不存在旧词模
List<String> tempList = new ArrayList<String>();
tempList.add(wordpat);
tempList.add(queryCityCode);
tempList.add(query);
tempList.add(kbdataid);
tempList.add(queryid);
list.add(tempList);
wordpatResultList.add(wordpat);
}
} else {
rows.add(query);
rows.add("生成词模【" + wordpat + "】格式不符合!");
text.add(rows);
}
} else {
rows.add(query);
rows.add("生成失败!");
text.add(rows);
}
}
}
logger.info("批量训练----客户问个数:" + combitionArray.length + ",插入词模个数:" + list.size() + ",过滤词模的个数:" + filterCount);
// 插入问题库自动学习词模
int count = -1;
if (list.size() > 0) {
count = CommonLibQueryManageDAO.insertWordpat(list, servicetype, userid, wordpattype);
if (count > 0) {
jsonObj.put("success", true);
jsonObj.put("msg", "生成成功!");
jsonObj.put("wordpatList", StringUtils.join(wordpatResultList, "@_@"));
jsonObj.put("OOVWord", StringUtils.join(oovWordList, "$_$"));
jsonObj.put("segmentWord", StringUtils.join(segmentWordList,"@@"));
jsonObj.put("OOVWordQuery", StringUtils.join(oovWordQueryList, "@@"));
} else {
jsonObj.put("success", false);
jsonObj.put("msg", "生成失败!");
}
} else if (combitionArray.length >= list.size() + filterCount && list.size() + filterCount > 0) {// 有成功处理的词模就算生成成功
jsonObj.put("success", true);
jsonObj.put("msg", "生成成功!");
jsonObj.put("wordpatList", StringUtils.join(wordpatResultList, "@_@"));
jsonObj.put("OOVWord", StringUtils.join(oovWordList, "$_$"));
jsonObj.put("segmentWord", StringUtils.join(segmentWordList,"@@"));
jsonObj.put("OOVWordQuery", StringUtils.join(oovWordQueryList, "@@"));
} else {
jsonObj.put("success", false);
jsonObj.put("msg", "生成失败!!");
}
if (text.size() > 0 && "分词学习".equals(autoWordpatRule)) {
// 错误报告
String filename = "produceWordpat_";
filename += DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
List<String> colTitle = new ArrayList<String>();
colTitle.add("客户问");
colTitle.add("生成结果");
boolean isWritten = ReadExcel.writeExcel(QuerymanageDAO.FILE_PATH_EXPORT, filename, null, null, colTitle,
text);
if (isWritten) {
// file = new File(FILE_PATH_EXPORT + filename + ".xls");
jsonObj.put("fileName", filename + ".xls");
}
}
return jsonObj;
}
/**
* @description 全量生成词模
* @param serviceid
* @param request
* @return
* @returnType Object
*/
public static Object produceAllWordpat(String serviceid, HttpServletRequest request) {
List<String> combitionArray = getAllQuery(serviceid, 0);
return produceWordpat(StringUtils.join(combitionArray, "@@"), request);
}
/**
* @description 全量生成词模
* @param serviceid
* @param request
* @return
* @returnType Object
*/
public static Object produceAllWordpat(String serviceid, String wordpattype, HttpServletRequest request) {
List<String> combitionArray = getAllQuery(serviceid, 0);
List<String> RemoveCombitionArray = getAllQuery(serviceid, 1);
Object obj = removeProduceWordpat(StringUtils.join(RemoveCombitionArray, "@@"), "2", request);
logger.info("标准问全量生成排除词模结果:" + JSONObject.toJSONString(obj));
return produceWordpat(StringUtils.join(combitionArray, "@@"), wordpattype, request);
}
/**
* 调用高析接口生成自学习词模 <br>
* 如果没有有效的词模,则返回空
*
* @param servicetype
* 行业商家
* @param query
* 问题
* @param queryCityCode
* 问题地市
* @return success : 生成结果 如果生成成功,结果中wordpat为词模<br>
* 如果生成失败,结果中detailAnalyzeResult和wordpatResult分别存高析结果和生成词模结果
*/
public static JSONObject getWordpat(String servicetype, String query, String queryCityCode, String autor) {
JSONObject result = new JSONObject();
result.put("success", false);
// 调用高析接口
JSONObject jsonObject = callDetailAnalyze(servicetype, query, queryCityCode, autor);
// 解析高析接口结果,生成词模
List<JSONObject> list = null;
if (jsonObject.containsKey("detailAnalyze")) {
list = detailAnalyze2Wordpat(jsonObject.getString("detailAnalyze"), autor);
} else {
result.put("detailAnalyzeResult", jsonObject);
}
// 判断是否有有效词模
if (list != null && list.size() > 0) {
result.put("success", true);
result.put("wordpatResult", list);
}
logger.info("分词结果:" + result);
return result;
}
/**
* 采用文法训练策略 <br>
* 如果没有有效的词模,则返回空
*
* @param servicetype
* 行业商家
* @param query
* 问题
* @param queryCityCode
* 问题地市
* @return success : 生成结果 如果生成成功,结果中wordpat为词模和lockWordpat为语义锁定词模<br>
* 如果生成失败,结果中detailAnalyzeResult和wordpatResult分别存高析结果和生成词模结果
*/
public static JSONObject getWordpat2(String servicetype, String query, String queryCityCode) {
JSONObject result = new JSONObject();
result.put("success", false);
// 调用高析接口
JSONObject jsonObject = callDetailAnalyze(servicetype, query, queryCityCode, "自学习");
// 解析高析接口结果,生成词模
List<JSONObject> list = null;
if (jsonObject.containsKey("detailAnalyze")) {
list = detailAnalyze4Wordpat(jsonObject.getString("detailAnalyze"), "自学习", optionWordMap.get(servicetype));
} else {
result.put("detailAnalyzeResult", jsonObject);
}
// 取第一个词模
if (list != null && list.size() > 0) {
JSONObject object = list.get(0);
result.put("success", true);
result.put("wordpat", object.getString("wordpat"));
result.put("lockWordpat", object.getString("lockWordpat"));
result.put("OOVWord", object.getJSONArray("OOVWord"));
result.put("segmentWord", object.getJSONArray("segmentWord"));
return result;
}
return result;
}
/**
* 生成自学习词模
*
* @param 参数调用接口的入参
* @return 词模
*/
public static String callKAnalyze(String servicetype, String query, String queryCityCode) {
// 获取负载均衡url
String url = getUrlLoadbalanceUrl(queryCityCode);
// 如果未配置对应省份的负载服务器,默认使用全国
if (StringUtils.isEmpty(url)) {
queryCityCode = "全国";
url = getUrlLoadbalanceUrl(queryCityCode);
}
// 取省份信息
String provinceCode = "全国";
if (!"电渠".equals(queryCityCode) && !"集团".equals(queryCityCode)) {
queryCityCode = queryCityCode.replace(",", "|");
provinceCode = queryCityCode.split("\\|")[0];
provinceCode = provinceCode.substring(0, 2) + "0000";
}
// 获取高级分析的接口串中的serviceInfo
String serviceInfo = MyUtil.getServiceInfo(servicetype, "问题生成词模", "", false, queryCityCode);
// 获取高级分析的串
String queryObject = MyUtil.getDAnalyzeQueryObject("问题生成词模", query, servicetype, serviceInfo);
logger.info("自学习词模高级分析接口的输入串:" + queryObject);
// 获取高级分析的客户端
NLPCaller4WSDelegate NLPCaller4WSClient = getServiceClient.NLPCaller4WSClient(url);
// 判断接口是否连接是否为null
if (NLPCaller4WSClient == null) {
// 返回的词模为空
return "";
}
// 获取接口的返回json串
String result = NLPCaller4WSClient.kAnalyze(queryObject);
// add by zhao lipeng. 20170210 START
logger.info("问题库自学习词模调用接口返回:" + result);
// add by zhao lipeng. 20170210 END
// 替换掉回车符和空格
result = result.replace("\n", "").replace(" ", "").trim();
// 判断返回串是否为"接口请求参数不合规范!"、""、null
if ("接口请求参数不合规范!".equals(result) || "".equals(result) || result == null) {
// 返回的词模为空
return "";
} else {
try {
// 将接口的返回串用JSONObject转换为JSONObject对象
JSONObject obj = JSONObject.parseObject(result);
// 将json串中的key为autoLearnedPat的value返回
return obj.getString("autoLearnedPat");
} catch (Exception e) {
e.printStackTrace();
// 转换json格式时出现错误
return "";
}
}
}
/**
* 调用高析接口(使用地市负载)
*
* @param servicetype
* 行业
*
* @param query
* 问法
* @param queryCityCode
* 地市编码,
* @param userId
* @return
*/
public static JSONObject callDetailAnalyze(String servicetype, String query, String queryCityCode, String userId) {
// 定义返回的json串
JSONObject jsonObj = new JSONObject();
// 判断servicetype为空串、空、null
if (" ".equals(servicetype) || "".equals(servicetype) || servicetype == null) {
// 将登录信息失效放入jsonObj的msg对象中
jsonObj.put("result", "登录信息已失效,请注销后重新登录!");
return jsonObj;
}
if (StringUtils.isEmpty(query)) {
// 将登录信息失效放入jsonObj的msg对象中
jsonObj.put("result", "咨询不能为空!");
return jsonObj;
}
// 默认使用全国地市
if (StringUtils.isEmpty(queryCityCode)) {
queryCityCode = "全国";
}
// 获取负载均衡url
String url = getUrlLoadbalanceUrl(queryCityCode);
// 如果未配置对应省份的负载服务器,默认使用全国
if (StringUtils.isEmpty(url)) {
queryCityCode = "全国";
url = getUrlLoadbalanceUrl(queryCityCode);
}
// 取省份信息
String provinceCode = "";
if ("电渠".equals(queryCityCode) || "集团".equals(queryCityCode) || "全国".equals(queryCityCode)) {
provinceCode = queryCityCode;
} else {
queryCityCode = queryCityCode.replace(",", "|");
provinceCode = queryCityCode.split("\\|")[0];
provinceCode = provinceCode.substring(0, 2) + "0000";
}
// 获取高级分析的接口串中的serviceInfo
String serviceInfo = MyUtil.getServiceInfo(servicetype, "高级分析", "", false, provinceCode, "否");
// 获取高级分析接口的入参字符串
String queryObject = MyUtil.getDAnalyzeQueryObject(userId, query, servicetype, serviceInfo);
logger.info("生成词模高级分析【" + GetLoadbalancingConfig.cityCodeToCityName.get(provinceCode) + "】接口地址:" + url);
logger.info("生成词模高级分析接口的输入串:" + queryObject);
// url = "http://180.153.51.235:8082/NLPWebService/NLPCallerWS?wsdl";
// 获取高级分析的客户端
NLPCaller4WSDelegate NLPCaller4WSClient = getServiceClient.NLPCaller4WSClient(url);
// 判断客户端是否为null
if (NLPCaller4WSClient == null) {
// 将无放入jsonObj的result对象中
// jsonObj.put("result", "无");
jsonObj.put("result",
"ERROR:生成词模高级分析【" + GetLoadbalancingConfig.cityCodeToCityName.get(provinceCode) + "】接口异常。");
return jsonObj;
}
String result = "";
try {
// 调用接口的方法获取词模
// result = NLPCaller4WSClient.kAnalyze(queryObject);
result = NLPCaller4WSClient.detailAnalyze(queryObject);
logger.info("生成词模高级分析接口的输出串:" + result);
// 替换掉返回串中的回车符
result = result.replace("\n", "");
} catch (Exception e) {
e.printStackTrace();
// 将无放入jsonObj的result对象中
jsonObj.put("result",
"ERROR:生成词模高级分析【" + GetLoadbalancingConfig.cityCodeToCityName.get(provinceCode) + "】接口调用失败。");
return jsonObj;
}
// 判断返回串是否为"接口请求参数不合规范!"、""、null
if ("接口请求参数不合规范!".equals(result) || "".equals(result) || result == null) {
// 将无放入jsonObj的result对象中
jsonObj.put("result", "无");
return jsonObj;
}
jsonObj.put("detailAnalyze", result);
return jsonObj;
}
/**
* 解析高级分析接口分词结果,生成词模
*
* @param result
* 高析接口返回结果
* @param autor
* 词模编者,例【编者=\"自学习\"】
* @return 词模集合,属性如下:<br>
* wordpat:简单词模<br>
* newWordpat:去除近类的词模,用于页面展示<br>
* isValid:词模是否有效<br>
* OOVWord:词模中OOV的分词集合
*/
public static List<JSONObject> detailAnalyze2Wordpat(String result, String autor) {
String rs = "";
// 定义返回的json串
List<JSONObject> resultList = new ArrayList<JSONObject>();
Map<String, String> map = new HashMap<String, String>();
try {
// 将接口返回的json串,反序列化为json数组
JSONArray jsonArray = JSONArray.parseArray(result);
// 循环遍历jsonArray数组
for (int i = 0; i < jsonArray.size(); i++) {
// 将jsonArray数组中的第i个转换成json对象
JSONObject obj = JSONObject.parseObject(jsonArray.get(i).toString());
// 得到多个分词的json串
// 定义分词的json数组
JSONArray allSegments = new JSONArray();
// 将obj对象中key为AllSegments的value变成json数组
JSONArray allSegmentsArray = obj.getJSONArray("allSegments");
// 遍历循环arrayAllSegments数组
for (int j = 0; j < allSegmentsArray.size(); j++) {
// 获取arrayAllSegments数组中的每一个值
String segments = allSegmentsArray.getString(j);
// 判断分词是否含有..( 和 nlp版本信息
if (!segments.contains("...(") && !segments.startsWith("NLU-Version")) {
// 根据分词得到分词数
String wordnum = segments.split("\\) \\(")[1].replace(" words)", "");
// 得到分词的内容
String word = segments.split("\\) \\(")[0] + ")";
map.put(word, wordnum);
}
}
List<JSONObject> list = getAutoWordpat(map, autor);
resultList.addAll(list);
}
} catch (Exception e) {
e.printStackTrace();
}
return resultList;
}
/**
* 解析高级分析接口分词结果,生成自学习词模
*
* @param result
* 高析接口返回结果
* @param autor
* 词模编者,例【编者=\"自学习\"】
* @return 词模集合,属性如下:<br>
* wordpat:简单词模<br>
* newWordpat:去除近类的词模,用于页面展示<br>
* isValid:词模是否有效<br>
* OOVWord:词模中OOV的分词集合
*/
public static List<JSONObject> detailAnalyze4Wordpat(String result, String autor, Set<String> optionWord) {
String rs = "";
// 定义返回的json串
List<JSONObject> resultList = new ArrayList<JSONObject>();
Map<String, String> map = new HashMap<String, String>();
try {
// 将接口返回的json串,反序列化为json数组
JSONArray jsonArray = JSONArray.parseArray(result);
// 循环遍历jsonArray数组
for (int i = 0; i < jsonArray.size(); i++) {
// 将jsonArray数组中的第i个转换成json对象
JSONObject obj = JSONObject.parseObject(jsonArray.get(i).toString());
// 得到多个分词的json串
// 定义分词的json数组
JSONArray allSegments = new JSONArray();
// 将obj对象中key为AllSegments的value变成json数组
JSONArray allSegmentsArray = obj.getJSONArray("allSegments");
// 遍历循环arrayAllSegments数组
for (int j = 0; j < allSegmentsArray.size(); j++) {
// 获取arrayAllSegments数组中的每一个值
String segments = allSegmentsArray.getString(j);
// 判断分词是否含有..( 和 nlp版本信息
if (!segments.contains("...(") && !segments.startsWith("NLU-Version")) {
// 根据分词得到分词数
String wordnum = segments.split("\\) \\(")[1].replace(" words)", "");
// 得到分词的内容
String word = segments.split("\\) \\(")[0] + ")";
map.put(word, wordnum);
break;// 取第一组分词
}
}
if (optionWord == null) {
optionWord = Collections.emptySet();
}
List<JSONObject> list = getLearnWordpat(map, autor, optionWord);
resultList.addAll(list);
}
} catch (Exception e) {
e.printStackTrace();
}
return resultList;
}
/**
* @description 获得业务下所有问题
* @param serviceid
* @return
* @returnType List<String>
*/
public static List<String> getAllQuery(String serviceid, int querytype) {
List<String> list = new ArrayList<String>();
Result rs = CommonLibQueryManageDAO.getQuery(serviceid, querytype);
if (rs != null && rs.getRowCount() > 0) {
// 循环遍历数据源
for (int i = 0; i < rs.getRowCount(); i++) {
String query = rs.getRows()[i].get("query") != null ? rs.getRows()[i].get("query").toString() : "";
if ("".equals(query)) {
continue;
}
String city = rs.getRows()[i].get("city") != null ? rs.getRows()[i].get("city").toString() : "";
String kbdataid = rs.getRows()[i].get("kbdataid").toString();
String queryid = rs.getRows()[i].get("id").toString();
String isserviceword = rs.getRows()[i].get("isstrictexclusion") == null ? " "
: rs.getRows()[i].get("isstrictexclusion").toString();
String content = city + "@#@" + query + "@#@" + kbdataid + "@#@" + queryid + "@#@" + isserviceword;
list.add(content);
}
}
return list;
}
/**
*
* @param map
* @return
* @returnType String
* @dateTime 2017-9-1下午03:24:06
*/
private static List<JSONObject> getAutoWordpat(Map<String, String> map, String autor) {
List<JSONObject> list = new ArrayList<JSONObject>();
for (Map.Entry<String, String> entry : map.entrySet()) {
JSONObject jsonObject = new JSONObject();
JSONArray array = new JSONArray();
String word = entry.getKey().replace(" ", "##");
String wordArray[] = word.split("##");
String wordpat = "";
int flag = 0;// 词模处理结果 0 可用 1 分词中没有近类和父类 2 分词中包含OOV
String _word = "";// 具体分词
for (int i = 0; i < wordArray.length; i++) {
String tempWord = wordArray[i];
_word = tempWord.split("\\(")[0];
if (!"".equals(tempWord) && !"".equals(_word.trim())) {// 分词本身不能为空
String dealWrod = dealWrod(tempWord);
if (dealWrod == null) {
flag = 1;
// 页面展示: word(OOV)
dealWrod = _word + "(OOV)";
// 记录当前词模中的OOV分词
array.add(_word);
}
String _tempWord = "<" + dealWrod + ">";
wordpat = wordpat + _tempWord + "*";
}
}
wordpat = wordpat.substring(0, wordpat.lastIndexOf("*")) + "@2#" + "编者=\"" + autor + "\"";
wordpat = SimpleString.worpattosimworpat(wordpat);
String newWordpat = wordpat.replace("近类", "");
jsonObject.put("wordpat", wordpat);
jsonObject.put("newWordpat", newWordpat);
jsonObject.put("isValid", flag == 0);
jsonObject.put("OOVWord", array);
list.add(jsonObject);
}
return list;
}
/**
*
* @param map
* @return
* @returnType String
* @dateTime 2017-9-1下午03:24:06
*/
private static List<JSONObject> getLearnWordpat(Map<String, String> map, String autor, Set<String> optionWord) {
List<JSONObject> list = new ArrayList<JSONObject>();
for (Map.Entry<String, String> entry : map.entrySet()) {
JSONObject jsonObject = new JSONObject();
JSONArray array = new JSONArray();
String word = entry.getKey().replace(" ", "##");
String wordArray[] = word.split("##");
StringBuilder wordpatBuilder = new StringBuilder("");
StringBuilder lockWordpat = new StringBuilder("");
int flag = 0;// 词模处理结果 0 可用 1 分词中没有近类和父类 2 分词中包含OOV
boolean lastFlag = false;// 上一个分词是否是OOV
int requiredNum = 0;// 必选词数量
String _word = "";// 具体分词
//具体分词
JSONArray arraySegment = new JSONArray();
for (int i = 0; i < wordArray.length; i++) {
String tempWord = wordArray[i];
_word = tempWord.split("\\(")[0];
String _tempWord = "";
String _lockWord = "";
if (!"".equals(tempWord) && StringUtils.isNotBlank(_word)) {// 分词本身不能为空
//增加分词
if(StringUtils.isNotBlank(_word.replaceAll("\\p{P}" , ""))){
arraySegment.add(_word);
}
List<String> dealWrod = dealWrod2List(tempWord);
if (dealWrod == null || dealWrod.isEmpty()) {
// 页面展示: word(OOV)
if (i > 0) {
wordpatBuilder.append('-');
lockWordpat.append('-');
}
wordpatBuilder.append(_word);
lockWordpat.append(_word);
// 记录当前词模中的OOV分词
// 过滤标点符号 --> update by 20191008 sundj
if(StringUtils.isNotBlank(_word.replaceAll("\\p{P}" , ""))){
array.add(_word);
}
lastFlag = true;
flag = 1;
requiredNum++;
} else {
for (String str : dealWrod) {
// 可选词
if (optionWord.contains(str.replaceFirst("!", ""))) {
_tempWord = "[" + StringUtils.join(dealWrod, "|") + "]";
break;
}
}
// 必选
if (StringUtils.isEmpty(_tempWord)) {
_tempWord = "<" + StringUtils.join(dealWrod, "|") + ">";
requiredNum++;
}
_lockWord = "<" + StringUtils.join(dealWrod, "|") + ">";
if (i > 0) {
if (lastFlag) {
wordpatBuilder.append('-');
lockWordpat.append('-');
} else {
wordpatBuilder.append('*');
lockWordpat.append('*');
}
}
wordpatBuilder.append(_tempWord);
lockWordpat.append(_lockWord);
lastFlag = false;
}
}
}
String wordpat = "";
//如果必选词数量大于2,则去掉最大未匹配字数 , author=sundj
wordpatBuilder.append("@2#").append("编者=\"").append(autor).append("\"");
if(requiredNum < 2){
wordpatBuilder.append("&最大未匹配字数=\"").append(requiredNum + 1).append("\"");
}
wordpat = wordpatBuilder.toString();
wordpat = SimpleString.worpattosimworpat(wordpat);
String lockWordpatStr = lockWordpat.append("@2#").append("编者=\"").append(autor).append("\"")
.append("&最大未匹配字数=\"").append(0).append("\"").append("&置信度=\"").append("1.1").append("\"")
.toString();
lockWordpatStr = SimpleString.worpattosimworpat(lockWordpatStr);
String newWordpat = wordpat.replace("近类", "");
jsonObject.put("wordpat", wordpat);
jsonObject.put("newWordpat", newWordpat);
jsonObject.put("lockWordpat", lockWordpatStr);
jsonObject.put("isValid", flag == 0);
jsonObject.put("OOVWord", array);
//增加返回分词
jsonObject.put("segmentWord", arraySegment);
list.add(jsonObject);
}
return list;
}
private static String dealWrod(String word) {
String _word = word.split("\\(")[0];
String tempWord = word.split("\\(")[1].split("\\)")[0];
String wordArray[] = tempWord.split("\\|");
String newWord = "";
if (tempWord.contains("近类") && tempWord.contains("父类")) {
for (int i = 0; i < wordArray.length; i++) {
String w = wordArray[i];
if (!w.endsWith("父类") && !w.equals("模板词") && !w.endsWith("词类")) {
newWord = newWord + w + "|";
}
}
} else {
for (int i = 0; i < wordArray.length; i++) {
String w = wordArray[i];
if (!w.equals("模板词") && !w.endsWith("词类")) {
newWord = newWord + w + "|";
}
}
}
if (tempWord.equals("OOV")) {// 如果分词中存在OOV直接过滤
return null;
}
if (newWord.contains("|")) {
newWord = newWord.substring(0, newWord.lastIndexOf("|"));
return newWord;
}
return null;
}
private static List<String> dealWrod2List(String word) {
List<String> rs = new ArrayList<String>();
String _word = word.split("\\(")[0];
String tempWord = word.split("\\(")[1].split("\\)")[0];
String wordArray[] = tempWord.split("\\|");
if (tempWord.contains("近类") && tempWord.contains("父类")) {
for (int i = 0; i < wordArray.length; i++) {
String w = wordArray[i];
if (!w.endsWith("父类") && !w.equals("模板词") && !w.endsWith("词类")) {
rs.add(w);
}
}
} else {
for (int i = 0; i < wordArray.length; i++) {
String w = wordArray[i];
if (!w.equals("模板词") && !w.endsWith("词类")) {
rs.add(w);
}
}
}
if (tempWord.equals("OOV")) {// 如果分词中存在OOV直接过滤
return null;
}
return rs;
}
/**
* 获取自学习词模及对应的客户问
*
* @param kbIdList
* @return
*/
private static Map<String, String> getAutoWordpatMap(List<String> kbIdList, String wordpattype) {
Result rs = CommonLibQueryManageDAO.selectWordpatByKbdataid(kbIdList, wordpattype);
Map<String, String> wordpatMap = new HashMap<String, String>();
if (rs != null && rs.getRowCount() > 0) {
for (int i = 0; i < rs.getRowCount(); i++) {
if (rs.getRows()[i].get("wordpat") != null) {
// 自学习词模:<翼支付|!翼支付近类>*<是什>*[<么|!没有近类>]@2#编者="问题库"&来源="翼支付是什么?"&最大未匹配字数="1"
String wordpat = rs.getRows()[i].get("wordpat").toString();
String[] split = wordpat.split("@2#");
if (split.length > 1) {
for (String str : split[1].split("&")) {
if (str.startsWith("来源=")) {// 自动生成的词模,返回值是来源
String query = str.substring(4, str.length() - 1);
wordpatMap.put(query, split[0]);
break;
}
}
}
}
}
}
return wordpatMap;
}
/**
* 获取自学习词模及对应的排除问
*
* @param kbIdList
* @return
*/
private static Map<String, String> getAutoWordpatMapByRemove(List<String> kbIdList, String wordpattype) {
Result rs = CommonLibQueryManageDAO.selectWordpatByKbdataid(kbIdList, wordpattype);
Map<String, String> wordpatMap = new HashMap<String, String>();
if (rs != null && rs.getRowCount() > 0) {
for (int i = 0; i < rs.getRowCount(); i++) {
if (rs.getRows()[i].get("wordpat") != null) {
// 自学习词模:<翼支付|!翼支付近类>*<是什>*[<么|!没有近类>]@2#编者="问题库"&来源="翼支付是什么?"&最大未匹配字数="1"
String wordpat = rs.getRows()[i].get("wordpat").toString();
String[] split = wordpat.split("@1#");
if (split.length > 1) {
for (String str : split[1].split("&")) {
if (str.startsWith("来源=")) {// 自动生成的词模,返回值是来源
String query = str.substring(4, str.length() - 1);
wordpatMap.put(query, split[0]);
break;
}
}
}
}
}
}
return wordpatMap;
}
/**
* 获取自学习词模及对应的客户问
*
* @param kbIdList
* @return
*/
private static Map<String, Set<String>> getAutoWordpatMap2Set(List<String> kbIdList, String wordpattype) {
Result rs = CommonLibQueryManageDAO.selectWordpatByKbdataid(kbIdList, wordpattype);
Map<String, Set<String>> wordpatMap = new HashMap<String, Set<String>>();
if (rs != null && rs.getRowCount() > 0) {
for (int i = 0; i < rs.getRowCount(); i++) {
if (rs.getRows()[i].get("wordpat") != null) {
// 自学习词模:<翼支付|!翼支付近类>*<是什>*[<么|!没有近类>]@2#编者="问题库"&来源="翼支付是什么?"&最大未匹配字数="1"
String wordpat = rs.getRows()[i].get("wordpat").toString();
String[] split = wordpat.split("@2#");
if (split.length > 1) {
for (String str : split[1].split("&")) {
if (str.startsWith("来源=")) {// 自动生成的词模,返回值是来源
String query = str.substring(4, str.length() - 1);
Set<String> set = wordpatMap.get(query);
if (set == null) {
set = new HashSet<String>();
wordpatMap.put(query, set);
}
set.add(split[0]);
break;
}
}
}
}
}
}
return wordpatMap;
}
public static String getUrlLoadbalanceUrl(String queryCityCode) {
String url = "";
String provinceCode = "全国";
Map<String, Map<String, String>> provinceToUrl = GetLoadbalancingConfig.provinceToUrl;
if ("全国".equals(queryCityCode) || "电渠".equals(queryCityCode) || "集团".equals(queryCityCode)
|| "".equals(queryCityCode) || queryCityCode == null) {
url = provinceToUrl.get("默认").get("高级分析");
logger.info("获取负载地址:【默认】" + url);
// url = GetLoadbalancingConfig.getDetailAnalyzeUrlByProvince("默认");
} else {
queryCityCode = queryCityCode.replace(",", "|");
provinceCode = queryCityCode.split("\\|")[0];
provinceCode = provinceCode.substring(0, 2) + "0000";
if ("010000".equals(provinceCode) || "000000".equals(provinceCode)) {// 如何为集团、电渠编码
// 去默认url
// url =
// GetLoadbalancingConfig.getDetailAnalyzeUrlByProvince("默认");
url = provinceToUrl.get("默认").get("高级分析");
logger.info("获取负载地址:【默认】" + url);
} else {
String province = GetLoadbalancingConfig.cityCodeToCityName.get(provinceCode);
if (provinceToUrl.containsKey(province)) {
// url =
// GetLoadbalancingConfig.getDetailAnalyzeUrlByProvinceCode(province);
url = provinceToUrl.get(province).get("高级分析");
logger.info("获取负载地址:【" + province + "】" + url);
} else {
return null;
}
}
}
return url;
}
/**
* @description 排除问题生成词模
* @param combition
* @param request
* @return
* @returnType Object
*/
public static Object removeProduceWordpat(String combition, String wordpattype, HttpServletRequest request) {
JSONObject jsonObj = new JSONObject();
Object sre = GetSession.getSessionByKey("accessUser");
User user = (User) sre;
String userid = user.getUserID();
// 获取行业
String servicetype = user.getIndustryOrganizationApplication();
String combitionArray[] = combition.split("@@");
List<List<String>> list = new ArrayList<List<String>>();// 待插入的词模数据
List<List<String>> text = new ArrayList<List<String>>();// 错误报告数据
int filterCount = 0;// 过滤的自学习词模数量
if (StringUtils.isEmpty(wordpattype)) {
wordpattype = "5";
}
// String wordpattype = "5";//词模类型
String autoWordpatRule = "默认方式";// 客户问自学习规则
// 读取自学习规则配置,商家默认配置
Result configValue = CommonLibMetafieldmappingDAO.getConfigValue("客户问自学习规则", servicetype);
if (configValue != null && configValue.getRowCount() > 0) {
autoWordpatRule = Objects.toString(configValue.getRows()[0].get("name"), "");
if ("分词学习".equals(autoWordpatRule)) {
wordpattype = "0";
}
}
// 可选词配置
Set<String> set = optionWordMap.get(servicetype);
if (CollectionUtils.isEmpty(set)) {
set = new HashSet<>();
Result optionWordRs = CommonLibMetafieldmappingDAO.getConfigValue("文法学习可选词类配置", servicetype);
if (optionWordRs != null && optionWordRs.getRowCount() > 0) {
for (int i = 0; i < optionWordRs.getRowCount(); i++) {
String optionWord = Objects.toString(optionWordRs.getRows()[i].get("name"), "");
set.add(optionWord);
}
}
optionWordMap.put(servicetype, set);
}
// 可选词配置
List<String> replaceList = replaceWordMap.get(servicetype);
if (CollectionUtils.isEmpty(replaceList)) {
replaceList = new ArrayList<>();
Result option = CommonLibMetafieldmappingDAO.getConfigValue("文法学习词类替换配置", servicetype);
if (option != null && option.getRowCount() > 0) {
for (int i = 0; i < option.getRowCount(); i++) {
String s = Objects.toString(option.getRows()[i].get("name"), "");
replaceList.add(s);
}
}
replaceWordMap.put(servicetype, replaceList);
}
// 获取摘要
List<String> kbIdList = new ArrayList<String>();
for (int i = 0; i < combitionArray.length; i++) {
String queryArray[] = combitionArray[i].split("@#@");
kbIdList.add(queryArray[2]);
}
// 生成客户问和对应的自学习词模 <排除问,词模>,一个排除问只有一条精准词模,中间##分隔
Map<String, String> wordpatMap = getAutoWordpatMapByRemove(kbIdList, wordpattype);
List<String> oovWordList = new ArrayList<String>();
List<String> wordpatResultList = new ArrayList<String>();
//包含OOV词的扩展问
List<String> oovWordQueryList = new ArrayList<String>();
//包含OOV词的扩展问的分词
List<String> segmentWordList = new ArrayList<String>();
for (int i = 0; i < combitionArray.length; i++) {
String queryArray[] = combitionArray[i].split("@#@");
String queryCityCode = queryArray[0];
// 排除问题关键词中*分隔
String query = queryArray[1];
String[] removequery = query.split("\\*");
String kbdataid = queryArray[2];
String queryid = queryArray[3];
// 排除问题的严格排除状态
String isstrictexclusion = "";
if (queryArray.length > 4) {
isstrictexclusion = queryArray[4];
}
List<String> wordpatList = new ArrayList<String>();
String wordpat = null;
StringBuffer wordpats = new StringBuffer();
// 调用高析接口生成词模,多个词模体*分隔
for (int j = 0; j < removequery.length; j++) {
if ("0".equals(wordpattype) || "2".equals(wordpattype)) {
JSONObject jsonObject = getWordpat2(servicetype, removequery[j], queryCityCode);
if (jsonObject.getBooleanValue("success")) {
// 将简单词模转化为普通词模,并返回转换结果
String removewordpat = SimpleString.SimpleWordPatToWordPat(jsonObject.getString("lockWordpat"));
wordpats.append(removewordpat.split("@2#")[0]).append("*");
JSONArray oovWord = jsonObject.getJSONArray("OOVWord");
JSONArray segmentWord = jsonObject.getJSONArray("segmentWord");
if (!CollectionUtils.isEmpty(oovWord)) {
oovWordList.add(StringUtils.join(oovWord, "$_$"));// 放入OOV分词
oovWordQueryList.add(combitionArray[i]);//放入有OOV词的扩展问
segmentWordList.add(StringUtils.join(segmentWord, "##"));
}
}
} else {
// 调用自学习生成词模的接口生成词模,可能是多个,以@_@分隔
String removewordpat = callKAnalyze(servicetype, removequery[j], queryCityCode);
wordpats.append(removewordpat).append("*");
}
}
wordpat = wordpats.substring(0, wordpats.length() - 1);
// 替换词模
for (String rep : replaceList) {
if (rep.contains("=>")) {
String[] split = rep.split("=>");
wordpat = wordpat.replaceAll(split[0], split[1]);
}
}
List<String> rows = new ArrayList<String>();// 生成词模失败报告
if (wordpat != null && !"".equals(wordpat)) {
// 判断词模是否含有@_@
if (wordpat.contains("@_@")) {
// 有的话,按照@_@进行拆分,并只取第一个
wordpat = wordpat.split("@_@")[0];
}
// 保留自学习词模返回值,并替换 编者=\"自学习\""=>编者="问题库"&来源="(当前问题)" ---> modify
// 2017-05-24
wordpat = "~"+wordpat + "@1#编者=\"问题库\"&来源=\"" + query.replace("&", "\\and") + "\"";
//修改排除词模,oov词分隔符采用*号
if("否".equals(isstrictexclusion)){//非严格排除
wordpat = wordpat.replace("><", ">*<");
}
if ("2".equals(wordpattype) && isstrictexclusion != null && "是".equals(isstrictexclusion)) {// 排除词模只生成一条词模,且必须是有序词模
wordpat += "&最大未匹配字数=0";
}
// 校验自动生成的词模是否符合规范
if (Check.CheckWordpat(wordpat, request)) {
// 获取客户问对应的旧词模
String oldWordpat = wordpatMap.get(query);
// 存在旧词模
if (oldWordpat != null && !"".equals(oldWordpat)) {
String newWordpat = wordpat.split("@1#")[0];
logger.info("新旧词模比较 ----新词模:\"" + newWordpat + "\",旧词模:\"" + oldWordpat + "\",针对问题:\"" + query
+ "\"");
// 新旧词模不相同,执行插入
if (!oldWordpat.equals(newWordpat)) {
List<String> tempList = new ArrayList<String>();
tempList.add(wordpat);
tempList.add(queryCityCode);
tempList.add(query);
tempList.add(kbdataid);
tempList.add(queryid);
list.add(tempList);
wordpatResultList.add(wordpat);
} else {// 新旧词模相同,不进行插入操作
filterCount++;// 记录过滤的词模数量
}
} else {// 不存在旧词模
List<String> tempList = new ArrayList<String>();
tempList.add(wordpat);
tempList.add(queryCityCode);
tempList.add(query);
tempList.add(kbdataid);
tempList.add(queryid);
list.add(tempList);
wordpatResultList.add(wordpat);
}
} else {
rows.add(query);
rows.add("生成词模【" + wordpat + "】格式不符合!");
text.add(rows);
}
} else {
rows.add(query);
rows.add("生成失败!");
text.add(rows);
}
}
logger.info("批量训练----客户问个数:" + combitionArray.length + ",插入词模个数:" + list.size() + ",过滤词模的个数:" + filterCount);
// 插入问题库自动学习词模
int count = -1;
if (!CollectionUtils.isEmpty(list)) {
count = CommonLibQueryManageDAO.insertWordpat(list, servicetype, userid, wordpattype);
if (count > 0) {
jsonObj.put("success", true);
jsonObj.put("msg", "生成成功!");
// jsonObj.put("wordpatList", StringUtils.join(wordpatResultList, "@_@"));
jsonObj.put("OOVWord", StringUtils.join(oovWordList, "$_$"));
jsonObj.put("OOVWordQuery", StringUtils.join(oovWordQueryList,"@@"));
jsonObj.put("segmentWord", StringUtils.join(segmentWordList,"@@"));
} else {
jsonObj.put("success", false);
jsonObj.put("msg", "生成失败!");
}
} else if (combitionArray.length > filterCount && filterCount > 0) {// 有成功处理的词模就算生成成功
jsonObj.put("success", true);
jsonObj.put("msg", "生成成功!");
// jsonObj.put("wordpatList", StringUtils.join(wordpatResultList, "@_@"));
jsonObj.put("OOVWord", StringUtils.join(oovWordList, "$_$"));
jsonObj.put("OOVWordQuery", StringUtils.join(oovWordQueryList,"@@"));
jsonObj.put("segmentWord", StringUtils.join(segmentWordList,"@@"));
} else {
jsonObj.put("success", false);
jsonObj.put("msg", "生成失败!!");
}
if (text.size() > 0 && "分词学习".equals(autoWordpatRule)) {
// 错误报告
String filename = "produceWordpat_";
filename += DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
List<String> colTitle = new ArrayList<String>();
colTitle.add("客户问");
colTitle.add("生成结果");
boolean isWritten = ReadExcel.writeExcel(QuerymanageDAO.FILE_PATH_EXPORT, filename, null, null, colTitle,
text);
if (isWritten) {
// file = new File(FILE_PATH_EXPORT + filename + ".xls");
jsonObj.put("fileName", filename + ".xls");
}
}
return jsonObj;
}
public static void main(String[] args) {
// String worpattosimworpat =
// SimpleString.worpattosimworpat("测试近类@2#编者=\"你好\"");
// worpattosimworpat = SimpleString.worpattosimworpat("测试近类@2# ");
// System.out.println(worpattosimworpat);
Map<String, String> map = new HashMap<String, String>();
// String segments = "我(!本人近类|!本行近类|!第一人称近类|!集团无效咨询单字父类|!冗余词词类|!我近类|模板词)
// 想(!集团无效咨询单字父类|!考虑近类|!梦想近类|!想近类|!想念近类|模板词)
// 去(!到近类|!火车到近类|!集团无效咨询单字父类|!去近类|!往近类|!走近类|模板词)
// 北京(!北京近类|!航班城市父类|!嘉实银行父类|!原子词词类|!中国城市父类|!中国行政城市父类|模板词) 天安(!原子词词类|模板词)
// 门(OOV) 看看(!电信业务父类|!看近类|模板词) (7 words)";
String segments = "我(!本人近类|!本行近类|!第一人称近类|!集团无效咨询单字父类|!冗余词词类|!我近类|模板词) 想(!集团无效咨询单字父类|!考虑近类|!梦想近类|!想近类|!想念近类|模板词) 去(!到近类|!火车到近类|!集团无效咨询单字父类|!去近类|!往近类|!走近类|模板词) 北京(!北京近类|!航班城市父类|!嘉实银行父类|!原子词词类|!中国城市父类|!中国行政城市父类|模板词) 天安(!原子词词类|模板词) 门(!集团无效咨询单字父类|!门近类|!商圈名父类|模板词) 看看(!电信业务父类|!看近类|模板词) (7 words)";
// 根据分词得到分词数
String wordnum = segments.split("\\) \\(")[1].replace(" words)", "");
// 得到分词的内容
String word = segments.split("\\) \\(")[0] + ")";
map.put(word, wordnum);
Set<String> optionWord = new HashSet<String>();
optionWord.add("想近类");
optionWord.add("本人近类");
List<JSONObject> wordpat = getLearnWordpat(map, "问题库", optionWord);
System.out.println(wordpat);
wordpat = getAutoWordpat(map, "问题库");
System.out.println(wordpat);
InsertOrUpdateParam param = new InsertOrUpdateParam();
param.simplewordpat = "[本人近类|本行近类|第一人称近类|我近类]*[考虑近类|梦想近类|想近类|想念近类]*到近类|火车到近类|去近类|往近类|走近类*北京近类-天安-门-看近类#无序#编者=\"问题库\"";
System.out.println(param.simplewordpat);
System.out.println(SimpleString.SimpleWordPatToWordPat(param));
param.simplewordpat = "[本人近类|本行近类|第一人称近类|我近类]*[考虑近类|梦想近类|想近类|想念近类]*到近类|火车到近类|去近类|往近类|走近类*北京近类-天安-看近类#无序#编者=\"问题库\"";
System.out.println(param.simplewordpat);
System.out.println(SimpleString.SimpleWordPatToWordPat(param));
}
}
| UTF-8 | Java | 50,872 | java | AnalyzeDAO.java | Java | [
{
"context": "il.getServiceClient;\n\n/**\n * 语义训练业务\n * \n * @author cwy-pc\n * \n */\npublic class AnalyzeDAO {\n\tpublic static ",
"end": 1283,
"score": 0.9995849132537842,
"start": 1277,
"tag": "USERNAME",
"value": "cwy-pc"
},
{
"context": "aller4WSClient.kAnalyze(queryObject);\n\n\t\t// add by zhao lipeng. 20170210 START\n\t\tlogger.info(\"问题库自学习词模调用接口返回:\" +",
"end": 14575,
"score": 0.9997146725654602,
"start": 14564,
"tag": "NAME",
"value": "zhao lipeng"
},
{
"context": "gger.info(\"问题库自学习词模调用接口返回:\" + result);\n\t\t// add by zhao lipeng. 20170210 END\n\n\t\t// 替换掉回车符和空格\n\t\tresult = result.r",
"end": 14658,
"score": 0.99959397315979,
"start": 14647,
"tag": "NAME",
"value": "zhao lipeng"
},
{
"context": "模高级分析接口的输入串:\" + queryObject);\n\n\t\t// url = \"http://180.153.51.235:8082/NLPWebService/NLPCallerWS?wsdl\";\n\t\t// 获取高级分析",
"end": 16958,
"score": 0.9997135400772095,
"start": 16944,
"tag": "IP_ADDRESS",
"value": "180.153.51.235"
},
{
"context": "当前词模中的OOV分词\n\t\t\t\t\t\t// 过滤标点符号 --> update by 20191008 sundj\n\t\t\t\t\t\tif(StringUtils.isNotBlank(_word.replaceAll(",
"end": 25696,
"score": 0.9072458148002625,
"start": 25691,
"tag": "USERNAME",
"value": "sundj"
},
{
"context": "ordpat = \"\";\n\t\t\t//如果必选词数量大于2,则去掉最大未匹配字数 , author=sundj\n\t\t\twordpatBuilder.append(\"@2#\").append(\"编者=\\\"\").a",
"end": 26700,
"score": 0.9996083378791809,
"start": 26695,
"tag": "USERNAME",
"value": "sundj"
}
] | null | [] | package com.knowology.km.bll;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.jstl.sql.Result;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.knowology.Bean.User;
import com.knowology.bll.CommonLibKbDataDAO;
import com.knowology.bll.CommonLibMetafieldmappingDAO;
import com.knowology.bll.CommonLibQueryManageDAO;
import com.knowology.km.NLPCallerWS.NLPCaller4WSDelegate;
import com.knowology.km.entity.InsertOrUpdateParam;
import com.knowology.km.util.Check;
import com.knowology.km.util.GetLoadbalancingConfig;
import com.knowology.km.util.GetSession;
import com.knowology.km.util.MyUtil;
import com.knowology.km.util.ReadExcel;
import com.knowology.km.util.SimpleString;
import com.knowology.km.util.getServiceClient;
/**
* 语义训练业务
*
* @author cwy-pc
*
*/
public class AnalyzeDAO {
public static Logger logger = Logger.getLogger("querymanage");
public static Map<String, Set<String>> optionWordMap = new ConcurrentHashMap<>();
public static Map<String, List<String>> replaceWordMap = new ConcurrentHashMap<>();
/**
* @description 生成词模
* @param combition
* @param request
* @return
* @returnType Object
*/
public static Object produceWordpat(String combition, HttpServletRequest request) {
return produceWordpat(combition, "5", request);
}
/**
* @description 生成词模
* @param combition
* @param removeFlag
* 排除问题-是否严格排除标识
* @param request
* @return
* @returnType Object
*/
public static Object produceWordpat(String combition, String wordpattype, HttpServletRequest request) {
JSONObject jsonObj = new JSONObject();
Object sre = GetSession.getSessionByKey("accessUser");
User user = (User) sre;
String userid = user.getUserID();
// 获取行业
String servicetype = user.getIndustryOrganizationApplication();
String combitionArray[] = combition.split("@@");
List<List<String>> list = new ArrayList<List<String>>();// 待插入的词模数据
List<List<String>> text = new ArrayList<List<String>>();// 错误报告数据
int filterCount = 0;// 过滤的自学习词模数量
if (StringUtils.isEmpty(wordpattype)) {
wordpattype = "5";
}
// String wordpattype = "5";//词模类型
String autoWordpatRule = "默认方式";// 客户问自学习规则
// 读取自学习规则配置,商家默认配置
Result configValue = CommonLibMetafieldmappingDAO.getConfigValue("客户问自学习规则", servicetype);
if (configValue != null && configValue.getRowCount() > 0) {
autoWordpatRule = Objects.toString(configValue.getRows()[0].get("name"), "");
if ("分词学习".equals(autoWordpatRule)) {
wordpattype = "0";
}
}
// 可选词配置
Set<String> set = optionWordMap.get(servicetype);
if (CollectionUtils.isEmpty(set)) {
set = new HashSet<>();
Result optionWordRs = CommonLibMetafieldmappingDAO.getConfigValue("文法学习可选词类配置", servicetype);
if (optionWordRs != null && optionWordRs.getRowCount() > 0) {
for (int i = 0; i < optionWordRs.getRowCount(); i++) {
String optionWord = Objects.toString(optionWordRs.getRows()[i].get("name"), "");
set.add(optionWord);
}
}
optionWordMap.put(servicetype, set);
}
// 可选词配置
List<String> replaceList = replaceWordMap.get(servicetype);
if (CollectionUtils.isEmpty(replaceList)) {
replaceList = new ArrayList<>();
Result option = CommonLibMetafieldmappingDAO.getConfigValue("文法学习词类替换配置", servicetype);
if (option != null && option.getRowCount() > 0) {
for (int i = 0; i < option.getRowCount(); i++) {
String s = Objects.toString(option.getRows()[i].get("name"), "");
replaceList.add(s);
}
}
replaceWordMap.put(servicetype, replaceList);
}
// 获取摘要
List<String> kbIdList = new ArrayList<String>();
for (int i = 0; i < combitionArray.length; i++) {
String queryArray[] = combitionArray[i].split("@#@");
kbIdList.add(queryArray[2]);
}
// 生成客户问和对应的自学习词模 <客户问,词模>,一个客户问会包含两个词模,普通词模,精准词模,中间##分隔
Map<String, String> wordpatMap = getAutoWordpatMap(kbIdList, wordpattype);
List<String> oovWordList = new ArrayList<String>();
List<String> wordpatResultList = new ArrayList<String>();
//包含OOV词的扩展问
List<String> oovWordQueryList = new ArrayList<String>();
//包含OOV词的原分词
List<String> segmentWordList = new ArrayList<String>();
for (int i = 0; i < combitionArray.length; i++) {
String queryArray[] = combitionArray[i].split("@#@");
String queryCityCode = queryArray[0];
String query = queryArray[1];
String kbdataid = queryArray[2];
String queryid = queryArray[3];
// 排除问题的严格排除状态
String isstrictexclusion = "";
if (queryArray.length > 4) {
isstrictexclusion = queryArray[4];
}
List<String> wordpatList = new ArrayList<String>();
String wordpat = null;
// 调用高析接口生成词模
if ("0".equals(wordpattype) || "2".equals(wordpattype)) {
JSONObject jsonObject = getWordpat2(servicetype, query, queryCityCode);
if (jsonObject.getBooleanValue("success")) {
// 将简单词模转化为普通词模,并返回转换结果
wordpat = SimpleString.SimpleWordPatToWordPat(jsonObject.getString("wordpat"));
wordpatList.add(wordpat);
wordpat = SimpleString.SimpleWordPatToWordPat(jsonObject.getString("lockWordpat"));
wordpatList.add(wordpat);
JSONArray oovWord = jsonObject.getJSONArray("OOVWord");
JSONArray segmentWord = jsonObject.getJSONArray("segmentWord");
if (!CollectionUtils.isEmpty(oovWord)) {
oovWordList.add(StringUtils.join(oovWord, "$_$"));// 放入OOV分词
oovWordQueryList.add(combitionArray[i]);
segmentWordList.add(StringUtils.join(segmentWord,"##"));
}
}
} else {
// 调用自学习生成词模的接口生成词模,可能是多个,以@_@分隔
wordpat = callKAnalyze(servicetype, query, queryCityCode);
wordpatList.add(wordpat);
}
for (int j = 0; j < wordpatList.size(); j++) {
wordpat = wordpatList.get(j);
// 替换词模
for (String rep : replaceList) {
if (rep.contains("=>")) {
String[] split = rep.split("=>");
wordpat.replaceAll(split[0], split[1]);
}
}
List<String> rows = new ArrayList<String>();// 生成词模失败报告
// logger.info("问题库自学习词模:" + wordpat);
if (wordpat != null && !"".equals(wordpat)) {
// 判断词模是否含有@_@
if (wordpat.contains("@_@")) {
// 有的话,按照@_@进行拆分,并只取第一个
wordpat = wordpat.split("@_@")[0];
}
// 获取词模中@前面的词模题,在加上@2#编者="问题库"&来源="(当前问题)"
// wordpat = wordpat.split("@")[0] + "@2#编者=\"问题库\"&来源=\""
// + query.replace("&", "\\and") + "\"";
// 保留自学习词模返回值,并替换 编者=\"自学习\""=>编者="问题库"&来源="(当前问题)" --->
// modify 2017-05-24
wordpat = wordpat.replace("编者=\"自学习\"", "编者=\"问题库\"&来源=\"" + query.replace("&", "\\and") + "\"");
// 校验自动生成的词模是否符合规范
if (Check.CheckWordpat(wordpat, request)) {
// 获取客户问对应的旧词模
String oldWordpat = wordpatMap.get(query);
// 存在旧词模
if (oldWordpat != null && !"".equals(oldWordpat)) {
String newWordpat = wordpat.split("@2#")[0];
logger.info("新旧词模比较 ----新词模:\"" + newWordpat + "\",旧词模:\"" + oldWordpat + "\",针对问题:\""
+ query + "\"");
// 新旧词模不相同,执行插入
if (!oldWordpat.equals(newWordpat)) {
List<String> tempList = new ArrayList<String>();
tempList.add(wordpat);
tempList.add(queryCityCode);
tempList.add(query);
tempList.add(kbdataid);
tempList.add(queryid);
list.add(tempList);
wordpatResultList.add(wordpat);
} else {// 新旧词模相同,不进行插入操作
filterCount++;// 记录过滤的词模数量
}
} else {// 不存在旧词模
List<String> tempList = new ArrayList<String>();
tempList.add(wordpat);
tempList.add(queryCityCode);
tempList.add(query);
tempList.add(kbdataid);
tempList.add(queryid);
list.add(tempList);
wordpatResultList.add(wordpat);
}
} else {
rows.add(query);
rows.add("生成词模【" + wordpat + "】格式不符合!");
text.add(rows);
}
} else {
rows.add(query);
rows.add("生成失败!");
text.add(rows);
}
}
}
logger.info("批量训练----客户问个数:" + combitionArray.length + ",插入词模个数:" + list.size() + ",过滤词模的个数:" + filterCount);
// 插入问题库自动学习词模
int count = -1;
if (list.size() > 0) {
count = CommonLibQueryManageDAO.insertWordpat(list, servicetype, userid, wordpattype);
if (count > 0) {
jsonObj.put("success", true);
jsonObj.put("msg", "生成成功!");
jsonObj.put("wordpatList", StringUtils.join(wordpatResultList, "@_@"));
jsonObj.put("OOVWord", StringUtils.join(oovWordList, "$_$"));
jsonObj.put("segmentWord", StringUtils.join(segmentWordList,"@@"));
jsonObj.put("OOVWordQuery", StringUtils.join(oovWordQueryList, "@@"));
} else {
jsonObj.put("success", false);
jsonObj.put("msg", "生成失败!");
}
} else if (combitionArray.length >= list.size() + filterCount && list.size() + filterCount > 0) {// 有成功处理的词模就算生成成功
jsonObj.put("success", true);
jsonObj.put("msg", "生成成功!");
jsonObj.put("wordpatList", StringUtils.join(wordpatResultList, "@_@"));
jsonObj.put("OOVWord", StringUtils.join(oovWordList, "$_$"));
jsonObj.put("segmentWord", StringUtils.join(segmentWordList,"@@"));
jsonObj.put("OOVWordQuery", StringUtils.join(oovWordQueryList, "@@"));
} else {
jsonObj.put("success", false);
jsonObj.put("msg", "生成失败!!");
}
if (text.size() > 0 && "分词学习".equals(autoWordpatRule)) {
// 错误报告
String filename = "produceWordpat_";
filename += DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
List<String> colTitle = new ArrayList<String>();
colTitle.add("客户问");
colTitle.add("生成结果");
boolean isWritten = ReadExcel.writeExcel(QuerymanageDAO.FILE_PATH_EXPORT, filename, null, null, colTitle,
text);
if (isWritten) {
// file = new File(FILE_PATH_EXPORT + filename + ".xls");
jsonObj.put("fileName", filename + ".xls");
}
}
return jsonObj;
}
/**
* @description 全量生成词模
* @param serviceid
* @param request
* @return
* @returnType Object
*/
public static Object produceAllWordpat(String serviceid, HttpServletRequest request) {
List<String> combitionArray = getAllQuery(serviceid, 0);
return produceWordpat(StringUtils.join(combitionArray, "@@"), request);
}
/**
* @description 全量生成词模
* @param serviceid
* @param request
* @return
* @returnType Object
*/
public static Object produceAllWordpat(String serviceid, String wordpattype, HttpServletRequest request) {
List<String> combitionArray = getAllQuery(serviceid, 0);
List<String> RemoveCombitionArray = getAllQuery(serviceid, 1);
Object obj = removeProduceWordpat(StringUtils.join(RemoveCombitionArray, "@@"), "2", request);
logger.info("标准问全量生成排除词模结果:" + JSONObject.toJSONString(obj));
return produceWordpat(StringUtils.join(combitionArray, "@@"), wordpattype, request);
}
/**
* 调用高析接口生成自学习词模 <br>
* 如果没有有效的词模,则返回空
*
* @param servicetype
* 行业商家
* @param query
* 问题
* @param queryCityCode
* 问题地市
* @return success : 生成结果 如果生成成功,结果中wordpat为词模<br>
* 如果生成失败,结果中detailAnalyzeResult和wordpatResult分别存高析结果和生成词模结果
*/
public static JSONObject getWordpat(String servicetype, String query, String queryCityCode, String autor) {
JSONObject result = new JSONObject();
result.put("success", false);
// 调用高析接口
JSONObject jsonObject = callDetailAnalyze(servicetype, query, queryCityCode, autor);
// 解析高析接口结果,生成词模
List<JSONObject> list = null;
if (jsonObject.containsKey("detailAnalyze")) {
list = detailAnalyze2Wordpat(jsonObject.getString("detailAnalyze"), autor);
} else {
result.put("detailAnalyzeResult", jsonObject);
}
// 判断是否有有效词模
if (list != null && list.size() > 0) {
result.put("success", true);
result.put("wordpatResult", list);
}
logger.info("分词结果:" + result);
return result;
}
/**
* 采用文法训练策略 <br>
* 如果没有有效的词模,则返回空
*
* @param servicetype
* 行业商家
* @param query
* 问题
* @param queryCityCode
* 问题地市
* @return success : 生成结果 如果生成成功,结果中wordpat为词模和lockWordpat为语义锁定词模<br>
* 如果生成失败,结果中detailAnalyzeResult和wordpatResult分别存高析结果和生成词模结果
*/
public static JSONObject getWordpat2(String servicetype, String query, String queryCityCode) {
JSONObject result = new JSONObject();
result.put("success", false);
// 调用高析接口
JSONObject jsonObject = callDetailAnalyze(servicetype, query, queryCityCode, "自学习");
// 解析高析接口结果,生成词模
List<JSONObject> list = null;
if (jsonObject.containsKey("detailAnalyze")) {
list = detailAnalyze4Wordpat(jsonObject.getString("detailAnalyze"), "自学习", optionWordMap.get(servicetype));
} else {
result.put("detailAnalyzeResult", jsonObject);
}
// 取第一个词模
if (list != null && list.size() > 0) {
JSONObject object = list.get(0);
result.put("success", true);
result.put("wordpat", object.getString("wordpat"));
result.put("lockWordpat", object.getString("lockWordpat"));
result.put("OOVWord", object.getJSONArray("OOVWord"));
result.put("segmentWord", object.getJSONArray("segmentWord"));
return result;
}
return result;
}
/**
* 生成自学习词模
*
* @param 参数调用接口的入参
* @return 词模
*/
public static String callKAnalyze(String servicetype, String query, String queryCityCode) {
// 获取负载均衡url
String url = getUrlLoadbalanceUrl(queryCityCode);
// 如果未配置对应省份的负载服务器,默认使用全国
if (StringUtils.isEmpty(url)) {
queryCityCode = "全国";
url = getUrlLoadbalanceUrl(queryCityCode);
}
// 取省份信息
String provinceCode = "全国";
if (!"电渠".equals(queryCityCode) && !"集团".equals(queryCityCode)) {
queryCityCode = queryCityCode.replace(",", "|");
provinceCode = queryCityCode.split("\\|")[0];
provinceCode = provinceCode.substring(0, 2) + "0000";
}
// 获取高级分析的接口串中的serviceInfo
String serviceInfo = MyUtil.getServiceInfo(servicetype, "问题生成词模", "", false, queryCityCode);
// 获取高级分析的串
String queryObject = MyUtil.getDAnalyzeQueryObject("问题生成词模", query, servicetype, serviceInfo);
logger.info("自学习词模高级分析接口的输入串:" + queryObject);
// 获取高级分析的客户端
NLPCaller4WSDelegate NLPCaller4WSClient = getServiceClient.NLPCaller4WSClient(url);
// 判断接口是否连接是否为null
if (NLPCaller4WSClient == null) {
// 返回的词模为空
return "";
}
// 获取接口的返回json串
String result = NLPCaller4WSClient.kAnalyze(queryObject);
// add by <NAME>. 20170210 START
logger.info("问题库自学习词模调用接口返回:" + result);
// add by <NAME>. 20170210 END
// 替换掉回车符和空格
result = result.replace("\n", "").replace(" ", "").trim();
// 判断返回串是否为"接口请求参数不合规范!"、""、null
if ("接口请求参数不合规范!".equals(result) || "".equals(result) || result == null) {
// 返回的词模为空
return "";
} else {
try {
// 将接口的返回串用JSONObject转换为JSONObject对象
JSONObject obj = JSONObject.parseObject(result);
// 将json串中的key为autoLearnedPat的value返回
return obj.getString("autoLearnedPat");
} catch (Exception e) {
e.printStackTrace();
// 转换json格式时出现错误
return "";
}
}
}
/**
* 调用高析接口(使用地市负载)
*
* @param servicetype
* 行业
*
* @param query
* 问法
* @param queryCityCode
* 地市编码,
* @param userId
* @return
*/
public static JSONObject callDetailAnalyze(String servicetype, String query, String queryCityCode, String userId) {
// 定义返回的json串
JSONObject jsonObj = new JSONObject();
// 判断servicetype为空串、空、null
if (" ".equals(servicetype) || "".equals(servicetype) || servicetype == null) {
// 将登录信息失效放入jsonObj的msg对象中
jsonObj.put("result", "登录信息已失效,请注销后重新登录!");
return jsonObj;
}
if (StringUtils.isEmpty(query)) {
// 将登录信息失效放入jsonObj的msg对象中
jsonObj.put("result", "咨询不能为空!");
return jsonObj;
}
// 默认使用全国地市
if (StringUtils.isEmpty(queryCityCode)) {
queryCityCode = "全国";
}
// 获取负载均衡url
String url = getUrlLoadbalanceUrl(queryCityCode);
// 如果未配置对应省份的负载服务器,默认使用全国
if (StringUtils.isEmpty(url)) {
queryCityCode = "全国";
url = getUrlLoadbalanceUrl(queryCityCode);
}
// 取省份信息
String provinceCode = "";
if ("电渠".equals(queryCityCode) || "集团".equals(queryCityCode) || "全国".equals(queryCityCode)) {
provinceCode = queryCityCode;
} else {
queryCityCode = queryCityCode.replace(",", "|");
provinceCode = queryCityCode.split("\\|")[0];
provinceCode = provinceCode.substring(0, 2) + "0000";
}
// 获取高级分析的接口串中的serviceInfo
String serviceInfo = MyUtil.getServiceInfo(servicetype, "高级分析", "", false, provinceCode, "否");
// 获取高级分析接口的入参字符串
String queryObject = MyUtil.getDAnalyzeQueryObject(userId, query, servicetype, serviceInfo);
logger.info("生成词模高级分析【" + GetLoadbalancingConfig.cityCodeToCityName.get(provinceCode) + "】接口地址:" + url);
logger.info("生成词模高级分析接口的输入串:" + queryObject);
// url = "http://172.16.58.3:8082/NLPWebService/NLPCallerWS?wsdl";
// 获取高级分析的客户端
NLPCaller4WSDelegate NLPCaller4WSClient = getServiceClient.NLPCaller4WSClient(url);
// 判断客户端是否为null
if (NLPCaller4WSClient == null) {
// 将无放入jsonObj的result对象中
// jsonObj.put("result", "无");
jsonObj.put("result",
"ERROR:生成词模高级分析【" + GetLoadbalancingConfig.cityCodeToCityName.get(provinceCode) + "】接口异常。");
return jsonObj;
}
String result = "";
try {
// 调用接口的方法获取词模
// result = NLPCaller4WSClient.kAnalyze(queryObject);
result = NLPCaller4WSClient.detailAnalyze(queryObject);
logger.info("生成词模高级分析接口的输出串:" + result);
// 替换掉返回串中的回车符
result = result.replace("\n", "");
} catch (Exception e) {
e.printStackTrace();
// 将无放入jsonObj的result对象中
jsonObj.put("result",
"ERROR:生成词模高级分析【" + GetLoadbalancingConfig.cityCodeToCityName.get(provinceCode) + "】接口调用失败。");
return jsonObj;
}
// 判断返回串是否为"接口请求参数不合规范!"、""、null
if ("接口请求参数不合规范!".equals(result) || "".equals(result) || result == null) {
// 将无放入jsonObj的result对象中
jsonObj.put("result", "无");
return jsonObj;
}
jsonObj.put("detailAnalyze", result);
return jsonObj;
}
/**
* 解析高级分析接口分词结果,生成词模
*
* @param result
* 高析接口返回结果
* @param autor
* 词模编者,例【编者=\"自学习\"】
* @return 词模集合,属性如下:<br>
* wordpat:简单词模<br>
* newWordpat:去除近类的词模,用于页面展示<br>
* isValid:词模是否有效<br>
* OOVWord:词模中OOV的分词集合
*/
public static List<JSONObject> detailAnalyze2Wordpat(String result, String autor) {
String rs = "";
// 定义返回的json串
List<JSONObject> resultList = new ArrayList<JSONObject>();
Map<String, String> map = new HashMap<String, String>();
try {
// 将接口返回的json串,反序列化为json数组
JSONArray jsonArray = JSONArray.parseArray(result);
// 循环遍历jsonArray数组
for (int i = 0; i < jsonArray.size(); i++) {
// 将jsonArray数组中的第i个转换成json对象
JSONObject obj = JSONObject.parseObject(jsonArray.get(i).toString());
// 得到多个分词的json串
// 定义分词的json数组
JSONArray allSegments = new JSONArray();
// 将obj对象中key为AllSegments的value变成json数组
JSONArray allSegmentsArray = obj.getJSONArray("allSegments");
// 遍历循环arrayAllSegments数组
for (int j = 0; j < allSegmentsArray.size(); j++) {
// 获取arrayAllSegments数组中的每一个值
String segments = allSegmentsArray.getString(j);
// 判断分词是否含有..( 和 nlp版本信息
if (!segments.contains("...(") && !segments.startsWith("NLU-Version")) {
// 根据分词得到分词数
String wordnum = segments.split("\\) \\(")[1].replace(" words)", "");
// 得到分词的内容
String word = segments.split("\\) \\(")[0] + ")";
map.put(word, wordnum);
}
}
List<JSONObject> list = getAutoWordpat(map, autor);
resultList.addAll(list);
}
} catch (Exception e) {
e.printStackTrace();
}
return resultList;
}
/**
* 解析高级分析接口分词结果,生成自学习词模
*
* @param result
* 高析接口返回结果
* @param autor
* 词模编者,例【编者=\"自学习\"】
* @return 词模集合,属性如下:<br>
* wordpat:简单词模<br>
* newWordpat:去除近类的词模,用于页面展示<br>
* isValid:词模是否有效<br>
* OOVWord:词模中OOV的分词集合
*/
public static List<JSONObject> detailAnalyze4Wordpat(String result, String autor, Set<String> optionWord) {
String rs = "";
// 定义返回的json串
List<JSONObject> resultList = new ArrayList<JSONObject>();
Map<String, String> map = new HashMap<String, String>();
try {
// 将接口返回的json串,反序列化为json数组
JSONArray jsonArray = JSONArray.parseArray(result);
// 循环遍历jsonArray数组
for (int i = 0; i < jsonArray.size(); i++) {
// 将jsonArray数组中的第i个转换成json对象
JSONObject obj = JSONObject.parseObject(jsonArray.get(i).toString());
// 得到多个分词的json串
// 定义分词的json数组
JSONArray allSegments = new JSONArray();
// 将obj对象中key为AllSegments的value变成json数组
JSONArray allSegmentsArray = obj.getJSONArray("allSegments");
// 遍历循环arrayAllSegments数组
for (int j = 0; j < allSegmentsArray.size(); j++) {
// 获取arrayAllSegments数组中的每一个值
String segments = allSegmentsArray.getString(j);
// 判断分词是否含有..( 和 nlp版本信息
if (!segments.contains("...(") && !segments.startsWith("NLU-Version")) {
// 根据分词得到分词数
String wordnum = segments.split("\\) \\(")[1].replace(" words)", "");
// 得到分词的内容
String word = segments.split("\\) \\(")[0] + ")";
map.put(word, wordnum);
break;// 取第一组分词
}
}
if (optionWord == null) {
optionWord = Collections.emptySet();
}
List<JSONObject> list = getLearnWordpat(map, autor, optionWord);
resultList.addAll(list);
}
} catch (Exception e) {
e.printStackTrace();
}
return resultList;
}
/**
* @description 获得业务下所有问题
* @param serviceid
* @return
* @returnType List<String>
*/
public static List<String> getAllQuery(String serviceid, int querytype) {
List<String> list = new ArrayList<String>();
Result rs = CommonLibQueryManageDAO.getQuery(serviceid, querytype);
if (rs != null && rs.getRowCount() > 0) {
// 循环遍历数据源
for (int i = 0; i < rs.getRowCount(); i++) {
String query = rs.getRows()[i].get("query") != null ? rs.getRows()[i].get("query").toString() : "";
if ("".equals(query)) {
continue;
}
String city = rs.getRows()[i].get("city") != null ? rs.getRows()[i].get("city").toString() : "";
String kbdataid = rs.getRows()[i].get("kbdataid").toString();
String queryid = rs.getRows()[i].get("id").toString();
String isserviceword = rs.getRows()[i].get("isstrictexclusion") == null ? " "
: rs.getRows()[i].get("isstrictexclusion").toString();
String content = city + "@#@" + query + "@#@" + kbdataid + "@#@" + queryid + "@#@" + isserviceword;
list.add(content);
}
}
return list;
}
/**
*
* @param map
* @return
* @returnType String
* @dateTime 2017-9-1下午03:24:06
*/
private static List<JSONObject> getAutoWordpat(Map<String, String> map, String autor) {
List<JSONObject> list = new ArrayList<JSONObject>();
for (Map.Entry<String, String> entry : map.entrySet()) {
JSONObject jsonObject = new JSONObject();
JSONArray array = new JSONArray();
String word = entry.getKey().replace(" ", "##");
String wordArray[] = word.split("##");
String wordpat = "";
int flag = 0;// 词模处理结果 0 可用 1 分词中没有近类和父类 2 分词中包含OOV
String _word = "";// 具体分词
for (int i = 0; i < wordArray.length; i++) {
String tempWord = wordArray[i];
_word = tempWord.split("\\(")[0];
if (!"".equals(tempWord) && !"".equals(_word.trim())) {// 分词本身不能为空
String dealWrod = dealWrod(tempWord);
if (dealWrod == null) {
flag = 1;
// 页面展示: word(OOV)
dealWrod = _word + "(OOV)";
// 记录当前词模中的OOV分词
array.add(_word);
}
String _tempWord = "<" + dealWrod + ">";
wordpat = wordpat + _tempWord + "*";
}
}
wordpat = wordpat.substring(0, wordpat.lastIndexOf("*")) + "@2#" + "编者=\"" + autor + "\"";
wordpat = SimpleString.worpattosimworpat(wordpat);
String newWordpat = wordpat.replace("近类", "");
jsonObject.put("wordpat", wordpat);
jsonObject.put("newWordpat", newWordpat);
jsonObject.put("isValid", flag == 0);
jsonObject.put("OOVWord", array);
list.add(jsonObject);
}
return list;
}
/**
*
* @param map
* @return
* @returnType String
* @dateTime 2017-9-1下午03:24:06
*/
private static List<JSONObject> getLearnWordpat(Map<String, String> map, String autor, Set<String> optionWord) {
List<JSONObject> list = new ArrayList<JSONObject>();
for (Map.Entry<String, String> entry : map.entrySet()) {
JSONObject jsonObject = new JSONObject();
JSONArray array = new JSONArray();
String word = entry.getKey().replace(" ", "##");
String wordArray[] = word.split("##");
StringBuilder wordpatBuilder = new StringBuilder("");
StringBuilder lockWordpat = new StringBuilder("");
int flag = 0;// 词模处理结果 0 可用 1 分词中没有近类和父类 2 分词中包含OOV
boolean lastFlag = false;// 上一个分词是否是OOV
int requiredNum = 0;// 必选词数量
String _word = "";// 具体分词
//具体分词
JSONArray arraySegment = new JSONArray();
for (int i = 0; i < wordArray.length; i++) {
String tempWord = wordArray[i];
_word = tempWord.split("\\(")[0];
String _tempWord = "";
String _lockWord = "";
if (!"".equals(tempWord) && StringUtils.isNotBlank(_word)) {// 分词本身不能为空
//增加分词
if(StringUtils.isNotBlank(_word.replaceAll("\\p{P}" , ""))){
arraySegment.add(_word);
}
List<String> dealWrod = dealWrod2List(tempWord);
if (dealWrod == null || dealWrod.isEmpty()) {
// 页面展示: word(OOV)
if (i > 0) {
wordpatBuilder.append('-');
lockWordpat.append('-');
}
wordpatBuilder.append(_word);
lockWordpat.append(_word);
// 记录当前词模中的OOV分词
// 过滤标点符号 --> update by 20191008 sundj
if(StringUtils.isNotBlank(_word.replaceAll("\\p{P}" , ""))){
array.add(_word);
}
lastFlag = true;
flag = 1;
requiredNum++;
} else {
for (String str : dealWrod) {
// 可选词
if (optionWord.contains(str.replaceFirst("!", ""))) {
_tempWord = "[" + StringUtils.join(dealWrod, "|") + "]";
break;
}
}
// 必选
if (StringUtils.isEmpty(_tempWord)) {
_tempWord = "<" + StringUtils.join(dealWrod, "|") + ">";
requiredNum++;
}
_lockWord = "<" + StringUtils.join(dealWrod, "|") + ">";
if (i > 0) {
if (lastFlag) {
wordpatBuilder.append('-');
lockWordpat.append('-');
} else {
wordpatBuilder.append('*');
lockWordpat.append('*');
}
}
wordpatBuilder.append(_tempWord);
lockWordpat.append(_lockWord);
lastFlag = false;
}
}
}
String wordpat = "";
//如果必选词数量大于2,则去掉最大未匹配字数 , author=sundj
wordpatBuilder.append("@2#").append("编者=\"").append(autor).append("\"");
if(requiredNum < 2){
wordpatBuilder.append("&最大未匹配字数=\"").append(requiredNum + 1).append("\"");
}
wordpat = wordpatBuilder.toString();
wordpat = SimpleString.worpattosimworpat(wordpat);
String lockWordpatStr = lockWordpat.append("@2#").append("编者=\"").append(autor).append("\"")
.append("&最大未匹配字数=\"").append(0).append("\"").append("&置信度=\"").append("1.1").append("\"")
.toString();
lockWordpatStr = SimpleString.worpattosimworpat(lockWordpatStr);
String newWordpat = wordpat.replace("近类", "");
jsonObject.put("wordpat", wordpat);
jsonObject.put("newWordpat", newWordpat);
jsonObject.put("lockWordpat", lockWordpatStr);
jsonObject.put("isValid", flag == 0);
jsonObject.put("OOVWord", array);
//增加返回分词
jsonObject.put("segmentWord", arraySegment);
list.add(jsonObject);
}
return list;
}
private static String dealWrod(String word) {
String _word = word.split("\\(")[0];
String tempWord = word.split("\\(")[1].split("\\)")[0];
String wordArray[] = tempWord.split("\\|");
String newWord = "";
if (tempWord.contains("近类") && tempWord.contains("父类")) {
for (int i = 0; i < wordArray.length; i++) {
String w = wordArray[i];
if (!w.endsWith("父类") && !w.equals("模板词") && !w.endsWith("词类")) {
newWord = newWord + w + "|";
}
}
} else {
for (int i = 0; i < wordArray.length; i++) {
String w = wordArray[i];
if (!w.equals("模板词") && !w.endsWith("词类")) {
newWord = newWord + w + "|";
}
}
}
if (tempWord.equals("OOV")) {// 如果分词中存在OOV直接过滤
return null;
}
if (newWord.contains("|")) {
newWord = newWord.substring(0, newWord.lastIndexOf("|"));
return newWord;
}
return null;
}
private static List<String> dealWrod2List(String word) {
List<String> rs = new ArrayList<String>();
String _word = word.split("\\(")[0];
String tempWord = word.split("\\(")[1].split("\\)")[0];
String wordArray[] = tempWord.split("\\|");
if (tempWord.contains("近类") && tempWord.contains("父类")) {
for (int i = 0; i < wordArray.length; i++) {
String w = wordArray[i];
if (!w.endsWith("父类") && !w.equals("模板词") && !w.endsWith("词类")) {
rs.add(w);
}
}
} else {
for (int i = 0; i < wordArray.length; i++) {
String w = wordArray[i];
if (!w.equals("模板词") && !w.endsWith("词类")) {
rs.add(w);
}
}
}
if (tempWord.equals("OOV")) {// 如果分词中存在OOV直接过滤
return null;
}
return rs;
}
/**
* 获取自学习词模及对应的客户问
*
* @param kbIdList
* @return
*/
private static Map<String, String> getAutoWordpatMap(List<String> kbIdList, String wordpattype) {
Result rs = CommonLibQueryManageDAO.selectWordpatByKbdataid(kbIdList, wordpattype);
Map<String, String> wordpatMap = new HashMap<String, String>();
if (rs != null && rs.getRowCount() > 0) {
for (int i = 0; i < rs.getRowCount(); i++) {
if (rs.getRows()[i].get("wordpat") != null) {
// 自学习词模:<翼支付|!翼支付近类>*<是什>*[<么|!没有近类>]@2#编者="问题库"&来源="翼支付是什么?"&最大未匹配字数="1"
String wordpat = rs.getRows()[i].get("wordpat").toString();
String[] split = wordpat.split("@2#");
if (split.length > 1) {
for (String str : split[1].split("&")) {
if (str.startsWith("来源=")) {// 自动生成的词模,返回值是来源
String query = str.substring(4, str.length() - 1);
wordpatMap.put(query, split[0]);
break;
}
}
}
}
}
}
return wordpatMap;
}
/**
* 获取自学习词模及对应的排除问
*
* @param kbIdList
* @return
*/
private static Map<String, String> getAutoWordpatMapByRemove(List<String> kbIdList, String wordpattype) {
Result rs = CommonLibQueryManageDAO.selectWordpatByKbdataid(kbIdList, wordpattype);
Map<String, String> wordpatMap = new HashMap<String, String>();
if (rs != null && rs.getRowCount() > 0) {
for (int i = 0; i < rs.getRowCount(); i++) {
if (rs.getRows()[i].get("wordpat") != null) {
// 自学习词模:<翼支付|!翼支付近类>*<是什>*[<么|!没有近类>]@2#编者="问题库"&来源="翼支付是什么?"&最大未匹配字数="1"
String wordpat = rs.getRows()[i].get("wordpat").toString();
String[] split = wordpat.split("@1#");
if (split.length > 1) {
for (String str : split[1].split("&")) {
if (str.startsWith("来源=")) {// 自动生成的词模,返回值是来源
String query = str.substring(4, str.length() - 1);
wordpatMap.put(query, split[0]);
break;
}
}
}
}
}
}
return wordpatMap;
}
/**
* 获取自学习词模及对应的客户问
*
* @param kbIdList
* @return
*/
private static Map<String, Set<String>> getAutoWordpatMap2Set(List<String> kbIdList, String wordpattype) {
Result rs = CommonLibQueryManageDAO.selectWordpatByKbdataid(kbIdList, wordpattype);
Map<String, Set<String>> wordpatMap = new HashMap<String, Set<String>>();
if (rs != null && rs.getRowCount() > 0) {
for (int i = 0; i < rs.getRowCount(); i++) {
if (rs.getRows()[i].get("wordpat") != null) {
// 自学习词模:<翼支付|!翼支付近类>*<是什>*[<么|!没有近类>]@2#编者="问题库"&来源="翼支付是什么?"&最大未匹配字数="1"
String wordpat = rs.getRows()[i].get("wordpat").toString();
String[] split = wordpat.split("@2#");
if (split.length > 1) {
for (String str : split[1].split("&")) {
if (str.startsWith("来源=")) {// 自动生成的词模,返回值是来源
String query = str.substring(4, str.length() - 1);
Set<String> set = wordpatMap.get(query);
if (set == null) {
set = new HashSet<String>();
wordpatMap.put(query, set);
}
set.add(split[0]);
break;
}
}
}
}
}
}
return wordpatMap;
}
public static String getUrlLoadbalanceUrl(String queryCityCode) {
String url = "";
String provinceCode = "全国";
Map<String, Map<String, String>> provinceToUrl = GetLoadbalancingConfig.provinceToUrl;
if ("全国".equals(queryCityCode) || "电渠".equals(queryCityCode) || "集团".equals(queryCityCode)
|| "".equals(queryCityCode) || queryCityCode == null) {
url = provinceToUrl.get("默认").get("高级分析");
logger.info("获取负载地址:【默认】" + url);
// url = GetLoadbalancingConfig.getDetailAnalyzeUrlByProvince("默认");
} else {
queryCityCode = queryCityCode.replace(",", "|");
provinceCode = queryCityCode.split("\\|")[0];
provinceCode = provinceCode.substring(0, 2) + "0000";
if ("010000".equals(provinceCode) || "000000".equals(provinceCode)) {// 如何为集团、电渠编码
// 去默认url
// url =
// GetLoadbalancingConfig.getDetailAnalyzeUrlByProvince("默认");
url = provinceToUrl.get("默认").get("高级分析");
logger.info("获取负载地址:【默认】" + url);
} else {
String province = GetLoadbalancingConfig.cityCodeToCityName.get(provinceCode);
if (provinceToUrl.containsKey(province)) {
// url =
// GetLoadbalancingConfig.getDetailAnalyzeUrlByProvinceCode(province);
url = provinceToUrl.get(province).get("高级分析");
logger.info("获取负载地址:【" + province + "】" + url);
} else {
return null;
}
}
}
return url;
}
/**
* @description 排除问题生成词模
* @param combition
* @param request
* @return
* @returnType Object
*/
public static Object removeProduceWordpat(String combition, String wordpattype, HttpServletRequest request) {
JSONObject jsonObj = new JSONObject();
Object sre = GetSession.getSessionByKey("accessUser");
User user = (User) sre;
String userid = user.getUserID();
// 获取行业
String servicetype = user.getIndustryOrganizationApplication();
String combitionArray[] = combition.split("@@");
List<List<String>> list = new ArrayList<List<String>>();// 待插入的词模数据
List<List<String>> text = new ArrayList<List<String>>();// 错误报告数据
int filterCount = 0;// 过滤的自学习词模数量
if (StringUtils.isEmpty(wordpattype)) {
wordpattype = "5";
}
// String wordpattype = "5";//词模类型
String autoWordpatRule = "默认方式";// 客户问自学习规则
// 读取自学习规则配置,商家默认配置
Result configValue = CommonLibMetafieldmappingDAO.getConfigValue("客户问自学习规则", servicetype);
if (configValue != null && configValue.getRowCount() > 0) {
autoWordpatRule = Objects.toString(configValue.getRows()[0].get("name"), "");
if ("分词学习".equals(autoWordpatRule)) {
wordpattype = "0";
}
}
// 可选词配置
Set<String> set = optionWordMap.get(servicetype);
if (CollectionUtils.isEmpty(set)) {
set = new HashSet<>();
Result optionWordRs = CommonLibMetafieldmappingDAO.getConfigValue("文法学习可选词类配置", servicetype);
if (optionWordRs != null && optionWordRs.getRowCount() > 0) {
for (int i = 0; i < optionWordRs.getRowCount(); i++) {
String optionWord = Objects.toString(optionWordRs.getRows()[i].get("name"), "");
set.add(optionWord);
}
}
optionWordMap.put(servicetype, set);
}
// 可选词配置
List<String> replaceList = replaceWordMap.get(servicetype);
if (CollectionUtils.isEmpty(replaceList)) {
replaceList = new ArrayList<>();
Result option = CommonLibMetafieldmappingDAO.getConfigValue("文法学习词类替换配置", servicetype);
if (option != null && option.getRowCount() > 0) {
for (int i = 0; i < option.getRowCount(); i++) {
String s = Objects.toString(option.getRows()[i].get("name"), "");
replaceList.add(s);
}
}
replaceWordMap.put(servicetype, replaceList);
}
// 获取摘要
List<String> kbIdList = new ArrayList<String>();
for (int i = 0; i < combitionArray.length; i++) {
String queryArray[] = combitionArray[i].split("@#@");
kbIdList.add(queryArray[2]);
}
// 生成客户问和对应的自学习词模 <排除问,词模>,一个排除问只有一条精准词模,中间##分隔
Map<String, String> wordpatMap = getAutoWordpatMapByRemove(kbIdList, wordpattype);
List<String> oovWordList = new ArrayList<String>();
List<String> wordpatResultList = new ArrayList<String>();
//包含OOV词的扩展问
List<String> oovWordQueryList = new ArrayList<String>();
//包含OOV词的扩展问的分词
List<String> segmentWordList = new ArrayList<String>();
for (int i = 0; i < combitionArray.length; i++) {
String queryArray[] = combitionArray[i].split("@#@");
String queryCityCode = queryArray[0];
// 排除问题关键词中*分隔
String query = queryArray[1];
String[] removequery = query.split("\\*");
String kbdataid = queryArray[2];
String queryid = queryArray[3];
// 排除问题的严格排除状态
String isstrictexclusion = "";
if (queryArray.length > 4) {
isstrictexclusion = queryArray[4];
}
List<String> wordpatList = new ArrayList<String>();
String wordpat = null;
StringBuffer wordpats = new StringBuffer();
// 调用高析接口生成词模,多个词模体*分隔
for (int j = 0; j < removequery.length; j++) {
if ("0".equals(wordpattype) || "2".equals(wordpattype)) {
JSONObject jsonObject = getWordpat2(servicetype, removequery[j], queryCityCode);
if (jsonObject.getBooleanValue("success")) {
// 将简单词模转化为普通词模,并返回转换结果
String removewordpat = SimpleString.SimpleWordPatToWordPat(jsonObject.getString("lockWordpat"));
wordpats.append(removewordpat.split("@2#")[0]).append("*");
JSONArray oovWord = jsonObject.getJSONArray("OOVWord");
JSONArray segmentWord = jsonObject.getJSONArray("segmentWord");
if (!CollectionUtils.isEmpty(oovWord)) {
oovWordList.add(StringUtils.join(oovWord, "$_$"));// 放入OOV分词
oovWordQueryList.add(combitionArray[i]);//放入有OOV词的扩展问
segmentWordList.add(StringUtils.join(segmentWord, "##"));
}
}
} else {
// 调用自学习生成词模的接口生成词模,可能是多个,以@_@分隔
String removewordpat = callKAnalyze(servicetype, removequery[j], queryCityCode);
wordpats.append(removewordpat).append("*");
}
}
wordpat = wordpats.substring(0, wordpats.length() - 1);
// 替换词模
for (String rep : replaceList) {
if (rep.contains("=>")) {
String[] split = rep.split("=>");
wordpat = wordpat.replaceAll(split[0], split[1]);
}
}
List<String> rows = new ArrayList<String>();// 生成词模失败报告
if (wordpat != null && !"".equals(wordpat)) {
// 判断词模是否含有@_@
if (wordpat.contains("@_@")) {
// 有的话,按照@_@进行拆分,并只取第一个
wordpat = wordpat.split("@_@")[0];
}
// 保留自学习词模返回值,并替换 编者=\"自学习\""=>编者="问题库"&来源="(当前问题)" ---> modify
// 2017-05-24
wordpat = "~"+wordpat + "@1#编者=\"问题库\"&来源=\"" + query.replace("&", "\\and") + "\"";
//修改排除词模,oov词分隔符采用*号
if("否".equals(isstrictexclusion)){//非严格排除
wordpat = wordpat.replace("><", ">*<");
}
if ("2".equals(wordpattype) && isstrictexclusion != null && "是".equals(isstrictexclusion)) {// 排除词模只生成一条词模,且必须是有序词模
wordpat += "&最大未匹配字数=0";
}
// 校验自动生成的词模是否符合规范
if (Check.CheckWordpat(wordpat, request)) {
// 获取客户问对应的旧词模
String oldWordpat = wordpatMap.get(query);
// 存在旧词模
if (oldWordpat != null && !"".equals(oldWordpat)) {
String newWordpat = wordpat.split("@1#")[0];
logger.info("新旧词模比较 ----新词模:\"" + newWordpat + "\",旧词模:\"" + oldWordpat + "\",针对问题:\"" + query
+ "\"");
// 新旧词模不相同,执行插入
if (!oldWordpat.equals(newWordpat)) {
List<String> tempList = new ArrayList<String>();
tempList.add(wordpat);
tempList.add(queryCityCode);
tempList.add(query);
tempList.add(kbdataid);
tempList.add(queryid);
list.add(tempList);
wordpatResultList.add(wordpat);
} else {// 新旧词模相同,不进行插入操作
filterCount++;// 记录过滤的词模数量
}
} else {// 不存在旧词模
List<String> tempList = new ArrayList<String>();
tempList.add(wordpat);
tempList.add(queryCityCode);
tempList.add(query);
tempList.add(kbdataid);
tempList.add(queryid);
list.add(tempList);
wordpatResultList.add(wordpat);
}
} else {
rows.add(query);
rows.add("生成词模【" + wordpat + "】格式不符合!");
text.add(rows);
}
} else {
rows.add(query);
rows.add("生成失败!");
text.add(rows);
}
}
logger.info("批量训练----客户问个数:" + combitionArray.length + ",插入词模个数:" + list.size() + ",过滤词模的个数:" + filterCount);
// 插入问题库自动学习词模
int count = -1;
if (!CollectionUtils.isEmpty(list)) {
count = CommonLibQueryManageDAO.insertWordpat(list, servicetype, userid, wordpattype);
if (count > 0) {
jsonObj.put("success", true);
jsonObj.put("msg", "生成成功!");
// jsonObj.put("wordpatList", StringUtils.join(wordpatResultList, "@_@"));
jsonObj.put("OOVWord", StringUtils.join(oovWordList, "$_$"));
jsonObj.put("OOVWordQuery", StringUtils.join(oovWordQueryList,"@@"));
jsonObj.put("segmentWord", StringUtils.join(segmentWordList,"@@"));
} else {
jsonObj.put("success", false);
jsonObj.put("msg", "生成失败!");
}
} else if (combitionArray.length > filterCount && filterCount > 0) {// 有成功处理的词模就算生成成功
jsonObj.put("success", true);
jsonObj.put("msg", "生成成功!");
// jsonObj.put("wordpatList", StringUtils.join(wordpatResultList, "@_@"));
jsonObj.put("OOVWord", StringUtils.join(oovWordList, "$_$"));
jsonObj.put("OOVWordQuery", StringUtils.join(oovWordQueryList,"@@"));
jsonObj.put("segmentWord", StringUtils.join(segmentWordList,"@@"));
} else {
jsonObj.put("success", false);
jsonObj.put("msg", "生成失败!!");
}
if (text.size() > 0 && "分词学习".equals(autoWordpatRule)) {
// 错误报告
String filename = "produceWordpat_";
filename += DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
List<String> colTitle = new ArrayList<String>();
colTitle.add("客户问");
colTitle.add("生成结果");
boolean isWritten = ReadExcel.writeExcel(QuerymanageDAO.FILE_PATH_EXPORT, filename, null, null, colTitle,
text);
if (isWritten) {
// file = new File(FILE_PATH_EXPORT + filename + ".xls");
jsonObj.put("fileName", filename + ".xls");
}
}
return jsonObj;
}
public static void main(String[] args) {
// String worpattosimworpat =
// SimpleString.worpattosimworpat("测试近类@2#编者=\"你好\"");
// worpattosimworpat = SimpleString.worpattosimworpat("测试近类@2# ");
// System.out.println(worpattosimworpat);
Map<String, String> map = new HashMap<String, String>();
// String segments = "我(!本人近类|!本行近类|!第一人称近类|!集团无效咨询单字父类|!冗余词词类|!我近类|模板词)
// 想(!集团无效咨询单字父类|!考虑近类|!梦想近类|!想近类|!想念近类|模板词)
// 去(!到近类|!火车到近类|!集团无效咨询单字父类|!去近类|!往近类|!走近类|模板词)
// 北京(!北京近类|!航班城市父类|!嘉实银行父类|!原子词词类|!中国城市父类|!中国行政城市父类|模板词) 天安(!原子词词类|模板词)
// 门(OOV) 看看(!电信业务父类|!看近类|模板词) (7 words)";
String segments = "我(!本人近类|!本行近类|!第一人称近类|!集团无效咨询单字父类|!冗余词词类|!我近类|模板词) 想(!集团无效咨询单字父类|!考虑近类|!梦想近类|!想近类|!想念近类|模板词) 去(!到近类|!火车到近类|!集团无效咨询单字父类|!去近类|!往近类|!走近类|模板词) 北京(!北京近类|!航班城市父类|!嘉实银行父类|!原子词词类|!中国城市父类|!中国行政城市父类|模板词) 天安(!原子词词类|模板词) 门(!集团无效咨询单字父类|!门近类|!商圈名父类|模板词) 看看(!电信业务父类|!看近类|模板词) (7 words)";
// 根据分词得到分词数
String wordnum = segments.split("\\) \\(")[1].replace(" words)", "");
// 得到分词的内容
String word = segments.split("\\) \\(")[0] + ")";
map.put(word, wordnum);
Set<String> optionWord = new HashSet<String>();
optionWord.add("想近类");
optionWord.add("本人近类");
List<JSONObject> wordpat = getLearnWordpat(map, "问题库", optionWord);
System.out.println(wordpat);
wordpat = getAutoWordpat(map, "问题库");
System.out.println(wordpat);
InsertOrUpdateParam param = new InsertOrUpdateParam();
param.simplewordpat = "[本人近类|本行近类|第一人称近类|我近类]*[考虑近类|梦想近类|想近类|想念近类]*到近类|火车到近类|去近类|往近类|走近类*北京近类-天安-门-看近类#无序#编者=\"问题库\"";
System.out.println(param.simplewordpat);
System.out.println(SimpleString.SimpleWordPatToWordPat(param));
param.simplewordpat = "[本人近类|本行近类|第一人称近类|我近类]*[考虑近类|梦想近类|想近类|想念近类]*到近类|火车到近类|去近类|往近类|走近类*北京近类-天安-看近类#无序#编者=\"问题库\"";
System.out.println(param.simplewordpat);
System.out.println(SimpleString.SimpleWordPatToWordPat(param));
}
}
| 50,859 | 0.639198 | 0.632335 | 1,309 | 32.614975 | 27.128052 | 300 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.720397 | false | false | 4 |
00f5bc4260b87afe181ae36c435800c006af3632 | 33,517,924,784,344 | 0245d7c48922d87e47671241ab5ff2cf3548c4d2 | /KeyRmd/src/Display.java | 3819ec03488ceba9091aec7c454828d0f66854ed | [] | no_license | naman2403/intro-java | https://github.com/naman2403/intro-java | 6988eb083580cd8e3b542c86eda1847ad01bfaaf | 5b9ffc1c1c692a7a0d5eccfb3f3b8498066e2996 | refs/heads/master | 2021-05-28T17:54:51.836000 | 2014-04-15T18:29:52 | 2014-04-15T18:29:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class Display extends JPanel{
private BufferedImage onimage;
private BufferedImage offimage;
public Display() {
//adding image on
try {
onimage = ImageIO.read(new File("on.png"));
} catch (IOException ex) {
// handle exception...
}
//adding image off
try {
offimage = ImageIO.read(new File("off.png"));
} catch (IOException ex) {
// handle exception...
}
repaint();
}
public void paint(Graphics g) {
if (Main.on) {
g.drawImage(onimage, 0, 0, null);
} else {
g.drawImage(offimage, 0, 0, null); // see javadoc for more info on the parameters
}
repaint();
}
} | UTF-8 | Java | 938 | java | Display.java | Java | [] | null | [] | import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class Display extends JPanel{
private BufferedImage onimage;
private BufferedImage offimage;
public Display() {
//adding image on
try {
onimage = ImageIO.read(new File("on.png"));
} catch (IOException ex) {
// handle exception...
}
//adding image off
try {
offimage = ImageIO.read(new File("off.png"));
} catch (IOException ex) {
// handle exception...
}
repaint();
}
public void paint(Graphics g) {
if (Main.on) {
g.drawImage(onimage, 0, 0, null);
} else {
g.drawImage(offimage, 0, 0, null); // see javadoc for more info on the parameters
}
repaint();
}
} | 938 | 0.566098 | 0.561834 | 41 | 21.902439 | 19.186892 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.02439 | false | false | 4 |
74b046bbdc9487f13741c85f83995a942efaba35 | 11,347,303,618,161 | 7d89fbe0729ea5427a5f59f34e820aee6fd3e60e | /app/src/main/java/com/example/yuta/uranaiapp/ResultActivity.java | 6f3eeb3ed81e646b7d72c1ea23846733e0f8e0af | [] | no_license | yutayokoi/android | https://github.com/yutayokoi/android | 41615131957a245d05e202ce221a452fd7cec507 | 92a386dd104d7c960ba7f261afb7a59a2df69bf2 | refs/heads/master | 2021-01-10T00:55:52.697000 | 2015-10-11T13:41:38 | 2015-10-11T13:41:38 | 43,996,569 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.yuta.uranaiapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class ResultActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
// 遷移元でセットしたインテントを取得
Intent intent = getIntent();
// インテントにセットしてあるデータを取得
// 引数には、遷移元でつけた名前(putExtraの第一引数)を指定
String name = intent.getStringExtra(MainActivity.INPUT_NAME);
// 第二引数の整数は、正常な値が返ってこなかった場合の値
int number = intent.getIntExtra(MainActivity.RESULT_NUMBER, 0);
// strings.xmlで定義した配列を持ってくる
String[] array = getResources().getStringArray(R.array.results);
// レイアウトよりTextViewを取得
TextView nameTextView = (TextView) findViewById(R.id.nameTextView);
TextView resultTextView = (TextView) findViewById(R.id.resultTextView);
// TextViewに名前をセット
nameTextView.setText(name);
resultTextView.setText(array[number]);
}
}
| UTF-8 | Java | 1,366 | java | ResultActivity.java | Java | [
{
"context": "package com.example.yuta.uranaiapp;\n\nimport android.content.Intent;\nimport",
"end": 24,
"score": 0.6737255454063416,
"start": 20,
"tag": "USERNAME",
"value": "yuta"
}
] | null | [] | package com.example.yuta.uranaiapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class ResultActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
// 遷移元でセットしたインテントを取得
Intent intent = getIntent();
// インテントにセットしてあるデータを取得
// 引数には、遷移元でつけた名前(putExtraの第一引数)を指定
String name = intent.getStringExtra(MainActivity.INPUT_NAME);
// 第二引数の整数は、正常な値が返ってこなかった場合の値
int number = intent.getIntExtra(MainActivity.RESULT_NUMBER, 0);
// strings.xmlで定義した配列を持ってくる
String[] array = getResources().getStringArray(R.array.results);
// レイアウトよりTextViewを取得
TextView nameTextView = (TextView) findViewById(R.id.nameTextView);
TextView resultTextView = (TextView) findViewById(R.id.resultTextView);
// TextViewに名前をセット
nameTextView.setText(name);
resultTextView.setText(array[number]);
}
}
| 1,366 | 0.704745 | 0.702988 | 36 | 30.611111 | 24.732208 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 4 |
4373c55023044f20a081432778226f737fc3a5f6 | 21,844,203,706,636 | fa1ad2e2ac7e376fc7cb3b3a6e1bb88eed3e80be | /studio/micro-services/tis/tis-3.7.2/tis-assemble/src/main/java/com/qlangtech/tis/exec/AbstractActionInvocation.java | aa5f05cfbc3335c345c5359fb879195c4865cd54 | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | permissive | alldatacenter/alldata | https://github.com/alldatacenter/alldata | 7bc7713c9f1d56ad6b8e59ea03206d1073b7e047 | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | refs/heads/master | 2023-08-05T07:32:25.442000 | 2023-08-03T13:17:24 | 2023-08-03T13:17:24 | 213,321,771 | 774 | 250 | Apache-2.0 | false | 2023-09-06T17:35:32 | 2019-10-07T07:36:18 | 2023-09-06T07:35:48 | 2023-09-06T17:35:30 | 1,610,032 | 1,898 | 711 | 14 | null | false | false |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.qlangtech.tis.exec;
import com.google.common.collect.Maps;
import com.qlangtech.tis.assemble.FullbuildPhase;
import com.qlangtech.tis.exec.datax.DataXExecuteInterceptor;
import com.qlangtech.tis.exec.impl.DefaultChainContext;
import com.qlangtech.tis.exec.impl.TrackableExecuteInterceptor;
import com.qlangtech.tis.exec.impl.WorkflowDumpAndJoinInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author 百岁(baisui@qlangtech.com)
* @date 2014年9月6日下午5:03:00
*/
public class AbstractActionInvocation implements ActionInvocation {
// 由数据中心触发的直接進入索引build階段
public static final String COMMAND_KEY_DIRECTBUILD = "directbuild";
private static final Logger logger = LoggerFactory.getLogger(AbstractActionInvocation.class);
// private static final IExecuteInterceptor[] directBuild = new IExecuteInterceptor[]{ // /////
// new IndexBuildWithHdfsPathInterceptor(), new IndexBackFlowInterceptor()};
// 工作流執行方式
// public static final IExecuteInterceptor[] workflowBuild = new IExecuteInterceptor[]{ // new WorkflowTableJoinInterceptor(),
// new WorkflowDumpAndJoinInterceptor(), new WorkflowIndexBuildInterceptor(), new IndexBackFlowInterceptor()};
public static final IExecuteInterceptor[] dataXBuild = new IExecuteInterceptor[]{new DataXExecuteInterceptor()};
// private static IIndexMetaData createIndexMetaData(DefaultChainContext chainContext) {
// if (!chainContext.hasIndexName()) {
// return new DummyIndexMetaData();
// }
// try {
// SnapshotDomain domain = HttpConfigFileReader.getResource(chainContext.getIndexName(), RunEnvironment.getSysRuntime(), ConfigFileReader.FILE_SCHEMA);
// return SolrFieldsParser.parse(() -> {
// return ConfigFileReader.FILE_SCHEMA.getContent(domain);
// });
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
/**
* 创建执行链
*
* @param chainContext
* @return
*/
public static ActionInvocation createExecChain(DefaultChainContext chainContext) throws Exception {
IExecuteInterceptor[] ints = null;
if (!chainContext.hasIndexName() && chainContext.getWorkflowId() != null) {
ints = new IExecuteInterceptor[]{new WorkflowDumpAndJoinInterceptor()};
//console中直接用workflow触发
// throw new NotImplementedException("console中直接用workflow触发");
} else if (chainContext.hasIndexName()) {
// IBasicAppSource appSource = chainContext.getAppSource();
ints = dataXBuild;
// appSource.accept(new IBasicAppSource.IAppSourceVisitor<IExecuteInterceptor[]>() {
// @Override
// public IExecuteInterceptor[] visit(DataxProcessor app) {
// return dataXBuild;
// }
//
// @Override
// public IExecuteInterceptor[] visit(ISingleTableAppSource single) {
// // return visitSolrAppSource(single);
// throw new UnsupportedOperationException();
// }
//
// @Override
// public IExecuteInterceptor[] visit(IDataFlowAppSource dataflow) {
// // return visitSolrAppSource(dataflow);
// throw new UnsupportedOperationException();
// }
//
// // private IExecuteInterceptor[] visitSolrAppSource(ISolrAppSource appSource) {
//
//// Objects.requireNonNull(chainContext.getIndexBuildFileSystem(), "IndexBuildFileSystem of chainContext can not be null");
//// Objects.requireNonNull(chainContext.getTableDumpFactory(), "tableDumpFactory of chainContext can not be null");
//// // chainContext.setIndexMetaData(createIndexMetaData(chainContext));
////
//// EntityName targetEntity = appSource.getTargetEntity();
//// chainContext.setAttribute(IExecChainContext.KEY_BUILD_TARGET_TABLE_NAME, targetEntity);
//// IPrimaryTabFinder pTabFinder = appSource.getPrimaryTabFinder();
//// chainContext.setAttribute(IFullBuildContext.KEY_ER_RULES, pTabFinder);
//// return workflowBuild;
// // throw new UnsupportedOperationException();
// //}
//
//
// });
} else {
// if ("true".equalsIgnoreCase(chainContext.getString(COMMAND_KEY_DIRECTBUILD))) {
// ints = directBuild;
// } else {
// ints = fullints;
throw new UnsupportedOperationException();
//}
}
Integer taskid = chainContext.getTaskId();
TrackableExecuteInterceptor.initialTaskPhase(taskid);
return createInvocation(chainContext, ints);
}
public static ActionInvocation createInvocation(IExecChainContext chainContext, IExecuteInterceptor[] ints) {
final ComponentOrders componentOrders = new ComponentOrders();
AbstractActionInvocation preInvocation = new AbstractActionInvocation();
preInvocation.setContext(chainContext);
preInvocation.setComponentOrders(componentOrders);
AbstractActionInvocation invocation = null;
for (int i = (ints.length - 1); i >= 0; i--) {
for (FullbuildPhase phase : ints[i].getPhase()) {
componentOrders.put(phase, i);
}
invocation = new AbstractActionInvocation();
invocation.setComponentOrders(componentOrders);
invocation.setContext(chainContext);
invocation.setInterceptor(ints[i]);
invocation.setSuccessor(preInvocation);
preInvocation = invocation;
}
logger.info("component description:");
for (Map.Entry<FullbuildPhase, Integer> componentEntry : componentOrders.entrySet()) {
logger.info(componentEntry.getKey() + ":" + componentEntry.getValue());
}
logger.info("description end");
return preInvocation;
}
private ComponentOrders componentOrders;
public static class ComponentOrders {
private final Map<FullbuildPhase, Integer> orders;
public ComponentOrders() {
super();
this.orders = Maps.newHashMap();
}
public Integer get(FullbuildPhase key) {
Integer index = this.orders.get(key);
if (index == null) {
throw new IllegalStateException("key:" + key + " can not find relevant map keys["
+ orders.keySet().stream().map((r) -> r.getName()).collect(Collectors.joining(",")) + "]");
}
return index;
}
public Set<Entry<FullbuildPhase, Integer>> entrySet() {
return orders.entrySet();
}
public Integer put(FullbuildPhase key, Integer value) {
return orders.put(key, value);
}
}
@Override
public ExecuteResult invoke() throws Exception {
if (componentOrders == null) {
throw new IllegalStateException("componentOrders can not be null");
}
ExecutePhaseRange phaseRange = chainContext.getExecutePhaseRange();
// String start = chainContext.getString(IFullBuildContext.COMPONENT_START);
// String end = chainContext.getString(IFullBuildContext.COMPONENT_END);
int startIndex = Integer.MIN_VALUE;
int endIndex = Integer.MAX_VALUE;
startIndex = componentOrders.get(phaseRange.getStart());
endIndex = componentOrders.get(phaseRange.getEnd());
if (interceptor == null) {
return ExecuteResult.SUCCESS;
} else {
int current;
try {
current = componentOrders.get(FullbuildPhase.getFirst(interceptor.getPhase()));
} catch (Throwable e) {
throw new IllegalStateException("component:" + FullbuildPhase.desc(interceptor.getPhase()) + " can not find value in componentOrders," + componentOrders.toString());
}
if (current >= startIndex && current <= endIndex) {
logger.info("execute " + FullbuildPhase.desc(interceptor.getPhase()) + ":" + current + "[" + startIndex + "," + endIndex + "]");
return interceptor.intercept(successor);
} else {
// 直接跳过
return successor.invoke();
}
}
}
public ComponentOrders getComponentOrders() {
return componentOrders;
}
public void setComponentOrders(ComponentOrders componentOrders) {
this.componentOrders = componentOrders;
}
@Override
public IExecChainContext getContext() {
return this.chainContext;
}
private IExecChainContext chainContext;
private IExecuteInterceptor interceptor;
private ActionInvocation successor;
public void setSuccessor(ActionInvocation successor) {
this.successor = successor;
}
public IExecuteInterceptor getSuccessor() {
return interceptor;
}
public void setInterceptor(IExecuteInterceptor successor) {
this.interceptor = successor;
}
public void setContext(IExecChainContext action) {
this.chainContext = action;
}
}
| UTF-8 | Java | 10,383 | java | AbstractActionInvocation.java | Java | [
{
"context": "port java.util.stream.Collectors;\n\n/**\n * @author 百岁(baisui@qlangtech.com)\n * @date 2014年9月6日下午5:03:00",
"end": 1366,
"score": 0.9995192885398865,
"start": 1364,
"tag": "NAME",
"value": "百岁"
},
{
"context": "t java.util.stream.Collectors;\n\n/**\n * @author 百岁(baisui@qlangtech.com)\n * @date 2014年9月6日下午5:03:00\n */\npublic class Abs",
"end": 1387,
"score": 0.9999306201934814,
"start": 1367,
"tag": "EMAIL",
"value": "baisui@qlangtech.com"
}
] | null | [] |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.qlangtech.tis.exec;
import com.google.common.collect.Maps;
import com.qlangtech.tis.assemble.FullbuildPhase;
import com.qlangtech.tis.exec.datax.DataXExecuteInterceptor;
import com.qlangtech.tis.exec.impl.DefaultChainContext;
import com.qlangtech.tis.exec.impl.TrackableExecuteInterceptor;
import com.qlangtech.tis.exec.impl.WorkflowDumpAndJoinInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author 百岁(<EMAIL>)
* @date 2014年9月6日下午5:03:00
*/
public class AbstractActionInvocation implements ActionInvocation {
// 由数据中心触发的直接進入索引build階段
public static final String COMMAND_KEY_DIRECTBUILD = "directbuild";
private static final Logger logger = LoggerFactory.getLogger(AbstractActionInvocation.class);
// private static final IExecuteInterceptor[] directBuild = new IExecuteInterceptor[]{ // /////
// new IndexBuildWithHdfsPathInterceptor(), new IndexBackFlowInterceptor()};
// 工作流執行方式
// public static final IExecuteInterceptor[] workflowBuild = new IExecuteInterceptor[]{ // new WorkflowTableJoinInterceptor(),
// new WorkflowDumpAndJoinInterceptor(), new WorkflowIndexBuildInterceptor(), new IndexBackFlowInterceptor()};
public static final IExecuteInterceptor[] dataXBuild = new IExecuteInterceptor[]{new DataXExecuteInterceptor()};
// private static IIndexMetaData createIndexMetaData(DefaultChainContext chainContext) {
// if (!chainContext.hasIndexName()) {
// return new DummyIndexMetaData();
// }
// try {
// SnapshotDomain domain = HttpConfigFileReader.getResource(chainContext.getIndexName(), RunEnvironment.getSysRuntime(), ConfigFileReader.FILE_SCHEMA);
// return SolrFieldsParser.parse(() -> {
// return ConfigFileReader.FILE_SCHEMA.getContent(domain);
// });
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
/**
* 创建执行链
*
* @param chainContext
* @return
*/
public static ActionInvocation createExecChain(DefaultChainContext chainContext) throws Exception {
IExecuteInterceptor[] ints = null;
if (!chainContext.hasIndexName() && chainContext.getWorkflowId() != null) {
ints = new IExecuteInterceptor[]{new WorkflowDumpAndJoinInterceptor()};
//console中直接用workflow触发
// throw new NotImplementedException("console中直接用workflow触发");
} else if (chainContext.hasIndexName()) {
// IBasicAppSource appSource = chainContext.getAppSource();
ints = dataXBuild;
// appSource.accept(new IBasicAppSource.IAppSourceVisitor<IExecuteInterceptor[]>() {
// @Override
// public IExecuteInterceptor[] visit(DataxProcessor app) {
// return dataXBuild;
// }
//
// @Override
// public IExecuteInterceptor[] visit(ISingleTableAppSource single) {
// // return visitSolrAppSource(single);
// throw new UnsupportedOperationException();
// }
//
// @Override
// public IExecuteInterceptor[] visit(IDataFlowAppSource dataflow) {
// // return visitSolrAppSource(dataflow);
// throw new UnsupportedOperationException();
// }
//
// // private IExecuteInterceptor[] visitSolrAppSource(ISolrAppSource appSource) {
//
//// Objects.requireNonNull(chainContext.getIndexBuildFileSystem(), "IndexBuildFileSystem of chainContext can not be null");
//// Objects.requireNonNull(chainContext.getTableDumpFactory(), "tableDumpFactory of chainContext can not be null");
//// // chainContext.setIndexMetaData(createIndexMetaData(chainContext));
////
//// EntityName targetEntity = appSource.getTargetEntity();
//// chainContext.setAttribute(IExecChainContext.KEY_BUILD_TARGET_TABLE_NAME, targetEntity);
//// IPrimaryTabFinder pTabFinder = appSource.getPrimaryTabFinder();
//// chainContext.setAttribute(IFullBuildContext.KEY_ER_RULES, pTabFinder);
//// return workflowBuild;
// // throw new UnsupportedOperationException();
// //}
//
//
// });
} else {
// if ("true".equalsIgnoreCase(chainContext.getString(COMMAND_KEY_DIRECTBUILD))) {
// ints = directBuild;
// } else {
// ints = fullints;
throw new UnsupportedOperationException();
//}
}
Integer taskid = chainContext.getTaskId();
TrackableExecuteInterceptor.initialTaskPhase(taskid);
return createInvocation(chainContext, ints);
}
public static ActionInvocation createInvocation(IExecChainContext chainContext, IExecuteInterceptor[] ints) {
final ComponentOrders componentOrders = new ComponentOrders();
AbstractActionInvocation preInvocation = new AbstractActionInvocation();
preInvocation.setContext(chainContext);
preInvocation.setComponentOrders(componentOrders);
AbstractActionInvocation invocation = null;
for (int i = (ints.length - 1); i >= 0; i--) {
for (FullbuildPhase phase : ints[i].getPhase()) {
componentOrders.put(phase, i);
}
invocation = new AbstractActionInvocation();
invocation.setComponentOrders(componentOrders);
invocation.setContext(chainContext);
invocation.setInterceptor(ints[i]);
invocation.setSuccessor(preInvocation);
preInvocation = invocation;
}
logger.info("component description:");
for (Map.Entry<FullbuildPhase, Integer> componentEntry : componentOrders.entrySet()) {
logger.info(componentEntry.getKey() + ":" + componentEntry.getValue());
}
logger.info("description end");
return preInvocation;
}
private ComponentOrders componentOrders;
public static class ComponentOrders {
private final Map<FullbuildPhase, Integer> orders;
public ComponentOrders() {
super();
this.orders = Maps.newHashMap();
}
public Integer get(FullbuildPhase key) {
Integer index = this.orders.get(key);
if (index == null) {
throw new IllegalStateException("key:" + key + " can not find relevant map keys["
+ orders.keySet().stream().map((r) -> r.getName()).collect(Collectors.joining(",")) + "]");
}
return index;
}
public Set<Entry<FullbuildPhase, Integer>> entrySet() {
return orders.entrySet();
}
public Integer put(FullbuildPhase key, Integer value) {
return orders.put(key, value);
}
}
@Override
public ExecuteResult invoke() throws Exception {
if (componentOrders == null) {
throw new IllegalStateException("componentOrders can not be null");
}
ExecutePhaseRange phaseRange = chainContext.getExecutePhaseRange();
// String start = chainContext.getString(IFullBuildContext.COMPONENT_START);
// String end = chainContext.getString(IFullBuildContext.COMPONENT_END);
int startIndex = Integer.MIN_VALUE;
int endIndex = Integer.MAX_VALUE;
startIndex = componentOrders.get(phaseRange.getStart());
endIndex = componentOrders.get(phaseRange.getEnd());
if (interceptor == null) {
return ExecuteResult.SUCCESS;
} else {
int current;
try {
current = componentOrders.get(FullbuildPhase.getFirst(interceptor.getPhase()));
} catch (Throwable e) {
throw new IllegalStateException("component:" + FullbuildPhase.desc(interceptor.getPhase()) + " can not find value in componentOrders," + componentOrders.toString());
}
if (current >= startIndex && current <= endIndex) {
logger.info("execute " + FullbuildPhase.desc(interceptor.getPhase()) + ":" + current + "[" + startIndex + "," + endIndex + "]");
return interceptor.intercept(successor);
} else {
// 直接跳过
return successor.invoke();
}
}
}
public ComponentOrders getComponentOrders() {
return componentOrders;
}
public void setComponentOrders(ComponentOrders componentOrders) {
this.componentOrders = componentOrders;
}
@Override
public IExecChainContext getContext() {
return this.chainContext;
}
private IExecChainContext chainContext;
private IExecuteInterceptor interceptor;
private ActionInvocation successor;
public void setSuccessor(ActionInvocation successor) {
this.successor = successor;
}
public IExecuteInterceptor getSuccessor() {
return interceptor;
}
public void setInterceptor(IExecuteInterceptor successor) {
this.interceptor = successor;
}
public void setContext(IExecChainContext action) {
this.chainContext = action;
}
}
| 10,370 | 0.642405 | 0.640557 | 263 | 38.072243 | 34.949154 | 181 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.48289 | false | false | 4 |
77e6b013844cfd9d004b99cd2f8f614e73aabcf3 | 34,943,853,957,918 | 22a203909379ecc230670fec40a345036c1a2a9f | /Java/design patterns java 2/src/br/com/alura/loja/TestesAdapter.java | ceb71a668589e36cc6727705ecc90e2fa0914a22 | [] | no_license | fernandosiillva/projetos | https://github.com/fernandosiillva/projetos | faced070945dff7160fe365f583086e320967d95 | 9c3dc142d875e6b3a1f06ee7e5a5dcbd43ab4628 | refs/heads/master | 2021-12-15T08:25:21.662000 | 2021-12-15T00:40:11 | 2021-12-15T00:40:11 | 222,556,237 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.alura.loja;
import java.math.BigDecimal;
import br.com.alura.loja.http.ApacheHttpAdapter;
import br.com.alura.loja.orcamento.ItemOrcamento;
import br.com.alura.loja.orcamento.Orcamento;
import br.com.alura.loja.orcamento.RegistroOrcamento;
public class TestesAdapter {
public static void main(String[] args) {
Orcamento orcamento = new Orcamento();
orcamento.adicionarItem(new ItemOrcamento(BigDecimal.TEN));
orcamento.aprovar();
orcamento.finalizar();
RegistroOrcamento registro = new RegistroOrcamento(new ApacheHttpAdapter());
registro.registrar(orcamento);
}
}
| UTF-8 | Java | 600 | java | TestesAdapter.java | Java | [] | null | [] | package br.com.alura.loja;
import java.math.BigDecimal;
import br.com.alura.loja.http.ApacheHttpAdapter;
import br.com.alura.loja.orcamento.ItemOrcamento;
import br.com.alura.loja.orcamento.Orcamento;
import br.com.alura.loja.orcamento.RegistroOrcamento;
public class TestesAdapter {
public static void main(String[] args) {
Orcamento orcamento = new Orcamento();
orcamento.adicionarItem(new ItemOrcamento(BigDecimal.TEN));
orcamento.aprovar();
orcamento.finalizar();
RegistroOrcamento registro = new RegistroOrcamento(new ApacheHttpAdapter());
registro.registrar(orcamento);
}
}
| 600 | 0.786667 | 0.786667 | 22 | 26.272728 | 23.132389 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.181818 | false | false | 4 |
ca6fe2efe16f9163689dffd8bc90e10b54e214e3 | 38,165,079,407,858 | 87e9b7db0736cf51c8a1f5627e1a7043bcbb28c5 | /src/test/java/entidade/JpaTest.java | c6f2af45a72bc69a86b5b49c2c111f489d172df6 | [] | no_license | paulaSatie/avaliacao-jpa-2012 | https://github.com/paulaSatie/avaliacao-jpa-2012 | 4af8abba2ec59640c7c340a8b7ed79a94568dd35 | 6ac82532c077c23ae28a5df79bdcbb6bb46d5bae | refs/heads/master | 2020-12-25T00:04:58.012000 | 2012-11-21T23:48:48 | 2012-11-21T23:48:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package entidade;
import com.mysema.query.jpa.impl.JPAQuery;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.BeforeClass;
import org.junit.Test;
public class JpaTest {
private static EntityManagerFactory emf;
@BeforeClass
public static void init() {
emf = Persistence.createEntityManagerFactory("jpaPU");
}
@Test
public void test() {
EntityManager entityManager = emf.createEntityManager();
entityManager.getTransaction().begin();
ProdutoSimples produtoSimples = new ProdutoSimples();
produtoSimples.setDescricao("OMO");
produtoSimples.setFabricante("Unilever");
produtoSimples.setPreco(4.98);
entityManager.persist(produtoSimples);
ProdutoComposto produtoComposto = new ProdutoComposto();
produtoComposto.setComposicao("Poder O2");
produtoComposto.setDescricao("Vanish");
produtoComposto.setPreco(8.50);
entityManager.persist(produtoComposto);
ProdutoSimples produtoSimples2 = new ProdutoSimples();
produtoSimples2.setDescricao("Ace");
produtoSimples2.setFabricante("Unilever");
produtoSimples2.setPreco(3.6);
produtoSimples2.setProdutoComposto(produtoComposto);
produtoComposto.getProdutos().add(produtoSimples2);
produtoComposto.getProdutos().add(produtoSimples);
entityManager.persist(produtoSimples2);
Pedido pedido = new Pedido();
pedido.setNomeCliente("Fernando");
pedido.addProduto(produtoSimples);
pedido.addProduto(produtoComposto);
entityManager.persist(pedido);
entityManager.getTransaction().commit();
}
}
| UTF-8 | Java | 1,827 | java | JpaTest.java | Java | [
{
"context": "do = new Pedido();\n pedido.setNomeCliente(\"Fernando\");\n pedido.addProduto(produtoSimples);\n ",
"end": 1616,
"score": 0.9997351765632629,
"start": 1608,
"tag": "NAME",
"value": "Fernando"
}
] | null | [] | package entidade;
import com.mysema.query.jpa.impl.JPAQuery;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.BeforeClass;
import org.junit.Test;
public class JpaTest {
private static EntityManagerFactory emf;
@BeforeClass
public static void init() {
emf = Persistence.createEntityManagerFactory("jpaPU");
}
@Test
public void test() {
EntityManager entityManager = emf.createEntityManager();
entityManager.getTransaction().begin();
ProdutoSimples produtoSimples = new ProdutoSimples();
produtoSimples.setDescricao("OMO");
produtoSimples.setFabricante("Unilever");
produtoSimples.setPreco(4.98);
entityManager.persist(produtoSimples);
ProdutoComposto produtoComposto = new ProdutoComposto();
produtoComposto.setComposicao("Poder O2");
produtoComposto.setDescricao("Vanish");
produtoComposto.setPreco(8.50);
entityManager.persist(produtoComposto);
ProdutoSimples produtoSimples2 = new ProdutoSimples();
produtoSimples2.setDescricao("Ace");
produtoSimples2.setFabricante("Unilever");
produtoSimples2.setPreco(3.6);
produtoSimples2.setProdutoComposto(produtoComposto);
produtoComposto.getProdutos().add(produtoSimples2);
produtoComposto.getProdutos().add(produtoSimples);
entityManager.persist(produtoSimples2);
Pedido pedido = new Pedido();
pedido.setNomeCliente("Fernando");
pedido.addProduto(produtoSimples);
pedido.addProduto(produtoComposto);
entityManager.persist(pedido);
entityManager.getTransaction().commit();
}
}
| 1,827 | 0.695129 | 0.686371 | 57 | 31.052631 | 21.184586 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.631579 | false | false | 4 |
ae0974651867904ad16f79b6cfa7a00f8b21d6f4 | 35,802,847,408,001 | 9feee75684dc82069feefc45d535f6ef5c975848 | /main/plugin_library/src/main/java/com/example/plugin_library/IPluginActivity.java | a676182647cfe1d7401fe6691bc233331830c094 | [] | no_license | Luozf12345/AndroidStudy | https://github.com/Luozf12345/AndroidStudy | 870de271674a5fae56e87a8790bc7fe44ad0397f | 4793c8613a3b23c2fecc1c793a625047f6847670 | refs/heads/master | 2021-07-18T08:34:39.616000 | 2020-05-09T12:42:13 | 2020-05-09T12:42:13 | 245,978,107 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.plugin_library;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
/**
* 代理Activity接口。Acitivity的有些方法是私有或者保护的,插件Activity实现该接口,可以让代理Activity调用
*
* @author luozf
* @date 2020/4/17
*/
public interface IPluginActivity {
/**
* 将插件Activity和代理Activity绑定
* @param activity
*/
void attach(Activity activity);
// 以下全都是Activity生命周期函数,
// 插件Activity本身 在被用作"插件"的时候不具备生命周期,由宿主里面的代理Activity类代为管理
void onCreate(Bundle saveInstanceState);
void onStart();
void onResume();
void onRestart();
void onPause();
void onStop();
void onDestroy();
void onActivityResult(int requestCode, int resultCode, Intent data);
}
| UTF-8 | Java | 900 | java | IPluginActivity.java | Java | [
{
"context": "者保护的,插件Activity实现该接口,可以让代理Activity调用\n *\n * @author luozf\n * @date 2020/4/17\n */\npublic interface IPluginAc",
"end": 218,
"score": 0.9995748400688171,
"start": 213,
"tag": "USERNAME",
"value": "luozf"
}
] | null | [] | package com.example.plugin_library;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
/**
* 代理Activity接口。Acitivity的有些方法是私有或者保护的,插件Activity实现该接口,可以让代理Activity调用
*
* @author luozf
* @date 2020/4/17
*/
public interface IPluginActivity {
/**
* 将插件Activity和代理Activity绑定
* @param activity
*/
void attach(Activity activity);
// 以下全都是Activity生命周期函数,
// 插件Activity本身 在被用作"插件"的时候不具备生命周期,由宿主里面的代理Activity类代为管理
void onCreate(Bundle saveInstanceState);
void onStart();
void onResume();
void onRestart();
void onPause();
void onStop();
void onDestroy();
void onActivityResult(int requestCode, int resultCode, Intent data);
}
| 900 | 0.702479 | 0.692837 | 38 | 18.105263 | 19.386362 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.421053 | false | false | 4 |
487ea26a79c40bd43497ca408ff8b85c685b6a21 | 39,015,482,924,083 | 5e8454e87cd613987547a2780303ba1fd34b38b0 | /HotelEmployee/src/US/Jianyang/Employee.java | 5a7c1222745d3c913e81319d538675daa52d8bdd | [] | no_license | JianyangW/Beginer-to-make-Coffee | https://github.com/JianyangW/Beginer-to-make-Coffee | 67a8772bccdfb1c4055cd1adf039bbfe4daf84e2 | 2a0150437c5fb4e38ccc4e7d547a464573fc6cbe | refs/heads/master | 2021-09-07T03:58:59.576000 | 2018-02-17T01:38:30 | 2018-02-17T01:38:30 | 105,592,789 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package US.Jianyang;
import java.security.PrivateKey;
public abstract class Employee {
private String name;
private String Gender;
private String E_number;
public Employee() {}
public Employee(String name, String Gender, String E_number) {
this.name = name;
this.E_number = E_number;
this.Gender = Gender;
}
public abstract void Work();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return Gender;
}
public void setGender(String gender) {
Gender = gender;
}
public String getE_number() {
return E_number;
}
public void setE_number(String e_number) {
E_number = e_number;
}
}
| UTF-8 | Java | 812 | java | Employee.java | Java | [] | null | [] | package US.Jianyang;
import java.security.PrivateKey;
public abstract class Employee {
private String name;
private String Gender;
private String E_number;
public Employee() {}
public Employee(String name, String Gender, String E_number) {
this.name = name;
this.E_number = E_number;
this.Gender = Gender;
}
public abstract void Work();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return Gender;
}
public void setGender(String gender) {
Gender = gender;
}
public String getE_number() {
return E_number;
}
public void setE_number(String e_number) {
E_number = e_number;
}
}
| 812 | 0.597291 | 0.597291 | 43 | 17.88372 | 16.051094 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.395349 | false | false | 4 |
046739030aef5d09a3448260ec9e1d9606ee7663 | 36,180,804,531,635 | ec7164a1c054e72ef17899a5704d56c97269651c | /meituan/src/second/Main.java | 22c09468388e0e5bc5f7d4c511c9928f787d7f11 | [] | no_license | ZhanLiao/interviewExamination | https://github.com/ZhanLiao/interviewExamination | d1ed016a016079ef8158ff06447bf11322bfb602 | 82756ef8322bccaa5d1adaf735d8eb1c7208d0e5 | refs/heads/master | 2023-06-15T22:29:25.994000 | 2021-07-21T10:29:12 | 2021-07-21T10:29:12 | 375,882,761 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package second;
import java.util.Scanner;
/**
* 美团第二道:围栏,固定长度的家具跨过围栏。围栏高度小于指定高度才能过去。
*/
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); // 围栏个数
int m = scanner.nextInt(); // 家具宽度
int h = scanner.nextInt(); // 最高能跨上的高度
int[] highs = new int[100000+1];
for (int i = 0; i < n; i++) {
highs[i] = scanner.nextInt();
}
int resVal = Integer.MAX_VALUE;
int index = 0;
for (int i = 0; i <= n - m; i++) {
boolean flag = true;
for (int j = 0; j < m; j++) {
if (highs[i+j] > h){
flag = false;
break;
}
}
if (flag){
if (resVal > highs[i]){
index = i;
resVal = highs[i];
}
}
}
if (resVal < Integer.MAX_VALUE){
System.out.println(index);
}else {
System.out.println(-1);
}
}
}
| UTF-8 | Java | 1,215 | java | Main.java | Java | [] | null | [] | package second;
import java.util.Scanner;
/**
* 美团第二道:围栏,固定长度的家具跨过围栏。围栏高度小于指定高度才能过去。
*/
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); // 围栏个数
int m = scanner.nextInt(); // 家具宽度
int h = scanner.nextInt(); // 最高能跨上的高度
int[] highs = new int[100000+1];
for (int i = 0; i < n; i++) {
highs[i] = scanner.nextInt();
}
int resVal = Integer.MAX_VALUE;
int index = 0;
for (int i = 0; i <= n - m; i++) {
boolean flag = true;
for (int j = 0; j < m; j++) {
if (highs[i+j] > h){
flag = false;
break;
}
}
if (flag){
if (resVal > highs[i]){
index = i;
resVal = highs[i];
}
}
}
if (resVal < Integer.MAX_VALUE){
System.out.println(index);
}else {
System.out.println(-1);
}
}
}
| 1,215 | 0.416742 | 0.405941 | 42 | 25.452381 | 15.429104 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.547619 | false | false | 4 |
ab027c4baffd9a5d902512932b16228698e0851c | 38,723,425,153,827 | 88367fdf2595ea0d2f1a0964fa7aafc11d49b66e | /src/java8/ch01/ex11/SS.java | 0f8c42f1db8d2ad591abe105c928105c7eececb4 | [] | no_license | tm-java/java2016 | https://github.com/tm-java/java2016 | 0274b79e9e78503e52ea46b584c8e14016da369e | 096c4d5ccdebb736908cb964fa0a4b291978bf64 | refs/heads/master | 2020-05-21T10:10:57.826000 | 2017-09-07T22:36:28 | 2017-09-07T22:36:28 | 69,303,562 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package java8.ch01.ex11;
public class SS implements IS, JS {
}
| UTF-8 | Java | 65 | java | SS.java | Java | [] | null | [] | package java8.ch01.ex11;
public class SS implements IS, JS {
}
| 65 | 0.723077 | 0.646154 | 5 | 12 | 14.710541 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 4 |
093ef58a4b66a50730788ade38a416a2eeafe976 | 33,767,032,925,353 | ca81462ee92f28d79ef88e3289fefe4de76747b5 | /src/main/java/org/sputnikdev/bluetooth/manager/impl/SharedDeviceGovernorImpl.java | a43d1aa74e5e81f1880d8c233e8affea27a763e4 | [
"Apache-2.0"
] | permissive | Dealermade/bluetooth-manager | https://github.com/Dealermade/bluetooth-manager | a03374631d53c31b1ae030ddb6a183944a4cbde3 | cd0e5a894b34cccb2134ced9de61c8f9c3d2d8cf | refs/heads/master | 2021-08-30T19:14:01.564000 | 2017-12-19T04:07:36 | 2017-12-19T04:07:36 | 109,864,307 | 0 | 0 | null | true | 2017-12-19T03:57:47 | 2017-11-07T16:50:17 | 2017-11-07T16:50:19 | 2017-12-19T03:57:47 | 470 | 0 | 0 | 0 | Java | false | null | package org.sputnikdev.bluetooth.manager.impl;
import com.google.common.collect.EvictingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sputnikdev.bluetooth.Filter;
import org.sputnikdev.bluetooth.URL;
import org.sputnikdev.bluetooth.manager.BluetoothObjectType;
import org.sputnikdev.bluetooth.manager.BluetoothObjectVisitor;
import org.sputnikdev.bluetooth.manager.BluetoothSmartDeviceListener;
import org.sputnikdev.bluetooth.manager.CharacteristicGovernor;
import org.sputnikdev.bluetooth.manager.DeviceDiscoveryListener;
import org.sputnikdev.bluetooth.manager.DeviceGovernor;
import org.sputnikdev.bluetooth.manager.DiscoveredDevice;
import org.sputnikdev.bluetooth.manager.GattService;
import org.sputnikdev.bluetooth.manager.GenericBluetoothDeviceListener;
import org.sputnikdev.bluetooth.manager.GovernorListener;
import org.sputnikdev.bluetooth.manager.NotReadyException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class SharedDeviceGovernorImpl implements DeviceGovernor, BluetoothObjectGovernor, DeviceDiscoveryListener {
private Logger logger = LoggerFactory.getLogger(DeviceGovernorImpl.class);
private final BluetoothManagerImpl bluetoothManager;
private final URL url;
private final Map<URL, DeviceGovernorHandler> governors = new ConcurrentHashMap<>();
private final List<GovernorListener> governorListeners = new CopyOnWriteArrayList<>();
private final List<GenericBluetoothDeviceListener> genericBluetoothDeviceListeners = new CopyOnWriteArrayList<>();
private final List<BluetoothSmartDeviceListener> bluetoothSmartDeviceListeners = new CopyOnWriteArrayList<>();
private final AtomicLong ready = new AtomicLong();
private final AtomicLong online = new AtomicLong();
private final AtomicLong blocked = new AtomicLong();
private final AtomicLong connected = new AtomicLong();
private final AtomicLong servicesResolved = new AtomicLong();
private final AtomicInteger governorsCount = new AtomicInteger();
private int bluetoothClass;
private boolean bleEnabled;
private String name;
private String alias;
private int onlineTimeout;
private short rssi;
private boolean rssiFilteringEnabled = true;
private long rssiReportingRate = 1000;
private short measuredTxPower;
private double signalPropagationExponent = DeviceGovernorImpl.DEAFULT_SIGNAL_PROPAGATION_EXPONENT;
private Date lastChanged;
private boolean connectionControl;
private boolean blockedControl;
SharedDeviceGovernorImpl(BluetoothManagerImpl bluetoothManager, URL url) {
this.bluetoothManager = bluetoothManager;
this.url = url;
this.bluetoothManager.addDeviceDiscoveryListener(this);
this.bluetoothManager.getRegisteredGovernors().forEach(this::registerGovernor);
this.bluetoothManager.getDiscoveredDevices().stream().map(DiscoveredDevice::getURL)
.forEach(this::registerGovernor);
}
@Override
public int getBluetoothClass() throws NotReadyException {
return bluetoothClass;
}
@Override
public boolean isBleEnabled() throws NotReadyException {
return bleEnabled;
}
@Override
public String getName() throws NotReadyException {
return name != null ? name : url.getDeviceAddress();
}
@Override
public String getAlias() throws NotReadyException {
return alias;
}
@Override
public void setAlias(String alias) throws NotReadyException {
governors.values().forEach(deviceGovernorHandler -> {
if (deviceGovernorHandler.deviceGovernor.isReady()) {
deviceGovernorHandler.deviceGovernor.setAlias(alias);
}
});
}
@Override
public String getDisplayName() throws NotReadyException {
String alias = getAlias();
return alias != null ? alias : getName();
}
@Override
public boolean isConnected() throws NotReadyException {
return connected.get() > 0;
}
@Override
public boolean getConnectionControl() {
return connectionControl;
}
@Override
public void setConnectionControl(boolean connected) {
connectionControl = connected;
governors.values().forEach(
deviceGovernorHandler -> deviceGovernorHandler.deviceGovernor.setConnectionControl(connected));
}
@Override
public boolean isBlocked() throws NotReadyException {
return blocked.get() > 0;
}
@Override
public boolean getBlockedControl() {
return blockedControl;
}
@Override
public void setBlockedControl(boolean blocked) {
blockedControl = blocked;
governors.values().forEach(
deviceGovernorHandler -> deviceGovernorHandler.deviceGovernor.setBlockedControl(blocked));
}
@Override
public boolean isOnline() {
return online.get() > 0;
}
@Override
public int getOnlineTimeout() {
return onlineTimeout;
}
@Override
public void setOnlineTimeout(int timeout) {
onlineTimeout = timeout;
governors.values().forEach(
deviceGovernorHandler -> deviceGovernorHandler.deviceGovernor.setOnlineTimeout(timeout));
}
@Override
public short getRSSI() throws NotReadyException {
return rssi;
}
@Override
public short getTxPower() {
return 0;
}
@Override
public short getMeasuredTxPower() {
return measuredTxPower;
}
@Override
public void setMeasuredTxPower(short txPower) {
measuredTxPower = txPower;
governors.values().forEach(
deviceGovernorHandler -> deviceGovernorHandler.deviceGovernor.setMeasuredTxPower(txPower));
}
@Override
public double getSignalPropagationExponent() {
return signalPropagationExponent;
}
@Override
public void setSignalPropagationExponent(double exponent) {
signalPropagationExponent = exponent;
governors.values().forEach(
deviceGovernorHandler -> deviceGovernorHandler.deviceGovernor.setSignalPropagationExponent(exponent));
}
@Override
public double getEstimatedDistance() {
return 0;
}
@Override
public void addBluetoothSmartDeviceListener(BluetoothSmartDeviceListener listener) {
bluetoothSmartDeviceListeners.add(listener);
}
@Override
public void removeBluetoothSmartDeviceListener(BluetoothSmartDeviceListener listener) {
bluetoothSmartDeviceListeners.remove(listener);
}
@Override
public void addGenericBluetoothDeviceListener(GenericBluetoothDeviceListener listener) {
genericBluetoothDeviceListeners.add(listener);
}
@Override
public void removeGenericBluetoothDeviceListener(GenericBluetoothDeviceListener listener) {
genericBluetoothDeviceListeners.remove(listener);
}
@Override
public void addGovernorListener(GovernorListener listener) {
governorListeners.add(listener);
}
@Override
public void removeGovernorListener(GovernorListener listener) {
governorListeners.remove(listener);
}
@Override
public Map<URL, List<CharacteristicGovernor>> getServicesToCharacteristicsMap() throws NotReadyException {
return null;
}
@Override
public List<URL> getCharacteristics() throws NotReadyException {
return null;
}
@Override
public List<CharacteristicGovernor> getCharacteristicGovernors() throws NotReadyException {
return null;
}
@Override
public URL getURL() {
return url;
}
@Override
public boolean isReady() {
return ready.get() > 0;
}
@Override
public BluetoothObjectType getType() {
return BluetoothObjectType.DEVICE;
}
@Override
public Date getLastActivity() {
return lastChanged;
}
@Override
public void accept(BluetoothObjectVisitor visitor) throws Exception {
visitor.visit(this);
}
@Override
public void discovered(DiscoveredDevice discoveredDevice) {
registerGovernor(discoveredDevice.getURL());
}
@Override
public void deviceLost(URL url) { /* do nothing */ }
@Override
public void update() { /* do nothing */ }
@Override
public void reset() { /* do nothing */ }
@Override
public void setRssiFilter(Filter<Short> filter) {
throw new IllegalStateException("Not supported by group governor");
}
@Override
public Filter<Short> getRssiFilter() {
return null;
}
@Override
public boolean isRssiFilteringEnabled() {
return rssiFilteringEnabled;
}
@Override
public void setRssiFilteringEnabled(boolean enabled) {
rssiFilteringEnabled = enabled;
governors.values().forEach(
deviceGovernorHandler -> deviceGovernorHandler.deviceGovernor.setRssiFilteringEnabled(enabled));
}
@Override
public void setRssiReportingRate(long rate) {
rssiReportingRate = rate;
governors.values().forEach(
deviceGovernorHandler -> deviceGovernorHandler.deviceGovernor.setRssiReportingRate(rate));
}
@Override
public long getRssiReportingRate() {
return rssiReportingRate;
}
private void registerGovernor(URL url) {
if (governorsCount.get() > 63) {
throw new IllegalStateException("Shared Device Governor can only span upto 63 device governors.");
}
if (url.isDevice() && this.url.getDeviceAddress().equals(url.getDeviceAddress())) {
governors.computeIfAbsent(url, newUrl -> {
DeviceGovernor deviceGovernor = BluetoothManagerFactory.getManager().getDeviceGovernor(url);
return new DeviceGovernorHandler(deviceGovernor, governorsCount.getAndIncrement());
});
}
}
private void updateLastUpdated(Date lastActivity) {
if (lastChanged == null || lastChanged.before(lastActivity)) {
lastChanged = lastActivity;
BluetoothManagerUtils.safeForEachError(governorListeners, listener -> {
listener.lastUpdatedChanged(lastActivity);
}, logger, "Execution error of a governor listener: last changed");
}
}
private void updateRssi(short newRssi) {
rssi = newRssi;
BluetoothManagerUtils.safeForEachError(genericBluetoothDeviceListeners, listener -> {
listener.rssiChanged(newRssi);
}, logger, "Execution error of a RSSI listener");
}
private final class DeviceGovernorHandler
implements GovernorListener, BluetoothSmartDeviceListener, GenericBluetoothDeviceListener {
private final DeviceGovernor deviceGovernor;
private final int index;
Lock rssiUpdateLock = new ReentrantLock();
private Queue<Short> rssi = EvictingQueue.create(10);
private short rssiAverage;
private DeviceGovernorHandler(DeviceGovernor deviceGovernor, int index) {
this.deviceGovernor = deviceGovernor;
this.index = index;
this.deviceGovernor.addBluetoothSmartDeviceListener(this);
this.deviceGovernor.addGenericBluetoothDeviceListener(this);
this.deviceGovernor.addGovernorListener(this);
if (deviceGovernor.isReady()) {
name = deviceGovernor.getName();
int deviceBluetoothClass = deviceGovernor.getBluetoothClass();
if (deviceBluetoothClass != 0) {
bluetoothClass = deviceBluetoothClass;
}
bleEnabled |= deviceGovernor.isBleEnabled();
String deviceAlias = deviceGovernor.getAlias();
if (deviceAlias != null) {
alias = deviceAlias;
}
updateRssi(deviceGovernor.getRSSI());
ready(true);
}
deviceGovernor.setOnlineTimeout(onlineTimeout);
deviceGovernor.setConnectionControl(connectionControl);
deviceGovernor.setBlockedControl(blockedControl);
deviceGovernor.setRssiFilteringEnabled(rssiFilteringEnabled);
deviceGovernor.setRssiReportingRate(rssiReportingRate);
deviceGovernor.setSignalPropagationExponent(signalPropagationExponent);
deviceGovernor.setMeasuredTxPower(measuredTxPower);
Date lastActivity = deviceGovernor.getLastActivity();
if (lastActivity != null) {
updateLastUpdated(lastActivity);
}
}
@Override
public void connected() {
notifyConnected(true);
}
@Override
public void disconnected() {
notifyConnected(false);
}
@Override
public void servicesResolved(List<GattService> gattServices) {
BluetoothManagerUtils.setState(servicesResolved, index, true,
() -> {
notifyServicesResolved(gattServices);
}, () -> {
notifyServicesUnresolved();
notifyServicesResolved(gattServices);
}
);
}
@Override
public void servicesUnresolved() {
BluetoothManagerUtils.setState(servicesResolved, index, false, () -> {
BluetoothManagerUtils.safeForEachError(bluetoothSmartDeviceListeners,
BluetoothSmartDeviceListener::servicesUnresolved,
logger, "Execution error of a service resolved listener");
});
}
@Override
public void online() {
notifyOnline(true);
}
@Override
public void offline() {
notifyOnline(false);
}
@Override
public void blocked(boolean newState) {
BluetoothManagerUtils.setState(blocked, index, newState, () -> {
BluetoothManagerUtils.safeForEachError(genericBluetoothDeviceListeners, listener -> {
listener.blocked(newState);
}, logger, "Execution error of a Blocked listener");
});
}
@Override
public void rssiChanged(short newRssi) {
if (rssiUpdateLock.tryLock()) {
try {
// the device reports RSSI too fast that we can't handle it, so we skip some readings
rssi.add(newRssi);
short average = (short) rssi.stream().mapToInt(Short::intValue).average().orElse(0);
if (rssiAverage != average) {
updateRssi(average);
}
rssiAverage = average;
} finally {
rssiUpdateLock.unlock();
}
}
}
@Override
public void ready(boolean isReady) {
notifyReady(isReady);
}
@Override
public void lastUpdatedChanged(Date lastActivity) {
updateLastUpdated(lastActivity);
}
private void notifyOnline(boolean newState) {
BluetoothManagerUtils.setState(online, index, newState, () -> {
BluetoothManagerUtils.safeForEachError(genericBluetoothDeviceListeners, listener -> {
if (newState) {
listener.online();
} else {
listener.offline();
}
}, logger, "Execution error of an online listener");
});
}
private void notifyReady(boolean newState) {
BluetoothManagerUtils.setState(ready, index, newState, () -> {
BluetoothManagerUtils.safeForEachError(governorListeners, listener -> {
listener.ready(newState);
}, logger, "Execution error of a governor listener: ready");
});
}
private void notifyConnected(boolean connected) {
BluetoothManagerUtils.safeForEachError(bluetoothSmartDeviceListeners, listener -> {
if (connected) {
listener.connected();
} else {
listener.disconnected();
}
}, logger, "Execution error of a connection listener");
}
private void notifyServicesResolved(List<GattService> services) {
BluetoothManagerUtils.safeForEachError(bluetoothSmartDeviceListeners, listener -> {
listener.servicesResolved(services);
}, logger, "Execution error of a service resolved listener");
}
private void notifyServicesUnresolved() {
BluetoothManagerUtils.safeForEachError(bluetoothSmartDeviceListeners,
BluetoothSmartDeviceListener::servicesUnresolved,
logger, "Execution error of a service resolved listener");
}
}
}
| UTF-8 | Java | 17,324 | java | SharedDeviceGovernorImpl.java | Java | [] | null | [] | package org.sputnikdev.bluetooth.manager.impl;
import com.google.common.collect.EvictingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sputnikdev.bluetooth.Filter;
import org.sputnikdev.bluetooth.URL;
import org.sputnikdev.bluetooth.manager.BluetoothObjectType;
import org.sputnikdev.bluetooth.manager.BluetoothObjectVisitor;
import org.sputnikdev.bluetooth.manager.BluetoothSmartDeviceListener;
import org.sputnikdev.bluetooth.manager.CharacteristicGovernor;
import org.sputnikdev.bluetooth.manager.DeviceDiscoveryListener;
import org.sputnikdev.bluetooth.manager.DeviceGovernor;
import org.sputnikdev.bluetooth.manager.DiscoveredDevice;
import org.sputnikdev.bluetooth.manager.GattService;
import org.sputnikdev.bluetooth.manager.GenericBluetoothDeviceListener;
import org.sputnikdev.bluetooth.manager.GovernorListener;
import org.sputnikdev.bluetooth.manager.NotReadyException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class SharedDeviceGovernorImpl implements DeviceGovernor, BluetoothObjectGovernor, DeviceDiscoveryListener {
private Logger logger = LoggerFactory.getLogger(DeviceGovernorImpl.class);
private final BluetoothManagerImpl bluetoothManager;
private final URL url;
private final Map<URL, DeviceGovernorHandler> governors = new ConcurrentHashMap<>();
private final List<GovernorListener> governorListeners = new CopyOnWriteArrayList<>();
private final List<GenericBluetoothDeviceListener> genericBluetoothDeviceListeners = new CopyOnWriteArrayList<>();
private final List<BluetoothSmartDeviceListener> bluetoothSmartDeviceListeners = new CopyOnWriteArrayList<>();
private final AtomicLong ready = new AtomicLong();
private final AtomicLong online = new AtomicLong();
private final AtomicLong blocked = new AtomicLong();
private final AtomicLong connected = new AtomicLong();
private final AtomicLong servicesResolved = new AtomicLong();
private final AtomicInteger governorsCount = new AtomicInteger();
private int bluetoothClass;
private boolean bleEnabled;
private String name;
private String alias;
private int onlineTimeout;
private short rssi;
private boolean rssiFilteringEnabled = true;
private long rssiReportingRate = 1000;
private short measuredTxPower;
private double signalPropagationExponent = DeviceGovernorImpl.DEAFULT_SIGNAL_PROPAGATION_EXPONENT;
private Date lastChanged;
private boolean connectionControl;
private boolean blockedControl;
SharedDeviceGovernorImpl(BluetoothManagerImpl bluetoothManager, URL url) {
this.bluetoothManager = bluetoothManager;
this.url = url;
this.bluetoothManager.addDeviceDiscoveryListener(this);
this.bluetoothManager.getRegisteredGovernors().forEach(this::registerGovernor);
this.bluetoothManager.getDiscoveredDevices().stream().map(DiscoveredDevice::getURL)
.forEach(this::registerGovernor);
}
@Override
public int getBluetoothClass() throws NotReadyException {
return bluetoothClass;
}
@Override
public boolean isBleEnabled() throws NotReadyException {
return bleEnabled;
}
@Override
public String getName() throws NotReadyException {
return name != null ? name : url.getDeviceAddress();
}
@Override
public String getAlias() throws NotReadyException {
return alias;
}
@Override
public void setAlias(String alias) throws NotReadyException {
governors.values().forEach(deviceGovernorHandler -> {
if (deviceGovernorHandler.deviceGovernor.isReady()) {
deviceGovernorHandler.deviceGovernor.setAlias(alias);
}
});
}
@Override
public String getDisplayName() throws NotReadyException {
String alias = getAlias();
return alias != null ? alias : getName();
}
@Override
public boolean isConnected() throws NotReadyException {
return connected.get() > 0;
}
@Override
public boolean getConnectionControl() {
return connectionControl;
}
@Override
public void setConnectionControl(boolean connected) {
connectionControl = connected;
governors.values().forEach(
deviceGovernorHandler -> deviceGovernorHandler.deviceGovernor.setConnectionControl(connected));
}
@Override
public boolean isBlocked() throws NotReadyException {
return blocked.get() > 0;
}
@Override
public boolean getBlockedControl() {
return blockedControl;
}
@Override
public void setBlockedControl(boolean blocked) {
blockedControl = blocked;
governors.values().forEach(
deviceGovernorHandler -> deviceGovernorHandler.deviceGovernor.setBlockedControl(blocked));
}
@Override
public boolean isOnline() {
return online.get() > 0;
}
@Override
public int getOnlineTimeout() {
return onlineTimeout;
}
@Override
public void setOnlineTimeout(int timeout) {
onlineTimeout = timeout;
governors.values().forEach(
deviceGovernorHandler -> deviceGovernorHandler.deviceGovernor.setOnlineTimeout(timeout));
}
@Override
public short getRSSI() throws NotReadyException {
return rssi;
}
@Override
public short getTxPower() {
return 0;
}
@Override
public short getMeasuredTxPower() {
return measuredTxPower;
}
@Override
public void setMeasuredTxPower(short txPower) {
measuredTxPower = txPower;
governors.values().forEach(
deviceGovernorHandler -> deviceGovernorHandler.deviceGovernor.setMeasuredTxPower(txPower));
}
@Override
public double getSignalPropagationExponent() {
return signalPropagationExponent;
}
@Override
public void setSignalPropagationExponent(double exponent) {
signalPropagationExponent = exponent;
governors.values().forEach(
deviceGovernorHandler -> deviceGovernorHandler.deviceGovernor.setSignalPropagationExponent(exponent));
}
@Override
public double getEstimatedDistance() {
return 0;
}
@Override
public void addBluetoothSmartDeviceListener(BluetoothSmartDeviceListener listener) {
bluetoothSmartDeviceListeners.add(listener);
}
@Override
public void removeBluetoothSmartDeviceListener(BluetoothSmartDeviceListener listener) {
bluetoothSmartDeviceListeners.remove(listener);
}
@Override
public void addGenericBluetoothDeviceListener(GenericBluetoothDeviceListener listener) {
genericBluetoothDeviceListeners.add(listener);
}
@Override
public void removeGenericBluetoothDeviceListener(GenericBluetoothDeviceListener listener) {
genericBluetoothDeviceListeners.remove(listener);
}
@Override
public void addGovernorListener(GovernorListener listener) {
governorListeners.add(listener);
}
@Override
public void removeGovernorListener(GovernorListener listener) {
governorListeners.remove(listener);
}
@Override
public Map<URL, List<CharacteristicGovernor>> getServicesToCharacteristicsMap() throws NotReadyException {
return null;
}
@Override
public List<URL> getCharacteristics() throws NotReadyException {
return null;
}
@Override
public List<CharacteristicGovernor> getCharacteristicGovernors() throws NotReadyException {
return null;
}
@Override
public URL getURL() {
return url;
}
@Override
public boolean isReady() {
return ready.get() > 0;
}
@Override
public BluetoothObjectType getType() {
return BluetoothObjectType.DEVICE;
}
@Override
public Date getLastActivity() {
return lastChanged;
}
@Override
public void accept(BluetoothObjectVisitor visitor) throws Exception {
visitor.visit(this);
}
@Override
public void discovered(DiscoveredDevice discoveredDevice) {
registerGovernor(discoveredDevice.getURL());
}
@Override
public void deviceLost(URL url) { /* do nothing */ }
@Override
public void update() { /* do nothing */ }
@Override
public void reset() { /* do nothing */ }
@Override
public void setRssiFilter(Filter<Short> filter) {
throw new IllegalStateException("Not supported by group governor");
}
@Override
public Filter<Short> getRssiFilter() {
return null;
}
@Override
public boolean isRssiFilteringEnabled() {
return rssiFilteringEnabled;
}
@Override
public void setRssiFilteringEnabled(boolean enabled) {
rssiFilteringEnabled = enabled;
governors.values().forEach(
deviceGovernorHandler -> deviceGovernorHandler.deviceGovernor.setRssiFilteringEnabled(enabled));
}
@Override
public void setRssiReportingRate(long rate) {
rssiReportingRate = rate;
governors.values().forEach(
deviceGovernorHandler -> deviceGovernorHandler.deviceGovernor.setRssiReportingRate(rate));
}
@Override
public long getRssiReportingRate() {
return rssiReportingRate;
}
private void registerGovernor(URL url) {
if (governorsCount.get() > 63) {
throw new IllegalStateException("Shared Device Governor can only span upto 63 device governors.");
}
if (url.isDevice() && this.url.getDeviceAddress().equals(url.getDeviceAddress())) {
governors.computeIfAbsent(url, newUrl -> {
DeviceGovernor deviceGovernor = BluetoothManagerFactory.getManager().getDeviceGovernor(url);
return new DeviceGovernorHandler(deviceGovernor, governorsCount.getAndIncrement());
});
}
}
private void updateLastUpdated(Date lastActivity) {
if (lastChanged == null || lastChanged.before(lastActivity)) {
lastChanged = lastActivity;
BluetoothManagerUtils.safeForEachError(governorListeners, listener -> {
listener.lastUpdatedChanged(lastActivity);
}, logger, "Execution error of a governor listener: last changed");
}
}
private void updateRssi(short newRssi) {
rssi = newRssi;
BluetoothManagerUtils.safeForEachError(genericBluetoothDeviceListeners, listener -> {
listener.rssiChanged(newRssi);
}, logger, "Execution error of a RSSI listener");
}
private final class DeviceGovernorHandler
implements GovernorListener, BluetoothSmartDeviceListener, GenericBluetoothDeviceListener {
private final DeviceGovernor deviceGovernor;
private final int index;
Lock rssiUpdateLock = new ReentrantLock();
private Queue<Short> rssi = EvictingQueue.create(10);
private short rssiAverage;
private DeviceGovernorHandler(DeviceGovernor deviceGovernor, int index) {
this.deviceGovernor = deviceGovernor;
this.index = index;
this.deviceGovernor.addBluetoothSmartDeviceListener(this);
this.deviceGovernor.addGenericBluetoothDeviceListener(this);
this.deviceGovernor.addGovernorListener(this);
if (deviceGovernor.isReady()) {
name = deviceGovernor.getName();
int deviceBluetoothClass = deviceGovernor.getBluetoothClass();
if (deviceBluetoothClass != 0) {
bluetoothClass = deviceBluetoothClass;
}
bleEnabled |= deviceGovernor.isBleEnabled();
String deviceAlias = deviceGovernor.getAlias();
if (deviceAlias != null) {
alias = deviceAlias;
}
updateRssi(deviceGovernor.getRSSI());
ready(true);
}
deviceGovernor.setOnlineTimeout(onlineTimeout);
deviceGovernor.setConnectionControl(connectionControl);
deviceGovernor.setBlockedControl(blockedControl);
deviceGovernor.setRssiFilteringEnabled(rssiFilteringEnabled);
deviceGovernor.setRssiReportingRate(rssiReportingRate);
deviceGovernor.setSignalPropagationExponent(signalPropagationExponent);
deviceGovernor.setMeasuredTxPower(measuredTxPower);
Date lastActivity = deviceGovernor.getLastActivity();
if (lastActivity != null) {
updateLastUpdated(lastActivity);
}
}
@Override
public void connected() {
notifyConnected(true);
}
@Override
public void disconnected() {
notifyConnected(false);
}
@Override
public void servicesResolved(List<GattService> gattServices) {
BluetoothManagerUtils.setState(servicesResolved, index, true,
() -> {
notifyServicesResolved(gattServices);
}, () -> {
notifyServicesUnresolved();
notifyServicesResolved(gattServices);
}
);
}
@Override
public void servicesUnresolved() {
BluetoothManagerUtils.setState(servicesResolved, index, false, () -> {
BluetoothManagerUtils.safeForEachError(bluetoothSmartDeviceListeners,
BluetoothSmartDeviceListener::servicesUnresolved,
logger, "Execution error of a service resolved listener");
});
}
@Override
public void online() {
notifyOnline(true);
}
@Override
public void offline() {
notifyOnline(false);
}
@Override
public void blocked(boolean newState) {
BluetoothManagerUtils.setState(blocked, index, newState, () -> {
BluetoothManagerUtils.safeForEachError(genericBluetoothDeviceListeners, listener -> {
listener.blocked(newState);
}, logger, "Execution error of a Blocked listener");
});
}
@Override
public void rssiChanged(short newRssi) {
if (rssiUpdateLock.tryLock()) {
try {
// the device reports RSSI too fast that we can't handle it, so we skip some readings
rssi.add(newRssi);
short average = (short) rssi.stream().mapToInt(Short::intValue).average().orElse(0);
if (rssiAverage != average) {
updateRssi(average);
}
rssiAverage = average;
} finally {
rssiUpdateLock.unlock();
}
}
}
@Override
public void ready(boolean isReady) {
notifyReady(isReady);
}
@Override
public void lastUpdatedChanged(Date lastActivity) {
updateLastUpdated(lastActivity);
}
private void notifyOnline(boolean newState) {
BluetoothManagerUtils.setState(online, index, newState, () -> {
BluetoothManagerUtils.safeForEachError(genericBluetoothDeviceListeners, listener -> {
if (newState) {
listener.online();
} else {
listener.offline();
}
}, logger, "Execution error of an online listener");
});
}
private void notifyReady(boolean newState) {
BluetoothManagerUtils.setState(ready, index, newState, () -> {
BluetoothManagerUtils.safeForEachError(governorListeners, listener -> {
listener.ready(newState);
}, logger, "Execution error of a governor listener: ready");
});
}
private void notifyConnected(boolean connected) {
BluetoothManagerUtils.safeForEachError(bluetoothSmartDeviceListeners, listener -> {
if (connected) {
listener.connected();
} else {
listener.disconnected();
}
}, logger, "Execution error of a connection listener");
}
private void notifyServicesResolved(List<GattService> services) {
BluetoothManagerUtils.safeForEachError(bluetoothSmartDeviceListeners, listener -> {
listener.servicesResolved(services);
}, logger, "Execution error of a service resolved listener");
}
private void notifyServicesUnresolved() {
BluetoothManagerUtils.safeForEachError(bluetoothSmartDeviceListeners,
BluetoothSmartDeviceListener::servicesUnresolved,
logger, "Execution error of a service resolved listener");
}
}
}
| 17,324 | 0.658104 | 0.65695 | 511 | 32.902153 | 29.277508 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.463796 | false | false | 4 |
8b7aa220a29eeee09903f320de2b90633cdf2ff5 | 38,216,619,014,410 | 486b466356472d19f1730045d891523141ea21dd | /app/src/main/java/com/example/katip/appcuario/act_home.java | 52cc2996c0af3e8a3e1fd70a60f2724ca26a1f54 | [] | no_license | kalbus/ProyectoAppcuario | https://github.com/kalbus/ProyectoAppcuario | ea275a5ab3c1fe640ebaf54bc2ca696770293def | 53ec818d6ab05ca61f2538650f8736c2bff66dbb | refs/heads/master | 2020-03-17T18:42:23.857000 | 2018-07-05T16:26:58 | 2018-07-05T16:26:58 | 133,830,393 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.katip.appcuario;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.example.katip.appcuario.MODELO.Pecera;
import com.example.katip.appcuario.MODELO.RegistroPecera;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class act_home extends AppCompatActivity {
private RegistroPecera registroPecera= new RegistroPecera();
RecyclerviewAdapterPeceras adapterPecera;
RecyclerView listaE;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lyt_home);
//Personalización
setTitle("Selecciona la pecera - Select the fish tank");
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.drawable.ic_logo);
//Fin de la personalización
listaE= findViewById(R.id.lista_E);
//URL base
final String url= "http://10.0.2.2:8000/api/";
// Objeto Retrofit inicializado
Retrofit retrofit= new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
//llamada de la interfaz
Servicios services = retrofit.create(Servicios.class);
Call<List<Pecera>> call= services.listaPeceras();
call.enqueue(new Callback<List<Pecera>>() {
@Override
public void onResponse(Call<List<Pecera>> call, Response<List<Pecera>> response) {
for (Pecera pecera: response.body()) {// body() tiene la lista de los datos
registroPecera.agregarPecera(pecera);
}
//Llenar el recycler view con las cartes de las peceras
adapterPecera= new RecyclerviewAdapterPeceras(act_home.this,registroPecera.getListaPeceras());
listaE.setLayoutManager(new GridLayoutManager(act_home.this,4));
listaE.setAdapter(adapterPecera);
}
@Override
public void onFailure(Call<List<Pecera>> call, Throwable t) {
Log.e("Algo Fallo",t.toString());
}
});
}
/**
* Método para añadir soporte al menú personalizado
* @param menu
* @return
*/
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_home, menu);
return true;
}
/**
* Eventos de los items del menu_home
* @param item
* @return
*/
public boolean onOptionsItemSelected(MenuItem item){
//Rsponde a los eventos del menu_home
switch (item.getItemId()){
case R.id.item_about:
//cargar activity de acerca
startActivity(new Intent(getApplicationContext(), act_acerca.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
| UTF-8 | Java | 3,516 | java | act_home.java | Java | [
{
"context": " //URL base\n final String url= \"http://10.0.2.2:8000/api/\";\n\n // Objeto Retrofit inicializa",
"end": 1425,
"score": 0.9973368644714355,
"start": 1417,
"tag": "IP_ADDRESS",
"value": "10.0.2.2"
}
] | null | [] | package com.example.katip.appcuario;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.example.katip.appcuario.MODELO.Pecera;
import com.example.katip.appcuario.MODELO.RegistroPecera;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class act_home extends AppCompatActivity {
private RegistroPecera registroPecera= new RegistroPecera();
RecyclerviewAdapterPeceras adapterPecera;
RecyclerView listaE;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lyt_home);
//Personalización
setTitle("Selecciona la pecera - Select the fish tank");
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.drawable.ic_logo);
//Fin de la personalización
listaE= findViewById(R.id.lista_E);
//URL base
final String url= "http://10.0.2.2:8000/api/";
// Objeto Retrofit inicializado
Retrofit retrofit= new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
//llamada de la interfaz
Servicios services = retrofit.create(Servicios.class);
Call<List<Pecera>> call= services.listaPeceras();
call.enqueue(new Callback<List<Pecera>>() {
@Override
public void onResponse(Call<List<Pecera>> call, Response<List<Pecera>> response) {
for (Pecera pecera: response.body()) {// body() tiene la lista de los datos
registroPecera.agregarPecera(pecera);
}
//Llenar el recycler view con las cartes de las peceras
adapterPecera= new RecyclerviewAdapterPeceras(act_home.this,registroPecera.getListaPeceras());
listaE.setLayoutManager(new GridLayoutManager(act_home.this,4));
listaE.setAdapter(adapterPecera);
}
@Override
public void onFailure(Call<List<Pecera>> call, Throwable t) {
Log.e("Algo Fallo",t.toString());
}
});
}
/**
* Método para añadir soporte al menú personalizado
* @param menu
* @return
*/
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_home, menu);
return true;
}
/**
* Eventos de los items del menu_home
* @param item
* @return
*/
public boolean onOptionsItemSelected(MenuItem item){
//Rsponde a los eventos del menu_home
switch (item.getItemId()){
case R.id.item_about:
//cargar activity de acerca
startActivity(new Intent(getApplicationContext(), act_acerca.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 3,516 | 0.638849 | 0.633438 | 106 | 32.122643 | 25.53529 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.490566 | false | false | 4 |
91d691b343b30649b59b6fb1d5f4bd8a1cf7dd2f | 38,860,864,135,895 | b6c01ab1734a0c224658f183b9b30635fd635ab4 | /g+20181022/.svn/pristine/2d/2d2205192926d7c97b6e51bef7879a5950955b3a.svn-base | cb349d10a96b433fc7329e2eb824d69f4967c656 | [] | no_license | GaoFuq/g-20181022 | https://github.com/GaoFuq/g-20181022 | 66f16d72db9b8b2e24725cde64dc0d10ecb0d311 | a5cd1d1acce9e1b4b2b2cfe8e6e18bf6ce12e069 | refs/heads/master | 2020-05-17T08:36:07.856000 | 2019-04-28T01:21:37 | 2019-04-28T01:21:37 | 183,607,932 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lf.tempcore.tempAdapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.lang.ref.WeakReference;
import java.util.List;
public abstract class TempListAdapter<D, H> extends
BaseAdapter {
private List<D> data;
WeakReference<Context> mContext;
private LayoutInflater inflater;
// private Context context;
private int srcId;
public List<D> getData() {
return data;
}
public void setData(List<D> data) {
this.data = data;
}
public TempListAdapter(List<D> data, Context context, int layoutId) {
super();
this.data = data;
mContext = new WeakReference<>(context);
// this.context = context;
this.srcId = layoutId;
}
/**
* 创建holder
*
* @return 返回holder对象
*/
protected abstract H createHolder();
/**
* 初始化holder的成员
*/
protected abstract void initHolder(int position, View v, H holder);
/**
* 绑定holer值用来显示
*/
public abstract void bunldHolderValue(int position, H holder, D item);
@Override
public int getCount() {
// TODO Auto-generated method stub
return data == null ? 0 : data.size();
}
@Override
public D getItem(int position) {
// TODO Auto-generated method stub
return data.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View rootView = convertView;
H holder;
if (rootView != null) {
holder = (H) rootView.getTag();
} else {
holder = createHolder();
rootView = this.getLayoutInflater().inflate(srcId, null);
initHolder(position, rootView, holder);
rootView.setTag(holder);
}
bunldHolderValue(position, holder, getItem(position));
return rootView;
}
/**
* 添加新数据
*
* @param data 新数据
*/
public void upDateLoadMore(List<D> data) {
if (this.data!=null){
this.data.addAll(data);
notifyDataSetChanged();
}
}
/**
* 刷新数据
*
* @param data 刷新数据
*/
public void upDateReflash(List<D> data) {
// this.data.clear();
// this.data.addAll(data);
if (this.data!=null){
this.data = data;
notifyDataSetChanged();
}
}
private LayoutInflater getLayoutInflater() {
// if (inflater==null) {
// inflater = LayoutInflater.from(context);
// }
return inflater == null ? LayoutInflater.from(getTempContext()) : inflater;
}
public Context getTempContext() {
// if (mContext.get() == null) {
// mContext = new WeakReference<>(TempActivity.this);
// }
return mContext.get();
}
// protected String makeImageUrl(String url) {
// if (TextUtils.isEmpty(url)) {
// return "";
// }
// return context.getResources().getString(R.string.image_head) + url;
// }
//
// protected String makeImageUrl(String url, int width, int height) {
// if (TextUtils.isEmpty(url))
// return "";
// if (TextUtils.isEmpty(width + "") || TextUtils.isEmpty(height + ""))
// return context.getResources().getString(R.string.image_head) + url + "&imgwidth=" + width + "&imgheight=" + height;
// return context.getResources().getString(R.string.image_head) + url;
// }
// /**
// * ImageView绑定加载图片
// *
// * @param imageView
// * @param url 图片地址 example:file:///sdcard/test.gif; assets://test.gif; http://www.test.com/x
// */
// protected void bindImageView(ImageView imageView, String url) {
//// Debug.info("BindImageUrl=" + url);
// x.image().bind(imageView, url);
// }
//
// /**
// * ImageView绑定加载图片
// *
// * @param imageView
// * @param url 图片地址 example:file:///sdcard/test.gif; assets://test.gif; http://www.test.com/x
// * @param callback 图片加载回调
// */
// protected void bindImageView(ImageView imageView, String url, Callback.CommonCallback<Drawable> callback) {
//// Debug.info("BindImageUrl=" + url);
// x.image().bind(imageView, url, callback);
// }
//
// /**
// * ImageView绑定加载图片
// *
// * @param imageView
// * @param url 图片地址 example:file:///sdcard/test.gif; assets://test.gif; http://www.test.com/x
// * @param option 加载设置类
// */
// protected void bindImageView(ImageView imageView, String url, ImageOptions option) {
//// Debug.info("BindImageUrl=" + url);
// x.image().bind(imageView, url, option);
// }
//
// /**
// * ImageView绑定加载图片
// *
// * @param imageView
// * @param url 图片地址 example:file:///sdcard/test.gif; assets://test.gif; http://www.test.com/x
// * @param option 加载设置类
// * @param callback 加载回调
// */
// protected void binImageView(ImageView imageView, String url, ImageOptions option, Callback.CommonCallback<Drawable> callback) {
//// Debug.info("BindImageUrl=" + url);
// x.image().bind(imageView, url, option, callback);
// }
}
| UTF-8 | Java | 5,653 | 2d2205192926d7c97b6e51bef7879a5950955b3a.svn-base | Java | [] | null | [] | package com.lf.tempcore.tempAdapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.lang.ref.WeakReference;
import java.util.List;
public abstract class TempListAdapter<D, H> extends
BaseAdapter {
private List<D> data;
WeakReference<Context> mContext;
private LayoutInflater inflater;
// private Context context;
private int srcId;
public List<D> getData() {
return data;
}
public void setData(List<D> data) {
this.data = data;
}
public TempListAdapter(List<D> data, Context context, int layoutId) {
super();
this.data = data;
mContext = new WeakReference<>(context);
// this.context = context;
this.srcId = layoutId;
}
/**
* 创建holder
*
* @return 返回holder对象
*/
protected abstract H createHolder();
/**
* 初始化holder的成员
*/
protected abstract void initHolder(int position, View v, H holder);
/**
* 绑定holer值用来显示
*/
public abstract void bunldHolderValue(int position, H holder, D item);
@Override
public int getCount() {
// TODO Auto-generated method stub
return data == null ? 0 : data.size();
}
@Override
public D getItem(int position) {
// TODO Auto-generated method stub
return data.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View rootView = convertView;
H holder;
if (rootView != null) {
holder = (H) rootView.getTag();
} else {
holder = createHolder();
rootView = this.getLayoutInflater().inflate(srcId, null);
initHolder(position, rootView, holder);
rootView.setTag(holder);
}
bunldHolderValue(position, holder, getItem(position));
return rootView;
}
/**
* 添加新数据
*
* @param data 新数据
*/
public void upDateLoadMore(List<D> data) {
if (this.data!=null){
this.data.addAll(data);
notifyDataSetChanged();
}
}
/**
* 刷新数据
*
* @param data 刷新数据
*/
public void upDateReflash(List<D> data) {
// this.data.clear();
// this.data.addAll(data);
if (this.data!=null){
this.data = data;
notifyDataSetChanged();
}
}
private LayoutInflater getLayoutInflater() {
// if (inflater==null) {
// inflater = LayoutInflater.from(context);
// }
return inflater == null ? LayoutInflater.from(getTempContext()) : inflater;
}
public Context getTempContext() {
// if (mContext.get() == null) {
// mContext = new WeakReference<>(TempActivity.this);
// }
return mContext.get();
}
// protected String makeImageUrl(String url) {
// if (TextUtils.isEmpty(url)) {
// return "";
// }
// return context.getResources().getString(R.string.image_head) + url;
// }
//
// protected String makeImageUrl(String url, int width, int height) {
// if (TextUtils.isEmpty(url))
// return "";
// if (TextUtils.isEmpty(width + "") || TextUtils.isEmpty(height + ""))
// return context.getResources().getString(R.string.image_head) + url + "&imgwidth=" + width + "&imgheight=" + height;
// return context.getResources().getString(R.string.image_head) + url;
// }
// /**
// * ImageView绑定加载图片
// *
// * @param imageView
// * @param url 图片地址 example:file:///sdcard/test.gif; assets://test.gif; http://www.test.com/x
// */
// protected void bindImageView(ImageView imageView, String url) {
//// Debug.info("BindImageUrl=" + url);
// x.image().bind(imageView, url);
// }
//
// /**
// * ImageView绑定加载图片
// *
// * @param imageView
// * @param url 图片地址 example:file:///sdcard/test.gif; assets://test.gif; http://www.test.com/x
// * @param callback 图片加载回调
// */
// protected void bindImageView(ImageView imageView, String url, Callback.CommonCallback<Drawable> callback) {
//// Debug.info("BindImageUrl=" + url);
// x.image().bind(imageView, url, callback);
// }
//
// /**
// * ImageView绑定加载图片
// *
// * @param imageView
// * @param url 图片地址 example:file:///sdcard/test.gif; assets://test.gif; http://www.test.com/x
// * @param option 加载设置类
// */
// protected void bindImageView(ImageView imageView, String url, ImageOptions option) {
//// Debug.info("BindImageUrl=" + url);
// x.image().bind(imageView, url, option);
// }
//
// /**
// * ImageView绑定加载图片
// *
// * @param imageView
// * @param url 图片地址 example:file:///sdcard/test.gif; assets://test.gif; http://www.test.com/x
// * @param option 加载设置类
// * @param callback 加载回调
// */
// protected void binImageView(ImageView imageView, String url, ImageOptions option, Callback.CommonCallback<Drawable> callback) {
//// Debug.info("BindImageUrl=" + url);
// x.image().bind(imageView, url, option, callback);
// }
}
| 5,653 | 0.579835 | 0.579652 | 190 | 27.710526 | 26.491018 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.563158 | false | false | 4 |
|
63ad67c8f25f9d47d1aaec9d1b67687eefb0abcb | 34,634,616,323,032 | df8e54ff5fbd5942280e3230123494a401c57730 | /code/on-the-way/pre-way/src/main/java/com/vika/way/pre/autumn/leetcode/editor/cn/P524LongestWordInDictionaryThroughDeleting.java | e8ce1b9f2864a4951727a2a5b1c7658216ee5317 | [] | no_license | kabitonn/cs-note | https://github.com/kabitonn/cs-note | 255297a0a0634335eefba79882f7314f7b97308f | 1235bb56a40bce7e2056f083ba8cda0cd08e39b4 | refs/heads/master | 2022-06-09T23:46:02.145000 | 2022-05-13T10:44:53 | 2022-05-13T10:44:53 | 224,864,415 | 0 | 1 | null | false | 2022-05-13T07:25:09 | 2019-11-29T13:58:19 | 2022-04-29T09:50:11 | 2022-05-13T07:25:08 | 25,366 | 0 | 0 | 3 | Java | false | false | //给定一个字符串和一个字符串字典,找到字典里面最长的字符串,该字符串可以通过删除给定字符串的某些字符来得到。如果答案不止一个,返回长度最长且字典顺序最小的字符
//串。如果答案不存在,则返回空字符串。
//
// 示例 1:
//
//
//输入:
//s = "abpcplea", d = ["ale","apple","monkey","plea"]
//
//输出:
//"apple"
//
//
// 示例 2:
//
//
//输入:
//s = "abpcplea", d = ["a","b","c"]
//
//输出:
//"a"
//
//
// 说明:
//
//
// 所有输入的字符串只包含小写字母。
// 字典的大小不会超过 1000。
// 所有输入的字符串长度不会超过 1000。
//
// Related Topics 排序 双指针
// 👍 89 👎 0
//Java:通过删除字母匹配到字典里最长单词
package com.vika.way.pre.autumn.leetcode.editor.cn;
import java.util.List;
public class P524LongestWordInDictionaryThroughDeleting {
public static void main(String[] args) {
Solution solution = new P524LongestWordInDictionaryThroughDeleting().new Solution();
// TO TEST
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public String findLongestWord(String s, List<String> d) {
d.sort((o1, o2) -> o1.length() == o2.length() ? o1.compareTo(o2) : o2.length() - o1.length());
for (String str : d) {
if (isSubSequence(str, s)) {
return str;
}
}
return "";
}
public boolean isSubSequence(String s, String t) {
if (s.length() > t.length()) {
return false;
} else if (s.length() == 0) {
return true;
}
int index = 0;
for (char c : t.toCharArray()) {
if (c == s.charAt(index)) {
index++;
if (index == s.length()) {
return true;
}
}
}
return false;
}
}
//leetcode submit region end(Prohibit modification and deletion)
} | UTF-8 | Java | 2,145 | java | P524LongestWordInDictionaryThroughDeleting.java | Java | [] | null | [] | //给定一个字符串和一个字符串字典,找到字典里面最长的字符串,该字符串可以通过删除给定字符串的某些字符来得到。如果答案不止一个,返回长度最长且字典顺序最小的字符
//串。如果答案不存在,则返回空字符串。
//
// 示例 1:
//
//
//输入:
//s = "abpcplea", d = ["ale","apple","monkey","plea"]
//
//输出:
//"apple"
//
//
// 示例 2:
//
//
//输入:
//s = "abpcplea", d = ["a","b","c"]
//
//输出:
//"a"
//
//
// 说明:
//
//
// 所有输入的字符串只包含小写字母。
// 字典的大小不会超过 1000。
// 所有输入的字符串长度不会超过 1000。
//
// Related Topics 排序 双指针
// 👍 89 👎 0
//Java:通过删除字母匹配到字典里最长单词
package com.vika.way.pre.autumn.leetcode.editor.cn;
import java.util.List;
public class P524LongestWordInDictionaryThroughDeleting {
public static void main(String[] args) {
Solution solution = new P524LongestWordInDictionaryThroughDeleting().new Solution();
// TO TEST
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public String findLongestWord(String s, List<String> d) {
d.sort((o1, o2) -> o1.length() == o2.length() ? o1.compareTo(o2) : o2.length() - o1.length());
for (String str : d) {
if (isSubSequence(str, s)) {
return str;
}
}
return "";
}
public boolean isSubSequence(String s, String t) {
if (s.length() > t.length()) {
return false;
} else if (s.length() == 0) {
return true;
}
int index = 0;
for (char c : t.toCharArray()) {
if (c == s.charAt(index)) {
index++;
if (index == s.length()) {
return true;
}
}
}
return false;
}
}
//leetcode submit region end(Prohibit modification and deletion)
} | 2,145 | 0.504183 | 0.488009 | 79 | 21.70886 | 23.245607 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.291139 | false | false | 4 |
cae95820bccd8efd07a7d8033f99a3a9f7a5fe47 | 11,115,375,389,301 | c188408c9ec0425666250b45734f8b4c9644a946 | /open-sphere-base/analysis/src/main/java/io/opensphere/analysis/export/view/DataElementsExportDialog.java | 43a5cdb7d66f4762ac04a6629c9d004e86a53808 | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | rkausch/opensphere-desktop | https://github.com/rkausch/opensphere-desktop | ef8067eb03197c758e3af40ebe49e182a450cc02 | c871c4364b3456685411fddd22414fd40ce65699 | refs/heads/snapshot_5.2.7 | 2023-04-13T21:00:00.575000 | 2020-07-29T17:56:10 | 2020-07-29T17:56:10 | 360,594,280 | 0 | 0 | Apache-2.0 | true | 2021-04-22T17:40:38 | 2021-04-22T16:58:41 | 2021-04-22T16:58:42 | 2021-04-22T17:40:38 | 73,289 | 0 | 0 | 1 | null | false | false | package io.opensphere.analysis.export.view;
import java.awt.Dimension;
import javax.swing.filechooser.FileFilter;
import io.opensphere.analysis.export.model.ExportOptionsModel;
import io.opensphere.core.preferences.PreferencesRegistry;
import io.opensphere.core.util.filesystem.MnemonicFileChooser;
/**
* The export dialog used to get the user's desired export options and export
* file.
*/
public class DataElementsExportDialog extends MnemonicFileChooser
{
/**
* Serialization id.
*/
private static final long serialVersionUID = 1L;
/**
* The options model, contains the user's inputs.
*/
private final ExportOptionsModel myModel;
/**
* Keeps the options model and the options UI in sync.
*/
private final ExportOptionsViewBinder myOptionsBinder;
/**
* The UI containing the options.
*/
private ExportOptionsUI myOptionsUI;
/**
* Constructs a new dialog.
*
* @param prefsRegistry The preferences registry.
* @param fileFilter The file filter to use or null if all files is ok.
* @param model The options model.
*/
public DataElementsExportDialog(PreferencesRegistry prefsRegistry, FileFilter fileFilter, ExportOptionsModel model)
{
super(prefsRegistry, null);
myModel = model;
initializeComponents(fileFilter);
myOptionsBinder = new ExportOptionsViewBinder(myOptionsUI, myModel);
}
/**
* Stops listening for UI and model changes.
*/
public void close()
{
myOptionsBinder.close();
}
/**
* Gets the export options view.
*
* @return The view containing different export options the user can choose
* from.
*/
protected ExportOptionsView getExportOptions()
{
return myOptionsUI;
}
/**
* Initializes all of the ui components.
*
* @param fileFilter The file filter to use.
*/
private void initializeComponents(FileFilter fileFilter)
{
Dimension d = new Dimension(740, 400);
setPreferredSize(d);
if (fileFilter != null)
{
addChoosableFileFilter(fileFilter);
super.setFileFilter(fileFilter);
}
myOptionsUI = new ExportOptionsUI();
setAccessory(myOptionsUI);
}
}
| UTF-8 | Java | 2,419 | java | DataElementsExportDialog.java | Java | [] | null | [] | package io.opensphere.analysis.export.view;
import java.awt.Dimension;
import javax.swing.filechooser.FileFilter;
import io.opensphere.analysis.export.model.ExportOptionsModel;
import io.opensphere.core.preferences.PreferencesRegistry;
import io.opensphere.core.util.filesystem.MnemonicFileChooser;
/**
* The export dialog used to get the user's desired export options and export
* file.
*/
public class DataElementsExportDialog extends MnemonicFileChooser
{
/**
* Serialization id.
*/
private static final long serialVersionUID = 1L;
/**
* The options model, contains the user's inputs.
*/
private final ExportOptionsModel myModel;
/**
* Keeps the options model and the options UI in sync.
*/
private final ExportOptionsViewBinder myOptionsBinder;
/**
* The UI containing the options.
*/
private ExportOptionsUI myOptionsUI;
/**
* Constructs a new dialog.
*
* @param prefsRegistry The preferences registry.
* @param fileFilter The file filter to use or null if all files is ok.
* @param model The options model.
*/
public DataElementsExportDialog(PreferencesRegistry prefsRegistry, FileFilter fileFilter, ExportOptionsModel model)
{
super(prefsRegistry, null);
myModel = model;
initializeComponents(fileFilter);
myOptionsBinder = new ExportOptionsViewBinder(myOptionsUI, myModel);
}
/**
* Stops listening for UI and model changes.
*/
public void close()
{
myOptionsBinder.close();
}
/**
* Gets the export options view.
*
* @return The view containing different export options the user can choose
* from.
*/
protected ExportOptionsView getExportOptions()
{
return myOptionsUI;
}
/**
* Initializes all of the ui components.
*
* @param fileFilter The file filter to use.
*/
private void initializeComponents(FileFilter fileFilter)
{
Dimension d = new Dimension(740, 400);
setPreferredSize(d);
if (fileFilter != null)
{
addChoosableFileFilter(fileFilter);
super.setFileFilter(fileFilter);
}
myOptionsUI = new ExportOptionsUI();
setAccessory(myOptionsUI);
}
}
| 2,419 | 0.633733 | 0.630839 | 90 | 24.877777 | 25.201777 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.311111 | false | false | 4 |
b4b692b5af133e566a7534063ce52bbcba1d2c36 | 14,955,076,151,726 | ea625fce203e307da3d83b0e56409e4c46f81916 | /Mobile Electronic Program Guide - Final Sem/example/example/src/com/msk/epg/ProgramList.java | ed9e602ea1d760aaef854c41a92580a94c44fe55 | [] | no_license | snbharath/BharathUnderGrad | https://github.com/snbharath/BharathUnderGrad | 8ce678116e0f4f16f1e2b9b24b0b02a21a429c90 | 79a5bb47fc28639f3ce6426d9cb7cbf0cf73b5c6 | refs/heads/master | 2021-01-10T03:34:42.512000 | 2017-08-23T04:06:19 | 2017-08-23T04:06:19 | 44,211,275 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.msk.epg;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
public class ProgramList extends Activity implements OnClickListener
{
private Button back_button,main_button;
int progs_id[];
JSONArray jArray;
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.program_list);
Calendar ci = Calendar.getInstance();
ArrayList<String> programList = new ArrayList<String>();
String time=ci.get(Calendar.HOUR_OF_DAY) + ":" + ci.get(Calendar.MINUTE)+ ":00";
String Date=ci.get(Calendar.YEAR) + "-" + (ci.get(Calendar.MONTH) + 1) + "-" +ci.get(Calendar.DAY_OF_MONTH);
final ListView pl=(ListView)findViewById(R.id.listView11);
back_button = (Button) findViewById(R.id.p_back_button);
main_button=(Button) findViewById(R.id.p_main_button);
back_button.setOnClickListener(this);
main_button.setOnClickListener(this);
Bundle bundle = getIntent().getExtras();
String name=bundle.getString("msg");
String result="";
InputStream isr=null;
try
{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://mobileepg.net63.net/programlistwithtime.php?prog="+name+"&date="+Date+"&time="+time);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr=entity.getContent();
}
catch(Exception e)
{
Log.e("Exception in Program List 1", e.toString());
}
try
{
BufferedReader reader=new BufferedReader(new InputStreamReader(isr));
StringBuilder sb= new StringBuilder();
String line=null;
while((line=reader.readLine())!=null)
{
sb.append(line+"\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e)
{
Log.e("Exception in Program List 2", e.toString());
}
try
{
String s="";
jArray=new JSONArray(result);
progs_id=new int [jArray.length()+1];
for(int ii=0;ii<jArray.length();ii++)
{
JSONObject json= jArray.getJSONObject(ii);
progs_id[ii]=Integer.parseInt(json.getString("pid"));
s="Name:"+json.getString("pname")+"\nDetails:"+json.getString("pdetails")+"\nDate:"+json.getString("pdate")+"\nStart Time:"+json.getString("pstime")+"\nEnd Time:"+json.getString("petime")+"\n";
programList.add(s);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, programList);
pl.setAdapter(adapter);
}
catch(Exception e)
{
Log.e("Exception in Program List 3", e.toString());
}
pl.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
try
{
// getting values from selected ListItem
JSONObject json = jArray.getJSONObject(position);
int prog_selec=progs_id[position];
Intent myIntent1 = new Intent(ProgramList.this,FavoriteAdd.class);
myIntent1.putExtra("selected_prog", prog_selec);
myIntent1.putExtra("pname", json.getString("pname"));
myIntent1.putExtra("cname", json.getString("cname"));
myIntent1.putExtra("pdate", json.getString("pdate"));
myIntent1.putExtra("pdetails", json.getString("pdetails"));
myIntent1.putExtra("pstime", json.getString("pstime"));
myIntent1.putExtra("petime", json.getString("petime"));
myIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.e(CONNECTIVITY_SERVICE, "inside programList class");
startActivity(myIntent1);
}
catch(Exception e)
{
Log.e("Exception in Program List 1", e.toString());
}
}
});
}
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if(v==back_button)
{
finish();
}
if(v==main_button)
{
Intent intent= new Intent(this,HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
}
| UTF-8 | Java | 4,658 | java | ProgramList.java | Java | [] | null | [] | package com.msk.epg;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
public class ProgramList extends Activity implements OnClickListener
{
private Button back_button,main_button;
int progs_id[];
JSONArray jArray;
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.program_list);
Calendar ci = Calendar.getInstance();
ArrayList<String> programList = new ArrayList<String>();
String time=ci.get(Calendar.HOUR_OF_DAY) + ":" + ci.get(Calendar.MINUTE)+ ":00";
String Date=ci.get(Calendar.YEAR) + "-" + (ci.get(Calendar.MONTH) + 1) + "-" +ci.get(Calendar.DAY_OF_MONTH);
final ListView pl=(ListView)findViewById(R.id.listView11);
back_button = (Button) findViewById(R.id.p_back_button);
main_button=(Button) findViewById(R.id.p_main_button);
back_button.setOnClickListener(this);
main_button.setOnClickListener(this);
Bundle bundle = getIntent().getExtras();
String name=bundle.getString("msg");
String result="";
InputStream isr=null;
try
{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://mobileepg.net63.net/programlistwithtime.php?prog="+name+"&date="+Date+"&time="+time);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr=entity.getContent();
}
catch(Exception e)
{
Log.e("Exception in Program List 1", e.toString());
}
try
{
BufferedReader reader=new BufferedReader(new InputStreamReader(isr));
StringBuilder sb= new StringBuilder();
String line=null;
while((line=reader.readLine())!=null)
{
sb.append(line+"\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e)
{
Log.e("Exception in Program List 2", e.toString());
}
try
{
String s="";
jArray=new JSONArray(result);
progs_id=new int [jArray.length()+1];
for(int ii=0;ii<jArray.length();ii++)
{
JSONObject json= jArray.getJSONObject(ii);
progs_id[ii]=Integer.parseInt(json.getString("pid"));
s="Name:"+json.getString("pname")+"\nDetails:"+json.getString("pdetails")+"\nDate:"+json.getString("pdate")+"\nStart Time:"+json.getString("pstime")+"\nEnd Time:"+json.getString("petime")+"\n";
programList.add(s);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, programList);
pl.setAdapter(adapter);
}
catch(Exception e)
{
Log.e("Exception in Program List 3", e.toString());
}
pl.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
try
{
// getting values from selected ListItem
JSONObject json = jArray.getJSONObject(position);
int prog_selec=progs_id[position];
Intent myIntent1 = new Intent(ProgramList.this,FavoriteAdd.class);
myIntent1.putExtra("selected_prog", prog_selec);
myIntent1.putExtra("pname", json.getString("pname"));
myIntent1.putExtra("cname", json.getString("cname"));
myIntent1.putExtra("pdate", json.getString("pdate"));
myIntent1.putExtra("pdetails", json.getString("pdetails"));
myIntent1.putExtra("pstime", json.getString("pstime"));
myIntent1.putExtra("petime", json.getString("petime"));
myIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.e(CONNECTIVITY_SERVICE, "inside programList class");
startActivity(myIntent1);
}
catch(Exception e)
{
Log.e("Exception in Program List 1", e.toString());
}
}
});
}
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if(v==back_button)
{
finish();
}
if(v==main_button)
{
Intent intent= new Intent(this,HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
}
| 4,658 | 0.709747 | 0.704594 | 149 | 30.261745 | 28.350727 | 197 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.885906 | false | false | 4 |
2456b392a2fa1ea2382a3f6bd899bcad47b1fd2e | 20,804,821,610,744 | a866bdf20cc93a3e173cf6153ebc8c0b813a68dc | /Trabalho de Bando de Dados/dados.java | 1b53dc25fff7f6996f1f4d076db60cf6a7ee7ceb | [] | no_license | souzar2/Trabalhos-Java | https://github.com/souzar2/Trabalhos-Java | 441e64943b8354e1a838c001bca50eddce8ce4c4 | 90670538516660d44cc629048750f0a27cb871aa | refs/heads/master | 2022-11-17T12:44:51.396000 | 2020-07-22T20:45:38 | 2020-07-22T20:45:38 | 281,779,366 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package trabalho;
public class dados {
private String descricao;
private String classificacao;
private double preco;
private String codigo;
public dados(String cassificacao, double preco, String codigo, String descricao) {
this.descricao = descricao;
this.classificacao = classificacao;
this.descricao = descricao;
this.preco = preco;
this.codigo = codigo;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public void setClassificacao(String classificacao) {
this.classificacao = classificacao;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getCodigo() {
return this.codigo;
}
public String getClassificacao() {
return this.classificacao;
}
public String retornaLinhaProduto() {
return ("Codigo: "+this.codigo+", Classificacao: "+this.classificacao+", Preço: R$ "+this.preco);
}
public String retornaLinhaUnimed() {
return("Codigo: "+this.codigo+", Descrição: "+this.descricao);
}
public double getPreco() {
return preco;
}
public void setPreco(double preco) {
this.preco = preco;
}
}
| ISO-8859-1 | Java | 1,215 | java | dados.java | Java | [] | null | [] | package trabalho;
public class dados {
private String descricao;
private String classificacao;
private double preco;
private String codigo;
public dados(String cassificacao, double preco, String codigo, String descricao) {
this.descricao = descricao;
this.classificacao = classificacao;
this.descricao = descricao;
this.preco = preco;
this.codigo = codigo;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public void setClassificacao(String classificacao) {
this.classificacao = classificacao;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getCodigo() {
return this.codigo;
}
public String getClassificacao() {
return this.classificacao;
}
public String retornaLinhaProduto() {
return ("Codigo: "+this.codigo+", Classificacao: "+this.classificacao+", Preço: R$ "+this.preco);
}
public String retornaLinhaUnimed() {
return("Codigo: "+this.codigo+", Descrição: "+this.descricao);
}
public double getPreco() {
return preco;
}
public void setPreco(double preco) {
this.preco = preco;
}
}
| 1,215 | 0.693894 | 0.693894 | 50 | 22.24 | 21.273985 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.7 | false | false | 4 |
839fdf068614892683e9b1a46cba3dad0196fdb7 | 10,204,842,321,314 | 2c1023acd445a3eeb226fd429ae2bc6f1f4c1ca8 | /Bundles/GoalBundle/src/main/java/dk/sdu/mmmi/cbse/goalbundle/GoalFactory.java | e93f1412e98e337656e3253178840f56115446ee | [] | no_license | Zebraged/4semesterprojject | https://github.com/Zebraged/4semesterprojject | 66da31c15cbe03b0b7936b283339ff8de31ff3d2 | 66d0f6c72625a70ab3db8673f9324532c0301d38 | refs/heads/master | 2021-04-09T13:08:32.798000 | 2018-05-16T07:52:02 | 2018-05-16T07:52:02 | 125,500,327 | 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 dk.sdu.mmmi.cbse.goalbundle;
import dk.sdu.mmmi.cbse.common.data.Entity;
import dk.sdu.mmmi.cbse.common.data.GameData;
import dk.sdu.mmmi.cbse.common.data.World;
import dk.sdu.mmmi.cbse.common.entityparts.AssetGenerator;
import dk.sdu.mmmi.cbse.common.entityparts.PositionPart;
import dk.sdu.mmmi.cbse.common.entityparts.SizePart;
import dk.sdu.mmmi.cbse.common.services.IEntityGenerator;
import java.io.File;
/**
*
* @author Marcg
*/
public class GoalFactory implements IEntityGenerator{
World world;
GameData data;
public void generate(String identifier, int x, int y, int z, World world, GameData data) {
this.world = world;
this.data = data;
if(identifier.toLowerCase().equals("goal")){
createGoal(x, y);
}
}
private void createGoal(int x, int y){
Entity goal = new Goal();
goal.add(new PositionPart(x, y, 3));
goal.add(new SizePart(32, 32));
goal = findImage(goal);
world.addEntity(goal);
}
private Entity findImage(Entity entity) {
File files = null;
files = new File("./Bundles/GoalBundle/src/main/resources/image/Idle");
File[] fileslist = files.listFiles();
if (fileslist != null) {
boolean foundImage = false;
for (File file : fileslist) {
if (file.getName().endsWith(".png")) {
if (!foundImage) { // only load first image to entity
entity.add(new AssetGenerator(entity, "image/", file.getName()));
foundImage = true;
}
}
}
}
return entity;
}
}
| UTF-8 | Java | 1,894 | java | GoalFactory.java | Java | [
{
"context": "Generator;\nimport java.io.File;\n\n/**\n *\n * @author Marcg\n */\npublic class GoalFactory implements IEntityGe",
"end": 628,
"score": 0.9954229593276978,
"start": 623,
"tag": "USERNAME",
"value": "Marcg"
}
] | 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 dk.sdu.mmmi.cbse.goalbundle;
import dk.sdu.mmmi.cbse.common.data.Entity;
import dk.sdu.mmmi.cbse.common.data.GameData;
import dk.sdu.mmmi.cbse.common.data.World;
import dk.sdu.mmmi.cbse.common.entityparts.AssetGenerator;
import dk.sdu.mmmi.cbse.common.entityparts.PositionPart;
import dk.sdu.mmmi.cbse.common.entityparts.SizePart;
import dk.sdu.mmmi.cbse.common.services.IEntityGenerator;
import java.io.File;
/**
*
* @author Marcg
*/
public class GoalFactory implements IEntityGenerator{
World world;
GameData data;
public void generate(String identifier, int x, int y, int z, World world, GameData data) {
this.world = world;
this.data = data;
if(identifier.toLowerCase().equals("goal")){
createGoal(x, y);
}
}
private void createGoal(int x, int y){
Entity goal = new Goal();
goal.add(new PositionPart(x, y, 3));
goal.add(new SizePart(32, 32));
goal = findImage(goal);
world.addEntity(goal);
}
private Entity findImage(Entity entity) {
File files = null;
files = new File("./Bundles/GoalBundle/src/main/resources/image/Idle");
File[] fileslist = files.listFiles();
if (fileslist != null) {
boolean foundImage = false;
for (File file : fileslist) {
if (file.getName().endsWith(".png")) {
if (!foundImage) { // only load first image to entity
entity.add(new AssetGenerator(entity, "image/", file.getName()));
foundImage = true;
}
}
}
}
return entity;
}
}
| 1,894 | 0.606653 | 0.604013 | 60 | 30.566668 | 24.198048 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.683333 | false | false | 4 |
9e46db757d83c4083ea51ef40c42bc49f8620ec1 | 3,659,312,167,190 | 8ed4926c0efbf0a851f4d863cac73154b22663b9 | /collect/server/src/main/java/com/data/server/component/CacheLoadListener.java | 7dce8f28faf8a6802fabe0acf6475b1ebd0aafaa | [] | no_license | thereishope/collect | https://github.com/thereishope/collect | 3a9a33fba0b0e5b64506982140a0d22058f08ce8 | 9358e2a35570051767713f541b29ddd65812032d | refs/heads/master | 2020-03-22T14:08:30.006000 | 2019-04-27T06:38:39 | 2019-04-27T06:38:39 | 138,000,080 | 8 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.data.server.component;
import com.data.server.ServerApplication;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
/**
* @author jiajun_chen palading_cr@163.com
* @title CacheLoadListener
* @project collect
* @date 2018/6/20-17:22
*/
/*@Component
public class CacheLoadListener implements CommandLineRunner {
public void run(String... strings) throws Exception {
ApplicationContext context = ServerApplication.context;
CacheHelper.loadCache();
}
public void loadCacheRemote(ApplicationContext context)
}*/
| UTF-8 | Java | 712 | java | CacheLoadListener.java | Java | [
{
"context": "ingframework.stereotype.Component;\n\n/**\n * @author jiajun_chen palading_cr@163.com\n * @title CacheLoadListener\n ",
"end": 311,
"score": 0.9978988766670227,
"start": 300,
"tag": "USERNAME",
"value": "jiajun_chen"
},
{
"context": ".stereotype.Component;\n\n/**\n * @author jiajun_chen palading_cr@163.com\n * @title CacheLoadListener\n * @project collect\n ",
"end": 331,
"score": 0.9999197125434875,
"start": 312,
"tag": "EMAIL",
"value": "palading_cr@163.com"
}
] | null | [] | package com.data.server.component;
import com.data.server.ServerApplication;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
/**
* @author jiajun_chen <EMAIL>
* @title CacheLoadListener
* @project collect
* @date 2018/6/20-17:22
*/
/*@Component
public class CacheLoadListener implements CommandLineRunner {
public void run(String... strings) throws Exception {
ApplicationContext context = ServerApplication.context;
CacheHelper.loadCache();
}
public void loadCacheRemote(ApplicationContext context)
}*/
| 700 | 0.77809 | 0.758427 | 25 | 27.48 | 23.020201 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.32 | false | false | 4 |
d2df2adc0b8072752b35a6a35b2122219d1ec2f1 | 807,453,888,532 | 708746786feb1297a03a41d67dfc7227bddcbddb | /Maven_40_DBMS_SEC/src/main/java/com/biz/sec/persistence/DetailDTO.java | 0624113c53c39c539b9ff7c41b9338eec8bbadda | [] | no_license | arhrina/maven | https://github.com/arhrina/maven | f069527e5a37bb537494c30e25fb2c0b95af0f93 | b517bde9bd0bab2d17c1e008cc7f161eaa73c572 | refs/heads/master | 2022-07-16T05:37:59.339000 | 2019-11-07T12:58:57 | 2019-11-07T12:58:57 | 218,206,831 | 0 | 0 | null | false | 2022-06-21T02:10:46 | 2019-10-29T04:52:39 | 2019-11-07T12:59:00 | 2022-06-21T02:10:42 | 84 | 0 | 0 | 11 | Java | false | false | package com.biz.sec.persistence;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.ToString;
import lombok.NoArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
@ToString
public class DetailDTO {
private long d_seq;
private long d_m_seq; // Master Table과 연계(relation)을 수행하는 key. foreign key
private String d_subject;
private String d_ok;
}
| UTF-8 | Java | 456 | java | DetailDTO.java | Java | [] | null | [] | package com.biz.sec.persistence;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.ToString;
import lombok.NoArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
@ToString
public class DetailDTO {
private long d_seq;
private long d_m_seq; // Master Table과 연계(relation)을 수행하는 key. foreign key
private String d_subject;
private String d_ok;
}
| 456 | 0.797727 | 0.797727 | 21 | 19.952381 | 15.914882 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 4 |
2527c75e81e94114f17c55b6ad31921dae6ce441 | 5,360,119,214,252 | fa93c9be2923e697fb8a2066f8fb65c7718cdec7 | /sources/com/avito/security/f0.java | b9bc2b050510dd76eb94f9cad5450646b9084010 | [] | no_license | Auch-Auch/avito_source | https://github.com/Auch-Auch/avito_source | b6c9f4b0e5c977b36d5fbc88c52f23ff908b7f8b | 76fdcc5b7e036c57ecc193e790b0582481768cdc | refs/heads/master | 2023-05-06T01:32:43.014000 | 2021-05-25T10:19:22 | 2021-05-25T10:19:22 | 370,650,685 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.avito.security;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class f0 extends e0 {
public static final <T> void a(List<T> list, Comparator<? super T> comparator) {
j1.b(list, "$this$sortWith");
j1.b(comparator, "comparator");
if (list.size() > 1) {
Collections.sort(list, comparator);
}
}
}
| UTF-8 | Java | 400 | java | f0.java | Java | [] | null | [] | package com.avito.security;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class f0 extends e0 {
public static final <T> void a(List<T> list, Comparator<? super T> comparator) {
j1.b(list, "$this$sortWith");
j1.b(comparator, "comparator");
if (list.size() > 1) {
Collections.sort(list, comparator);
}
}
}
| 400 | 0.63 | 0.6175 | 14 | 27.571428 | 20.944532 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.785714 | false | false | 4 |
93737ec4d0379b2995ecc7b377bd3699fd02bfd1 | 8,057,358,678,219 | bc20f45df8698385ae60f5ea4954fd2eedaf2416 | /ProxyTest/src/com/hsh/proxy/Proxy_static_test.java | 71148cab0f406f358fd55585372b60439e57cfcb | [] | no_license | hsh075623201/workspace | https://github.com/hsh075623201/workspace | 21864c8ccf61f81441e82962d017c311b9aab1cf | 757059bbaee0b20b685e84000be3704f044e021d | refs/heads/master | 2021-01-17T15:25:46.621000 | 2015-08-23T06:34:32 | 2015-08-23T06:34:32 | 33,172,955 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hsh.proxy;
/**
* ¾²Ì¬´úÀí²âÊÔ
* @author HSH
*
*/
public class Proxy_static_test {
public static void main(String[] args){
PeopleImpl peopleImpl = new PeopleImpl();
Proxy_static pro = new Proxy_static(peopleImpl);
pro.eat();
pro.talk();
}
}
| WINDOWS-1252 | Java | 281 | java | Proxy_static_test.java | Java | [
{
"context": "kage com.hsh.proxy;\n/**\n * ¾²Ì¬´úÀí²âÊÔ\n * @author HSH\n *\n */\npublic class Proxy_static_test {\n\t\n\tpublic",
"end": 57,
"score": 0.9820899963378906,
"start": 54,
"tag": "USERNAME",
"value": "HSH"
}
] | null | [] | package com.hsh.proxy;
/**
* ¾²Ì¬´úÀí²âÊÔ
* @author HSH
*
*/
public class Proxy_static_test {
public static void main(String[] args){
PeopleImpl peopleImpl = new PeopleImpl();
Proxy_static pro = new Proxy_static(peopleImpl);
pro.eat();
pro.talk();
}
}
| 281 | 0.657993 | 0.64684 | 16 | 15.8125 | 16.237375 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 4 |
726b548d1458e617fbac85a02e0f908d7697ba72 | 24,249,385,383,634 | 6c8ffd20a4a6cfdfdfca2e43ba467f9277edc291 | /springboot2x-ehcache/src/main/java/com/cicada/mybatis/service/impl/UserServiceImpl.java | a411e991ce1eccd6b3838240412e23974b924b03 | [] | no_license | coldcicada/spring-respository | https://github.com/coldcicada/spring-respository | 9b4f52a11d8f747c5558f88aa3bdd19a07fa6a86 | 6cb43ae7abb5810e7e8ae7902a6efca9bbaf8cfe | refs/heads/master | 2022-06-25T22:53:33.080000 | 2019-08-07T03:18:35 | 2019-08-07T03:18:35 | 190,581,763 | 0 | 0 | null | false | 2022-06-17T02:22:55 | 2019-06-06T12:58:09 | 2019-08-07T03:26:01 | 2022-06-17T02:22:55 | 176 | 0 | 0 | 2 | Java | false | false | package com.cicada.mybatis.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.cicada.mybatis.dao.UserRepository;
import com.cicada.mybatis.pojo.User;
import com.cicada.mybatis.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
@Cacheable(value = "user")
public List<User> findAllUsers() {
return this.userRepository.findAll();
}
@Override
@Cacheable(value = "user")
public User findUserById(Integer id) {
return this.userRepository.getOne(id);
}
@Override
@Cacheable(value = "user", key = "#pageable.pageSize")
public Page<User> findUserByPage(Pageable pageable) {
return this.userRepository.findAll(pageable);
}
@Override
@CacheEvict(value = "user", allEntries = true)
public void saveUser(User user) {
this.userRepository.save(user);
}
}
| UTF-8 | Java | 1,257 | java | UserServiceImpl.java | Java | [] | null | [] | package com.cicada.mybatis.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.cicada.mybatis.dao.UserRepository;
import com.cicada.mybatis.pojo.User;
import com.cicada.mybatis.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
@Cacheable(value = "user")
public List<User> findAllUsers() {
return this.userRepository.findAll();
}
@Override
@Cacheable(value = "user")
public User findUserById(Integer id) {
return this.userRepository.getOne(id);
}
@Override
@Cacheable(value = "user", key = "#pageable.pageSize")
public Page<User> findUserByPage(Pageable pageable) {
return this.userRepository.findAll(pageable);
}
@Override
@CacheEvict(value = "user", allEntries = true)
public void saveUser(User user) {
this.userRepository.save(user);
}
}
| 1,257 | 0.735879 | 0.735879 | 44 | 27.568182 | 21.209343 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.409091 | false | false | 4 |
c223a8656ed89d4bc6c938bce5e2a495358188c8 | 24,249,385,385,087 | ca297eb038647d1d825b2c19d860e70aa9da8999 | /treespringboot1/src/main/java/com/jc/treespringboot/service/TreeServiceImpl.java | 896657c8c94fee41c34fbb7088596a1ef7fe3894 | [] | no_license | kaqiulee/wechatTree | https://github.com/kaqiulee/wechatTree | a61a6b2df8cc236cd4886dd81f97efc4c3a60262 | 983a49ef73aa3b81eae449b50195ae992fe3e797 | refs/heads/master | 2023-08-13T14:38:56.482000 | 2021-10-12T13:50:25 | 2021-10-12T13:50:25 | 416,350,747 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jc.treespringboot.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jc.treespringboot.dao.UserMapper;
import com.jc.treespringboot.dao.WaterMapper;
import com.jc.treespringboot.entity.Step;
import com.jc.treespringboot.entity.Tree;
import com.jc.treespringboot.entity.User;
import com.jc.treespringboot.entity.Water;
import com.jc.treespringboot.model.TreeMod;
import com.jc.treespringboot.support.config.ServerConfig;
import com.jc.treespringboot.support.utils.LocationUtils;
import com.jc.treespringboot.support.utils.WXBizDataCrypt;
import com.jc.treespringboot.dao.StepMapper;
import com.jc.treespringboot.dao.TreeMapper;
import com.jc.treespringboot.support.AccessResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class TreeServiceImpl implements TreeService {
@Autowired
private UserMapper userMapper;
@Autowired
private TreeMapper treeMapper;
@Autowired
private StepMapper stepMapper;
@Autowired
private WaterMapper waterMapper;
@Override
public AccessResult plantTree(TreeMod tree) {
User user = userMapper.selectBySessionId(tree.getSessionId());
if (user == null) {
return new AccessResult(-1, "无法根据sessionId找到对应用户", null);
}
//判断周围50米是否已经有树了
//1. 第一点将 Tree 类和数据表tree 中的经纬度改为 double
//2 .得到当前位置经纬度, 经度和维度分别加减 0.01 ,得到一个长方形的范围,根据这个范围查数据库
// 获取所有的树
//3 . 得到的所有树跟当前位置求距离,如果有小于50米的,则报错,提示你的周围已经有树,请换一个位置种树;
// 如果没有小于50米的,则进行种树
List<Tree> trees = treeMapper.getDistanceTrees(tree.getLongitude(), tree.getLatitude());
for (Tree t : trees) {
// 判断 t 和 tree 的距离是否小于50米
double distance = LocationUtils.getDistance(t.getLatitude(), t.getLongitude(),
tree.getLatitude(), tree.getLongitude());
if (distance < 50) {
return new AccessResult(-1, "你的周围有其他树,请换一个位置种树!", null);
}
}
TreeMod tree2 = new TreeMod();
BeanUtils.copyProperties(tree, tree2);
tree2.setUserId(user.getId());
int result = treeMapper.plantTree(tree2); // 1, 成功 0 失败
AccessResult accessResult = new AccessResult();
if (result == 1) {
accessResult.setErrcode(0); // 0 成功, -1 失败
accessResult.setErrmsg("success plant");
} else {
accessResult.setErrcode(-1);
accessResult.setErrmsg("error plant");
}
return accessResult;
}
@Override
public Tree getTree(int treeid) {
Tree tree = treeMapper.getTree(treeid);
return tree;
}
@Override
public AccessResult getTreeByUserId(int userid) {
List<Tree> trees = treeMapper.getTreeByUserId(userid);
if (trees.size() == 1) {
Map<String, Tree> map = new HashMap<>();
map.put("tree", trees.get(0));
return new AccessResult(0, "查询成功", map);
} else {
return new AccessResult(-1, "查询失败", null);
}
}
@Override
public AccessResult getTreeBySessionId(String sessionId) {
List<Tree> trees = treeMapper.getTreeBySessionId(sessionId);
if (trees.size() == 1) {
Map<String, Tree> map = new HashMap<>();
map.put("tree", trees.get(0));
return new AccessResult(0, "查询成功", map);
} else {
return new AccessResult(-1, "查询失败", null);
}
}
private JSONObject decryptInfo(String encryptedData, String iv, String sessionKey) {
String appId = ServerConfig.appID;
WXBizDataCrypt biz = new WXBizDataCrypt(appId, sessionKey);
String data = biz.decryptData(encryptedData, iv);
if (data == null) {
return null;
}
JSONObject jsonObj = JSON.parseObject(data);
return jsonObj;
}
@Override
public AccessResult water(String encryptedData, String iv, String sessionId) {
//1. 根据 sessionId 得到 user对象
//2. 解密 encryptedData 得到运动数据
//3. 将当天的运动step 进行浇水
User user = userMapper.selectBySessionId(sessionId);
if (user == null) {
return new AccessResult(-1, "无法根据sessionId找到对应用户", null);
}
//解码运动数据
JSONObject jsonObj = this.decryptInfo(encryptedData, iv, user.getSessionKey());
if (jsonObj == null) {
return new AccessResult(-1, "解码运动数据失败", null);
}
List<JSONObject> stepInfoList = JSON.parseArray(jsonObj.getString("stepInfoList").toString(), JSONObject.class);
System.out.println(stepInfoList);
//将运动数据保存在db中
for (JSONObject object : stepInfoList) {
Integer timestamp = (Integer) object.get("timestamp");
Long timestamp2 = timestamp.longValue();
int step = (int) object.get("step");
Date time = new Date(timestamp2 * 1000);
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
if (UserServiceImpl.isToday(sf.format(time))) {
List<Step> steps = stepMapper.selectStep(user.getId());
if (steps.size() > 0) {
stepMapper.updateStep(user.getId(), step);
} else {
stepMapper.insertStep(user.getId(), step);
}
//使用运动步数进行浇水
return useStepToWater(user.getId(), step);
}
}
return new AccessResult(-1, "没有当天的运动步数", null);
}
public AccessResult useStepToWater(Integer userId, int step) {
//获取当天已经浇水的数据
Date now = new Date();
List<Water> list = waterMapper.getWater(userId, now);
int sum = 0;
for (Water water : list) {
sum += water.getWater();
}
if (step < sum) {
return new AccessResult(-1, "运动步数错误", null);
}
if (step == sum) {
return new AccessResult(-1, "你今天的步数用完了,运动后再来吧!", null);
}
//将这次的浇水数据保存在DB中
List<Tree> trees = treeMapper.getTreeByUserId(userId);
Water water = new Water();
water.setUserId(userId);
water.setTreeId(trees.get(0).getId());
water.setTime(new Date());
water.setWater(step - sum);
waterMapper.insertWater(water);
treeMapper.updateLife(trees.get(0).getId(), step - sum);
Map<String, Integer> map = new HashMap<>();
map.put("water", step - sum);
return new AccessResult(0, "成功浇水!", map);
}
@Override
public AccessResult cutTree(String seesionId) {
List<Tree> trees = treeMapper.getTreeBySessionId(seesionId);
if (trees.size() >= 1) {
int lenth = trees.size();
int i; //循环次数=长度
for (i = 0; i <= lenth; i++) {
if (trees.get(i).getLife() >= 5000) {
treeMapper.updateTree();
treeMapper.deleteTree();
return new AccessResult(0, "收获成功!请到树木收藏夹查看!", null);
}
else {
continue;
}
}
}
else {
return new AccessResult(-1, "收获失败!没有树可以收获!", null);
}
return new AccessResult(-1, "text:null", null);
}
//查询树的收藏夹
@Override
public AccessResult haveTree(String sessionId) {
List<Tree> trees = treeMapper.getTreeBySessionId(sessionId);
if (trees.size() >= 1) {
return new AccessResult(0, "查询成功", null);
} else {
return new AccessResult(-1, "您没有收获树哦!继续努力吧!", null);
}
}
@Override
public AccessResult haveTree1(String sessionId) {
List<Tree> trees = treeMapper.getTreeBySessionId(sessionId);
if (trees.size() >= 1) {
return new AccessResult(0, "查询成功", null);
} else {
return new AccessResult(-1, "您没有收获树哦!继续努力吧!", null);
}
}
}
| UTF-8 | Java | 9,009 | java | TreeServiceImpl.java | Java | [] | null | [] | package com.jc.treespringboot.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jc.treespringboot.dao.UserMapper;
import com.jc.treespringboot.dao.WaterMapper;
import com.jc.treespringboot.entity.Step;
import com.jc.treespringboot.entity.Tree;
import com.jc.treespringboot.entity.User;
import com.jc.treespringboot.entity.Water;
import com.jc.treespringboot.model.TreeMod;
import com.jc.treespringboot.support.config.ServerConfig;
import com.jc.treespringboot.support.utils.LocationUtils;
import com.jc.treespringboot.support.utils.WXBizDataCrypt;
import com.jc.treespringboot.dao.StepMapper;
import com.jc.treespringboot.dao.TreeMapper;
import com.jc.treespringboot.support.AccessResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class TreeServiceImpl implements TreeService {
@Autowired
private UserMapper userMapper;
@Autowired
private TreeMapper treeMapper;
@Autowired
private StepMapper stepMapper;
@Autowired
private WaterMapper waterMapper;
@Override
public AccessResult plantTree(TreeMod tree) {
User user = userMapper.selectBySessionId(tree.getSessionId());
if (user == null) {
return new AccessResult(-1, "无法根据sessionId找到对应用户", null);
}
//判断周围50米是否已经有树了
//1. 第一点将 Tree 类和数据表tree 中的经纬度改为 double
//2 .得到当前位置经纬度, 经度和维度分别加减 0.01 ,得到一个长方形的范围,根据这个范围查数据库
// 获取所有的树
//3 . 得到的所有树跟当前位置求距离,如果有小于50米的,则报错,提示你的周围已经有树,请换一个位置种树;
// 如果没有小于50米的,则进行种树
List<Tree> trees = treeMapper.getDistanceTrees(tree.getLongitude(), tree.getLatitude());
for (Tree t : trees) {
// 判断 t 和 tree 的距离是否小于50米
double distance = LocationUtils.getDistance(t.getLatitude(), t.getLongitude(),
tree.getLatitude(), tree.getLongitude());
if (distance < 50) {
return new AccessResult(-1, "你的周围有其他树,请换一个位置种树!", null);
}
}
TreeMod tree2 = new TreeMod();
BeanUtils.copyProperties(tree, tree2);
tree2.setUserId(user.getId());
int result = treeMapper.plantTree(tree2); // 1, 成功 0 失败
AccessResult accessResult = new AccessResult();
if (result == 1) {
accessResult.setErrcode(0); // 0 成功, -1 失败
accessResult.setErrmsg("success plant");
} else {
accessResult.setErrcode(-1);
accessResult.setErrmsg("error plant");
}
return accessResult;
}
@Override
public Tree getTree(int treeid) {
Tree tree = treeMapper.getTree(treeid);
return tree;
}
@Override
public AccessResult getTreeByUserId(int userid) {
List<Tree> trees = treeMapper.getTreeByUserId(userid);
if (trees.size() == 1) {
Map<String, Tree> map = new HashMap<>();
map.put("tree", trees.get(0));
return new AccessResult(0, "查询成功", map);
} else {
return new AccessResult(-1, "查询失败", null);
}
}
@Override
public AccessResult getTreeBySessionId(String sessionId) {
List<Tree> trees = treeMapper.getTreeBySessionId(sessionId);
if (trees.size() == 1) {
Map<String, Tree> map = new HashMap<>();
map.put("tree", trees.get(0));
return new AccessResult(0, "查询成功", map);
} else {
return new AccessResult(-1, "查询失败", null);
}
}
private JSONObject decryptInfo(String encryptedData, String iv, String sessionKey) {
String appId = ServerConfig.appID;
WXBizDataCrypt biz = new WXBizDataCrypt(appId, sessionKey);
String data = biz.decryptData(encryptedData, iv);
if (data == null) {
return null;
}
JSONObject jsonObj = JSON.parseObject(data);
return jsonObj;
}
@Override
public AccessResult water(String encryptedData, String iv, String sessionId) {
//1. 根据 sessionId 得到 user对象
//2. 解密 encryptedData 得到运动数据
//3. 将当天的运动step 进行浇水
User user = userMapper.selectBySessionId(sessionId);
if (user == null) {
return new AccessResult(-1, "无法根据sessionId找到对应用户", null);
}
//解码运动数据
JSONObject jsonObj = this.decryptInfo(encryptedData, iv, user.getSessionKey());
if (jsonObj == null) {
return new AccessResult(-1, "解码运动数据失败", null);
}
List<JSONObject> stepInfoList = JSON.parseArray(jsonObj.getString("stepInfoList").toString(), JSONObject.class);
System.out.println(stepInfoList);
//将运动数据保存在db中
for (JSONObject object : stepInfoList) {
Integer timestamp = (Integer) object.get("timestamp");
Long timestamp2 = timestamp.longValue();
int step = (int) object.get("step");
Date time = new Date(timestamp2 * 1000);
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
if (UserServiceImpl.isToday(sf.format(time))) {
List<Step> steps = stepMapper.selectStep(user.getId());
if (steps.size() > 0) {
stepMapper.updateStep(user.getId(), step);
} else {
stepMapper.insertStep(user.getId(), step);
}
//使用运动步数进行浇水
return useStepToWater(user.getId(), step);
}
}
return new AccessResult(-1, "没有当天的运动步数", null);
}
public AccessResult useStepToWater(Integer userId, int step) {
//获取当天已经浇水的数据
Date now = new Date();
List<Water> list = waterMapper.getWater(userId, now);
int sum = 0;
for (Water water : list) {
sum += water.getWater();
}
if (step < sum) {
return new AccessResult(-1, "运动步数错误", null);
}
if (step == sum) {
return new AccessResult(-1, "你今天的步数用完了,运动后再来吧!", null);
}
//将这次的浇水数据保存在DB中
List<Tree> trees = treeMapper.getTreeByUserId(userId);
Water water = new Water();
water.setUserId(userId);
water.setTreeId(trees.get(0).getId());
water.setTime(new Date());
water.setWater(step - sum);
waterMapper.insertWater(water);
treeMapper.updateLife(trees.get(0).getId(), step - sum);
Map<String, Integer> map = new HashMap<>();
map.put("water", step - sum);
return new AccessResult(0, "成功浇水!", map);
}
@Override
public AccessResult cutTree(String seesionId) {
List<Tree> trees = treeMapper.getTreeBySessionId(seesionId);
if (trees.size() >= 1) {
int lenth = trees.size();
int i; //循环次数=长度
for (i = 0; i <= lenth; i++) {
if (trees.get(i).getLife() >= 5000) {
treeMapper.updateTree();
treeMapper.deleteTree();
return new AccessResult(0, "收获成功!请到树木收藏夹查看!", null);
}
else {
continue;
}
}
}
else {
return new AccessResult(-1, "收获失败!没有树可以收获!", null);
}
return new AccessResult(-1, "text:null", null);
}
//查询树的收藏夹
@Override
public AccessResult haveTree(String sessionId) {
List<Tree> trees = treeMapper.getTreeBySessionId(sessionId);
if (trees.size() >= 1) {
return new AccessResult(0, "查询成功", null);
} else {
return new AccessResult(-1, "您没有收获树哦!继续努力吧!", null);
}
}
@Override
public AccessResult haveTree1(String sessionId) {
List<Tree> trees = treeMapper.getTreeBySessionId(sessionId);
if (trees.size() >= 1) {
return new AccessResult(0, "查询成功", null);
} else {
return new AccessResult(-1, "您没有收获树哦!继续努力吧!", null);
}
}
}
| 9,009 | 0.593807 | 0.58503 | 252 | 31.551588 | 24.321779 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.698413 | false | false | 4 |
521bc1f1c9fe16d9b0cdcb2103beb0e6a0c2e9b0 | 22,136,261,468,630 | f7cc8938ccf25a514c6a6ccdfb4dcc49f80b5c12 | /microvibe-booster/booster-core/src/main/java/io/microvibe/booster/core/api/ReplyCode.java | 85de046a20c306bd0916bc97649b51603eafae1a | [
"Apache-2.0"
] | permissive | microsignal/vibe | https://github.com/microsignal/vibe | 6f8b8d91aa6fa0dfc7020ca023ea8c3cb0d82e37 | 4b3e2d5b5a6f3b3e021276b7e496d6eaa1b7b665 | refs/heads/master | 2021-09-25T13:07:16.911000 | 2018-10-22T05:14:14 | 2018-10-22T05:14:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.microvibe.booster.core.api;
import io.microvibe.booster.commons.spring.MessageResources;
import io.microvibe.booster.commons.utils.StringUtils;
import java.util.regex.Pattern;
public enum ReplyCode {
// 成功
Success("R0000", "操作成功"), //
// 系统错误
Error("R0001", "操作失败"), //
SysLogicError("R0002", "系统逻辑异常"), //
// 数据校验类错误
RequestParseError("R1000", "接口报文数据解析失败"), //
RequestHeadError("R1001", "接口报文头格式有误"), //
RequestHeadEmpty("R1002", "接口报文头不能为空"), //
RequestBodyError("R1003", "接口报文体格式有误"), //
RequestBodyEmpty("R1004", "接口报文体不能为空"), //
RequestCodeEmpty("R1005", "接口代码不能为空"), //
RequestCodeUnsupported("R1006", "接口代码不支持"), //
RequestParamError("R1007", "参数校验失败"),
RequestAppIdError("R1010", "appId无效"), //
RequestAppIdEmpty("R1011", "appId不能为空"), //
RequestAppSecretError("R1012", "appSecret无效"), //
RequestAppSecretEmpty("R1013", "appSecret不能为空"), //
RequestTokenError("R1014", "AccessToken无效"), //
RequestTokenEmpty("R1015", "AccessToken不能为空"), //
RequestTokenGenError("R1016", "AccessToken生成失败"), //
RequestCaptchaInvalid("R1017", "验证码无效"), //
RequestLoginTokenInvalid("R1018", "登录令牌无效"), //
RequestPasswordError("R1019", "密码错误"),
RequestPageParamEmpty("R1020", "查询分页条件不能为空"), //
// 权限限制类错误
TxnUnauthorizedError("R2000", "权限不足"), //
TxnSessionUnauthenticated("R2001", "当前会话未认证"), //
TxnAuthChannelUnsupported("R2002", "认证方式不支持"), //
TxnSessionKickedOut("R2003", "当前用户被强制退出"), //
TxnSessionUserDeleted("R2004", "当前用户被删除"), //
TxnSessionUserBlocked("R2005", "当前用户被封禁"), //
// 逻辑处理类错误
TxnProcessError("R3000", "处理错误"), //
TxnUnimplemented("R3001", "功能尚未实现"), //
TxnUnavailable("R3002", "功能暂不可用"), //
TxnDataNotExist("R3003", "数据信息不存在"), //
TxnDataAlreadyExist("R3004", "数据信息已存在"), //
TxnDataUncompleted("R3005", "数据信息不完整"), //
// 消息响应类错误
ResponseFormatError("R4001", "响应数据编码失败"), //
;
private String code;
private String message;
private ReplyCode(String code, String message) {
this.code = code;
this.message = message;
}
@Override
public String toString() {
return code;
}
public int getCodeAsInt() {
return Integer.parseInt(code.replaceFirst("^[^\\d]+", ""));
}
public String getCode() {
return code;
}
public String getMessage() {
return MessageResources.getMessageOrDefault(code, message);
}
public void fail(String message) {
throw new ApiException(this, message);
}
public void fail() {
fail(null);
}
public void assertPattern(String message, Pattern pattern, String str) {
if (!pattern.matcher(str).matches()) {
fail(message);
}
}
public void assertPattern(String message, String pattern, String str) {
if (!Pattern.compile(pattern).matcher(str).matches()) {
fail(message);
}
}
public void assertTrue(String message, boolean expression) {
if (!expression) {
fail(message);
}
}
public void assertNull(String message, Object object) {
if (object != null) {
fail(message);
}
}
public void assertEmpty(String message, String str) {
if (str != null && !"".equals(str)) {
fail(message);
}
}
public void assertBlank(String message, String str) {
if (StringUtils.isNotBlank(str)) {
fail(message);
}
}
public void assertEquals(String message, Object o1, Object o2) {
if (!o1.equals(o2)) {
fail(message);
}
}
public void assertNotTrue(String message, boolean expression) {
if (expression) {
fail(message);
}
}
public void assertNotNull(String message, Object object) {
if (object == null) {
fail(message);
}
}
public void assertNotEmpty(String message, String str) {
if (str == null || "".equals(str)) {
fail(message);
}
}
public void assertNotBlank(String message, String str) {
if (StringUtils.isBlank(str)) {
fail(message);
}
}
public void assertNotEquals(String message, Object o1, Object o2) {
if (o1.equals(o2)) {
fail(message);
}
}
}
| UTF-8 | Java | 4,357 | java | ReplyCode.java | Java | [] | null | [] | package io.microvibe.booster.core.api;
import io.microvibe.booster.commons.spring.MessageResources;
import io.microvibe.booster.commons.utils.StringUtils;
import java.util.regex.Pattern;
public enum ReplyCode {
// 成功
Success("R0000", "操作成功"), //
// 系统错误
Error("R0001", "操作失败"), //
SysLogicError("R0002", "系统逻辑异常"), //
// 数据校验类错误
RequestParseError("R1000", "接口报文数据解析失败"), //
RequestHeadError("R1001", "接口报文头格式有误"), //
RequestHeadEmpty("R1002", "接口报文头不能为空"), //
RequestBodyError("R1003", "接口报文体格式有误"), //
RequestBodyEmpty("R1004", "接口报文体不能为空"), //
RequestCodeEmpty("R1005", "接口代码不能为空"), //
RequestCodeUnsupported("R1006", "接口代码不支持"), //
RequestParamError("R1007", "参数校验失败"),
RequestAppIdError("R1010", "appId无效"), //
RequestAppIdEmpty("R1011", "appId不能为空"), //
RequestAppSecretError("R1012", "appSecret无效"), //
RequestAppSecretEmpty("R1013", "appSecret不能为空"), //
RequestTokenError("R1014", "AccessToken无效"), //
RequestTokenEmpty("R1015", "AccessToken不能为空"), //
RequestTokenGenError("R1016", "AccessToken生成失败"), //
RequestCaptchaInvalid("R1017", "验证码无效"), //
RequestLoginTokenInvalid("R1018", "登录令牌无效"), //
RequestPasswordError("R1019", "密码错误"),
RequestPageParamEmpty("R1020", "查询分页条件不能为空"), //
// 权限限制类错误
TxnUnauthorizedError("R2000", "权限不足"), //
TxnSessionUnauthenticated("R2001", "当前会话未认证"), //
TxnAuthChannelUnsupported("R2002", "认证方式不支持"), //
TxnSessionKickedOut("R2003", "当前用户被强制退出"), //
TxnSessionUserDeleted("R2004", "当前用户被删除"), //
TxnSessionUserBlocked("R2005", "当前用户被封禁"), //
// 逻辑处理类错误
TxnProcessError("R3000", "处理错误"), //
TxnUnimplemented("R3001", "功能尚未实现"), //
TxnUnavailable("R3002", "功能暂不可用"), //
TxnDataNotExist("R3003", "数据信息不存在"), //
TxnDataAlreadyExist("R3004", "数据信息已存在"), //
TxnDataUncompleted("R3005", "数据信息不完整"), //
// 消息响应类错误
ResponseFormatError("R4001", "响应数据编码失败"), //
;
private String code;
private String message;
private ReplyCode(String code, String message) {
this.code = code;
this.message = message;
}
@Override
public String toString() {
return code;
}
public int getCodeAsInt() {
return Integer.parseInt(code.replaceFirst("^[^\\d]+", ""));
}
public String getCode() {
return code;
}
public String getMessage() {
return MessageResources.getMessageOrDefault(code, message);
}
public void fail(String message) {
throw new ApiException(this, message);
}
public void fail() {
fail(null);
}
public void assertPattern(String message, Pattern pattern, String str) {
if (!pattern.matcher(str).matches()) {
fail(message);
}
}
public void assertPattern(String message, String pattern, String str) {
if (!Pattern.compile(pattern).matcher(str).matches()) {
fail(message);
}
}
public void assertTrue(String message, boolean expression) {
if (!expression) {
fail(message);
}
}
public void assertNull(String message, Object object) {
if (object != null) {
fail(message);
}
}
public void assertEmpty(String message, String str) {
if (str != null && !"".equals(str)) {
fail(message);
}
}
public void assertBlank(String message, String str) {
if (StringUtils.isNotBlank(str)) {
fail(message);
}
}
public void assertEquals(String message, Object o1, Object o2) {
if (!o1.equals(o2)) {
fail(message);
}
}
public void assertNotTrue(String message, boolean expression) {
if (expression) {
fail(message);
}
}
public void assertNotNull(String message, Object object) {
if (object == null) {
fail(message);
}
}
public void assertNotEmpty(String message, String str) {
if (str == null || "".equals(str)) {
fail(message);
}
}
public void assertNotBlank(String message, String str) {
if (StringUtils.isBlank(str)) {
fail(message);
}
}
public void assertNotEquals(String message, Object o1, Object o2) {
if (o1.equals(o2)) {
fail(message);
}
}
}
| 4,357 | 0.679099 | 0.640767 | 163 | 22.687117 | 21.471203 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.852761 | false | false | 4 |
e5617615ac51fbd9107869ee3007f5a60da7dffb | 26,998,164,450,251 | 60a800d36c7f51d077ab306c4839996ef7d4296b | /RestaurantSystem/src/com/catering/servlet/IncomeServlet.java | 386830d4643bec8098a57088de0cd92a30d26dcf | [] | no_license | mxj-jay/RestaurantSystem | https://github.com/mxj-jay/RestaurantSystem | a5ca79db49e1b1c3213ca309943614e294b410de | b4a9d22e1909c38eba9c42af0fa130ecabb53acd | refs/heads/master | 2020-03-24T17:52:05.970000 | 2019-10-14T10:04:40 | 2019-10-14T10:04:40 | 142,874,463 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.catering.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.catering.bean.Cuisine;
import com.catering.bean.PageBean;
import com.catering.dao.CuisineDao;
import com.catering.dao.FormDao;
import com.catering.dao.ItemDao;
import com.catering.util.StringUtil;
public class IncomeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String action=request.getParameter("action");
ItemDao itemDao = new ItemDao();
FormDao formDao=new FormDao();
CuisineDao cuisineDao=new CuisineDao();
if(!StringUtil.isNotEmpty(action)){ //初始化
cuisineDao.resetTotal();
}
int total=0,pageNo=1,pageSize=8;
if(request.getParameter("pageNo")!=null){
pageNo=Integer.parseInt(request.getParameter("pageNo"));
}
if(request.getParameter("pageSize")!=null){
pageSize=Integer.parseInt(request.getParameter("pageSize"));
}
List<Cuisine> clist=cuisineDao.findAllByPage(pageNo, pageSize);
PageBean<Cuisine> pBean=new PageBean<Cuisine>();
pBean.setData(clist);
pBean.setPageNo(pageNo);
pBean.setPageSize(pageSize);
pBean.setTotal(cuisineDao.getCount());
if(!StringUtil.isNotEmpty(action)){
request.setAttribute("pBean",pBean);
request.getRequestDispatcher("statistics/statistics.jsp").forward(request, response);
}else if("total".equals(action)){ //查询该菜品总数
int cid=Integer.parseInt(request.getParameter("cid"));
total=itemDao.getTotal(cid);
cuisineDao.updateTotal(total,cid);
request.getRequestDispatcher("incomeServlet?action=totalover").forward(request, response);
}else if("income".equals(action)){ //查询收益
String date=request.getParameter("date");
int income=formDao.getIncome(date);
request.setAttribute("income", income);
request.setAttribute("date", date);
request.setAttribute("pBean",pBean);
request.getRequestDispatcher("statistics/statistics.jsp").forward(request, response);
}else if("totalover".equals(action)){
request.setAttribute("pBean",pBean);
request.getRequestDispatcher("statistics/statistics.jsp").forward(request, response);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
| GB18030 | Java | 2,611 | java | IncomeServlet.java | Java | [] | null | [] | package com.catering.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.catering.bean.Cuisine;
import com.catering.bean.PageBean;
import com.catering.dao.CuisineDao;
import com.catering.dao.FormDao;
import com.catering.dao.ItemDao;
import com.catering.util.StringUtil;
public class IncomeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String action=request.getParameter("action");
ItemDao itemDao = new ItemDao();
FormDao formDao=new FormDao();
CuisineDao cuisineDao=new CuisineDao();
if(!StringUtil.isNotEmpty(action)){ //初始化
cuisineDao.resetTotal();
}
int total=0,pageNo=1,pageSize=8;
if(request.getParameter("pageNo")!=null){
pageNo=Integer.parseInt(request.getParameter("pageNo"));
}
if(request.getParameter("pageSize")!=null){
pageSize=Integer.parseInt(request.getParameter("pageSize"));
}
List<Cuisine> clist=cuisineDao.findAllByPage(pageNo, pageSize);
PageBean<Cuisine> pBean=new PageBean<Cuisine>();
pBean.setData(clist);
pBean.setPageNo(pageNo);
pBean.setPageSize(pageSize);
pBean.setTotal(cuisineDao.getCount());
if(!StringUtil.isNotEmpty(action)){
request.setAttribute("pBean",pBean);
request.getRequestDispatcher("statistics/statistics.jsp").forward(request, response);
}else if("total".equals(action)){ //查询该菜品总数
int cid=Integer.parseInt(request.getParameter("cid"));
total=itemDao.getTotal(cid);
cuisineDao.updateTotal(total,cid);
request.getRequestDispatcher("incomeServlet?action=totalover").forward(request, response);
}else if("income".equals(action)){ //查询收益
String date=request.getParameter("date");
int income=formDao.getIncome(date);
request.setAttribute("income", income);
request.setAttribute("date", date);
request.setAttribute("pBean",pBean);
request.getRequestDispatcher("statistics/statistics.jsp").forward(request, response);
}else if("totalover".equals(action)){
request.setAttribute("pBean",pBean);
request.getRequestDispatcher("statistics/statistics.jsp").forward(request, response);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
| 2,611 | 0.746806 | 0.745257 | 73 | 34.38356 | 23.951796 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.068493 | false | false | 4 |
0a528c42c543b1998b810d035f093953e7c4798f | 489,626,309,683 | 754549de022bb11d4f68a958ac3c55040a406c09 | /com.bcs.core/src/main/java/com/bcs/core/db/service/InvoiceService.java | f177bdd69257f357abb7281e70638ce0a271e101 | [] | no_license | michaelchou-XtremeApp/TaishinRose | https://github.com/michaelchou-XtremeApp/TaishinRose | 10ab5d32ebe96ea63504942c94d283d2f5f1df9c | af6fa0bd354576b0b9ed7b47ffa8b0e2cd2308f4 | refs/heads/develop-LDAP | 2020-07-28T15:38:13.930000 | 2019-09-19T03:15:12 | 2019-09-19T03:15:12 | 209,452,564 | 0 | 0 | null | false | 2019-11-13T12:10:55 | 2019-09-19T03:14:18 | 2019-09-19T03:17:19 | 2019-11-13T12:10:54 | 13,935 | 0 | 0 | 1 | Java | false | false | package com.bcs.core.db.service;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.bcs.core.db.entity.Invoice;
import com.bcs.core.db.repository.InvoiceRepository;
import com.bcs.core.invoice.service.InvoiceStatus;
import com.bcs.core.utils.ObjectUtil;
@Service
public class InvoiceService {
@Autowired
private InvoiceRepository invoiceRepository;
/** Logger */
private static Logger logger = Logger.getLogger(InvoiceService.class);
public void save(Invoice invoice){
invoiceRepository.save(invoice);
}
@Transactional(rollbackFor=Exception.class, timeout = 30)
public List<Invoice> findByCampaignId(String campaignId) {
logger.debug("campaignId:" + campaignId);
return invoiceRepository.findByCampaignId(campaignId);
}
public String generateInvoiceId() {
String invoiceId = UUID.randomUUID().toString().toLowerCase();
while (invoiceRepository.findOne(invoiceId) != null) {
invoiceId = UUID.randomUUID().toString().toLowerCase();
}
return invoiceId;
}
@Transactional(rollbackFor=Exception.class, timeout = 30)
public List<Invoice> findNotUsedToGetPrizeByMid(String MID, String gameId) {
logger.debug("MID" + MID);
return invoiceRepository.findNotUsedToGetPrizeByMid(MID, gameId);
}
@Transactional(rollbackFor=Exception.class, timeout = 30)
public boolean checkIsExisted(String invNum, String campaignId) {
logger.debug("invNum=" + invNum + ", campaignId=" + campaignId);
List<String> statusList = new ArrayList<String>();
statusList.add(InvoiceStatus.VALID);
statusList.add(InvoiceStatus.NOT_FOUND);
List<Invoice> invoiceList = invoiceRepository.findByStatusInAndInvNumAndCampaignId(statusList, invNum, campaignId);
logger.debug(ObjectUtil.objectToJsonStr(invoiceList));
return CollectionUtils.isNotEmpty(invoiceList);
}
public List<Invoice> findByStatus(String status) {
logger.debug("status" + status);
return invoiceRepository.findByStatus(status);
}
}
| UTF-8 | Java | 2,467 | java | InvoiceService.java | Java | [] | null | [] | package com.bcs.core.db.service;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.bcs.core.db.entity.Invoice;
import com.bcs.core.db.repository.InvoiceRepository;
import com.bcs.core.invoice.service.InvoiceStatus;
import com.bcs.core.utils.ObjectUtil;
@Service
public class InvoiceService {
@Autowired
private InvoiceRepository invoiceRepository;
/** Logger */
private static Logger logger = Logger.getLogger(InvoiceService.class);
public void save(Invoice invoice){
invoiceRepository.save(invoice);
}
@Transactional(rollbackFor=Exception.class, timeout = 30)
public List<Invoice> findByCampaignId(String campaignId) {
logger.debug("campaignId:" + campaignId);
return invoiceRepository.findByCampaignId(campaignId);
}
public String generateInvoiceId() {
String invoiceId = UUID.randomUUID().toString().toLowerCase();
while (invoiceRepository.findOne(invoiceId) != null) {
invoiceId = UUID.randomUUID().toString().toLowerCase();
}
return invoiceId;
}
@Transactional(rollbackFor=Exception.class, timeout = 30)
public List<Invoice> findNotUsedToGetPrizeByMid(String MID, String gameId) {
logger.debug("MID" + MID);
return invoiceRepository.findNotUsedToGetPrizeByMid(MID, gameId);
}
@Transactional(rollbackFor=Exception.class, timeout = 30)
public boolean checkIsExisted(String invNum, String campaignId) {
logger.debug("invNum=" + invNum + ", campaignId=" + campaignId);
List<String> statusList = new ArrayList<String>();
statusList.add(InvoiceStatus.VALID);
statusList.add(InvoiceStatus.NOT_FOUND);
List<Invoice> invoiceList = invoiceRepository.findByStatusInAndInvNumAndCampaignId(statusList, invNum, campaignId);
logger.debug(ObjectUtil.objectToJsonStr(invoiceList));
return CollectionUtils.isNotEmpty(invoiceList);
}
public List<Invoice> findByStatus(String status) {
logger.debug("status" + status);
return invoiceRepository.findByStatus(status);
}
}
| 2,467 | 0.708553 | 0.70531 | 72 | 33.263889 | 27.428186 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false | 4 |
e32a8029098856d4dd95623b3963f7a608489f61 | 489,626,313,707 | 00fd199b15039f70e6bd6c60094e810f3315bf4f | /Levelbuilder.java | e6b3d0c5433370157d2e9e6d63c172ee081a12f1 | [] | no_license | stevenghekiere1982/WOZ---the-real-game | https://github.com/stevenghekiere1982/WOZ---the-real-game | e197cda6e3e71d0948641bb828182f79804e220b | b7a1cf0699b3513ea5fc5eea00602cf44f18d155 | refs/heads/master | 2020-03-18T14:10:14.873000 | 2018-06-09T05:35:13 | 2018-06-09T05:35:13 | 134,833,998 | 0 | 21 | null | false | 2018-06-09T05:35:14 | 2018-05-25T09:21:26 | 2018-06-09T05:33:53 | 2018-06-09T05:35:13 | 47 | 0 | 5 | 0 | Java | false | null |
/**
* class Levelbuilder - geef hier een beschrijving van deze class
*
* @author (stijn demeyere)
* @version (4/06)
*/
public class Levelbuilder
{
public Room buildLevel1()
{
Room outside, theater, pub, lab, office, keyroom;
Personage trol, witch;
Item key , jacket , sword;
// create the rooms
outside = new Room("outside the main entrance of the university");
theater = new Room("in a lecture theater");
pub = new Room("in the campus pub");
lab = new Room("in a computing lab");
office = new Room("in the computing admin office");
keyroom = new Room("an now unlocked dusty room");
// initialise room exits
outside.setExit("east", theater);
outside.setExit("south", lab);
outside.setExit("west", pub);
theater.setExit("west", outside);
pub.setExit("east", outside);
lab.setExit("north", outside);
lab.setExit("east", office);
office.setExit("west", lab);
keyroom.setExit("south", lab);
// create figures
trol = new Personage("trol", "klein hyperactief ventje", 100, 15, true);
witch = new Personage("witch", "a bitchy witchy", 70, 35, false);
office.addPersonage(trol);
pub.addPersonage(witch);
//createItems
key = new Item("key",1,"opens a door");
jacket = new Item("jacket", 2 , "protects the user a little");
sword = new Item("sword",8,"increases damage");
return outside; // start game outside
}
}
| UTF-8 | Java | 1,613 | java | Levelbuilder.java | Java | [
{
"context": "er een beschrijving van deze class\n *\n * @author (stijn demeyere)\n * @version (4/06)\n */\npublic class Levelbuilder",
"end": 100,
"score": 0.9998676180839539,
"start": 86,
"tag": "NAME",
"value": "stijn demeyere"
}
] | null | [] |
/**
* class Levelbuilder - geef hier een beschrijving van deze class
*
* @author (<NAME>)
* @version (4/06)
*/
public class Levelbuilder
{
public Room buildLevel1()
{
Room outside, theater, pub, lab, office, keyroom;
Personage trol, witch;
Item key , jacket , sword;
// create the rooms
outside = new Room("outside the main entrance of the university");
theater = new Room("in a lecture theater");
pub = new Room("in the campus pub");
lab = new Room("in a computing lab");
office = new Room("in the computing admin office");
keyroom = new Room("an now unlocked dusty room");
// initialise room exits
outside.setExit("east", theater);
outside.setExit("south", lab);
outside.setExit("west", pub);
theater.setExit("west", outside);
pub.setExit("east", outside);
lab.setExit("north", outside);
lab.setExit("east", office);
office.setExit("west", lab);
keyroom.setExit("south", lab);
// create figures
trol = new Personage("trol", "klein hyperactief ventje", 100, 15, true);
witch = new Personage("witch", "a bitchy witchy", 70, 35, false);
office.addPersonage(trol);
pub.addPersonage(witch);
//createItems
key = new Item("key",1,"opens a door");
jacket = new Item("jacket", 2 , "protects the user a little");
sword = new Item("sword",8,"increases damage");
return outside; // start game outside
}
}
| 1,605 | 0.572226 | 0.562306 | 52 | 30 | 22.555914 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.096154 | false | false | 4 |
3a31d860a2ba51bb06baf059f18581bd273d62ce | 22,539,988,403,345 | 7497fb5063e65e725845d96f02b11a0862a8a3f1 | /ioswaggerpetstore/src/main/java/controls/PetCreate.java | 90c00b3f0e19379dbe20aea387af5f8456b0cfd4 | [] | no_license | adomanich/PetStoreAPITest | https://github.com/adomanich/PetStoreAPITest | f7f39ac3c8d970ceee04274b3c3c8512fb080382 | 0fef6ec1f4a90fd383d4614046511566374e674e | refs/heads/master | 2022-11-22T12:48:35.695000 | 2019-08-29T16:56:06 | 2019-08-29T16:56:06 | 202,783,648 | 0 | 0 | null | false | 2022-11-16T11:53:50 | 2019-08-16T19:00:18 | 2019-08-29T16:56:08 | 2022-11-16T11:53:46 | 65 | 0 | 0 | 4 | Java | false | false | package controls;
import models.Category;
import models.Pet;
import models.TagsItems;
import org.apache.commons.lang3.RandomStringUtils;
import java.util.Collections;
public class PetCreate {
private int id = Integer.parseInt(RandomStringUtils.randomNumeric(6));
private String name = RandomStringUtils.randomAlphabetic(7);
private Pet pet;
public Pet createPet() {
pet = Pet.builder()
.id(id)
.category(Category.builder()
.id(id)
.name(name)
.build())
.name(name)
.photoUrls(Collections.singletonList(RandomStringUtils.randomAlphabetic(10)))
.tagsItems(Collections.singletonList(TagsItems.builder()
.id(id)
.name(name)
.build())
)
.status("avaliable")
.build();
return pet;
}
}
| UTF-8 | Java | 1,024 | java | PetCreate.java | Java | [
{
"context": " .id(id)\r\n .name(name)\r\n .build())\r\n ",
"end": 568,
"score": 0.5607883334159851,
"start": 564,
"tag": "NAME",
"value": "name"
},
{
"context": " .id(id)\r\n .name(name)\r\n .build())\r\n ",
"end": 871,
"score": 0.5374265313148499,
"start": 867,
"tag": "NAME",
"value": "name"
}
] | null | [] | package controls;
import models.Category;
import models.Pet;
import models.TagsItems;
import org.apache.commons.lang3.RandomStringUtils;
import java.util.Collections;
public class PetCreate {
private int id = Integer.parseInt(RandomStringUtils.randomNumeric(6));
private String name = RandomStringUtils.randomAlphabetic(7);
private Pet pet;
public Pet createPet() {
pet = Pet.builder()
.id(id)
.category(Category.builder()
.id(id)
.name(name)
.build())
.name(name)
.photoUrls(Collections.singletonList(RandomStringUtils.randomAlphabetic(10)))
.tagsItems(Collections.singletonList(TagsItems.builder()
.id(id)
.name(name)
.build())
)
.status("avaliable")
.build();
return pet;
}
}
| 1,024 | 0.515625 | 0.510742 | 33 | 29.030304 | 21.660583 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 4 |
e91bdfdddac951563225882722c7b0a006aab4b2 | 4,982,162,096,022 | fa627782d9ab4557b047ea68b34126d2391a10cf | /src/main/java/by/makedon/graphicseditor/window/menubar/toolsmenu/item/PencilMenuItem.java | fc851ab9a15c514741a8709cfc0c7c233158171f | [] | no_license | egormakedon/graphics-editor | https://github.com/egormakedon/graphics-editor | c5fd74d6187a28c52dddc29e3cd2091be7da3a77 | ad669066071713ac733a5091ea37653d43ff6952 | refs/heads/master | 2022-04-14T07:26:47.238000 | 2020-03-02T15:09:40 | 2020-03-02T15:09:40 | 83,542,682 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package by.makedon.graphicseditor.window.menubar.toolsmenu.item;
import by.makedon.graphicseditor.manager.DrawManager;
import by.makedon.graphicseditor.tool.ToolManager;
import by.makedon.graphicseditor.tool.impl.Pencil;
import by.makedon.graphicseditor.util.Constants;
import by.makedon.graphicseditor.window.menubar.AbstractMenuItem;
import javax.swing.*;
/**
* @author Yahor Makedon
*/
public class PencilMenuItem extends AbstractMenuItem {
public PencilMenuItem(JMenu toolsMenu) {
super(Constants.PENCIL_MENU_ITEM_NAME, Constants.PENCIL_MENU_ITEM_ICON_PATH);
addActionListener((e) -> {
if (!(DrawManager.getInstance().getTool() instanceof Pencil)) {
setMenuName(toolsMenu, Constants.TOOLS_MENU_NAME, Constants.PENCIL_MENU_ITEM_NAME);
DrawManager.getInstance()
.setTool(ToolManager.getInstance()
.getTool(Pencil.class));
}
});
}
}
| UTF-8 | Java | 1,002 | java | PencilMenuItem.java | Java | [
{
"context": "ctMenuItem;\n\nimport javax.swing.*;\n\n/**\n * @author Yahor Makedon\n */\npublic class PencilMenuItem extends AbstractM",
"end": 389,
"score": 0.9998805522918701,
"start": 376,
"tag": "NAME",
"value": "Yahor Makedon"
}
] | null | [] | package by.makedon.graphicseditor.window.menubar.toolsmenu.item;
import by.makedon.graphicseditor.manager.DrawManager;
import by.makedon.graphicseditor.tool.ToolManager;
import by.makedon.graphicseditor.tool.impl.Pencil;
import by.makedon.graphicseditor.util.Constants;
import by.makedon.graphicseditor.window.menubar.AbstractMenuItem;
import javax.swing.*;
/**
* @author <NAME>
*/
public class PencilMenuItem extends AbstractMenuItem {
public PencilMenuItem(JMenu toolsMenu) {
super(Constants.PENCIL_MENU_ITEM_NAME, Constants.PENCIL_MENU_ITEM_ICON_PATH);
addActionListener((e) -> {
if (!(DrawManager.getInstance().getTool() instanceof Pencil)) {
setMenuName(toolsMenu, Constants.TOOLS_MENU_NAME, Constants.PENCIL_MENU_ITEM_NAME);
DrawManager.getInstance()
.setTool(ToolManager.getInstance()
.getTool(Pencil.class));
}
});
}
}
| 995 | 0.670659 | 0.670659 | 27 | 36.111111 | 29.613977 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.518519 | false | false | 4 |
6176569b003fb1b46856b551469fa5f82bbe0a0f | 30,073,361,039,053 | 60c773dc5a9e425bc25c226ca48cd79a8bc0a662 | /Crypto/src/Caesar.java | 7fcbed1fdcbd1a34934b9a4bf93598a336967b51 | [] | no_license | m0xf4240/Crypto | https://github.com/m0xf4240/Crypto | f906c30c285a0d10ee6561f0091565c987b887cb | 00a2181883ad464a5c28084d0964c28389aa5dec | refs/heads/master | 2021-05-27T13:49:40.138000 | 2013-04-13T06:41:17 | 2013-04-13T06:41:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class Caesar {
private char[] ciphertext;
private int spaceSize;
private Byte[] vig;
private double[] english;
public Caesar(Byte[] vigenered, File gb) throws IOException{
this.setSpaceSize(vigenered.length);
this.setVig(vigenered);
System.out.println("Vig size passed:"+ this.getVig().length);
this.setEnglish(makeEnglish(gb));
decrypt();
//ArrayList<CharBuffer> ciphercol=this.toChars();
}
// public void bruteForce() throws IOException{
// for (int key=0; key<this.getSpaceSize(); key++){
// char[] cleartext = this.decrypt(key);
//// for (int i=0; i<cleartext.length; i++){
//// System.out.print(cleartext[i]);
////// }
//// System.out.println("\n");
////
//// //Press enter to continue
//// System.in.read();
// }
// }
public void decrypt() throws IOException{
System.out.println("In decrypt");
Byte[] v=this.getVig();
// Byte[]b=new Byte[v.length];
//System.out.println("v.size: " + v.size());
// for(int k=0;k<v.length;k++){
// System.out.println(v.get(1)[1]);
// System.out.println("v.getk: " +v.get(k)[1] + " " + k);
// System.out.println("b:");
// for(int i=0;i<v.length;i++){
// System.out.println(b[i]);
// }
double o=calcChi(v);
double [] sure=new double[255];
sure[0]=o;
//System.out.println("Sure.length is: "+ sure.length);
Byte[] thisone=new Byte[v.length];
for(int i=0;i<v.length;i++){
thisone[i]=v[i];
}
for(int i=1;i<sure.length;i++){
thisone=shiftBytes(thisone);
sure[i]=calcChi(thisone);
// if (i%100==0){
// System.out.println(i);
// }
// }
System.out.println("Out");
//System.in.read();
//System.out.println("Comparing Chis in Decrypt");
}
int bestIndex=0;
for(int j=1;j<sure.length;j++ ){
if(!compareChis(sure[bestIndex],sure[j])){
bestIndex=j;
}
}
Byte[] best = shiftBy(v,bestIndex+1); //+1
// v.remove(k);
// v.add(k,check);
//System.in.read();
System.out.println("Setting vig");
this.setVig(best);
}
public boolean compareChis(double o, double s){
//System.out.print("*");
if(o<s){
return true;
//when o is better
}
else
//when s is better
return false;
}
public Byte[] shiftBytes(Byte []b){
//System.out.println("Incrementing Bytes by one");
//System.out.println("Before: " + b[0] + b[1]);
for(int i=0;i<b.length;i++){
// String th=String.valueOf(b[i]);
// Integer thi=Integer.getInteger(th);
// thi=thi+1;
//byte temp =thi.byteValue(); //i].byteValue();
//System.out.println("temp is: "+ temp);
byte temp=b[i].byteValue();
int t=(int)temp;
t=t+1;
temp=(byte)t;
b[i] = Byte.valueOf(temp);
}
//System.out.println("After: " + b[0] + b[1]);
// Byte[] n=new Byte[b.length];
// for(int i=1;i<n.length-1;i++){
// n[i-1]=b[i];
// }
// n[n.length-1]=b[0];
return b;
}
public Byte[] shiftBy(Byte []b, int shift){
// System.out.println("Incrementing Bytes by integer");
// System.out.println("Beforek: " + b[0] + b[1]);
System.out.println(b.length+": shift"+shift);
for(int i=0;i<b.length;i++){
for (int j=0; j<shift; j++) {
System.out.println(b[i].byteValue());
byte temp = b[i].byteValue();
temp++;
b[i] = Byte.valueOf(temp);
}
}
// System.out.println("Afterk: " + b[0] + b[1]);
// Byte[] n=new Byte[b.length];
// for(int i=shift;i<n.length;i++){
// n[i-shift]=b[i];
// }
// for(int i=0;i<shift;i++){
// n[n.length-shift+i]=b[i];
// }
//System.out.println("Returning Incremented Bytes");
return b;
}
public double calcChi(Byte[] b){
// HashMap<Byte, Double> cFreq=new HashMap<Byte, Double>();
//
// for(Byte c:b){
// if(!cFreq.containsKey(c)){
// cFreq.put(c,1.0);
// }
// else{
// cFreq.put(c, cFreq.get(c)+1);
// }
// }
// for (Map.Entry<Byte,Double> entry : cFreq.entrySet()) {
// cFreq.put(entry.getKey(), entry.setValue(entry.getValue()/cFreq.size()));
// }
// //System.out.println("Done Calculatuing frequncies in calcChi");
// double temp=0.0;
// for (Map.Entry<Byte,Double> entry : cFreq.entrySet()) {
// if(this.english.get(entry.getKey())!=null){
// double t1=entry.getValue();
// //System.out.println("entry value: "+ entry.);
// double t2=this.english.get(entry.getKey());
// //temp=temp+((Math.pow(entry.getValue()-this.english.get(entry),2))/this.english.get(entry));
// temp=temp+((Math.pow((t1-t2), 2))/t2);
// }
// else
// temp=temp+1005.99;
// }
// //System.out.println("returnign calcChi");
// return temp;
int[] counts = new int[255];
for(int i=0; i<255; i++) {
counts[i] = 0;
}
//make an expected count array from warandpeace by freq
double sum1 =0;
int size = this.getSpaceSize();
for(int j=0; j<26; j++) {
sum1 = sum1 + Math.pow((counts[j] - size*this.getEnglish()[j]),2)/(size*this.getEnglish()[j]);
}
return sum1;
}
// private char[] decrypt(int key){
// char [] cleartext = new char[this.getCiphertext().length];
// for (int i = 0; i < cleartext.length; i = (i + 1)) {
// cleartext[i] = (char)((this.getSpaceSize() + (this.getCiphertext()[i] - key)) % this.getSpaceSize());
// }
// return cleartext;
// }
public char[] getCiphertext() {
return ciphertext;
}
public void setCiphertext(char[] ciphertext) {
this.ciphertext = ciphertext;
}
public int getSpaceSize() {
return spaceSize;
}
public void setSpaceSize(int spaceSize) {
this.spaceSize = spaceSize;
}
public Byte[] getVig() {
return vig;
}
public void setVig(Byte[] vig) {
this.vig = vig;
}
public double[] makeEnglish(File h) throws IOException{
System.out.println("Making english");
RandomAccessFile b=new RandomAccessFile(h,"r");
byte[]rabbit=new byte[(int)b.length()];
b.read(rabbit);
b.close();
double[] mFreq=new double[255];
for(int i=0;i<rabbit.length; i++){
mFreq[rabbit[i]]+=1;
}
for(double d:mFreq){
d/=(this.getSpaceSize()*6);
}
//this.setEnglish((HashMap<Byte, Double>)mFreq);
return mFreq;
}
public double[] getEnglish() {
return english;
}
public void setEnglish(double[] english) {
this.english = english;
}
}
| UTF-8 | Java | 6,295 | java | Caesar.java | Java | [] | null | [] | import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class Caesar {
private char[] ciphertext;
private int spaceSize;
private Byte[] vig;
private double[] english;
public Caesar(Byte[] vigenered, File gb) throws IOException{
this.setSpaceSize(vigenered.length);
this.setVig(vigenered);
System.out.println("Vig size passed:"+ this.getVig().length);
this.setEnglish(makeEnglish(gb));
decrypt();
//ArrayList<CharBuffer> ciphercol=this.toChars();
}
// public void bruteForce() throws IOException{
// for (int key=0; key<this.getSpaceSize(); key++){
// char[] cleartext = this.decrypt(key);
//// for (int i=0; i<cleartext.length; i++){
//// System.out.print(cleartext[i]);
////// }
//// System.out.println("\n");
////
//// //Press enter to continue
//// System.in.read();
// }
// }
public void decrypt() throws IOException{
System.out.println("In decrypt");
Byte[] v=this.getVig();
// Byte[]b=new Byte[v.length];
//System.out.println("v.size: " + v.size());
// for(int k=0;k<v.length;k++){
// System.out.println(v.get(1)[1]);
// System.out.println("v.getk: " +v.get(k)[1] + " " + k);
// System.out.println("b:");
// for(int i=0;i<v.length;i++){
// System.out.println(b[i]);
// }
double o=calcChi(v);
double [] sure=new double[255];
sure[0]=o;
//System.out.println("Sure.length is: "+ sure.length);
Byte[] thisone=new Byte[v.length];
for(int i=0;i<v.length;i++){
thisone[i]=v[i];
}
for(int i=1;i<sure.length;i++){
thisone=shiftBytes(thisone);
sure[i]=calcChi(thisone);
// if (i%100==0){
// System.out.println(i);
// }
// }
System.out.println("Out");
//System.in.read();
//System.out.println("Comparing Chis in Decrypt");
}
int bestIndex=0;
for(int j=1;j<sure.length;j++ ){
if(!compareChis(sure[bestIndex],sure[j])){
bestIndex=j;
}
}
Byte[] best = shiftBy(v,bestIndex+1); //+1
// v.remove(k);
// v.add(k,check);
//System.in.read();
System.out.println("Setting vig");
this.setVig(best);
}
public boolean compareChis(double o, double s){
//System.out.print("*");
if(o<s){
return true;
//when o is better
}
else
//when s is better
return false;
}
public Byte[] shiftBytes(Byte []b){
//System.out.println("Incrementing Bytes by one");
//System.out.println("Before: " + b[0] + b[1]);
for(int i=0;i<b.length;i++){
// String th=String.valueOf(b[i]);
// Integer thi=Integer.getInteger(th);
// thi=thi+1;
//byte temp =thi.byteValue(); //i].byteValue();
//System.out.println("temp is: "+ temp);
byte temp=b[i].byteValue();
int t=(int)temp;
t=t+1;
temp=(byte)t;
b[i] = Byte.valueOf(temp);
}
//System.out.println("After: " + b[0] + b[1]);
// Byte[] n=new Byte[b.length];
// for(int i=1;i<n.length-1;i++){
// n[i-1]=b[i];
// }
// n[n.length-1]=b[0];
return b;
}
public Byte[] shiftBy(Byte []b, int shift){
// System.out.println("Incrementing Bytes by integer");
// System.out.println("Beforek: " + b[0] + b[1]);
System.out.println(b.length+": shift"+shift);
for(int i=0;i<b.length;i++){
for (int j=0; j<shift; j++) {
System.out.println(b[i].byteValue());
byte temp = b[i].byteValue();
temp++;
b[i] = Byte.valueOf(temp);
}
}
// System.out.println("Afterk: " + b[0] + b[1]);
// Byte[] n=new Byte[b.length];
// for(int i=shift;i<n.length;i++){
// n[i-shift]=b[i];
// }
// for(int i=0;i<shift;i++){
// n[n.length-shift+i]=b[i];
// }
//System.out.println("Returning Incremented Bytes");
return b;
}
public double calcChi(Byte[] b){
// HashMap<Byte, Double> cFreq=new HashMap<Byte, Double>();
//
// for(Byte c:b){
// if(!cFreq.containsKey(c)){
// cFreq.put(c,1.0);
// }
// else{
// cFreq.put(c, cFreq.get(c)+1);
// }
// }
// for (Map.Entry<Byte,Double> entry : cFreq.entrySet()) {
// cFreq.put(entry.getKey(), entry.setValue(entry.getValue()/cFreq.size()));
// }
// //System.out.println("Done Calculatuing frequncies in calcChi");
// double temp=0.0;
// for (Map.Entry<Byte,Double> entry : cFreq.entrySet()) {
// if(this.english.get(entry.getKey())!=null){
// double t1=entry.getValue();
// //System.out.println("entry value: "+ entry.);
// double t2=this.english.get(entry.getKey());
// //temp=temp+((Math.pow(entry.getValue()-this.english.get(entry),2))/this.english.get(entry));
// temp=temp+((Math.pow((t1-t2), 2))/t2);
// }
// else
// temp=temp+1005.99;
// }
// //System.out.println("returnign calcChi");
// return temp;
int[] counts = new int[255];
for(int i=0; i<255; i++) {
counts[i] = 0;
}
//make an expected count array from warandpeace by freq
double sum1 =0;
int size = this.getSpaceSize();
for(int j=0; j<26; j++) {
sum1 = sum1 + Math.pow((counts[j] - size*this.getEnglish()[j]),2)/(size*this.getEnglish()[j]);
}
return sum1;
}
// private char[] decrypt(int key){
// char [] cleartext = new char[this.getCiphertext().length];
// for (int i = 0; i < cleartext.length; i = (i + 1)) {
// cleartext[i] = (char)((this.getSpaceSize() + (this.getCiphertext()[i] - key)) % this.getSpaceSize());
// }
// return cleartext;
// }
public char[] getCiphertext() {
return ciphertext;
}
public void setCiphertext(char[] ciphertext) {
this.ciphertext = ciphertext;
}
public int getSpaceSize() {
return spaceSize;
}
public void setSpaceSize(int spaceSize) {
this.spaceSize = spaceSize;
}
public Byte[] getVig() {
return vig;
}
public void setVig(Byte[] vig) {
this.vig = vig;
}
public double[] makeEnglish(File h) throws IOException{
System.out.println("Making english");
RandomAccessFile b=new RandomAccessFile(h,"r");
byte[]rabbit=new byte[(int)b.length()];
b.read(rabbit);
b.close();
double[] mFreq=new double[255];
for(int i=0;i<rabbit.length; i++){
mFreq[rabbit[i]]+=1;
}
for(double d:mFreq){
d/=(this.getSpaceSize()*6);
}
//this.setEnglish((HashMap<Byte, Double>)mFreq);
return mFreq;
}
public double[] getEnglish() {
return english;
}
public void setEnglish(double[] english) {
this.english = english;
}
}
| 6,295 | 0.590627 | 0.577442 | 249 | 24.281124 | 20.389414 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.180723 | false | false | 4 |
9f1365d42110809d4ac00cdbf9b219261d718272 | 21,930,103,075,296 | 773b90096085c3266210ba7b4a0b62b7a9b74e13 | /LeituraArquivoDelimetado/src/Aplicativo.java | 1ee0f7a070a2a511f00ff4e23d7a464484a7c623 | [] | no_license | Marcosdbras/workspace-java | https://github.com/Marcosdbras/workspace-java | 831259f1c36bb4abd30cf54b0da7b1d9ac13f59e | 6596dcd87e99056a69139c7359dec98ba0eca1de | refs/heads/master | 2021-01-01T06:03:17.967000 | 2017-10-01T13:24:41 | 2017-10-01T13:24:41 | 97,344,804 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.File;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Aplicativo {
public static void main(String[] args) throws Exception {
int[][] elementos = new int[4][4];
//Informando o que localizar, no caso somente dígito
Pattern p = Pattern.compile("\\d");
Scanner s = new Scanner(new File("dados.txt") );
int j = 0;
while (s.hasNextLine()) {
String line = s.nextLine();
//Localizando o que está definido no Pattern
Matcher m = p.matcher(line);
int i = 0;
while (m.find()) {
elementos[j][i] = Integer.parseInt(m.group());
i++;
}
j++;
}
for (int a = 0; a < elementos.length;a++) {
for (int b = 0; b < elementos[a].length;b++) {
System.out.print(elementos[a][b]+"\t");
}
System.out.println();
}
}
}
| UTF-8 | Java | 924 | java | Aplicativo.java | Java | [] | null | [] | import java.io.File;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Aplicativo {
public static void main(String[] args) throws Exception {
int[][] elementos = new int[4][4];
//Informando o que localizar, no caso somente dígito
Pattern p = Pattern.compile("\\d");
Scanner s = new Scanner(new File("dados.txt") );
int j = 0;
while (s.hasNextLine()) {
String line = s.nextLine();
//Localizando o que está definido no Pattern
Matcher m = p.matcher(line);
int i = 0;
while (m.find()) {
elementos[j][i] = Integer.parseInt(m.group());
i++;
}
j++;
}
for (int a = 0; a < elementos.length;a++) {
for (int b = 0; b < elementos[a].length;b++) {
System.out.print(elementos[a][b]+"\t");
}
System.out.println();
}
}
}
| 924 | 0.555315 | 0.548807 | 55 | 15.763637 | 17.730265 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.654546 | false | false | 4 |
ead6b2855f429374bc1e76ae48aa970c999c8ec0 | 16,492,674,459,378 | 006ec49031555f1232fb4a0ec60149ddf2016498 | /app/src/main/java/com/example/administrator/itsdemo/fragment/SetCarMoneyFragment.java | 0fc40b4acc82d4375a3f8ecfbe2414590dfeb04f | [] | no_license | Merpyzf/ITSDemo | https://github.com/Merpyzf/ITSDemo | bfd64e33a5833497b0ddceec6ae949de798564f9 | 97694dfbc25d379752ed5f45385f1a14cdeed0cc | refs/heads/master | 2021-01-21T17:24:31.699000 | 2017-05-25T04:19:45 | 2017-05-25T04:19:45 | 91,952,488 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.administrator.itsdemo.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.administrator.itsdemo.Common;
import com.example.administrator.itsdemo.R;
import com.example.administrator.itsdemo.utils.HttpAsyncUtils;
import com.example.administrator.itsdemo.utils.PreUtils;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by Administrator on 2017/5/12.
*/
public class SetCarMoneyFragment extends Fragment {
private Button btn_getCarSpeed;
private SeekBar seekBar;
private EditText edit_max;
private EditText edit_min;
private int max;
private int min;
private Button btn_setCarSpeed;
private int currentValue;
private View view;
private TextView carShow;
private Button carStar;//开始监控
private Timer timer = null;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
savedInstanceState) {
view = inflater.inflate(R.layout.fragment_set_car_money, container,false);
iniUI();
iniEvent();
return view;
}
private void iniEvent() {
//获取小车阀值
btn_getCarSpeed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//
currentValue = seekBar.getProgress();
min = PreUtils.getInt(getContext(),currentValue+"号车min金额", 20);
max = PreUtils.getInt(getContext(),currentValue+"号车max金额", 60);
edit_min.setText("" + min);
// edit_max.setText("" + max);
}
});
//设置小车阀值
btn_setCarSpeed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String _min = edit_min.getText().toString();
String _max = edit_max.getText().toString();
if(TextUtils.isEmpty(_max)) {
max = 60;
}else{
max = Integer.parseInt(_max);
}
if(TextUtils.isEmpty(_min)) {
min = 20;
}else{
min = Integer.parseInt(_min);
}
currentValue = seekBar.getProgress();
PreUtils.setInt(getContext(), currentValue+"号车min金额",min);
PreUtils.setInt(getContext(), currentValue+"号车max金额",max);
Toast.makeText(getContext(), "设置成功", Toast.LENGTH_SHORT).show();
}
});
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
carShow.setText(progress+ "号车");
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
carStar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//开始监控
currentValue = seekBar.getProgress();
min = PreUtils.getInt(getContext(),currentValue+"号车min金额", 20);
max = PreUtils.getInt(getContext(),currentValue+"号车max金额", 60);
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
new HttpAsyncUtils(Common.GET_CAR_ACCOUNT_BALANCE, "{\"CarId\":" + currentValue + ", " +
"\"UserName\":\"Z0004\"}") {
@Override
public void success(String data) {
try {
JSONObject obj = new JSONObject(data);
int money = (int) obj.get("Balance");
Log.i("TAG", "success: " + money);
if(money<min){
Toast.makeText(getContext(), "余额不足,请充值", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void error() {
}
};
}
};
timer = new Timer();
timer.schedule(timerTask,0,5000);
}
});
}
private void iniUI() {
btn_setCarSpeed = (Button) view.findViewById(R.id.car_set_money_value);
btn_getCarSpeed = (Button) view.findViewById(R.id.car_get_money);
carStar = (Button) view.findViewById(R.id.car_money_start);
seekBar = (SeekBar) view.findViewById(R.id.car_money_seek_bar);
edit_min = (EditText) view.findViewById(R.id.car_money_min);
edit_max = (EditText) view.findViewById(R.id.car_money_max);
carShow = (TextView) view.findViewById(R.id.car_money_value_show);
seekBar.setProgress(1);
}
@Override
public void onDestroy() {
if(timer !=null){
timer.cancel();
}
super.onDestroy();
}
}
| UTF-8 | Java | 6,323 | java | SetCarMoneyFragment.java | Java | [
{
"context": "er;\nimport java.util.TimerTask;\n\n/**\n * Created by Administrator on 2017/5/12.\n */\n\npublic class SetCarMoneyFragme",
"end": 1082,
"score": 0.9584813714027405,
"start": 1069,
"tag": "NAME",
"value": "Administrator"
},
{
"context": "+\n \"\\\"UserName\\\":\\\"Z0004\\\"}\") {\n @Override\n ",
"end": 4430,
"score": 0.9995130300521851,
"start": 4425,
"tag": "USERNAME",
"value": "Z0004"
}
] | null | [] | package com.example.administrator.itsdemo.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.administrator.itsdemo.Common;
import com.example.administrator.itsdemo.R;
import com.example.administrator.itsdemo.utils.HttpAsyncUtils;
import com.example.administrator.itsdemo.utils.PreUtils;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by Administrator on 2017/5/12.
*/
public class SetCarMoneyFragment extends Fragment {
private Button btn_getCarSpeed;
private SeekBar seekBar;
private EditText edit_max;
private EditText edit_min;
private int max;
private int min;
private Button btn_setCarSpeed;
private int currentValue;
private View view;
private TextView carShow;
private Button carStar;//开始监控
private Timer timer = null;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
savedInstanceState) {
view = inflater.inflate(R.layout.fragment_set_car_money, container,false);
iniUI();
iniEvent();
return view;
}
private void iniEvent() {
//获取小车阀值
btn_getCarSpeed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//
currentValue = seekBar.getProgress();
min = PreUtils.getInt(getContext(),currentValue+"号车min金额", 20);
max = PreUtils.getInt(getContext(),currentValue+"号车max金额", 60);
edit_min.setText("" + min);
// edit_max.setText("" + max);
}
});
//设置小车阀值
btn_setCarSpeed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String _min = edit_min.getText().toString();
String _max = edit_max.getText().toString();
if(TextUtils.isEmpty(_max)) {
max = 60;
}else{
max = Integer.parseInt(_max);
}
if(TextUtils.isEmpty(_min)) {
min = 20;
}else{
min = Integer.parseInt(_min);
}
currentValue = seekBar.getProgress();
PreUtils.setInt(getContext(), currentValue+"号车min金额",min);
PreUtils.setInt(getContext(), currentValue+"号车max金额",max);
Toast.makeText(getContext(), "设置成功", Toast.LENGTH_SHORT).show();
}
});
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
carShow.setText(progress+ "号车");
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
carStar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//开始监控
currentValue = seekBar.getProgress();
min = PreUtils.getInt(getContext(),currentValue+"号车min金额", 20);
max = PreUtils.getInt(getContext(),currentValue+"号车max金额", 60);
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
new HttpAsyncUtils(Common.GET_CAR_ACCOUNT_BALANCE, "{\"CarId\":" + currentValue + ", " +
"\"UserName\":\"Z0004\"}") {
@Override
public void success(String data) {
try {
JSONObject obj = new JSONObject(data);
int money = (int) obj.get("Balance");
Log.i("TAG", "success: " + money);
if(money<min){
Toast.makeText(getContext(), "余额不足,请充值", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void error() {
}
};
}
};
timer = new Timer();
timer.schedule(timerTask,0,5000);
}
});
}
private void iniUI() {
btn_setCarSpeed = (Button) view.findViewById(R.id.car_set_money_value);
btn_getCarSpeed = (Button) view.findViewById(R.id.car_get_money);
carStar = (Button) view.findViewById(R.id.car_money_start);
seekBar = (SeekBar) view.findViewById(R.id.car_money_seek_bar);
edit_min = (EditText) view.findViewById(R.id.car_money_min);
edit_max = (EditText) view.findViewById(R.id.car_money_max);
carShow = (TextView) view.findViewById(R.id.car_money_value_show);
seekBar.setProgress(1);
}
@Override
public void onDestroy() {
if(timer !=null){
timer.cancel();
}
super.onDestroy();
}
}
| 6,323 | 0.548091 | 0.543258 | 202 | 29.727722 | 25.991241 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.564356 | false | false | 4 |
7e61db5c3bf591f895864e5dd1b0dfc38242af2a | 6,107,443,536,122 | 091c44879f019b7a009e03ad43a8ae01ccbe392e | /CafeteriaBW/src/cdp/Canela.java | f91c97ca3db74f73f921f176c3acef6cb2f10e80 | [] | no_license | neimarp/AbstractFactory | https://github.com/neimarp/AbstractFactory | aafdcdcd8a6b4cc528c2f588c8248164892c8c10 | bb650d0e4a41375e227988a05de1a64614f05e0c | refs/heads/master | 2021-01-10T07:03:10.813000 | 2015-10-14T10:57:57 | 2015-10-14T10:57:57 | 44,219,783 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cdp;
public class Canela extends Ingrediente {
public Canela(int qtd) {
super("canela", qtd,"g");
}
}
| UTF-8 | Java | 117 | java | Canela.java | Java | [] | null | [] | package cdp;
public class Canela extends Ingrediente {
public Canela(int qtd) {
super("canela", qtd,"g");
}
}
| 117 | 0.666667 | 0.666667 | 9 | 12 | 14.483707 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.888889 | false | false | 4 |
71ae9626ffdf2dea6210526b4006c713c8e5ae52 | 24,000,277,294,919 | da2a39281a888eab0f44da859512a2759fd898bb | /newbijia/newbijia/src/com/llkj/newbjia/sortlistview/SortModel.java | 95bb65cc61e2f1fcf8a1d6a588924ecb92f84cd5 | [] | no_license | theBjia/bjia | https://github.com/theBjia/bjia | 250c1332331e0e0553a63abb67759d604eb4cace | 36ada00cef85be9c42fa23329c8e15d88bc26ccf | refs/heads/master | 2020-12-31T00:17:53.051000 | 2015-05-31T03:38:22 | 2015-05-31T03:38:22 | 36,276,388 | 3 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.llkj.newbjia.sortlistview;
public class SortModel {
private String name; // 显示的数据
private String sortLetters; // 显示数据拼音的首字母
private String pic;
private String uid;
private String phone;
private String flag;
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSortLetters() {
return sortLetters;
}
public void setSortLetters(String sortLetters) {
this.sortLetters = sortLetters;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
| UTF-8 | Java | 936 | java | SortModel.java | Java | [] | null | [] | package com.llkj.newbjia.sortlistview;
public class SortModel {
private String name; // 显示的数据
private String sortLetters; // 显示数据拼音的首字母
private String pic;
private String uid;
private String phone;
private String flag;
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSortLetters() {
return sortLetters;
}
public void setSortLetters(String sortLetters) {
this.sortLetters = sortLetters;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
| 936 | 0.684327 | 0.684327 | 64 | 13.15625 | 13.93312 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.140625 | false | false | 4 |
f3baeda2017c3cf07af190aafb790d7babf99bdd | 20,607,253,105,814 | 273beca6f1e92a4b3fb9c6bf509ba0c50e754889 | /src/com/company/Main.java | 9b215e3b65644de8487dd565001ecca62da1a09e | [] | no_license | Freatnor/Interfaces-and-Abstract-Classes-Lab | https://github.com/Freatnor/Interfaces-and-Abstract-Classes-Lab | dcd1babff46211333d4bbdba1f80ed4cb3504fec | d2878ccd510444bd9fc67f314853c9009741ddc9 | refs/heads/master | 2021-01-17T09:31:47.471000 | 2016-06-28T21:12:41 | 2016-06-28T21:12:41 | 62,169,432 | 0 | 0 | null | true | 2016-06-28T19:44:55 | 2016-06-28T19:44:53 | 2016-06-28T14:21:13 | 2016-06-28T16:47:11 | 1 | 0 | 0 | 0 | null | null | null | package com.company;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// write your code here
List<Remote> remotes = new ArrayList<>();
remotes.add(new Samsung());
remotes.add(new LG());
remotes.add(new Panasonic());
remotes.add(new Sony());
remotes.add(new Toshiba());
remotes.add(new Sharp());
int i = 0;
for (Remote remote : remotes) {
remote.numberButtonPressed(i);
remote.channelDown();
remote.channelUp();
i++;
}
}
}
| UTF-8 | Java | 629 | java | Main.java | Java | [] | null | [] | package com.company;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// write your code here
List<Remote> remotes = new ArrayList<>();
remotes.add(new Samsung());
remotes.add(new LG());
remotes.add(new Panasonic());
remotes.add(new Sony());
remotes.add(new Toshiba());
remotes.add(new Sharp());
int i = 0;
for (Remote remote : remotes) {
remote.numberButtonPressed(i);
remote.channelDown();
remote.channelUp();
i++;
}
}
}
| 629 | 0.551669 | 0.550079 | 28 | 21.464285 | 15.630744 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 4 |
c47dba83399a0af0bd24c2698f04baec8fe3153f | 20,607,253,104,989 | da386f7a5b380ce4c991336f055210d694df94a6 | /src/test/Main.java | b53d6e86642b4ac092d92b52bc10283b8e2c1ff3 | [] | no_license | somyungsub/outsourcing-java | https://github.com/somyungsub/outsourcing-java | 3728d31088ba5abd8447278b0358cf6f6ec7e7ce | 6e2bbf091990836899fad80cae34bdc0690f4bf7 | refs/heads/master | 2021-06-25T21:27:23.357000 | 2020-10-03T23:58:18 | 2020-10-03T23:58:18 | 130,565,934 | 6 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("src\\test\\test.txt");
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis, "utf-8"));
String str = "";
String save = "";
Map<Integer, String> map = new HashMap<>();
int count = 0;
while ((str = br.readLine()) != null) {
if (str.equals(";")) {
map.put(count++, save);
save = "";
}
save += str;
}
map.put(count, save);
for (Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getValue().length());
}
}
}
| UTF-8 | Java | 981 | java | Main.java | Java | [] | null | [] | package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("src\\test\\test.txt");
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis, "utf-8"));
String str = "";
String save = "";
Map<Integer, String> map = new HashMap<>();
int count = 0;
while ((str = br.readLine()) != null) {
if (str.equals(";")) {
map.put(count++, save);
save = "";
}
save += str;
}
map.put(count, save);
for (Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getValue().length());
}
}
}
| 981 | 0.571865 | 0.569827 | 32 | 29.65625 | 20.043093 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8125 | false | false | 4 |
18cb478fc3c9240030fc3e7533a445c1c483fbc7 | 32,512,902,473,750 | 87d7616caf0a6f81a6891fee214cd034260cb674 | /dmzapi/src/main/java/com/dmz/library/dmzapi/utils/DateUtils.java | 752f530077c9e1b4d4ed212a1594c956bb5bd065 | [] | no_license | dmz1024/EBusiness | https://github.com/dmz1024/EBusiness | 1ba38bdf100ad2e89abcce6c956f8e984d9feb52 | 84a9b2069becaaff5f7a760b62419878d64af40e | refs/heads/master | 2021-08-15T05:00:40.118000 | 2017-11-17T11:04:30 | 2017-11-17T11:04:30 | 103,493,861 | 1 | 2 | null | false | 2017-11-17T11:04:31 | 2017-09-14T06:20:46 | 2017-10-08T20:00:38 | 2017-11-17T11:04:31 | 174,779 | 1 | 1 | 1 | Java | false | null | package com.dmz.library.dmzapi.utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class DateUtils {
// 输入年月日,获得星期值
public static String returnWeek(int year, int month, int day) {
// 根据日历类对象的方法,实例化一个当前的日历类对象
Calendar calendar = Calendar.getInstance();
// 设置日历对象的年月日
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);// �·���0-11
calendar.set(Calendar.DAY_OF_MONTH, day);
// 得到本月中的第一天是星期几
int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
String[] weeks = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};// 字符串数组
return weeks[week];
}
// 输入年月,得到那个月1号是星期几
public static int returnFirstdayIsWeek(int year, int month) {
// 根据日历类对象的方法,实例化一个当前的日历类对象
Calendar calendar = Calendar.getInstance();
// 设置日历对象的年月日
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);// 月份是0-11
calendar.set(Calendar.DAY_OF_MONTH, 1);
// 得到本月中的第一天是星期几
int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
int[] weeks = {0, 1, 2, 3, 4, 5, 6};// 字符串数组
return weeks[week];
}
// 输入年月,得到那个月一共多少天
public static int maxDayOfMonth(int year, int month) {
// 根据日历类对象的方法,实例化一个当前的日历类对象
Calendar calendar = Calendar.getInstance();
// 设置日历对象的年月日
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);// 月份是0-11
calendar.set(Calendar.DAY_OF_MONTH, 1);
// 得到当前月份的最大值
int day = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
return day;
}
public static String getYMD() {
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return sDateFormat.format(System.currentTimeMillis());
}
public static int getHour(){
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.HOUR_OF_DAY);
}
} | UTF-8 | Java | 2,418 | java | DateUtils.java | Java | [] | null | [] | package com.dmz.library.dmzapi.utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class DateUtils {
// 输入年月日,获得星期值
public static String returnWeek(int year, int month, int day) {
// 根据日历类对象的方法,实例化一个当前的日历类对象
Calendar calendar = Calendar.getInstance();
// 设置日历对象的年月日
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);// �·���0-11
calendar.set(Calendar.DAY_OF_MONTH, day);
// 得到本月中的第一天是星期几
int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
String[] weeks = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};// 字符串数组
return weeks[week];
}
// 输入年月,得到那个月1号是星期几
public static int returnFirstdayIsWeek(int year, int month) {
// 根据日历类对象的方法,实例化一个当前的日历类对象
Calendar calendar = Calendar.getInstance();
// 设置日历对象的年月日
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);// 月份是0-11
calendar.set(Calendar.DAY_OF_MONTH, 1);
// 得到本月中的第一天是星期几
int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
int[] weeks = {0, 1, 2, 3, 4, 5, 6};// 字符串数组
return weeks[week];
}
// 输入年月,得到那个月一共多少天
public static int maxDayOfMonth(int year, int month) {
// 根据日历类对象的方法,实例化一个当前的日历类对象
Calendar calendar = Calendar.getInstance();
// 设置日历对象的年月日
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);// 月份是0-11
calendar.set(Calendar.DAY_OF_MONTH, 1);
// 得到当前月份的最大值
int day = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
return day;
}
public static String getYMD() {
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return sDateFormat.format(System.currentTimeMillis());
}
public static int getHour(){
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.HOUR_OF_DAY);
}
} | 2,418 | 0.616742 | 0.604639 | 64 | 30 | 23.348581 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.859375 | false | false | 4 |
9210e97b0e458ab44716531957cb26803ee67045 | 38,826,504,367,106 | 33487a51096e45bb5825ad7efcb9dbd79f309415 | /src/test/java/com/mau/practice/MinAvgTwoSlice.java | 9e9b9fd62de09372a78867d3c65386f0b5574f60 | [] | no_license | MauF/codility-tests | https://github.com/MauF/codility-tests | 059dcfc962a69cbc969ee58f0327b46af8b47bf0 | 57d1d9948a3cf841a161d3fce48ab29b5405afc6 | refs/heads/master | 2020-03-31T13:51:51.147000 | 2018-11-26T23:02:57 | 2018-11-26T23:02:57 | 152,271,230 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mau.practice;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import java.util.TreeMap;
import java.util.TreeSet;
public class MinAvgTwoSlice {
class Solution {
public int[] prefixSum(int[] A) {
int[] ret = new int[A.length];
ret[0] = A[0];
for (int i = 1; i < A.length; i++) {
ret[i] = ret[i - 1] + A[i];
}
return ret;
}
public int solution(int[] A) {
//main idea: will find min average by checking only 2 and 3 contiguous elements at a time
int sum1, sum2 = 0;
double minAverage = Double.MAX_VALUE;
double currentAverage1 = Double.MAX_VALUE;
double currentAverage2 = Double.MAX_VALUE;
int minAverageSliceIndex = 0; //for size 2 arrays, this will always be true
//if array is > 2 elements
for (int i = 0; i < A.length - 2; i++) {
sum1 = A[i] + A[i + 1];
currentAverage1 = sum1 / 2.0d;
if (currentAverage1 < minAverage) {
minAverage = currentAverage1;
minAverageSliceIndex = i;
}
sum2 = sum1 + A[i + 2];
currentAverage2 = sum2 / 3.0d;
if (currentAverage2 < minAverage) {
minAverage = currentAverage2;
minAverageSliceIndex = i;
}
}
//check last 2 contiguous elements from the end - they won't otherwise be checked because
//when checking 2 and 3 contiguous elements at a time, will stop checking 3 elements from the end
currentAverage1 = (A[A.length - 2] + A[A.length - 1]) / 2.0d;
if (currentAverage1 < minAverage) {
minAverage = currentAverage1;
minAverageSliceIndex = A.length - 2;
}
return minAverageSliceIndex;
}
}
@Test
public void test_01() {
Solution s = new Solution();
// s.prefixSum(new int[]{10, 4, 16, 20});
Assertions.assertEquals(1, s.solution(new int[]{4, 2, 2, 5, 1, 5, 8}));
}
@Test
public void test_02() {
Solution s = new Solution();
Assertions.assertArrayEquals(new int[]{10, 14, 30, 50}, s.prefixSum(new int[]{10, 4, 16, 20}));
}
}
| UTF-8 | Java | 2,436 | java | MinAvgTwoSlice.java | Java | [] | null | [] | package com.mau.practice;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import java.util.TreeMap;
import java.util.TreeSet;
public class MinAvgTwoSlice {
class Solution {
public int[] prefixSum(int[] A) {
int[] ret = new int[A.length];
ret[0] = A[0];
for (int i = 1; i < A.length; i++) {
ret[i] = ret[i - 1] + A[i];
}
return ret;
}
public int solution(int[] A) {
//main idea: will find min average by checking only 2 and 3 contiguous elements at a time
int sum1, sum2 = 0;
double minAverage = Double.MAX_VALUE;
double currentAverage1 = Double.MAX_VALUE;
double currentAverage2 = Double.MAX_VALUE;
int minAverageSliceIndex = 0; //for size 2 arrays, this will always be true
//if array is > 2 elements
for (int i = 0; i < A.length - 2; i++) {
sum1 = A[i] + A[i + 1];
currentAverage1 = sum1 / 2.0d;
if (currentAverage1 < minAverage) {
minAverage = currentAverage1;
minAverageSliceIndex = i;
}
sum2 = sum1 + A[i + 2];
currentAverage2 = sum2 / 3.0d;
if (currentAverage2 < minAverage) {
minAverage = currentAverage2;
minAverageSliceIndex = i;
}
}
//check last 2 contiguous elements from the end - they won't otherwise be checked because
//when checking 2 and 3 contiguous elements at a time, will stop checking 3 elements from the end
currentAverage1 = (A[A.length - 2] + A[A.length - 1]) / 2.0d;
if (currentAverage1 < minAverage) {
minAverage = currentAverage1;
minAverageSliceIndex = A.length - 2;
}
return minAverageSliceIndex;
}
}
@Test
public void test_01() {
Solution s = new Solution();
// s.prefixSum(new int[]{10, 4, 16, 20});
Assertions.assertEquals(1, s.solution(new int[]{4, 2, 2, 5, 1, 5, 8}));
}
@Test
public void test_02() {
Solution s = new Solution();
Assertions.assertArrayEquals(new int[]{10, 14, 30, 50}, s.prefixSum(new int[]{10, 4, 16, 20}));
}
}
| 2,436 | 0.525452 | 0.493021 | 75 | 31.48 | 27.241322 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.746667 | false | false | 4 |
f87a840758549e920dcaceb050903208d17ae432 | 36,266,703,886,786 | 4c8d889ddd11b642343804d2ebed6429558bf5b4 | /CODE/Exam_2/sach.java | 7ad0bec87b8d6d98996c9240a86e86bcf3839b21 | [] | no_license | nhatnguyen789/Lap_trinh_JAVA | https://github.com/nhatnguyen789/Lap_trinh_JAVA | 3d305dd0ff7ab169a42854157141c96e1048633d | 0e2f4e84c5d8fa897eb4935a91c51a9294ffd3c4 | refs/heads/main | 2023-07-28T15:29:19.465000 | 2021-09-02T15:35:39 | 2021-09-02T15:35:39 | 402,461,671 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class sach {
protected String Sach;
protected String tacgia;
protected int soluong;
public void setSoluong(int soluong) {
this.soluong = soluong;
}
public void setSach(String sach) {
Sach = sach;
}
public void setTacgia(String tacgia) {
this.tacgia = tacgia;
}
public String getSach() {
return Sach;
}
public int getSoluong() {
return soluong;
}
public String getTacgia() {
return tacgia;
}
public void Input()
{
Scanner scanner = new Scanner(System.in);
System.out.print("sach : ");
Sach = scanner.nextLine();
}
public sach() {};
public sach(String sach,String tacgia,String soluong){};
}
| UTF-8 | Java | 821 | java | sach.java | Java | [] | null | [] | import java.util.Scanner;
public class sach {
protected String Sach;
protected String tacgia;
protected int soluong;
public void setSoluong(int soluong) {
this.soluong = soluong;
}
public void setSach(String sach) {
Sach = sach;
}
public void setTacgia(String tacgia) {
this.tacgia = tacgia;
}
public String getSach() {
return Sach;
}
public int getSoluong() {
return soluong;
}
public String getTacgia() {
return tacgia;
}
public void Input()
{
Scanner scanner = new Scanner(System.in);
System.out.print("sach : ");
Sach = scanner.nextLine();
}
public sach() {};
public sach(String sach,String tacgia,String soluong){};
}
| 821 | 0.557856 | 0.557856 | 39 | 19.051283 | 15.801572 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.435897 | false | false | 4 |
dfdd6f033b94cd43213d820685d9e464c9b26021 | 39,273,180,961,428 | 5220bc5021e7d4b34785478522942d34c7f4d38f | /bundles/target/src/main/java/org/jscsi/target/scsi/modeSense/ModeParameterHeader6.java | 13e4c9af6eda08aced11b693b18ec38a9d2545ff | [
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] | permissive | yorkart/jSCSI | https://github.com/yorkart/jSCSI | c197d88854a87bf15931e5086ceabb17bc55cb51 | 05dc742b2a1be64562a8afbf2467d4193d73d6f0 | refs/heads/master | 2020-07-28T19:51:03.974000 | 2019-09-21T14:08:50 | 2019-09-21T14:08:50 | 209,516,955 | 0 | 0 | BSD-3-Clause | true | 2019-09-19T09:41:53 | 2019-09-19T09:41:52 | 2019-09-07T03:53:00 | 2018-01-22T20:37:33 | 70,412 | 0 | 0 | 0 | null | false | false | package org.jscsi.target.scsi.modeSense;
import java.nio.ByteBuffer;
/**
* A {@link ModeParameterHeader} sub-class. Instances of this class are sent in response to <code>MODE SENSE (6)</code>
* SCSI commands and have a serialized length of 4 bytes.
*
* @author Andreas Ergenzinger
*/
public final class ModeParameterHeader6 extends ModeParameterHeader {
/**
* The length of this object when serialized.
*/
static final int SIZE = 4;
/**
* The length in bytes of the MODE DATA LENGTH field.
*/
static final int MODE_DATA_LENGTH_FIELD_SIZE = 1;
/**
* The constructor.
*
* @param modeDataLength the total length in bytes of all MODE DATA list elements
* @param blockDescriptorLength the total length in bytes of all BLOCK DESCRIPTOR list elements
*/
public ModeParameterHeader6(final int modeDataLength, final int blockDescriptorLength) {
super(modeDataLength, blockDescriptorLength);
}
public void serialize(ByteBuffer byteBuffer, int index) {
byteBuffer.position(index);
byteBuffer.put((byte) modeDataLength);
byteBuffer.put(mediumType);
byteBuffer.put(deviceSpecificParameter);
byteBuffer.put((byte) blockDescriptorLength);
}
public int size() {
return SIZE;
}
}
| UTF-8 | Java | 1,377 | java | ModeParameterHeader6.java | Java | [
{
"context": "ve a serialized length of 4 bytes.\r\n *\r\n * @author Andreas Ergenzinger\r\n */\r\npublic final class ModeParameterHeader6 ext",
"end": 298,
"score": 0.9998372197151184,
"start": 279,
"tag": "NAME",
"value": "Andreas Ergenzinger"
}
] | null | [] | package org.jscsi.target.scsi.modeSense;
import java.nio.ByteBuffer;
/**
* A {@link ModeParameterHeader} sub-class. Instances of this class are sent in response to <code>MODE SENSE (6)</code>
* SCSI commands and have a serialized length of 4 bytes.
*
* @author <NAME>
*/
public final class ModeParameterHeader6 extends ModeParameterHeader {
/**
* The length of this object when serialized.
*/
static final int SIZE = 4;
/**
* The length in bytes of the MODE DATA LENGTH field.
*/
static final int MODE_DATA_LENGTH_FIELD_SIZE = 1;
/**
* The constructor.
*
* @param modeDataLength the total length in bytes of all MODE DATA list elements
* @param blockDescriptorLength the total length in bytes of all BLOCK DESCRIPTOR list elements
*/
public ModeParameterHeader6(final int modeDataLength, final int blockDescriptorLength) {
super(modeDataLength, blockDescriptorLength);
}
public void serialize(ByteBuffer byteBuffer, int index) {
byteBuffer.position(index);
byteBuffer.put((byte) modeDataLength);
byteBuffer.put(mediumType);
byteBuffer.put(deviceSpecificParameter);
byteBuffer.put((byte) blockDescriptorLength);
}
public int size() {
return SIZE;
}
}
| 1,364 | 0.6565 | 0.652142 | 47 | 27.297873 | 30.790932 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.297872 | false | false | 4 |
d00d258989d7cdf0aaf30c2d80faca9dcc72ad47 | 39,298,950,780,056 | 93ebfce8ad8369763b77fd34ce2f9b050f8b1741 | /app/src/main/java/com/nychareport/backlog/activities/MainActivity.java | 740efcf50d58d93fe02516bd660e24ce6fc51fac | [] | no_license | benrosenthal/Project-4 | https://github.com/benrosenthal/Project-4 | 358f72ab451cd26b8795ccb3b787a1823922eba3 | 4352591fbcdca968a894608424a0c3815aeb9a6b | refs/heads/master | 2021-01-18T16:16:47.290000 | 2016-05-09T16:31:09 | 2016-05-09T16:31:09 | 54,145,993 | 0 | 0 | null | true | 2016-03-17T19:33:14 | 2016-03-17T19:33:13 | 2016-03-16T14:11:16 | 2016-03-17T18:37:14 | 412 | 0 | 0 | 0 | null | null | null | package com.nychareport.backlog.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.nychareport.backlog.R;
public class MainActivity extends AppCompatActivity {
private Button postProblemButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeViews();
}
private void initializeViews() {
postProblemButton = (Button) findViewById(R.id.btn_make_post);
postProblemButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, PostProblemActivity.class);
startActivity(intent);
}
});
}
}
| UTF-8 | Java | 943 | java | MainActivity.java | Java | [] | null | [] | package com.nychareport.backlog.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.nychareport.backlog.R;
public class MainActivity extends AppCompatActivity {
private Button postProblemButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeViews();
}
private void initializeViews() {
postProblemButton = (Button) findViewById(R.id.btn_make_post);
postProblemButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, PostProblemActivity.class);
startActivity(intent);
}
});
}
}
| 943 | 0.69141 | 0.69035 | 32 | 28.46875 | 23.62994 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
f173e6737e2694da762956484f1424d0cb681347 | 37,366,215,505,638 | e7488e2521feacc341ff992303cb2170a068a183 | /vskeddemos/projects/springloadeddemo/src/com/vsked/task/MyTask.java | 7fb7c2b4a69b2a33e1f2a8578dba2b0b2bba8c19 | [
"MIT"
] | permissive | brucevsked/vskeddemolist | https://github.com/brucevsked/vskeddemolist | 6b061d5657d503865726fb98314c5ff0b1dbb1cf | f863783b5b2b4e21e878ee3b295a3b5e03f39d94 | refs/heads/master | 2023-07-21T21:20:48.900000 | 2023-07-13T08:11:19 | 2023-07-13T08:11:19 | 38,467,274 | 29 | 12 | MIT | false | 2022-10-26T01:32:56 | 2015-07-03T02:21:29 | 2022-08-04T01:06:46 | 2022-10-26T01:32:55 | 610,712 | 17 | 12 | 0 | Java | false | false | package com.vsked.task;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyTask implements Runnable{
public Long IntervalTime=2000L;
private SimpleDateFormat mySdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
@Override
public void run() {
while(true){
try {
Thread.sleep(IntervalTime);
System.out.println("VVV"+mySdf.format(new Date()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| UTF-8 | Java | 494 | java | MyTask.java | Java | [] | null | [] | package com.vsked.task;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyTask implements Runnable{
public Long IntervalTime=2000L;
private SimpleDateFormat mySdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
@Override
public void run() {
while(true){
try {
Thread.sleep(IntervalTime);
System.out.println("VVV"+mySdf.format(new Date()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| 494 | 0.663968 | 0.65587 | 25 | 17.76 | 20.034531 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.68 | false | false | 4 |
f77371c104d7caf2f164e50956a2cc1317929166 | 35,545,149,384,949 | 8dd41c260154f5917b081207808c14cf7c9e50f7 | /app/src/main/java/android/izy/service/NetworkManager.java | 8958c3bbdbeaae5704021c06f3d91ebd5e3c37e3 | [] | no_license | simahuan/libraries | https://github.com/simahuan/libraries | aeabb27458532eb6106304551932efb0fc1af371 | ca6b5ada5868f611b4340e4462df97dd15885666 | refs/heads/master | 2020-04-17T06:52:25.405000 | 2019-01-18T04:24:18 | 2019-01-18T04:24:18 | 166,342,991 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package android.izy.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
/**
* 网络管理类
*
* @author yangyp
* @version 1.0, 2014年8月4日 上午11:45:52
*/
public class NetworkManager implements NetworkStateCallback {
static final String TAG = NetworkManager.class.getSimpleName();
private Context context;
private TelephonyManager telephonyManager;
private BroadcastReceiver connectivityReceiver;
private PhoneStateListener phoneStateListener;
private NetworkStateCallback call;
public NetworkManager(Context context) {
this.context = context;
telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
connectivityReceiver = new ConnectivityReceiver(this);
phoneStateListener = new PhoneStateChangeListener(this);
}
public void registerConnectivityReceiver(NetworkStateCallback call) {
this.call = call;
Log.d(TAG, "registerConnectivityReceiver()...");
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
// context.registerReceiver(connectivityReceiver, new
// IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
context.registerReceiver(connectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
public void unregisterConnectivityReceiver() {
Log.d(TAG, "unregisterConnectivityReceiver()...");
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
context.unregisterReceiver(connectivityReceiver);
}
@Override
public void onConnected(int netType) {
if (call != null) {
call.onConnected(netType);
}
}
@Override
public void onDisconnected(int netType) {
if (call != null) {
call.onDisconnected(netType);
}
}
}
| UTF-8 | Java | 1,939 | java | NetworkManager.java | Java | [
{
"context": "ort android.util.Log;\n\n/**\n * 网络管理类\n * \n * @author yangyp\n * @version 1.0, 2014年8月4日 上午11:45:52\n */\npublic ",
"end": 329,
"score": 0.9996045827865601,
"start": 323,
"tag": "USERNAME",
"value": "yangyp"
}
] | null | [] | package android.izy.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
/**
* 网络管理类
*
* @author yangyp
* @version 1.0, 2014年8月4日 上午11:45:52
*/
public class NetworkManager implements NetworkStateCallback {
static final String TAG = NetworkManager.class.getSimpleName();
private Context context;
private TelephonyManager telephonyManager;
private BroadcastReceiver connectivityReceiver;
private PhoneStateListener phoneStateListener;
private NetworkStateCallback call;
public NetworkManager(Context context) {
this.context = context;
telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
connectivityReceiver = new ConnectivityReceiver(this);
phoneStateListener = new PhoneStateChangeListener(this);
}
public void registerConnectivityReceiver(NetworkStateCallback call) {
this.call = call;
Log.d(TAG, "registerConnectivityReceiver()...");
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
// context.registerReceiver(connectivityReceiver, new
// IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
context.registerReceiver(connectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
public void unregisterConnectivityReceiver() {
Log.d(TAG, "unregisterConnectivityReceiver()...");
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
context.unregisterReceiver(connectivityReceiver);
}
@Override
public void onConnected(int netType) {
if (call != null) {
call.onConnected(netType);
}
}
@Override
public void onDisconnected(int netType) {
if (call != null) {
call.onDisconnected(netType);
}
}
}
| 1,939 | 0.795206 | 0.78791 | 61 | 30.459017 | 26.869188 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.52459 | false | false | 4 |
e91595c1188c78933e963ed4063bc7191a5b3be5 | 34,179,349,794,262 | e9c59117166da8201e95ad3d339ac2ff2246eefa | /xmlimport/src/main/java/be/vlaanderen/dov/services/xmlimport/dto/UploadOption.java | db48bbc21cf740fc7d974af0d2b95c00fb22f8a2 | [] | no_license | DOV-Vlaanderen/dov-services-quickstart | https://github.com/DOV-Vlaanderen/dov-services-quickstart | 9c148b3644663e022eadf3d020e53ef3f60293e6 | 6ff52938861bbddb4960201e629d9bd943456f67 | refs/heads/master | 2023-07-31T04:21:29.678000 | 2023-04-07T16:10:38 | 2023-04-07T16:10:38 | 251,585,144 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Copyright (C) 2010-2017 DOV, http://dov.vlaanderen.be/
// All rights reserved
package be.vlaanderen.dov.services.xmlimport.dto;
/**
* Data transfer object that represents the InvoerOptie pojo.
*
* @author DEBAETSP
*/
public final class UploadOption {
private Code property;
private String propertyValue;
public UploadOption() {
}
public UploadOption(String code, String beschrijving) {
propertyValue = Boolean.TRUE.toString();
property = new Code(code, beschrijving);
}
/**
* simple getter.
*
* @return the property
*/
public Code getProperty() {
return property;
}
/**
* simple setter.
*
* @param property the property to set
*/
public void setProperty(Code property) {
this.property = property;
}
/**
* simple getter.
*
* @return the propertyValue
*/
public String getPropertyValue() {
return propertyValue;
}
/**
* simple setter.
*
* @param propertyValue the propertyValue to set
*/
public void setPropertyValue(String propertyValue) {
this.propertyValue = propertyValue;
}
/**
* convenience method to convert the property to a boolean.
*
* @return true of false, according to Boolean.parseBoolean
*/
public boolean isOptieActivated() {
boolean result = false;
if (this.propertyValue != null) {
result = Boolean.parseBoolean(this.propertyValue);
}
return result;
}
}
| UTF-8 | Java | 1,567 | java | UploadOption.java | Java | [
{
"context": "hat represents the InvoerOptie pojo.\n *\n * @author DEBAETSP\n */\n\npublic final class UploadOption {\n\n priva",
"end": 221,
"score": 0.9987878799438477,
"start": 213,
"tag": "USERNAME",
"value": "DEBAETSP"
}
] | null | [] | // Copyright (C) 2010-2017 DOV, http://dov.vlaanderen.be/
// All rights reserved
package be.vlaanderen.dov.services.xmlimport.dto;
/**
* Data transfer object that represents the InvoerOptie pojo.
*
* @author DEBAETSP
*/
public final class UploadOption {
private Code property;
private String propertyValue;
public UploadOption() {
}
public UploadOption(String code, String beschrijving) {
propertyValue = Boolean.TRUE.toString();
property = new Code(code, beschrijving);
}
/**
* simple getter.
*
* @return the property
*/
public Code getProperty() {
return property;
}
/**
* simple setter.
*
* @param property the property to set
*/
public void setProperty(Code property) {
this.property = property;
}
/**
* simple getter.
*
* @return the propertyValue
*/
public String getPropertyValue() {
return propertyValue;
}
/**
* simple setter.
*
* @param propertyValue the propertyValue to set
*/
public void setPropertyValue(String propertyValue) {
this.propertyValue = propertyValue;
}
/**
* convenience method to convert the property to a boolean.
*
* @return true of false, according to Boolean.parseBoolean
*/
public boolean isOptieActivated() {
boolean result = false;
if (this.propertyValue != null) {
result = Boolean.parseBoolean(this.propertyValue);
}
return result;
}
}
| 1,567 | 0.603701 | 0.598596 | 76 | 19.618422 | 19.812256 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.210526 | false | false | 4 |
54d153404691dcc501869f91c3766356f2bbef76 | 27,273,042,397,491 | 544c7bd1fa7766863ae1cc537cd4f7b14dea750e | /src/com/model/SearchObj.java | 5e3d365348de829ef41e1193317e73c10bfed883 | [] | no_license | 12sandeep1994/WebUsageDataMining | https://github.com/12sandeep1994/WebUsageDataMining | cb5e6fc09a008472303d8e021eb034ed1d6f4236 | 153cca8c3b4f0e9d2875af764322384a7973987d | refs/heads/master | 2020-05-16T07:04:50.220000 | 2019-04-22T21:29:36 | 2019-04-22T21:29:36 | 182,870,073 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.model;
import java.io.Serializable;
public class SearchObj implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getHiddenUrl() {
return hiddenUrl;
}
public void setHiddenUrl(String hiddenUrl) {
this.hiddenUrl = hiddenUrl;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public int getSearchId() {
return searchId;
}
public void setSearchId(int searchId) {
this.searchId = searchId;
}
public double getFeatureVector() {
return featureVector;
}
public void setFeatureVector(double featureVector) {
this.featureVector = featureVector;
}
private String userId;
private String query;
private String url;
private String hiddenUrl;
private String title;
private String desc;
private int searchId;
private double featureVector;
}
| UTF-8 | Java | 1,441 | java | SearchObj.java | Java | [] | null | [] | package com.model;
import java.io.Serializable;
public class SearchObj implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getHiddenUrl() {
return hiddenUrl;
}
public void setHiddenUrl(String hiddenUrl) {
this.hiddenUrl = hiddenUrl;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public int getSearchId() {
return searchId;
}
public void setSearchId(int searchId) {
this.searchId = searchId;
}
public double getFeatureVector() {
return featureVector;
}
public void setFeatureVector(double featureVector) {
this.featureVector = featureVector;
}
private String userId;
private String query;
private String url;
private String hiddenUrl;
private String title;
private String desc;
private int searchId;
private double featureVector;
}
| 1,441 | 0.651631 | 0.650937 | 93 | 13.494623 | 14.75435 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.193548 | false | false | 4 |
fb15c201f4bfbdd749320595e2aca5eef8b31016 | 37,744,172,623,786 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/11/11_9b616166a57a102f841dfb3bfeb1403296c266de/AbstractScopeCookieContainerFilter/11_9b616166a57a102f841dfb3bfeb1403296c266de_AbstractScopeCookieContainerFilter_t.java | be6d98ba26b17861d77117b45a74b81e8a4c804b | [] | no_license | zhongxingyu/Seer | https://github.com/zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false | /*
* Copyright (c) 2012, Mayocat <hello@mayocat.org>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mayocat.context;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import org.mayocat.configuration.SecuritySettings;
import org.mayocat.security.Cipher;
import org.mayocat.security.EncryptionException;
import org.mayocat.context.scope.WebScope;
import org.mayocat.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import com.sun.jersey.core.util.Base64;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;
/**
* Base class for cookie-based scope container filters such as {@link SessionScopeCookieContainerFilter} or {@link
* FlashScopeCookieContainerFilter}
*
* @version $Id$
*/
public abstract class AbstractScopeCookieContainerFilter<T extends WebScope>
implements ContainerResponseFilter, ContainerRequestFilter
{
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractScopeCookieContainerFilter.class);
protected abstract String getScopeAndCookieName();
protected abstract boolean scopeExistsAndNotEmpty(WebContext context);
protected abstract T getScope(WebContext context);
protected abstract void setScope(WebContext context, T scope);
protected abstract boolean encryptAndSign();
protected abstract T cast(Object object);
protected int getCookieDuration()
{
return -1;
}
private final static String HMAC_SHA256_ALGORITHM = "HmacSHA256";
public ContainerResponse filter(ContainerRequest containerRequest, ContainerResponse containerResponse)
{
WebContext context = Utils.getComponent(WebContext.class);
if (context != null && scopeExistsAndNotEmpty(context)) {
storeScopeInCookies(context, containerResponse);
}
else {
deleteCookie(containerResponse);
}
return containerResponse;
}
@Override
public ContainerRequest filter(ContainerRequest containerRequest)
{
T scope = null;
WebContext context = Utils.getComponent(WebContext.class);
try {
scope = getScopeFromCookies(containerRequest);
if (scope != null) {
setScope(context, scope);
}
} catch (IOException e) {
LOGGER.error("Failed to get {} from cookies", getScopeAndCookieName(), e);
} catch (EncryptionException e) {
LOGGER.error("Failed to get {} from cookies", getScopeAndCookieName(), e);
}
return containerRequest;
}
protected void deleteCookie(ContainerResponse containerResponse)
{
NewCookie scope = new NewCookie(getScopeAndCookieName(), "", "/", null, 1, "", 0, false);
Response cookieResponse =
Response.fromResponse(containerResponse.getResponse()).cookie(scope).build();
containerResponse.setResponse(cookieResponse);
}
protected void storeScopeInCookies(WebContext context, ContainerResponse containerResponse)
{
Cipher cipher = Utils.getComponent(Cipher.class);
T cookieScope = getScope(context);
try {
String cookieValue;
String serialized = serialize(cookieScope);
if (encryptAndSign()) {
String encryptedData = cipher.encrypt(serialized);
String signature = computeSignature(encryptedData);
cookieValue = encode(encryptedData + signature);
} else {
cookieValue = encode(serialized);
}
try {
T originalScope = getScopeFromCookies(containerResponse.getContainerRequest());
if (originalScope != null && originalScope.equals(cookieScope)) {
return;
}
} catch (IOException e) {
// Keep going.
// It may mean a serialized class has changed and could not be loaded
// This means me have a new scope and it's OK to override it
}
NewCookie scope =
new NewCookie(getScopeAndCookieName(), cookieValue, "/", null, 1, "",
getCookieDuration(), false);
Response cookieResponse =
Response.fromResponse(containerResponse.getResponse()).cookie(scope).build();
containerResponse.setResponse(cookieResponse);
} catch (IOException | EncryptionException | GeneralSecurityException e) {
LOGGER.error("Failed to store cookies in {}", getScopeAndCookieName(), e);
}
}
protected T getScopeFromCookies(ContainerRequest containerRequest) throws IOException, EncryptionException
{
Cipher cipher = Utils.getComponent(Cipher.class);
String cookieData = decode(getCookie(containerRequest, getScopeAndCookieName()));
if (!Strings.isNullOrEmpty(cookieData)) {
try {
if (encryptAndSign()) {
if (cookieData.length() < 44) {
LOGGER.warn("Invalid length when reading {} from cookies", getScopeAndCookieName());
return null;
}
String encryptedCookie = cookieData.substring(0, cookieData.length() - 44);
String signature = cookieData.substring(cookieData.length() - 44);
if (!signature.equals(computeSignature(encryptedCookie))) {
// Signing key has been changed or message has been tampered with
LOGGER.warn("Invalid HMAC signature when reading {} from cookies", getScopeAndCookieName());
return null;
}
cookieData = cipher.decrypt(encryptedCookie);
}
T scope = cast(deserialize(cookieData));
return scope;
} catch (GeneralSecurityException | ClassNotFoundException e) {
LOGGER.error("Failed to de-serialize {} from cookies", getScopeAndCookieName(), e);
} catch (ClassCastException e2) {
// Ignore and return null -> scope will be destroyed
}
}
return null;
}
protected Object deserialize(String serialized) throws IOException, ClassNotFoundException
{
byte[] data = Base64.decode(serialized);
ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(data));
Object object = objectInputStream.readObject();
objectInputStream.close();
return object;
}
protected String serialize(Serializable object) throws IOException
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(object);
objectOutputStream.close();
return new String(Base64.encode(byteArrayOutputStream.toByteArray()));
}
protected String getCookie(ContainerRequest request, String cookieName)
{
MultivaluedMap<String, String> cookies = request.getCookieNameValueMap();
if (cookies != null) {
for (String name : cookies.keySet()) {
if (cookieName.equals(name)) {
return cookies.getFirst(name);
}
}
}
return null;
}
private String computeSignature(String message) throws GeneralSecurityException
{
SecuritySettings securitySettings = Utils.getComponent(SecuritySettings.class);
SecretKeySpec signingKey =
new SecretKeySpec(securitySettings.getSigningKey().getBytes(), HMAC_SHA256_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(message.getBytes(Charsets.UTF_8));
String result = new String(Base64.encode(rawHmac));
return result;
}
private String encode(String s)
{
if (s == null) {
// garbage in, garbage out
return null;
}
try {
return URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
private String decode(String s)
{
if (s == null) {
// garbage in, garbage out
return null;
}
try {
return URLDecoder.decode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
| UTF-8 | Java | 9,773 | java | 11_9b616166a57a102f841dfb3bfeb1403296c266de_AbstractScopeCookieContainerFilter_t.java | Java | [
{
"context": " /*\n * Copyright (c) 2012, Mayocat <hello@mayocat.org>\n *\n * This Source Code Form",
"end": 35,
"score": 0.9996128678321838,
"start": 28,
"tag": "NAME",
"value": "Mayocat"
},
{
"context": " /*\n * Copyright (c) 2012, Mayocat <hello@mayocat.org>\n *\n * This Source Code Form is subject to the ",
"end": 54,
"score": 0.9999285936355591,
"start": 37,
"tag": "EMAIL",
"value": "hello@mayocat.org"
}
] | null | [] | /*
* Copyright (c) 2012, Mayocat <<EMAIL>>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mayocat.context;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import org.mayocat.configuration.SecuritySettings;
import org.mayocat.security.Cipher;
import org.mayocat.security.EncryptionException;
import org.mayocat.context.scope.WebScope;
import org.mayocat.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import com.sun.jersey.core.util.Base64;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;
/**
* Base class for cookie-based scope container filters such as {@link SessionScopeCookieContainerFilter} or {@link
* FlashScopeCookieContainerFilter}
*
* @version $Id$
*/
public abstract class AbstractScopeCookieContainerFilter<T extends WebScope>
implements ContainerResponseFilter, ContainerRequestFilter
{
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractScopeCookieContainerFilter.class);
protected abstract String getScopeAndCookieName();
protected abstract boolean scopeExistsAndNotEmpty(WebContext context);
protected abstract T getScope(WebContext context);
protected abstract void setScope(WebContext context, T scope);
protected abstract boolean encryptAndSign();
protected abstract T cast(Object object);
protected int getCookieDuration()
{
return -1;
}
private final static String HMAC_SHA256_ALGORITHM = "HmacSHA256";
public ContainerResponse filter(ContainerRequest containerRequest, ContainerResponse containerResponse)
{
WebContext context = Utils.getComponent(WebContext.class);
if (context != null && scopeExistsAndNotEmpty(context)) {
storeScopeInCookies(context, containerResponse);
}
else {
deleteCookie(containerResponse);
}
return containerResponse;
}
@Override
public ContainerRequest filter(ContainerRequest containerRequest)
{
T scope = null;
WebContext context = Utils.getComponent(WebContext.class);
try {
scope = getScopeFromCookies(containerRequest);
if (scope != null) {
setScope(context, scope);
}
} catch (IOException e) {
LOGGER.error("Failed to get {} from cookies", getScopeAndCookieName(), e);
} catch (EncryptionException e) {
LOGGER.error("Failed to get {} from cookies", getScopeAndCookieName(), e);
}
return containerRequest;
}
protected void deleteCookie(ContainerResponse containerResponse)
{
NewCookie scope = new NewCookie(getScopeAndCookieName(), "", "/", null, 1, "", 0, false);
Response cookieResponse =
Response.fromResponse(containerResponse.getResponse()).cookie(scope).build();
containerResponse.setResponse(cookieResponse);
}
protected void storeScopeInCookies(WebContext context, ContainerResponse containerResponse)
{
Cipher cipher = Utils.getComponent(Cipher.class);
T cookieScope = getScope(context);
try {
String cookieValue;
String serialized = serialize(cookieScope);
if (encryptAndSign()) {
String encryptedData = cipher.encrypt(serialized);
String signature = computeSignature(encryptedData);
cookieValue = encode(encryptedData + signature);
} else {
cookieValue = encode(serialized);
}
try {
T originalScope = getScopeFromCookies(containerResponse.getContainerRequest());
if (originalScope != null && originalScope.equals(cookieScope)) {
return;
}
} catch (IOException e) {
// Keep going.
// It may mean a serialized class has changed and could not be loaded
// This means me have a new scope and it's OK to override it
}
NewCookie scope =
new NewCookie(getScopeAndCookieName(), cookieValue, "/", null, 1, "",
getCookieDuration(), false);
Response cookieResponse =
Response.fromResponse(containerResponse.getResponse()).cookie(scope).build();
containerResponse.setResponse(cookieResponse);
} catch (IOException | EncryptionException | GeneralSecurityException e) {
LOGGER.error("Failed to store cookies in {}", getScopeAndCookieName(), e);
}
}
protected T getScopeFromCookies(ContainerRequest containerRequest) throws IOException, EncryptionException
{
Cipher cipher = Utils.getComponent(Cipher.class);
String cookieData = decode(getCookie(containerRequest, getScopeAndCookieName()));
if (!Strings.isNullOrEmpty(cookieData)) {
try {
if (encryptAndSign()) {
if (cookieData.length() < 44) {
LOGGER.warn("Invalid length when reading {} from cookies", getScopeAndCookieName());
return null;
}
String encryptedCookie = cookieData.substring(0, cookieData.length() - 44);
String signature = cookieData.substring(cookieData.length() - 44);
if (!signature.equals(computeSignature(encryptedCookie))) {
// Signing key has been changed or message has been tampered with
LOGGER.warn("Invalid HMAC signature when reading {} from cookies", getScopeAndCookieName());
return null;
}
cookieData = cipher.decrypt(encryptedCookie);
}
T scope = cast(deserialize(cookieData));
return scope;
} catch (GeneralSecurityException | ClassNotFoundException e) {
LOGGER.error("Failed to de-serialize {} from cookies", getScopeAndCookieName(), e);
} catch (ClassCastException e2) {
// Ignore and return null -> scope will be destroyed
}
}
return null;
}
protected Object deserialize(String serialized) throws IOException, ClassNotFoundException
{
byte[] data = Base64.decode(serialized);
ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(data));
Object object = objectInputStream.readObject();
objectInputStream.close();
return object;
}
protected String serialize(Serializable object) throws IOException
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(object);
objectOutputStream.close();
return new String(Base64.encode(byteArrayOutputStream.toByteArray()));
}
protected String getCookie(ContainerRequest request, String cookieName)
{
MultivaluedMap<String, String> cookies = request.getCookieNameValueMap();
if (cookies != null) {
for (String name : cookies.keySet()) {
if (cookieName.equals(name)) {
return cookies.getFirst(name);
}
}
}
return null;
}
private String computeSignature(String message) throws GeneralSecurityException
{
SecuritySettings securitySettings = Utils.getComponent(SecuritySettings.class);
SecretKeySpec signingKey =
new SecretKeySpec(securitySettings.getSigningKey().getBytes(), HMAC_SHA256_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(message.getBytes(Charsets.UTF_8));
String result = new String(Base64.encode(rawHmac));
return result;
}
private String encode(String s)
{
if (s == null) {
// garbage in, garbage out
return null;
}
try {
return URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
private String decode(String s)
{
if (s == null) {
// garbage in, garbage out
return null;
}
try {
return URLDecoder.decode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
| 9,763 | 0.629796 | 0.625192 | 253 | 37.624504 | 30.780449 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.604743 | false | false | 4 |
3ce034e82e9b2297a029310ae55e112e3e644ed8 | 3,221,225,526,171 | 048a5a1043c574a4df39220c25558b0aa9c6b914 | /src/day04_Variables/PersonalInfo.java | 698f84cf5cb9c17ac1beb48fbc2c04e3efffdefc | [] | no_license | arvindmits/Java | https://github.com/arvindmits/Java | 97e37e6009be9364a22520f177983ab486202534 | 68175f96220cb812cb98f226a0dc5bcb3e8634fe | refs/heads/master | 2023-03-16T06:36:47.530000 | 2021-01-04T19:10:06 | 2021-01-04T19:10:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day04_Variables;
import javax.xml.bind.SchemaOutputResolver;
/*
Task: declare those variables and print them to the console:
firstName
lastName
age
country
SSN
Gender
isEmployed
*/
public class PersonalInfo {
public static void main(String[] args) {
String firstName = "Rumeysa";
String lastName = "Dogan";
int age = 33;
String country = "Turkey";
String SSN = "123-78-9876";
String gender = "Female";
boolean isEmployed = false;
System.out.println("First Name: " + firstName);
System.out.println("Last Name: " + lastName);
System.out.println("Age: " + age);
System.out.println("Country: " + country);
System.out.println("SSN: " + SSN);
System.out.println("Gender: " + gender);
System.out.println("Employed: " + isEmployed);
}
}
| UTF-8 | Java | 905 | java | PersonalInfo.java | Java | [
{
"context": "hose variables and print them to the console:\n\n firstName\n lastName\n age\n country\n SSN\n Gend",
"end": 149,
"score": 0.9975711703300476,
"start": 140,
"tag": "NAME",
"value": "firstName"
},
{
"context": " and print them to the console:\n\n firstName\n lastName\n age\n country\n SSN\n Gender\n isEmpl",
"end": 162,
"score": 0.9991012215614319,
"start": 154,
"tag": "NAME",
"value": "lastName"
},
{
"context": " main(String[] args) {\n\n String firstName = \"Rumeysa\";\n String lastName = \"Dogan\";\n int age ",
"end": 329,
"score": 0.9998376369476318,
"start": 322,
"tag": "NAME",
"value": "Rumeysa"
},
{
"context": "g firstName = \"Rumeysa\";\n String lastName = \"Dogan\";\n int age = 33;\n String country = \"Tur",
"end": 362,
"score": 0.9997828006744385,
"start": 357,
"tag": "NAME",
"value": "Dogan"
},
{
"context": "alse;\n\n System.out.println(\"First Name: \" + firstName);\n System.out.println(\"Last Name: \" + las",
"end": 572,
"score": 0.9972975850105286,
"start": 563,
"tag": "NAME",
"value": "firstName"
},
{
"context": "Name);\n System.out.println(\"Last Name: \" + lastName);\n System.out.println(\"Age: \" + age",
"end": 627,
"score": 0.9983155727386475,
"start": 619,
"tag": "NAME",
"value": "lastName"
}
] | null | [] | package day04_Variables;
import javax.xml.bind.SchemaOutputResolver;
/*
Task: declare those variables and print them to the console:
firstName
lastName
age
country
SSN
Gender
isEmployed
*/
public class PersonalInfo {
public static void main(String[] args) {
String firstName = "Rumeysa";
String lastName = "Dogan";
int age = 33;
String country = "Turkey";
String SSN = "123-78-9876";
String gender = "Female";
boolean isEmployed = false;
System.out.println("First Name: " + firstName);
System.out.println("Last Name: " + lastName);
System.out.println("Age: " + age);
System.out.println("Country: " + country);
System.out.println("SSN: " + SSN);
System.out.println("Gender: " + gender);
System.out.println("Employed: " + isEmployed);
}
}
| 905 | 0.59116 | 0.576796 | 39 | 22.205128 | 20.56407 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.410256 | false | false | 4 |
e6e4de972e11516f3f90d40643b8e0cea8888fba | 39,393,440,047,004 | 0721305fd9b1c643a7687b6382dccc56a82a2dad | /src/app.zenly.locator_4.8.0_base_source_from_JADX/sources/app/zenly/locator/inbox/C3845j.java | b47c68ad43391d8c63f943a4369c8e3eb0545b96 | [] | no_license | a2en/Zenly_re | https://github.com/a2en/Zenly_re | 09c635ad886c8285f70a8292ae4f74167a4ad620 | f87af0c2dd0bc14fd772c69d5bc70cd8aa727516 | refs/heads/master | 2020-12-13T17:07:11.442000 | 2020-01-17T04:32:44 | 2020-01-17T04:32:44 | 234,470,083 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package app.zenly.locator.inbox;
import app.zenly.locator.inbox.p103o.C3887d;
import kotlin.jvm.internal.C12932j;
/* renamed from: app.zenly.locator.inbox.j */
public final class C3845j {
/* renamed from: a */
private final C3887d f10229a;
public C3845j(C3887d dVar) {
C12932j.m33818b(dVar, "model");
this.f10229a = dVar;
}
/* renamed from: a */
public final C3887d mo10441a() {
return this.f10229a;
}
}
| UTF-8 | Java | 461 | java | C3845j.java | Java | [] | null | [] | package app.zenly.locator.inbox;
import app.zenly.locator.inbox.p103o.C3887d;
import kotlin.jvm.internal.C12932j;
/* renamed from: app.zenly.locator.inbox.j */
public final class C3845j {
/* renamed from: a */
private final C3887d f10229a;
public C3845j(C3887d dVar) {
C12932j.m33818b(dVar, "model");
this.f10229a = dVar;
}
/* renamed from: a */
public final C3887d mo10441a() {
return this.f10229a;
}
}
| 461 | 0.64859 | 0.5141 | 21 | 20.952381 | 16.21133 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.380952 | false | false | 4 |
5badb44c6a9b13b12fe33d2bb22491d7088aa771 | 39,393,440,044,394 | 99c2328143b0e1e57092182ba1241852088bd8b7 | /src/test/java/eKonsultacje/testy/NowaKonsultacjaMieszkaniecSonda.java | 8ee50788383a1cfa074adc08d257d2b98c4f8535 | [] | no_license | MarioIsDead/eKonsultacje | https://github.com/MarioIsDead/eKonsultacje | d6a66626b7d2b799fcc10a54c20bc6e9c49ec283 | 46f330c93095fcadb4ae30b54150c5df1c0339c6 | refs/heads/master | 2020-11-28T09:23:59.269000 | 2020-02-21T11:20:22 | 2020-02-21T11:20:22 | 229,768,947 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package eKonsultacje.testy;
import eKonsultacje.Strony.Bazowa;
import eKonsultacje.Strony.MainPage;
import eKonsultacje.Strony.MainPageNewKonsultacja;
import eKonsultacje.Strony.stronaLogowania;
import org.openqa.selenium.JavascriptExecutor;
import org.testng.annotations.Test;
public class NowaKonsultacjaMieszkaniecSonda extends Bazowa {
@Test
public void logowanieUsera() throws InterruptedException{
driver.get("http://ekonsultacje.eboi.pl:5004");
stronaLogowania logowanie = new stronaLogowania(driver);
logowanie.zalogowanie();
MainPage konsultacjeMenu = new MainPage(driver);
konsultacjeMenu.konsultacjeLink();
konsultacjeMenu.konsultacjaLinkNew();
MainPageNewKonsultacja roboczaKonsultacja = new MainPageNewKonsultacja(driver);
roboczaKonsultacja.nowaKonsultacjaSonda();
roboczaKonsultacja.tylkoDlaMieszkanca();
roboczaKonsultacja.grupySpoleczne();
roboczaKonsultacja.jednostka();
roboczaKonsultacja.obszar();
roboczaKonsultacja.kategoria();
roboczaKonsultacja.krotkiOpis();
roboczaKonsultacja.dataRozpoczeciaProjektu("2020-02-12","2020-02-29");
roboczaKonsultacja.regulamin();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,800)");
roboczaKonsultacja.nowaForma();
roboczaKonsultacja.sonda();
roboczaKonsultacja.sondaRobocza();
roboczaKonsultacja.opisSondy();
roboczaKonsultacja.pytaniePierwsze("Czy zgadzasz się na... ?");
roboczaKonsultacja.pokazOdpowiedzi();
roboczaKonsultacja.odpowiedz();
roboczaKonsultacja.odpowiedz1Input("Tak");
roboczaKonsultacja.kolejnaOdpowiedz();
roboczaKonsultacja.odpowiedz();
roboczaKonsultacja.odpowiedz2Input2("Nie");
roboczaKonsultacja.kolejnaOdpowiedz();
js.executeScript("window.scrollBy(0,500)");
roboczaKonsultacja.zapisz();
Thread.sleep(1000);
roboczaKonsultacja.sondaPublikuj();
roboczaKonsultacja.utworz();
}
} | UTF-8 | Java | 2,100 | java | NowaKonsultacjaMieszkaniecSonda.java | Java | [] | null | [] | package eKonsultacje.testy;
import eKonsultacje.Strony.Bazowa;
import eKonsultacje.Strony.MainPage;
import eKonsultacje.Strony.MainPageNewKonsultacja;
import eKonsultacje.Strony.stronaLogowania;
import org.openqa.selenium.JavascriptExecutor;
import org.testng.annotations.Test;
public class NowaKonsultacjaMieszkaniecSonda extends Bazowa {
@Test
public void logowanieUsera() throws InterruptedException{
driver.get("http://ekonsultacje.eboi.pl:5004");
stronaLogowania logowanie = new stronaLogowania(driver);
logowanie.zalogowanie();
MainPage konsultacjeMenu = new MainPage(driver);
konsultacjeMenu.konsultacjeLink();
konsultacjeMenu.konsultacjaLinkNew();
MainPageNewKonsultacja roboczaKonsultacja = new MainPageNewKonsultacja(driver);
roboczaKonsultacja.nowaKonsultacjaSonda();
roboczaKonsultacja.tylkoDlaMieszkanca();
roboczaKonsultacja.grupySpoleczne();
roboczaKonsultacja.jednostka();
roboczaKonsultacja.obszar();
roboczaKonsultacja.kategoria();
roboczaKonsultacja.krotkiOpis();
roboczaKonsultacja.dataRozpoczeciaProjektu("2020-02-12","2020-02-29");
roboczaKonsultacja.regulamin();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,800)");
roboczaKonsultacja.nowaForma();
roboczaKonsultacja.sonda();
roboczaKonsultacja.sondaRobocza();
roboczaKonsultacja.opisSondy();
roboczaKonsultacja.pytaniePierwsze("Czy zgadzasz się na... ?");
roboczaKonsultacja.pokazOdpowiedzi();
roboczaKonsultacja.odpowiedz();
roboczaKonsultacja.odpowiedz1Input("Tak");
roboczaKonsultacja.kolejnaOdpowiedz();
roboczaKonsultacja.odpowiedz();
roboczaKonsultacja.odpowiedz2Input2("Nie");
roboczaKonsultacja.kolejnaOdpowiedz();
js.executeScript("window.scrollBy(0,500)");
roboczaKonsultacja.zapisz();
Thread.sleep(1000);
roboczaKonsultacja.sondaPublikuj();
roboczaKonsultacja.utworz();
}
} | 2,100 | 0.720343 | 0.703668 | 49 | 41.857143 | 17.482353 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.918367 | false | false | 4 |
e501be95eef9a8e21d639e6740f8e64180ed91d1 | 39,582,418,604,015 | 35df283a14f71be15fbb79db349ce813d47550ac | /Banco_JPA_relacionamento_onetoone/src/br/com/bancoexemplo/service/InvestimentoService.java | 0018c2b0e6903b9c04cbf7f4118655181a87b62c | [] | no_license | barbosaclaudiob/projetos_JPA | https://github.com/barbosaclaudiob/projetos_JPA | 2b97b54569d5e50e4b169f3bffabaec8eb6968dc | a6fa8dac0ce47c04c636510d80f4e43830c021de | refs/heads/master | 2016-09-06T00:22:40.493000 | 2014-12-09T16:09:46 | 2014-12-09T16:09:46 | 27,773,656 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.bancoexemplo.service;
import java.util.List;
import javax.persistence.TypedQuery;
import br.com.bancoexemplo.modelo.Investimento;
import br.com.bancoexemplo.util.UtilEntityManager;
public class InvestimentoService extends GenericService<Investimento> {
public InvestimentoService() {
super(Investimento.class);
}
public List<Investimento> buscarPor(String descricao){
StringBuilder jpql = new StringBuilder();
jpql.append("SELECT i FROM investimento i");
jpql.append(" WHERE i.descricao LIKE :descricao");
TypedQuery<Investimento> query = UtilEntityManager.getEM().createQuery(jpql.toString(), Investimento.class);
query.setParameter("descricao", "%" + descricao + "%");
return query.getResultList();
}
}
| UTF-8 | Java | 751 | java | InvestimentoService.java | Java | [] | null | [] | package br.com.bancoexemplo.service;
import java.util.List;
import javax.persistence.TypedQuery;
import br.com.bancoexemplo.modelo.Investimento;
import br.com.bancoexemplo.util.UtilEntityManager;
public class InvestimentoService extends GenericService<Investimento> {
public InvestimentoService() {
super(Investimento.class);
}
public List<Investimento> buscarPor(String descricao){
StringBuilder jpql = new StringBuilder();
jpql.append("SELECT i FROM investimento i");
jpql.append(" WHERE i.descricao LIKE :descricao");
TypedQuery<Investimento> query = UtilEntityManager.getEM().createQuery(jpql.toString(), Investimento.class);
query.setParameter("descricao", "%" + descricao + "%");
return query.getResultList();
}
}
| 751 | 0.765646 | 0.765646 | 26 | 27.884615 | 27.994955 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.423077 | false | false | 4 |
2acc92a37533148fe1039841b7bbfe6fd874e0a1 | 12,678,743,510,727 | 580b52090b55c44e95fa812668c8082e79ceea2d | /app/src/main/java/com/example/gitubusers/activities/LoginActivity.java | 7d2fb2d48b8b1585c2c5d1c8effdf63f499e491d | [] | no_license | bertrand751979/GitubUsers | https://github.com/bertrand751979/GitubUsers | 5eee32c2c9fa7f6153a07bbf015150dfcc2fbcc2 | 3d985bf4ac375413d5bd82fa0595cf1a3f8cb2bc | refs/heads/master | 2023-08-21T10:38:32.604000 | 2021-10-30T19:37:40 | 2021-10-30T19:37:40 | 421,787,225 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.gitubusers.activities;
import static com.example.gitubusers.activities.MainActivity.PROFIL_LIST_KEY;
import static com.example.gitubusers.activities.MainActivity.PROFIL_REGISTER_LIST_KEY;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.gitubusers.R;
import com.example.gitubusers.SharedPreferencesManager;
import com.example.gitubusers.model.Profil;
import java.util.ArrayList;
public class LoginActivity extends AppCompatActivity {
private EditText txtLogin;
private EditText txtPassword;
private ImageView btnConnexion;
private TextView linkConnexion;
private ArrayList<Profil> myProfilList = new ArrayList<>();
private ArrayList<Profil> registerList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
SharedPreferencesManager.getInstance(this).getProfil(PROFIL_LIST_KEY);
//myProfilList = new ArrayList<> (SharedPreferencesManager.getInstance(LoginActivity.this).getProfil(PROFIL_LIST_KEY));
Log.e("La taille profil List: ", String.valueOf(myProfilList.size()));
registerList = new ArrayList<>(SharedPreferencesManager.getInstance(this).getProfil(PROFIL_REGISTER_LIST_KEY));
Log.e("La taille List: ", String.valueOf(registerList.size()));
txtLogin = findViewById(R.id.edit_text_user_password);
txtPassword = findViewById(R.id.edit_text_user_password);
btnConnexion = findViewById(R.id.button_connexion);
linkConnexion = findViewById(R.id.textview_register);
btnConnexion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isRegister();
//Toast.makeText(LoginActivity.this, "La liste des profil est: "+myProfilList.size(), Toast.LENGTH_SHORT).show();
}
});
linkConnexion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
}
private void isRegister() {
boolean resultat = false;
for (Profil registerProfil : registerList) {
if (txtLogin.getText().toString().equalsIgnoreCase(registerProfil.getLoginProfil()) &&
txtPassword.getText().toString().equalsIgnoreCase(registerProfil.getPasswordProfil())) {
resultat = true;
}
}
if (resultat == true) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
Toast.makeText(LoginActivity.this,"connecte",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LoginActivity.this, "Inconnu", Toast.LENGTH_SHORT).show();
}
}
} | UTF-8 | Java | 3,209 | java | LoginActivity.java | Java | [] | null | [] | package com.example.gitubusers.activities;
import static com.example.gitubusers.activities.MainActivity.PROFIL_LIST_KEY;
import static com.example.gitubusers.activities.MainActivity.PROFIL_REGISTER_LIST_KEY;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.gitubusers.R;
import com.example.gitubusers.SharedPreferencesManager;
import com.example.gitubusers.model.Profil;
import java.util.ArrayList;
public class LoginActivity extends AppCompatActivity {
private EditText txtLogin;
private EditText txtPassword;
private ImageView btnConnexion;
private TextView linkConnexion;
private ArrayList<Profil> myProfilList = new ArrayList<>();
private ArrayList<Profil> registerList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
SharedPreferencesManager.getInstance(this).getProfil(PROFIL_LIST_KEY);
//myProfilList = new ArrayList<> (SharedPreferencesManager.getInstance(LoginActivity.this).getProfil(PROFIL_LIST_KEY));
Log.e("La taille profil List: ", String.valueOf(myProfilList.size()));
registerList = new ArrayList<>(SharedPreferencesManager.getInstance(this).getProfil(PROFIL_REGISTER_LIST_KEY));
Log.e("La taille List: ", String.valueOf(registerList.size()));
txtLogin = findViewById(R.id.edit_text_user_password);
txtPassword = findViewById(R.id.edit_text_user_password);
btnConnexion = findViewById(R.id.button_connexion);
linkConnexion = findViewById(R.id.textview_register);
btnConnexion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isRegister();
//Toast.makeText(LoginActivity.this, "La liste des profil est: "+myProfilList.size(), Toast.LENGTH_SHORT).show();
}
});
linkConnexion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
}
private void isRegister() {
boolean resultat = false;
for (Profil registerProfil : registerList) {
if (txtLogin.getText().toString().equalsIgnoreCase(registerProfil.getLoginProfil()) &&
txtPassword.getText().toString().equalsIgnoreCase(registerProfil.getPasswordProfil())) {
resultat = true;
}
}
if (resultat == true) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
Toast.makeText(LoginActivity.this,"connecte",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LoginActivity.this, "Inconnu", Toast.LENGTH_SHORT).show();
}
}
} | 3,209 | 0.688065 | 0.688065 | 78 | 40.153847 | 31.955931 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.705128 | false | false | 4 |
7f6f397e9b510925a0a253183bf13189a6203d5f | 36,816,459,698,078 | 9ee4bba12ba4be5cb439cc9b2c396c6880511761 | /BreakingRules/app/src/main/java/com/example/david/breakingrules/MainActivity.java | 06da105fa117f0760c8a82de983b67d144040537 | [] | no_license | DavoWavo/AndroidDev | https://github.com/DavoWavo/AndroidDev | 655a232962d130f4034438aff6b7e759e6c9d8ea | 9cd479b59cfd2b81cd2d375af8cb8e8a75295d0b | refs/heads/master | 2020-07-10T10:39:25.424000 | 2019-08-25T04:16:58 | 2019-08-25T04:16:58 | 149,247,876 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.david.breakingrules;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView status;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = findViewById(R.id.time);
button = findViewById(R.id.button);
//pre asyncTask implementation, didn't update the view
// button.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// try {
// for (int i = 3; i >= 0; i--) {
// Thread.sleep(1000);
// Log.d("debugMode", Integer.toString(i));
// status.setText(Integer.toString(i));
// }
// } catch (InterruptedException ie) {
// ie.printStackTrace();
// }
// }
// });
//calling the asyncCount to create another thread to do the work
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new AsyncCount().execute("");
}
});
}
//the asyncCount thread, used to handle the delay, counting and updating
private class AsyncCount extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
int count = params.length;
for (int i = 3; i >= 0; i--) {
try {
Thread.sleep(1000);
publishProgress(Integer.toString(i));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return Integer.toString(count);
}
@Override
protected void onProgressUpdate(String... text) {
status.setText(text[0]);
}
}
}
| UTF-8 | Java | 2,253 | java | MainActivity.java | Java | [] | null | [] | package com.example.david.breakingrules;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView status;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = findViewById(R.id.time);
button = findViewById(R.id.button);
//pre asyncTask implementation, didn't update the view
// button.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// try {
// for (int i = 3; i >= 0; i--) {
// Thread.sleep(1000);
// Log.d("debugMode", Integer.toString(i));
// status.setText(Integer.toString(i));
// }
// } catch (InterruptedException ie) {
// ie.printStackTrace();
// }
// }
// });
//calling the asyncCount to create another thread to do the work
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new AsyncCount().execute("");
}
});
}
//the asyncCount thread, used to handle the delay, counting and updating
private class AsyncCount extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
int count = params.length;
for (int i = 3; i >= 0; i--) {
try {
Thread.sleep(1000);
publishProgress(Integer.toString(i));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return Integer.toString(count);
}
@Override
protected void onProgressUpdate(String... text) {
status.setText(text[0]);
}
}
}
| 2,253 | 0.54949 | 0.543276 | 69 | 31.652174 | 21.508896 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.536232 | false | false | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.