blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ed6f81b299601f9ae00c85b34e6ab5c032e09d25
| 7,687,991,492,431 |
2cca2a4f4c22d599770cf986e96f0f20f2ca8ea3
|
/src/test/java/restassured/automation/testcases/Restassured_Automation_MethodologItem.java
|
31d2eced5bf554d08afe65da20c348c6a897687e
|
[] |
no_license
|
bswjitsamal/practiceForAll
|
https://github.com/bswjitsamal/practiceForAll
|
c694aa0f8878af44fcaceab8258a874d98087b6c
|
09d32cbf3bc95a7e592e84994ea52ae264d3b64d
|
refs/heads/main
| 2023-06-12T23:20:32.681000 | 2021-07-04T13:14:08 | 2021-07-04T13:14:08 | 382,297,352 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package restassured.automation.testcases;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import org.awaitility.Awaitility;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.aventstack.extentreports.Status;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import restassured.automation.Pojo.MethodologyItem_Pojo;
import restassured.automation.Pojo.User_Pojo;
import restassured.automation.listeners.ExtentTestManager;
import restassured.automation.utils.Restassured_Automation_Utils;
import restassured.automation.utils.read_Configuration_Propertites;
public class Restassured_Automation_MethodologItem {
String URL;
String AuthorizationKey;
List<String> listRevisionId;
List<String> listOrdId;
List<String> methodologyId;
List<String> workFlow;
List<String> methodlogyItemId;
Restassured_Automation_Utils allUtils;
Properties post;
final static String ALPHANUMERIC_CHARACTERS = "0123456789abcdefghijklmnopqrstuvwxyz";
private static String getRandomAlphaNum() {
Random r = new Random();
int offset = r.nextInt(ALPHANUMERIC_CHARACTERS.length());
return ALPHANUMERIC_CHARACTERS.substring(offset, offset + 3);
}
@BeforeTest(groups = { "IntegrationTests", "EndToEnd", "IntegrationTests1" })
public void setup() throws IOException {
read_Configuration_Propertites configDetails = new read_Configuration_Propertites();
Properties BaseUrl = configDetails.loadproperty("Configuration");
URL = BaseUrl.getProperty("ApiBaseUrl");
AuthorizationKey = BaseUrl.getProperty("AuthorizationKey");
Awaitility.reset();
Awaitility.setDefaultPollDelay(999, MILLISECONDS);
Awaitility.setDefaultPollInterval(99, SECONDS);
Awaitility.setDefaultTimeout(99, SECONDS);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_getAllMethodologyItemsForARevision_status404() {
allUtils = new Restassured_Automation_Utils();
// Fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
/**
* GETTING THE REVISION ID
*/
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String id = revId.substring(1, revId.length() - 1);
// String subId = id.substring(8, 12);
String patchId = "/api/methodologyItem/revision/";
Response getEngagementTypeRes = allUtils.get_URL_Without_Params(URL, AuthorizationKey, patchId);
getEngagementTypeRes.prettyPrint();
Assert.assertEquals(getEngagementTypeRes.statusCode(), 404);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(getEngagementTypeRes.statusCode());
ExtentTestManager.getTest().log(Status.INFO, getEngagementTypeRes.asString());
allUtils.validate_HTTPStrictTransportSecurity(getEngagementTypeRes);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_GetAllMethodologyItemsForARevision_status400() {
allUtils = new Restassured_Automation_Utils();
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
/**
* GETTING THE REVISION ID
*/
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
System.out.println("revision id----->" + revId);
String id = revId.substring(1, revId.length() - 1);
System.out.println("substring------>" + id);
System.out.println("Length----->" + id.length());
String subId = id.substring(0, 19);
/*
* String patchId = "/api/methodologyItem/revision/" + subId +
* getRandomAlphaNum() + allUtils.getRandomNumber(1, 20);
*/
String patchId = "/api/methodologyItem/revisionss/" + revId.substring(1,25);
Response getEngagementTypeRes = allUtils.get_URL_Without_Params(URL, AuthorizationKey, patchId);
getEngagementTypeRes.prettyPrint();
Assert.assertEquals(getEngagementTypeRes.statusCode(), 400);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(getEngagementTypeRes.statusCode());
ExtentTestManager.getTest().log(Status.INFO, getEngagementTypeRes.asString());
allUtils.validate_HTTPStrictTransportSecurity(getEngagementTypeRes);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_GetAllMethodologyItemsForARevision_status200() {
allUtils = new Restassured_Automation_Utils();
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
/**
* GETTING THE REVISION ID
*/
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(1)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25);
Response getEngagementTypeRes = allUtils.get_URL_Without_Params(URL, AuthorizationKey, patchId);
getEngagementTypeRes.prettyPrint();
Assert.assertEquals(getEngagementTypeRes.statusCode(), 200);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(getEngagementTypeRes.statusCode());
ExtentTestManager.getTest().log(Status.INFO, getEngagementTypeRes.asString());
allUtils.validate_HTTPStrictTransportSecurity(getEngagementTypeRes);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PostCreateANewMethodologyItemWithinTheMethodologyTree_status200()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType", post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
//map.put("parentId", post.getProperty("postMethodologyItemItemType"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
Assert.assertEquals(postMethodologyItem.statusCode(), 200);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(postMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, postMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(postMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PostCreateANewMethodologyItemWithinTheMethodologyTree_status400()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
//map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType", post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
//map.put("parentId", post.getProperty("postMethodologyItemItemType"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
Assert.assertEquals(postMethodologyItem.statusCode(), 400);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(postMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, postMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(postMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PostCreateANewMethodologyItemWithinTheMethodologyTree_status404()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator2 = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator2.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
/**
* FETCHING REVISION ID
*/
JsonPath jsonPathEvaluator = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator.get("revisions");
String revId = String.valueOf(listRevisionI1.get(2));
/**
* FETCHING METHODOLOGY ID
*/
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
methodologyId = jsonPathEvaluator1.get("id");
System.out.println("Methodology id------->" + methodologyId);
String mId = String.valueOf(methodologyId.get(2));
System.out.println(mId);
String patchId1 = "/api/methodologyItem/revision/" + methodologyId.get(2) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType", post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
//map.put("parentId", post.getProperty("postMethodologyItemItemType"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId1, createPhase);
postMethodologyItem.prettyPrint();
Assert.assertEquals(postMethodologyItem.statusCode(), 404);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(postMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, postMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(postMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PutMoveATreeItemToAFolderAtSpecifiedIndex_status204()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
String title = post.getProperty("postMethodologyTitle") + getRandomAlphaNum()
+ allUtils.getRandomNumber(1, 20);
Map<String,String> map=new HashMap<String, String>();
map.put("title", title);
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
JsonPath jsonEvaluator = postMethodologyItem.jsonPath();
String revision = jsonEvaluator.get("revisionId");
String methodItemId = jsonEvaluator.get("methodologyItemId");
String patchId1 = "/api/methodologyItem/revision/" + revision + "/move/" + methodItemId;
Map<String,String> map1=new HashMap<String, String>();
map1.put("title", post.getProperty("putMethodologyItemTitle"));
map1.put("itemType",post.getProperty("postMethodologyItemItemType"));
map1.put("index", post.getProperty("postMethodologyItemIndex"));
map1.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo1=new User_Pojo();
String createPhase1=pojo.phaseAdd(map1);
Response putMethodologyItem = allUtils.put_URLPOJO(URL, AuthorizationKey, patchId1, createPhase1);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 204);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PutMoveATreeItemToAFolderAtSpecifiedIndex_status400()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
System.out.println("Revision id-------->" + revId);
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
JsonPath jsonEvaluator = postMethodologyItem.jsonPath();
String revision = jsonEvaluator.get("revisionId");
String methodItemId = jsonEvaluator.get("methodologyItemId");
String patchId1 = "/api/methodologyItem/revision/" + revision + "/move/" + methodItemId;
Map<String,String> map1=new HashMap<String, String>();
map1.put("title", post.getProperty("postMethodologyItemBadTitle"));
map1.put("itemType",post.getProperty("postMethodologyItemItemType"));
map1.put("index", post.getProperty("postMethodologyItemIndex"));
map1.put("parentId", post.getProperty("putMethodologyItemParentId") + getRandomAlphaNum()
+ allUtils.getRandomNumber(1, 5));
User_Pojo pojo1=new User_Pojo();
String createPhase1=pojo.phaseAdd(map1);
Response putMethodologyItem = allUtils.put_URLPOJO(URL, AuthorizationKey, patchId1, createPhase1);
// putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 400);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PutMoveATreeItemToAFolderAtSpecifiedIndex_status409()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
String revId = String.valueOf(listRevisionI1.get(2));
System.out.println("Revision id------>" + revId);
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
// String
// title=post.getProperty("postMethodologyTitle")+getRandomAlphaNum()+getMethodology.getRandomNumber(1,
// 20);
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
JsonPath jsonEvaluator = postMethodologyItem.jsonPath();
String revision = jsonEvaluator.get("revisionId");
String methodItemId = jsonEvaluator.get("methodologyItemId");
String patchId1 = "/api/methodologyItem/revision/" + revision + "/move/" + methodItemId;
Map<String,String> map1=new HashMap<String, String>();
map1.put("title", post.getProperty("putMethodologyItemTitle"));
map1.put("itemType",post.getProperty("postMethodologyItemItemType"));
map1.put("index", post.getProperty("postMethodologyItemIndex"));
map1.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo1=new User_Pojo();
String createPhase1=pojo.phaseAdd(map1);
Response putMethodologyItem = allUtils.put_URLPOJO(URL, AuthorizationKey, patchId1, createPhase1);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 409);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PatchUpdateAMethodologyItemForTheRevision_status204()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(1));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
JsonPath jsonEvaluvator2 = postMethodologyItem.jsonPath();
String revision = jsonEvaluvator2.get("revisionId");
String methodItemId = jsonEvaluvator2.get("methodologyItemId");
System.out.println("Method id------>" + methodItemId);
System.out.println("Revision id------>" + revision);
String patchId1 = "/api/methodologyItem/revision/" + revision + "/item/" + methodItemId;
Map<String, String> map1 = new HashMap<String, String>();
map1.put("title", post.getProperty("putMethodologyItemTitle")+getRandomAlphaNum());
User_Pojo po=new User_Pojo();
String data=po.phaseAdd(map1);
Response putMethodologyItem = allUtils.patch_URLPOJO(URL, AuthorizationKey, patchId1, data);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 204);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PatchUpdateAMethodologyItemForTheRevision_status400()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
JsonPath jsonEvaluvator2 = postMethodologyItem.jsonPath();
String revision = jsonEvaluvator2.get("revisionId");
String methodItemId = jsonEvaluvator2.get("methodologyItemId");
System.out.println("Method id------>" + methodItemId);
System.out.println("Revision id------>" + revision);
String patchId1 = "/api/methodologyItem/revision/" + revision + "/item/" + methodItemId;
Map<String,String> map1=new HashMap<String, String>();
map1.put("title", post.getProperty("putMethodologyItemBadTitle"));
map1.put("itemType",post.getProperty("postMethodologyItemItemType"));
map1.put("index", post.getProperty("postMethodologyItemIndex"));
//map1.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo1=new User_Pojo();
String createPhase1=pojo1.phaseAdd(map1);
Response putMethodologyItem = allUtils.patch_URLPOJO(URL, AuthorizationKey, patchId1, createPhase1);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 400);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PatchUpdateAMethodologyItemForTheRevision_status404()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Restassured_Automation_Utils getMethodology = new Restassured_Automation_Utils();
Response getMethodologyRes = getMethodology.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
String patchId1 = "/api/methodologyItem/revisionss/" + revId.substring(1, 25) + "/item/" + revId.substring(1, 25);
Map<String,String> map1=new HashMap<String, String>();
map1.put("title", post.getProperty("putMethodologyItemTitle")+getRandomAlphaNum());
map1.put("itemType",post.getProperty("postMethodologyItemItemType"));
map1.put("index", post.getProperty("postMethodologyItemIndex"));
//map1.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo1=new User_Pojo();
String createPhase1=pojo1.phaseAdd(map1);
Response putMethodologyItem = allUtils.patch_URLPOJO(URL, AuthorizationKey, patchId1, createPhase1);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 404);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PatchUpdateAMethodologyItemForTheRevision_status409()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
JsonPath jsonEvaluvator2 = postMethodologyItem.jsonPath();
String revision = jsonEvaluvator2.get("revisionId");
String methodItemId = jsonEvaluvator2.get("methodologyItemId");
String title=jsonEvaluvator2.get("title");
System.out.println("Method id------>" + methodItemId);
System.out.println("Revision id------>" + revision);
String patchId1 = "/api/methodologyItem/revision/" + revision + "/item/" + methodItemId;
Map<String, String> map1 = new HashMap<String, String>();
map1.put("title", title);
User_Pojo po=new User_Pojo();
String data=po.phaseAdd(map1);
Response putMethodologyItem = allUtils.patch_URLPOJO(URL, AuthorizationKey, patchId1, data);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 409);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PostInitialiseAWorkProgram_status204()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
/**
* Creating an phase
*/
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
JsonPath jsonEvaluator = postMethodologyItem.jsonPath();
String revision = jsonEvaluator.get("revisionId");
String methodItemId = jsonEvaluator.get("methodologyItemId");
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
String patchId1 = "/api/methodologyItem/revision/" + revision + "/workProgram/" + methodItemId + "/initialize";
/*
mi.setTitle(post.getProperty("putMethodologyItemTitle"));
mi.setParentId(post.getProperty("postMethodologyItemParentId"));
mi.setIndex(post.getProperty("postMethodologyItemIndex"));
mi.setItemType(post.getProperty("postMethodologyItemItemType"));*/
Map<String,String> data=new HashMap<String, String>();
data.put("ruleContextType", "Standard");
User_Pojo po=new User_Pojo();
String initialize=po.initializeWorkProgramType(data);
Response putMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId1, initialize);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 204);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PostInitialiseAWorkProgram_status400()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
/**
* Creating an phase
*/
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
JsonPath jsonEvaluator = postMethodologyItem.jsonPath();
String revision = jsonEvaluator.get("revisionId");
String methodItemId = jsonEvaluator.get("methodologyItemId");
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
String patchId1 = "/api/methodologyItem/revision/" + revision + "/workProgram/" + methodItemId + "/initialize";
/*
mi.setTitle(post.getProperty("putMethodologyItemTitle"));
mi.setParentId(post.getProperty("postMethodologyItemParentId"));
mi.setIndex(post.getProperty("postMethodologyItemIndex"));
mi.setItemType(post.getProperty("postMethodologyItemItemType"));*/
Map<String,String> data=new HashMap<String, String>();
data.put("ruleContextType", post.getProperty("postRuleContextType1"));
User_Pojo po=new User_Pojo();
String initialize=po.initializeWorkProgramType(data);
Response putMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId1, initialize);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 400);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PostInitialiseAWorkProgram_status404()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
/**
* Creating an phase
*/
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
JsonPath jsonEvaluator = postMethodologyItem.jsonPath();
String revision = jsonEvaluator.get("revisionId");
String methodItemId = jsonEvaluator.get("methodologyItemId");
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
String patchId1 = "/api/methodologyItem/revision/" + revision + "/workProgramss/" + methodItemId + "/initialize";
/*
mi.setTitle(post.getProperty("putMethodologyItemTitle"));
mi.setParentId(post.getProperty("postMethodologyItemParentId"));
mi.setIndex(post.getProperty("postMethodologyItemIndex"));
mi.setItemType(post.getProperty("postMethodologyItemItemType"));*/
Map<String,String> data=new HashMap<String, String>();
data.put("ruleContextType", post.getProperty("postRuleContextType1"));
User_Pojo po=new User_Pojo();
String initialize=po.initializeWorkProgramType(data);
Response putMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId1, initialize);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 404);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_DeleteMarkAnItemAsDeleted_status204()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
/**
* Creating an phase
*/
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
JsonPath jsonEvaluator = postMethodologyItem.jsonPath();
String revision = jsonEvaluator.get("revisionId");
String methodItemId = jsonEvaluator.get("methodologyItemId");
String patchId1 = "/api/methodologyItem/revision/" + revision + "/item/" + methodItemId;
Response putMethodologyItem = allUtils.delete(URL, AuthorizationKey, patchId1);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 204);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_DeleteMarkAnItemAsDeleted_status400()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
/**
* Creating an phase
*/
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
JsonPath jsonEvaluator = postMethodologyItem.jsonPath();
String revision = jsonEvaluator.get("revisionId");
String methodItemId = jsonEvaluator.get("methodologyItemId");
String patchId1 = "/api/methodologyItem/revision/" + revision + "/item/" + methodItemId;
allUtils.delete(URL, AuthorizationKey, patchId1);
Response putMethodologyItem = allUtils.delete(URL, AuthorizationKey, patchId1);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 400);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_UpdateItemsWorkFlowWithStatus_204() throws IOException {
Restassured_Automation_Utils allUtils = new Restassured_Automation_Utils();
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
/**
* GETTING THE REVISION ID
*/
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25);
Restassured_Automation_Utils getEngagementType = new Restassured_Automation_Utils();
Response getEngagementTypeRes = getEngagementType.get_URL_Without_Params(URL, AuthorizationKey, patchId);
getEngagementTypeRes.prettyPrint();
// Assert.assertEquals(getEngagementTypeRes.statusCode(), 200);
JsonPath workFlowJson = getEngagementTypeRes.jsonPath();
// workFlow=workFlowJson.get("workFlowState");
methodlogyItemId = workFlowJson.get("methodologyItemId");
String methodItemId = methodlogyItemId.get(1);
Properties post = read_Configuration_Propertites.loadproperty("Configuration");
String workFlowParam = post.getProperty("postWorkFlowState");
String postId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/workProgram/" + methodItemId
+ "/workFlow/" + workFlowParam;
Response postWorkFlowRes = getEngagementType.post_URL_WithoutBody(URL, AuthorizationKey, postId);
postWorkFlowRes.prettyPrint();
Assert.assertEquals(postWorkFlowRes.getStatusCode(), 204);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(postWorkFlowRes.statusCode());
ExtentTestManager.getTest().log(Status.INFO, postWorkFlowRes.asString());
getEngagementType.validate_HTTPStrictTransportSecurity(postWorkFlowRes);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_UpdateItemsWorkFlowWithStatus_400() throws IOException {
Restassured_Automation_Utils allUtils = new Restassured_Automation_Utils();
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
/**
* GETTING THE REVISION ID
*/
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25);
Restassured_Automation_Utils getEngagementType = new Restassured_Automation_Utils();
Response getEngagementTypeRes = getEngagementType.get_URL_Without_Params(URL, AuthorizationKey, patchId);
getEngagementTypeRes.prettyPrint();
// Assert.assertEquals(getEngagementTypeRes.statusCode(), 200);
JsonPath workFlowJson = getEngagementTypeRes.jsonPath();
// workFlow=workFlowJson.get("workFlowState");
methodlogyItemId = workFlowJson.get("methodologyItemId");
String methodItemId = methodlogyItemId.get(1);
Properties post = read_Configuration_Propertites.loadproperty("Configuration");
String workFlowParam = post.getProperty("postWorkFlowState1");
String postId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/workProgram/" + methodItemId
+ "/workFlow/" + workFlowParam;
Response postWorkFlowRes = getEngagementType.post_URL_WithoutBody(URL, AuthorizationKey, postId);
postWorkFlowRes.prettyPrint();
Assert.assertEquals(postWorkFlowRes.getStatusCode(), 400);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(postWorkFlowRes.statusCode());
ExtentTestManager.getTest().log(Status.INFO, postWorkFlowRes.asString());
getEngagementType.validate_HTTPStrictTransportSecurity(postWorkFlowRes);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_UpdateItemsWorkFlowWithStatus_404() throws IOException {
Restassured_Automation_Utils allUtils = new Restassured_Automation_Utils();
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
/**
* GETTING THE REVISION ID
*/
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25);
Restassured_Automation_Utils getEngagementType = new Restassured_Automation_Utils();
Response getEngagementTypeRes = getEngagementType.get_URL_Without_Params(URL, AuthorizationKey, patchId);
getEngagementTypeRes.prettyPrint();
// Assert.assertEquals(getEngagementTypeRes.statusCode(), 200);
JsonPath workFlowJson = getEngagementTypeRes.jsonPath();
// workFlow=workFlowJson.get("workFlowState");
methodlogyItemId = workFlowJson.get("methodologyItemId");
String methodItemId = methodlogyItemId.get(1);
Properties post = read_Configuration_Propertites.loadproperty("Configuration");
String workFlowParam = post.getProperty("postWorkFlowState1");
String postId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item/" + methodItemId
+ "/workFlow/" + workFlowParam;
Response postWorkFlowRes = getEngagementType.post_URL_WithoutBody(URL, AuthorizationKey, postId);
postWorkFlowRes.prettyPrint();
Assert.assertEquals(postWorkFlowRes.getStatusCode(), 404);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(postWorkFlowRes.statusCode());
ExtentTestManager.getTest().log(Status.INFO, postWorkFlowRes.asString());
getEngagementType.validate_HTTPStrictTransportSecurity(postWorkFlowRes);
}
@Test(groups = { "EndToEnd" })
public void MethodologyItem_EndToEnd_Scenario() throws IOException {
Restassured_Automation_Utils allUtils = new Restassured_Automation_Utils();
/**
* FETCHING THE ORGANISATION ID
*/
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
/**
* FETCHING THE PARTICULAR REVISION ID FROM METHODOLOGY
*/
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25);
Restassured_Automation_Utils getEngagementType = new Restassured_Automation_Utils();
Response getEngagementTypeRes = getEngagementType.get_URL_Without_Params(URL, AuthorizationKey, patchId);
// getEngagementTypeRes.prettyPrint();
// Assert.assertEquals(getEngagementTypeRes.statusCode(), 200);
/**
* PERFORMING THE POST OPERATION
*/
String patchId1 = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Properties post1 = read_Configuration_Propertites.loadproperty("Configuration");
MethodologyItem_Pojo mi = new MethodologyItem_Pojo();
mi.setTitle(post1.getProperty("postMethodologyItemTitle"));
mi.setParentId(post1.getProperty("postMethodologyItemParentId"));
mi.setIndex(post1.getProperty("postMethodologyItemIndex"));
mi.setItemType(post1.getProperty("postMethodologyItemItemType"));
Restassured_Automation_Utils MethodologyItem = new Restassured_Automation_Utils();
Response postMethodologyItem = MethodologyItem.post_URLPOJO(URL, AuthorizationKey, patchId1, mi);
postMethodologyItem.prettyPrint();
JsonPath jsonEvaluator = postMethodologyItem.jsonPath();
String revision = jsonEvaluator.get("revisionId");
String methodItemId = jsonEvaluator.get("methodologyItemId");
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
/**
* PERFORMING THE PUT OPERATION
*/
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
String patchId2 = "/api/methodologyItem/revision/" + revision + "/item/" + methodItemId;
mi.setTitle(post1.getProperty("putMethodologyItemTitle") + MethodologyItem.getRandomNumber(1, 20));
mi.setParentId(post1.getProperty("postMethodologyItemParentId"));
mi.setIndex(post1.getProperty("postMethodologyItemIndex"));
mi.setItemType(post1.getProperty("postMethodologyItemItemType"));
Response putMethodologyItem = MethodologyItem.patch_URLPOJO(URL, AuthorizationKey, patchId2, mi);
putMethodologyItem.prettyPrint();
// Assert.assertEquals(putMethodologyItem.statusCode(), 204);
JsonPath jsonEvaluator1 = putMethodologyItem.jsonPath();
String revision1 = jsonEvaluator.get("revisionId");
String methodItemId1 = jsonEvaluator.get("methodologyItemId");
/**
* PERFORMING DELETE OPERATION
*/
String patchId3 = "/api/methodologyItem/revision/" + revision1 + "/item/" + methodItemId1;
Response deleteMethodologyItem = MethodologyItem.delete(URL, AuthorizationKey, patchId3);
deleteMethodologyItem.prettyPrint();
Assert.assertEquals(deleteMethodologyItem.statusCode(), 204);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(deleteMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, deleteMethodologyItem.asString());
MethodologyItem.validate_HTTPStrictTransportSecurity(deleteMethodologyItem);
}
}
|
UTF-8
|
Java
| 59,548 |
java
|
Restassured_Automation_MethodologItem.java
|
Java
|
[] | null |
[] |
package restassured.automation.testcases;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import org.awaitility.Awaitility;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.aventstack.extentreports.Status;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import restassured.automation.Pojo.MethodologyItem_Pojo;
import restassured.automation.Pojo.User_Pojo;
import restassured.automation.listeners.ExtentTestManager;
import restassured.automation.utils.Restassured_Automation_Utils;
import restassured.automation.utils.read_Configuration_Propertites;
public class Restassured_Automation_MethodologItem {
String URL;
String AuthorizationKey;
List<String> listRevisionId;
List<String> listOrdId;
List<String> methodologyId;
List<String> workFlow;
List<String> methodlogyItemId;
Restassured_Automation_Utils allUtils;
Properties post;
final static String ALPHANUMERIC_CHARACTERS = "0123456789abcdefghijklmnopqrstuvwxyz";
private static String getRandomAlphaNum() {
Random r = new Random();
int offset = r.nextInt(ALPHANUMERIC_CHARACTERS.length());
return ALPHANUMERIC_CHARACTERS.substring(offset, offset + 3);
}
@BeforeTest(groups = { "IntegrationTests", "EndToEnd", "IntegrationTests1" })
public void setup() throws IOException {
read_Configuration_Propertites configDetails = new read_Configuration_Propertites();
Properties BaseUrl = configDetails.loadproperty("Configuration");
URL = BaseUrl.getProperty("ApiBaseUrl");
AuthorizationKey = BaseUrl.getProperty("AuthorizationKey");
Awaitility.reset();
Awaitility.setDefaultPollDelay(999, MILLISECONDS);
Awaitility.setDefaultPollInterval(99, SECONDS);
Awaitility.setDefaultTimeout(99, SECONDS);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_getAllMethodologyItemsForARevision_status404() {
allUtils = new Restassured_Automation_Utils();
// Fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
/**
* GETTING THE REVISION ID
*/
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String id = revId.substring(1, revId.length() - 1);
// String subId = id.substring(8, 12);
String patchId = "/api/methodologyItem/revision/";
Response getEngagementTypeRes = allUtils.get_URL_Without_Params(URL, AuthorizationKey, patchId);
getEngagementTypeRes.prettyPrint();
Assert.assertEquals(getEngagementTypeRes.statusCode(), 404);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(getEngagementTypeRes.statusCode());
ExtentTestManager.getTest().log(Status.INFO, getEngagementTypeRes.asString());
allUtils.validate_HTTPStrictTransportSecurity(getEngagementTypeRes);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_GetAllMethodologyItemsForARevision_status400() {
allUtils = new Restassured_Automation_Utils();
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
/**
* GETTING THE REVISION ID
*/
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
System.out.println("revision id----->" + revId);
String id = revId.substring(1, revId.length() - 1);
System.out.println("substring------>" + id);
System.out.println("Length----->" + id.length());
String subId = id.substring(0, 19);
/*
* String patchId = "/api/methodologyItem/revision/" + subId +
* getRandomAlphaNum() + allUtils.getRandomNumber(1, 20);
*/
String patchId = "/api/methodologyItem/revisionss/" + revId.substring(1,25);
Response getEngagementTypeRes = allUtils.get_URL_Without_Params(URL, AuthorizationKey, patchId);
getEngagementTypeRes.prettyPrint();
Assert.assertEquals(getEngagementTypeRes.statusCode(), 400);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(getEngagementTypeRes.statusCode());
ExtentTestManager.getTest().log(Status.INFO, getEngagementTypeRes.asString());
allUtils.validate_HTTPStrictTransportSecurity(getEngagementTypeRes);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_GetAllMethodologyItemsForARevision_status200() {
allUtils = new Restassured_Automation_Utils();
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
/**
* GETTING THE REVISION ID
*/
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(1)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25);
Response getEngagementTypeRes = allUtils.get_URL_Without_Params(URL, AuthorizationKey, patchId);
getEngagementTypeRes.prettyPrint();
Assert.assertEquals(getEngagementTypeRes.statusCode(), 200);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(getEngagementTypeRes.statusCode());
ExtentTestManager.getTest().log(Status.INFO, getEngagementTypeRes.asString());
allUtils.validate_HTTPStrictTransportSecurity(getEngagementTypeRes);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PostCreateANewMethodologyItemWithinTheMethodologyTree_status200()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType", post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
//map.put("parentId", post.getProperty("postMethodologyItemItemType"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
Assert.assertEquals(postMethodologyItem.statusCode(), 200);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(postMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, postMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(postMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PostCreateANewMethodologyItemWithinTheMethodologyTree_status400()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
//map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType", post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
//map.put("parentId", post.getProperty("postMethodologyItemItemType"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
Assert.assertEquals(postMethodologyItem.statusCode(), 400);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(postMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, postMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(postMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PostCreateANewMethodologyItemWithinTheMethodologyTree_status404()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator2 = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator2.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
/**
* FETCHING REVISION ID
*/
JsonPath jsonPathEvaluator = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator.get("revisions");
String revId = String.valueOf(listRevisionI1.get(2));
/**
* FETCHING METHODOLOGY ID
*/
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
methodologyId = jsonPathEvaluator1.get("id");
System.out.println("Methodology id------->" + methodologyId);
String mId = String.valueOf(methodologyId.get(2));
System.out.println(mId);
String patchId1 = "/api/methodologyItem/revision/" + methodologyId.get(2) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType", post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
//map.put("parentId", post.getProperty("postMethodologyItemItemType"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId1, createPhase);
postMethodologyItem.prettyPrint();
Assert.assertEquals(postMethodologyItem.statusCode(), 404);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(postMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, postMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(postMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PutMoveATreeItemToAFolderAtSpecifiedIndex_status204()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
String title = post.getProperty("postMethodologyTitle") + getRandomAlphaNum()
+ allUtils.getRandomNumber(1, 20);
Map<String,String> map=new HashMap<String, String>();
map.put("title", title);
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
JsonPath jsonEvaluator = postMethodologyItem.jsonPath();
String revision = jsonEvaluator.get("revisionId");
String methodItemId = jsonEvaluator.get("methodologyItemId");
String patchId1 = "/api/methodologyItem/revision/" + revision + "/move/" + methodItemId;
Map<String,String> map1=new HashMap<String, String>();
map1.put("title", post.getProperty("putMethodologyItemTitle"));
map1.put("itemType",post.getProperty("postMethodologyItemItemType"));
map1.put("index", post.getProperty("postMethodologyItemIndex"));
map1.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo1=new User_Pojo();
String createPhase1=pojo.phaseAdd(map1);
Response putMethodologyItem = allUtils.put_URLPOJO(URL, AuthorizationKey, patchId1, createPhase1);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 204);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PutMoveATreeItemToAFolderAtSpecifiedIndex_status400()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
System.out.println("Revision id-------->" + revId);
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
JsonPath jsonEvaluator = postMethodologyItem.jsonPath();
String revision = jsonEvaluator.get("revisionId");
String methodItemId = jsonEvaluator.get("methodologyItemId");
String patchId1 = "/api/methodologyItem/revision/" + revision + "/move/" + methodItemId;
Map<String,String> map1=new HashMap<String, String>();
map1.put("title", post.getProperty("postMethodologyItemBadTitle"));
map1.put("itemType",post.getProperty("postMethodologyItemItemType"));
map1.put("index", post.getProperty("postMethodologyItemIndex"));
map1.put("parentId", post.getProperty("putMethodologyItemParentId") + getRandomAlphaNum()
+ allUtils.getRandomNumber(1, 5));
User_Pojo pojo1=new User_Pojo();
String createPhase1=pojo.phaseAdd(map1);
Response putMethodologyItem = allUtils.put_URLPOJO(URL, AuthorizationKey, patchId1, createPhase1);
// putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 400);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PutMoveATreeItemToAFolderAtSpecifiedIndex_status409()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
String revId = String.valueOf(listRevisionI1.get(2));
System.out.println("Revision id------>" + revId);
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
// String
// title=post.getProperty("postMethodologyTitle")+getRandomAlphaNum()+getMethodology.getRandomNumber(1,
// 20);
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
JsonPath jsonEvaluator = postMethodologyItem.jsonPath();
String revision = jsonEvaluator.get("revisionId");
String methodItemId = jsonEvaluator.get("methodologyItemId");
String patchId1 = "/api/methodologyItem/revision/" + revision + "/move/" + methodItemId;
Map<String,String> map1=new HashMap<String, String>();
map1.put("title", post.getProperty("putMethodologyItemTitle"));
map1.put("itemType",post.getProperty("postMethodologyItemItemType"));
map1.put("index", post.getProperty("postMethodologyItemIndex"));
map1.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo1=new User_Pojo();
String createPhase1=pojo.phaseAdd(map1);
Response putMethodologyItem = allUtils.put_URLPOJO(URL, AuthorizationKey, patchId1, createPhase1);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 409);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PatchUpdateAMethodologyItemForTheRevision_status204()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(1));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
JsonPath jsonEvaluvator2 = postMethodologyItem.jsonPath();
String revision = jsonEvaluvator2.get("revisionId");
String methodItemId = jsonEvaluvator2.get("methodologyItemId");
System.out.println("Method id------>" + methodItemId);
System.out.println("Revision id------>" + revision);
String patchId1 = "/api/methodologyItem/revision/" + revision + "/item/" + methodItemId;
Map<String, String> map1 = new HashMap<String, String>();
map1.put("title", post.getProperty("putMethodologyItemTitle")+getRandomAlphaNum());
User_Pojo po=new User_Pojo();
String data=po.phaseAdd(map1);
Response putMethodologyItem = allUtils.patch_URLPOJO(URL, AuthorizationKey, patchId1, data);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 204);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PatchUpdateAMethodologyItemForTheRevision_status400()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
JsonPath jsonEvaluvator2 = postMethodologyItem.jsonPath();
String revision = jsonEvaluvator2.get("revisionId");
String methodItemId = jsonEvaluvator2.get("methodologyItemId");
System.out.println("Method id------>" + methodItemId);
System.out.println("Revision id------>" + revision);
String patchId1 = "/api/methodologyItem/revision/" + revision + "/item/" + methodItemId;
Map<String,String> map1=new HashMap<String, String>();
map1.put("title", post.getProperty("putMethodologyItemBadTitle"));
map1.put("itemType",post.getProperty("postMethodologyItemItemType"));
map1.put("index", post.getProperty("postMethodologyItemIndex"));
//map1.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo1=new User_Pojo();
String createPhase1=pojo1.phaseAdd(map1);
Response putMethodologyItem = allUtils.patch_URLPOJO(URL, AuthorizationKey, patchId1, createPhase1);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 400);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PatchUpdateAMethodologyItemForTheRevision_status404()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Restassured_Automation_Utils getMethodology = new Restassured_Automation_Utils();
Response getMethodologyRes = getMethodology.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
String patchId1 = "/api/methodologyItem/revisionss/" + revId.substring(1, 25) + "/item/" + revId.substring(1, 25);
Map<String,String> map1=new HashMap<String, String>();
map1.put("title", post.getProperty("putMethodologyItemTitle")+getRandomAlphaNum());
map1.put("itemType",post.getProperty("postMethodologyItemItemType"));
map1.put("index", post.getProperty("postMethodologyItemIndex"));
//map1.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo1=new User_Pojo();
String createPhase1=pojo1.phaseAdd(map1);
Response putMethodologyItem = allUtils.patch_URLPOJO(URL, AuthorizationKey, patchId1, createPhase1);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 404);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PatchUpdateAMethodologyItemForTheRevision_status409()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
JsonPath jsonEvaluvator2 = postMethodologyItem.jsonPath();
String revision = jsonEvaluvator2.get("revisionId");
String methodItemId = jsonEvaluvator2.get("methodologyItemId");
String title=jsonEvaluvator2.get("title");
System.out.println("Method id------>" + methodItemId);
System.out.println("Revision id------>" + revision);
String patchId1 = "/api/methodologyItem/revision/" + revision + "/item/" + methodItemId;
Map<String, String> map1 = new HashMap<String, String>();
map1.put("title", title);
User_Pojo po=new User_Pojo();
String data=po.phaseAdd(map1);
Response putMethodologyItem = allUtils.patch_URLPOJO(URL, AuthorizationKey, patchId1, data);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 409);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PostInitialiseAWorkProgram_status204()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
/**
* Creating an phase
*/
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
JsonPath jsonEvaluator = postMethodologyItem.jsonPath();
String revision = jsonEvaluator.get("revisionId");
String methodItemId = jsonEvaluator.get("methodologyItemId");
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
String patchId1 = "/api/methodologyItem/revision/" + revision + "/workProgram/" + methodItemId + "/initialize";
/*
mi.setTitle(post.getProperty("putMethodologyItemTitle"));
mi.setParentId(post.getProperty("postMethodologyItemParentId"));
mi.setIndex(post.getProperty("postMethodologyItemIndex"));
mi.setItemType(post.getProperty("postMethodologyItemItemType"));*/
Map<String,String> data=new HashMap<String, String>();
data.put("ruleContextType", "Standard");
User_Pojo po=new User_Pojo();
String initialize=po.initializeWorkProgramType(data);
Response putMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId1, initialize);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 204);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PostInitialiseAWorkProgram_status400()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
/**
* Creating an phase
*/
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
JsonPath jsonEvaluator = postMethodologyItem.jsonPath();
String revision = jsonEvaluator.get("revisionId");
String methodItemId = jsonEvaluator.get("methodologyItemId");
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
String patchId1 = "/api/methodologyItem/revision/" + revision + "/workProgram/" + methodItemId + "/initialize";
/*
mi.setTitle(post.getProperty("putMethodologyItemTitle"));
mi.setParentId(post.getProperty("postMethodologyItemParentId"));
mi.setIndex(post.getProperty("postMethodologyItemIndex"));
mi.setItemType(post.getProperty("postMethodologyItemItemType"));*/
Map<String,String> data=new HashMap<String, String>();
data.put("ruleContextType", post.getProperty("postRuleContextType1"));
User_Pojo po=new User_Pojo();
String initialize=po.initializeWorkProgramType(data);
Response putMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId1, initialize);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 400);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_PostInitialiseAWorkProgram_status404()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
/**
* Creating an phase
*/
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
JsonPath jsonEvaluator = postMethodologyItem.jsonPath();
String revision = jsonEvaluator.get("revisionId");
String methodItemId = jsonEvaluator.get("methodologyItemId");
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
String patchId1 = "/api/methodologyItem/revision/" + revision + "/workProgramss/" + methodItemId + "/initialize";
/*
mi.setTitle(post.getProperty("putMethodologyItemTitle"));
mi.setParentId(post.getProperty("postMethodologyItemParentId"));
mi.setIndex(post.getProperty("postMethodologyItemIndex"));
mi.setItemType(post.getProperty("postMethodologyItemItemType"));*/
Map<String,String> data=new HashMap<String, String>();
data.put("ruleContextType", post.getProperty("postRuleContextType1"));
User_Pojo po=new User_Pojo();
String initialize=po.initializeWorkProgramType(data);
Response putMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId1, initialize);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 404);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_DeleteMarkAnItemAsDeleted_status204()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
/**
* Creating an phase
*/
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
JsonPath jsonEvaluator = postMethodologyItem.jsonPath();
String revision = jsonEvaluator.get("revisionId");
String methodItemId = jsonEvaluator.get("methodologyItemId");
String patchId1 = "/api/methodologyItem/revision/" + revision + "/item/" + methodItemId;
Response putMethodologyItem = allUtils.delete(URL, AuthorizationKey, patchId1);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 204);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_DeleteMarkAnItemAsDeleted_status400()
throws JsonIOException, JsonSyntaxException, IOException {
allUtils = new Restassured_Automation_Utils();
post = read_Configuration_Propertites.loadproperty("Configuration");
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
/**
* Creating an phase
*/
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Map<String,String> map=new HashMap<String, String>();
map.put("title", post.getProperty("postMethodologyItemTitle"));
map.put("itemType",post.getProperty("postMethodologyItemItemType"));
map.put("index", post.getProperty("postMethodologyItemIndex"));
map.put("parentId", post.getProperty("postMethodologyItemParentId"));
User_Pojo pojo=new User_Pojo();
String createPhase=pojo.phaseAdd(map);
Response postMethodologyItem = allUtils.post_URLPOJO(URL, AuthorizationKey, patchId, createPhase);
postMethodologyItem.prettyPrint();
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
JsonPath jsonEvaluator = postMethodologyItem.jsonPath();
String revision = jsonEvaluator.get("revisionId");
String methodItemId = jsonEvaluator.get("methodologyItemId");
String patchId1 = "/api/methodologyItem/revision/" + revision + "/item/" + methodItemId;
allUtils.delete(URL, AuthorizationKey, patchId1);
Response putMethodologyItem = allUtils.delete(URL, AuthorizationKey, patchId1);
putMethodologyItem.prettyPrint();
Assert.assertEquals(putMethodologyItem.statusCode(), 400);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(putMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, putMethodologyItem.asString());
allUtils.validate_HTTPStrictTransportSecurity(putMethodologyItem);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_UpdateItemsWorkFlowWithStatus_204() throws IOException {
Restassured_Automation_Utils allUtils = new Restassured_Automation_Utils();
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
/**
* GETTING THE REVISION ID
*/
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25);
Restassured_Automation_Utils getEngagementType = new Restassured_Automation_Utils();
Response getEngagementTypeRes = getEngagementType.get_URL_Without_Params(URL, AuthorizationKey, patchId);
getEngagementTypeRes.prettyPrint();
// Assert.assertEquals(getEngagementTypeRes.statusCode(), 200);
JsonPath workFlowJson = getEngagementTypeRes.jsonPath();
// workFlow=workFlowJson.get("workFlowState");
methodlogyItemId = workFlowJson.get("methodologyItemId");
String methodItemId = methodlogyItemId.get(1);
Properties post = read_Configuration_Propertites.loadproperty("Configuration");
String workFlowParam = post.getProperty("postWorkFlowState");
String postId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/workProgram/" + methodItemId
+ "/workFlow/" + workFlowParam;
Response postWorkFlowRes = getEngagementType.post_URL_WithoutBody(URL, AuthorizationKey, postId);
postWorkFlowRes.prettyPrint();
Assert.assertEquals(postWorkFlowRes.getStatusCode(), 204);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(postWorkFlowRes.statusCode());
ExtentTestManager.getTest().log(Status.INFO, postWorkFlowRes.asString());
getEngagementType.validate_HTTPStrictTransportSecurity(postWorkFlowRes);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_UpdateItemsWorkFlowWithStatus_400() throws IOException {
Restassured_Automation_Utils allUtils = new Restassured_Automation_Utils();
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
/**
* GETTING THE REVISION ID
*/
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25);
Restassured_Automation_Utils getEngagementType = new Restassured_Automation_Utils();
Response getEngagementTypeRes = getEngagementType.get_URL_Without_Params(URL, AuthorizationKey, patchId);
getEngagementTypeRes.prettyPrint();
// Assert.assertEquals(getEngagementTypeRes.statusCode(), 200);
JsonPath workFlowJson = getEngagementTypeRes.jsonPath();
// workFlow=workFlowJson.get("workFlowState");
methodlogyItemId = workFlowJson.get("methodologyItemId");
String methodItemId = methodlogyItemId.get(1);
Properties post = read_Configuration_Propertites.loadproperty("Configuration");
String workFlowParam = post.getProperty("postWorkFlowState1");
String postId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/workProgram/" + methodItemId
+ "/workFlow/" + workFlowParam;
Response postWorkFlowRes = getEngagementType.post_URL_WithoutBody(URL, AuthorizationKey, postId);
postWorkFlowRes.prettyPrint();
Assert.assertEquals(postWorkFlowRes.getStatusCode(), 400);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(postWorkFlowRes.statusCode());
ExtentTestManager.getTest().log(Status.INFO, postWorkFlowRes.asString());
getEngagementType.validate_HTTPStrictTransportSecurity(postWorkFlowRes);
}
@Test(groups = "IntegrationTests")
public void MethodologyItem_UpdateItemsWorkFlowWithStatus_404() throws IOException {
Restassured_Automation_Utils allUtils = new Restassured_Automation_Utils();
// fetching Org Id
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
/**
* GETTING THE REVISION ID
*/
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25);
Restassured_Automation_Utils getEngagementType = new Restassured_Automation_Utils();
Response getEngagementTypeRes = getEngagementType.get_URL_Without_Params(URL, AuthorizationKey, patchId);
getEngagementTypeRes.prettyPrint();
// Assert.assertEquals(getEngagementTypeRes.statusCode(), 200);
JsonPath workFlowJson = getEngagementTypeRes.jsonPath();
// workFlow=workFlowJson.get("workFlowState");
methodlogyItemId = workFlowJson.get("methodologyItemId");
String methodItemId = methodlogyItemId.get(1);
Properties post = read_Configuration_Propertites.loadproperty("Configuration");
String workFlowParam = post.getProperty("postWorkFlowState1");
String postId = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item/" + methodItemId
+ "/workFlow/" + workFlowParam;
Response postWorkFlowRes = getEngagementType.post_URL_WithoutBody(URL, AuthorizationKey, postId);
postWorkFlowRes.prettyPrint();
Assert.assertEquals(postWorkFlowRes.getStatusCode(), 404);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(postWorkFlowRes.statusCode());
ExtentTestManager.getTest().log(Status.INFO, postWorkFlowRes.asString());
getEngagementType.validate_HTTPStrictTransportSecurity(postWorkFlowRes);
}
@Test(groups = { "EndToEnd" })
public void MethodologyItem_EndToEnd_Scenario() throws IOException {
Restassured_Automation_Utils allUtils = new Restassured_Automation_Utils();
/**
* FETCHING THE ORGANISATION ID
*/
Response OrganizationsDetails = allUtils.get_URL_Without_Params(URL, AuthorizationKey, "/api/org");
JsonPath jsonPathEvaluator = OrganizationsDetails.jsonPath();
listOrdId = jsonPathEvaluator.get("id");
// OrganizationsDetails.prettyPrint();
/**
* FETCHING THE PARTICULAR REVISION ID FROM METHODOLOGY
*/
Response getMethodologyRes = allUtils.get_URL_QueryParams(URL, AuthorizationKey, "/api/methodology",
"Organization", listOrdId.get(3));
// getMethodologyRes.prettyPrint();
JsonPath jsonPathEvaluator1 = getMethodologyRes.jsonPath();
ArrayList<Map<String, ?>> listRevisionI1 = jsonPathEvaluator1.get("revisions");
System.out.println(String.valueOf(listRevisionI1.get(0)));
String revId = String.valueOf(listRevisionI1.get(2));
String patchId = "/api/methodologyItem/revision/" + revId.substring(1, 25);
Restassured_Automation_Utils getEngagementType = new Restassured_Automation_Utils();
Response getEngagementTypeRes = getEngagementType.get_URL_Without_Params(URL, AuthorizationKey, patchId);
// getEngagementTypeRes.prettyPrint();
// Assert.assertEquals(getEngagementTypeRes.statusCode(), 200);
/**
* PERFORMING THE POST OPERATION
*/
String patchId1 = "/api/methodologyItem/revision/" + revId.substring(1, 25) + "/item";
Properties post1 = read_Configuration_Propertites.loadproperty("Configuration");
MethodologyItem_Pojo mi = new MethodologyItem_Pojo();
mi.setTitle(post1.getProperty("postMethodologyItemTitle"));
mi.setParentId(post1.getProperty("postMethodologyItemParentId"));
mi.setIndex(post1.getProperty("postMethodologyItemIndex"));
mi.setItemType(post1.getProperty("postMethodologyItemItemType"));
Restassured_Automation_Utils MethodologyItem = new Restassured_Automation_Utils();
Response postMethodologyItem = MethodologyItem.post_URLPOJO(URL, AuthorizationKey, patchId1, mi);
postMethodologyItem.prettyPrint();
JsonPath jsonEvaluator = postMethodologyItem.jsonPath();
String revision = jsonEvaluator.get("revisionId");
String methodItemId = jsonEvaluator.get("methodologyItemId");
// Assert.assertEquals(postMethodologyItem.statusCode(), 200);
/**
* PERFORMING THE PUT OPERATION
*/
String methodologyItemId = postMethodologyItem.asString();
System.out.println("---->" + methodologyItemId);
String patchId2 = "/api/methodologyItem/revision/" + revision + "/item/" + methodItemId;
mi.setTitle(post1.getProperty("putMethodologyItemTitle") + MethodologyItem.getRandomNumber(1, 20));
mi.setParentId(post1.getProperty("postMethodologyItemParentId"));
mi.setIndex(post1.getProperty("postMethodologyItemIndex"));
mi.setItemType(post1.getProperty("postMethodologyItemItemType"));
Response putMethodologyItem = MethodologyItem.patch_URLPOJO(URL, AuthorizationKey, patchId2, mi);
putMethodologyItem.prettyPrint();
// Assert.assertEquals(putMethodologyItem.statusCode(), 204);
JsonPath jsonEvaluator1 = putMethodologyItem.jsonPath();
String revision1 = jsonEvaluator.get("revisionId");
String methodItemId1 = jsonEvaluator.get("methodologyItemId");
/**
* PERFORMING DELETE OPERATION
*/
String patchId3 = "/api/methodologyItem/revision/" + revision1 + "/item/" + methodItemId1;
Response deleteMethodologyItem = MethodologyItem.delete(URL, AuthorizationKey, patchId3);
deleteMethodologyItem.prettyPrint();
Assert.assertEquals(deleteMethodologyItem.statusCode(), 204);
/**
* Extent report generation
*/
ExtentTestManager.statusLogMessage(deleteMethodologyItem.statusCode());
ExtentTestManager.getTest().log(Status.INFO, deleteMethodologyItem.asString());
MethodologyItem.validate_HTTPStrictTransportSecurity(deleteMethodologyItem);
}
}
| 59,548 | 0.764224 | 0.754198 | 1,472 | 39.453804 | 32.704197 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.402174 | false | false |
7
|
a4f9d658379810d834adfba687084e2b671892fe
| 7,687,991,491,032 |
9cb83f3b3c05ab29454812fabdda2c26a0e39754
|
/Leetcode-2/Array/39.组合总数/Solution.java
|
a6922617b21bd6864b44b4d5d351e8b3cbed1010
|
[] |
no_license
|
heathjay/niuke
|
https://github.com/heathjay/niuke
|
0da093bd6b1bd3099955d5ffac3f749e85ccf29a
|
ad3e82ddf9aac2e718d77571f2191815ce1bd44d
|
refs/heads/master
| 2023-08-21T00:18:29.116000 | 2021-10-20T08:48:36 | 2021-10-20T08:48:36 | 306,721,910 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<int[]> freq = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
int len = candidates.length;
if(len == 0) return res;
Arrays.sort(candidates);
dfs(candidates, new ArrayList<Integer>(), target, 0);
return res;
}
public void dfs(int[] candidates, ArrayList<Integer> path, int target, int indx){
int len = candidates.length;
if(indx == len){
return;
}
if(target == 0){
res.add(new ArrayList<Integer>(path));
return;
}
//直接跳过
dfs(candidates, path, target, indx+1);
if(target - candidates[indx] >= 0){
path.add(candidates[indx]);
//使用该位
dfs(candidates, path, target-candidates[indx], indx);
path.remove(path.size()-1);
}
}
}
|
UTF-8
|
Java
| 979 |
java
|
Solution.java
|
Java
|
[] | null |
[] |
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<int[]> freq = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
int len = candidates.length;
if(len == 0) return res;
Arrays.sort(candidates);
dfs(candidates, new ArrayList<Integer>(), target, 0);
return res;
}
public void dfs(int[] candidates, ArrayList<Integer> path, int target, int indx){
int len = candidates.length;
if(indx == len){
return;
}
if(target == 0){
res.add(new ArrayList<Integer>(path));
return;
}
//直接跳过
dfs(candidates, path, target, indx+1);
if(target - candidates[indx] >= 0){
path.add(candidates[indx]);
//使用该位
dfs(candidates, path, target-candidates[indx], indx);
path.remove(path.size()-1);
}
}
}
| 979 | 0.530633 | 0.524403 | 31 | 30.096775 | 21.702318 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.903226 | false | false |
7
|
f1e88b26b807266127691f66aaeab79b9d57248c
| 29,600,914,632,130 |
ba0b7cb8eec8091ca799c094ae6a0d23bd84a816
|
/src/main/java/com/whizzosoftware/hobson/liftmyq/state/ConfigurationWaitState.java
|
7d308e2b40afd9b72cd341261d550da25587c68d
|
[] |
no_license
|
whizzosoftware/hobson-hub-liftmaster-myq
|
https://github.com/whizzosoftware/hobson-hub-liftmaster-myq
|
bcc7d6f3d656780f622e773f1c7627fe0db49b5b
|
8aef944618c17709d0b8816a3ce135db1254e9f0
|
refs/heads/master
| 2021-01-09T21:52:39.413000 | 2017-03-28T23:32:44 | 2017-03-28T23:32:44 | 55,423,804 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*******************************************************************************
* Copyright (c) 2016 Whizzo Software, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.whizzosoftware.hobson.liftmyq.state;
import com.whizzosoftware.hobson.api.plugin.PluginStatus;
import com.whizzosoftware.hobson.api.plugin.http.HttpResponse;
import com.whizzosoftware.hobson.api.property.PropertyContainer;
import org.slf4j.LoggerFactory;
/**
* The "configuration wait" state of the plugin. This means that the plugin does not have myQ cloud credentials
* yet and must wait for the user to provide them.
*
* @author Dan Noguerol
*/
public class ConfigurationWaitState implements State {
private boolean notConfiguredSet = false;
public ConfigurationWaitState() {
LoggerFactory.getLogger(getClass()).debug("Entering configurationWaitState");
}
@Override
public void onRefresh(StateContext ctx) {
PropertyContainer pc = ctx.getConfiguration();
if (pc != null && pc.hasPropertyValue("username") && pc.hasPropertyValue("password")) {
ctx.setState(new LoggingInState());
} else if (!notConfiguredSet) {
ctx.setPluginStatus(PluginStatus.notConfigured("No username or password has been set"));
notConfiguredSet = true;
}
}
@Override
public void onPluginConfigurationUpdate(StateContext ctx) {
onRefresh(ctx);
}
@Override
public void onHttpResponse(StateContext ctx, HttpResponse response, Object reqCtx) {
}
@Override
public void onHttpRequestFailure(StateContext ctx, Throwable cause, Object reqCtx) {
}
@Override
public void setDeviceState(StateContext ctx, String deviceId, Boolean state) {
}
}
|
UTF-8
|
Java
| 2,046 |
java
|
ConfigurationWaitState.java
|
Java
|
[
{
"context": "t wait for the user to provide them.\n *\n * @author Dan Noguerol\n */\npublic class ConfigurationWaitState implement",
"end": 915,
"score": 0.9998761415481567,
"start": 903,
"tag": "NAME",
"value": "Dan Noguerol"
}
] | null |
[] |
/*******************************************************************************
* Copyright (c) 2016 Whizzo Software, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.whizzosoftware.hobson.liftmyq.state;
import com.whizzosoftware.hobson.api.plugin.PluginStatus;
import com.whizzosoftware.hobson.api.plugin.http.HttpResponse;
import com.whizzosoftware.hobson.api.property.PropertyContainer;
import org.slf4j.LoggerFactory;
/**
* The "configuration wait" state of the plugin. This means that the plugin does not have myQ cloud credentials
* yet and must wait for the user to provide them.
*
* @author <NAME>
*/
public class ConfigurationWaitState implements State {
private boolean notConfiguredSet = false;
public ConfigurationWaitState() {
LoggerFactory.getLogger(getClass()).debug("Entering configurationWaitState");
}
@Override
public void onRefresh(StateContext ctx) {
PropertyContainer pc = ctx.getConfiguration();
if (pc != null && pc.hasPropertyValue("username") && pc.hasPropertyValue("password")) {
ctx.setState(new LoggingInState());
} else if (!notConfiguredSet) {
ctx.setPluginStatus(PluginStatus.notConfigured("No username or password has been set"));
notConfiguredSet = true;
}
}
@Override
public void onPluginConfigurationUpdate(StateContext ctx) {
onRefresh(ctx);
}
@Override
public void onHttpResponse(StateContext ctx, HttpResponse response, Object reqCtx) {
}
@Override
public void onHttpRequestFailure(StateContext ctx, Throwable cause, Object reqCtx) {
}
@Override
public void setDeviceState(StateContext ctx, String deviceId, Boolean state) {
}
}
| 2,040 | 0.663245 | 0.658847 | 60 | 33.099998 | 32.737186 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
7
|
152e797a981d3e1f1ee24448804e82d65820f17a
| 10,651,518,955,225 |
f60e4b86964fbafb3d8eb099fa4feec34c7f79ed
|
/src/main/java/finance/financialSys/framework/domain/GenerateReportCommand.java
|
d7f3be395f123285f2e63e7638023f65d899dcf8
|
[] |
no_license
|
ridwantahir/BankingFramework
|
https://github.com/ridwantahir/BankingFramework
|
0a564156979567169af6abd87d9d9dcd22b4c600
|
7907278deab450cdd922c84be938baaabe3fb62d
|
refs/heads/master
| 2023-03-08T11:47:48.850000 | 2023-02-26T02:17:47 | 2023-02-26T02:17:47 | 89,897,877 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package finance.financialSys.framework.domain;
import finance.financialSys.framework.controller.AUIMediator;
import finance.financialSys.framework.controller.IReportController;
public class GenerateReportCommand implements IFinCommand {
IReportController controller = Utility.getReportController();
@Override
public void execute(AUIMediator mediator) {
controller.generateReport();
}
}
|
UTF-8
|
Java
| 413 |
java
|
GenerateReportCommand.java
|
Java
|
[] | null |
[] |
package finance.financialSys.framework.domain;
import finance.financialSys.framework.controller.AUIMediator;
import finance.financialSys.framework.controller.IReportController;
public class GenerateReportCommand implements IFinCommand {
IReportController controller = Utility.getReportController();
@Override
public void execute(AUIMediator mediator) {
controller.generateReport();
}
}
| 413 | 0.801453 | 0.801453 | 15 | 25.533333 | 26.849871 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false |
7
|
c429910e290cca76e27cc0fbcb15c47bb1101b0d
| 13,554,916,828,557 |
0dea332f991a4f7daaad358ab342454f65ab8f65
|
/app/src/main/java/com/huangjie/googleplay/fragment/HotFragment.java
|
c6f67613be47d29ced81e02514e7664701d40e81
|
[] |
no_license
|
HappyJie135588/GooglePlay
|
https://github.com/HappyJie135588/GooglePlay
|
09261edb64d1db90597c5567d5582f85cb7a330a
|
04d96e5655de29fbd12885bea267b6da4d1b7231
|
refs/heads/master
| 2020-07-07T02:05:30.018000 | 2017-06-26T11:23:36 | 2017-06-26T11:23:36 | 74,040,508 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.huangjie.googleplay.fragment;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.graphics.drawable.shapes.Shape;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.huangjie.googleplay.R;
import com.huangjie.googleplay.http.HotProtocol;
import com.huangjie.googleplay.utils.DrawableUtils;
import com.huangjie.googleplay.utils.UIUtils;
import com.huangjie.googleplay.widget.FlowLayout;
import java.util.List;
import java.util.Random;
/**
* Created by 黄杰 on 2017/4/30.
*/
public class HotFragment extends BaseFragment {
private HotProtocol mProtocol;
private List<String> mDatas;
@Override
protected View onLoadSuccessView() {
//UI展示
ScrollView rootView = new ScrollView(UIUtils.getContext());
//加载流式布局
FlowLayout layout = new FlowLayout(UIUtils.getContext());
layout.setSpace(UIUtils.dp2px(4), UIUtils.dp2px(4));
layout.setPadding(UIUtils.dp2px(4), UIUtils.dp2px(4), UIUtils.dp2px(4), UIUtils.dp2px(4));
rootView.addView(layout);
//给流式加载数据
for (int i = 0; i < mDatas.size(); i++) {
final String data = mDatas.get(i);
TextView tv = new TextView(UIUtils.getContext());
tv.setText(data);
tv.setTextSize(UIUtils.dp2px(16));
tv.setTextColor(Color.WHITE);
tv.setGravity(Gravity.CENTER);
int padding = UIUtils.dp2px(4);
tv.setPadding(padding, padding, padding, padding);
Random random = new Random();
int alpha = 0xff;
int red = random.nextInt(170) + 30;//0-255 30->200
int green = random.nextInt(170) + 30;
int blue = random.nextInt(170) + 30;
int argb = Color.argb(alpha, red, green, blue);
int shape = GradientDrawable.RECTANGLE;
int raduis = UIUtils.dp2px(4);
//获得默认时的样式的drawable
GradientDrawable normalBg = DrawableUtils.getShape(shape, raduis, argb);
GradientDrawable pressedBg = DrawableUtils.getShape(shape, raduis, Color.GRAY);
StateListDrawable selector = DrawableUtils.getSelector(pressedBg, normalBg);
tv.setBackgroundDrawable(selector);
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(UIUtils.getContext(), data, Toast.LENGTH_SHORT).show();
}
});
layout.addView(tv);
}
return rootView;
}
@Override
protected LoadingPager.LoadedResult onLoadingData() {
mProtocol = new HotProtocol();
try {
mDatas = mProtocol.loadData(0);
if (mDatas == null || mDatas.size() == 0) {
return LoadingPager.LoadedResult.EMPTY;
}
return LoadingPager.LoadedResult.SUCCESS;
} catch (Throwable throwable) {
throwable.printStackTrace();
return LoadingPager.LoadedResult.ERROR;
}
}
}
|
UTF-8
|
Java
| 3,374 |
java
|
HotFragment.java
|
Java
|
[
{
"context": "List;\nimport java.util.Random;\n\n/**\n * Created by 黄杰 on 2017/4/30.\n */\n\npublic class HotFragment exten",
"end": 754,
"score": 0.9994753003120422,
"start": 752,
"tag": "NAME",
"value": "黄杰"
}
] | null |
[] |
package com.huangjie.googleplay.fragment;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.graphics.drawable.shapes.Shape;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.huangjie.googleplay.R;
import com.huangjie.googleplay.http.HotProtocol;
import com.huangjie.googleplay.utils.DrawableUtils;
import com.huangjie.googleplay.utils.UIUtils;
import com.huangjie.googleplay.widget.FlowLayout;
import java.util.List;
import java.util.Random;
/**
* Created by 黄杰 on 2017/4/30.
*/
public class HotFragment extends BaseFragment {
private HotProtocol mProtocol;
private List<String> mDatas;
@Override
protected View onLoadSuccessView() {
//UI展示
ScrollView rootView = new ScrollView(UIUtils.getContext());
//加载流式布局
FlowLayout layout = new FlowLayout(UIUtils.getContext());
layout.setSpace(UIUtils.dp2px(4), UIUtils.dp2px(4));
layout.setPadding(UIUtils.dp2px(4), UIUtils.dp2px(4), UIUtils.dp2px(4), UIUtils.dp2px(4));
rootView.addView(layout);
//给流式加载数据
for (int i = 0; i < mDatas.size(); i++) {
final String data = mDatas.get(i);
TextView tv = new TextView(UIUtils.getContext());
tv.setText(data);
tv.setTextSize(UIUtils.dp2px(16));
tv.setTextColor(Color.WHITE);
tv.setGravity(Gravity.CENTER);
int padding = UIUtils.dp2px(4);
tv.setPadding(padding, padding, padding, padding);
Random random = new Random();
int alpha = 0xff;
int red = random.nextInt(170) + 30;//0-255 30->200
int green = random.nextInt(170) + 30;
int blue = random.nextInt(170) + 30;
int argb = Color.argb(alpha, red, green, blue);
int shape = GradientDrawable.RECTANGLE;
int raduis = UIUtils.dp2px(4);
//获得默认时的样式的drawable
GradientDrawable normalBg = DrawableUtils.getShape(shape, raduis, argb);
GradientDrawable pressedBg = DrawableUtils.getShape(shape, raduis, Color.GRAY);
StateListDrawable selector = DrawableUtils.getSelector(pressedBg, normalBg);
tv.setBackgroundDrawable(selector);
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(UIUtils.getContext(), data, Toast.LENGTH_SHORT).show();
}
});
layout.addView(tv);
}
return rootView;
}
@Override
protected LoadingPager.LoadedResult onLoadingData() {
mProtocol = new HotProtocol();
try {
mDatas = mProtocol.loadData(0);
if (mDatas == null || mDatas.size() == 0) {
return LoadingPager.LoadedResult.EMPTY;
}
return LoadingPager.LoadedResult.SUCCESS;
} catch (Throwable throwable) {
throwable.printStackTrace();
return LoadingPager.LoadedResult.ERROR;
}
}
}
| 3,374 | 0.639675 | 0.62342 | 90 | 35.91111 | 22.898153 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.855556 | false | false |
7
|
19b9ebc72f0d4f2a9536683f22f0dc1ac0013520
| 36,094,905,188,344 |
d60e287543a95a20350c2caeabafbec517cabe75
|
/LACCPlus/Hadoop/2315_2.java
|
9396e93891b9cf407bc043349402b168ac0517e1
|
[
"MIT"
] |
permissive
|
sgholamian/log-aware-clone-detection
|
https://github.com/sgholamian/log-aware-clone-detection
|
242067df2db6fd056f8d917cfbc143615c558b2c
|
9993cb081c420413c231d1807bfff342c39aa69a
|
refs/heads/main
| 2023-07-20T09:32:19.757000 | 2021-08-27T15:02:50 | 2021-08-27T15:02:50 | 337,837,827 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
//,temp,TestLightWeightLinkedSet.java,185,204,temp,TestLightWeightHashSet.java,150,170
//,3
public class xxx {
@Test
public void testRemoveMulti() {
LOG.info("Test remove multi");
for (Integer i : list) {
assertTrue(set.add(i));
}
for (int i = 0; i < NUM / 2; i++) {
assertTrue(set.remove(list.get(i)));
}
// the deleted elements should not be there
for (int i = 0; i < NUM / 2; i++) {
assertFalse(set.contains(list.get(i)));
}
// the rest should be there
for (int i = NUM / 2; i < NUM; i++) {
assertTrue(set.contains(list.get(i)));
}
LOG.info("Test remove multi - DONE");
}
};
|
UTF-8
|
Java
| 658 |
java
|
2315_2.java
|
Java
|
[] | null |
[] |
//,temp,TestLightWeightLinkedSet.java,185,204,temp,TestLightWeightHashSet.java,150,170
//,3
public class xxx {
@Test
public void testRemoveMulti() {
LOG.info("Test remove multi");
for (Integer i : list) {
assertTrue(set.add(i));
}
for (int i = 0; i < NUM / 2; i++) {
assertTrue(set.remove(list.get(i)));
}
// the deleted elements should not be there
for (int i = 0; i < NUM / 2; i++) {
assertFalse(set.contains(list.get(i)));
}
// the rest should be there
for (int i = NUM / 2; i < NUM; i++) {
assertTrue(set.contains(list.get(i)));
}
LOG.info("Test remove multi - DONE");
}
};
| 658 | 0.580547 | 0.553191 | 26 | 24.346153 | 21.173174 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.846154 | false | false |
10
|
24f01487faddf34c3dcec4d3992e3fd7e6f5d669
| 36,507,222,049,481 |
8837a734da3a2dccbe025cb817dbdc0849529ac2
|
/a_Appium_Pack/ActivityAndPackageInfo/src/com/example/activityandpackageinfo/MainActivity.java
|
98e1cdd23bed9bacd9de86209b23f9bcc131d0fb
|
[] |
no_license
|
jigyasa-at-git/QTPS_SelApp
|
https://github.com/jigyasa-at-git/QTPS_SelApp
|
8f3b557e2b46bafb5e9060b9c1ed9da27f98cad2
|
e4ebea7e5521aaad1e243cd75c62d17b6f94f9a7
|
refs/heads/master
| 2021-03-12T23:06:29.458000 | 2015-08-22T21:04:31 | 2015-08-22T21:04:31 | 41,224,248 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.activityandpackageinfo;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
private static final String TAG = " Installed app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
final PackageManager pm = getPackageManager();
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> appList = pm.queryIntentActivities(mainIntent, 0);
Collections.sort(appList, new ResolveInfo.DisplayNameComparator(pm));
for (ResolveInfo temp : appList) {
Log.v("my logs", "package and activity name = "
+ temp.activityInfo.packageName + " "
+ temp.activityInfo.name);
}
/*
final PackageManager pm = getPackageManager();
//get a list of installed apps.
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo packageInfo : packages) {
Log.d(TAG, "Installed package :" + packageInfo.packageName);
Log.d(TAG, "Source dir : " + packageInfo.sourceDir);
Log.d(TAG, "Launch Activity :" + pm.getLaunchIntentForPackage(packageInfo.packageName));
}
*/
}
}
|
UTF-8
|
Java
| 1,537 |
java
|
MainActivity.java
|
Java
|
[] | null |
[] |
package com.example.activityandpackageinfo;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
private static final String TAG = " Installed app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
final PackageManager pm = getPackageManager();
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> appList = pm.queryIntentActivities(mainIntent, 0);
Collections.sort(appList, new ResolveInfo.DisplayNameComparator(pm));
for (ResolveInfo temp : appList) {
Log.v("my logs", "package and activity name = "
+ temp.activityInfo.packageName + " "
+ temp.activityInfo.name);
}
/*
final PackageManager pm = getPackageManager();
//get a list of installed apps.
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo packageInfo : packages) {
Log.d(TAG, "Installed package :" + packageInfo.packageName);
Log.d(TAG, "Source dir : " + packageInfo.sourceDir);
Log.d(TAG, "Launch Activity :" + pm.getLaunchIntentForPackage(packageInfo.packageName));
}
*/
}
}
| 1,537 | 0.720885 | 0.720234 | 50 | 28.74 | 26.418032 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.68 | false | false |
10
|
9395ed67540eaf93a36414854ed64b535026221b
| 1,090,921,700,673 |
0623eb2a0b567f64d9265770045355ec837c43f8
|
/trunk/Install_sinapse/src/install/sinapse/Cuadro.java
|
adc3d0359b1a21423a93092323d98bc6ce899ce7
|
[] |
no_license
|
Sinapse-Energia/APP-Installation
|
https://github.com/Sinapse-Energia/APP-Installation
|
76ce7a2c874d1403acf1b661d849c118caad9a9d
|
a29c4255ad865fb0402c2e971825407555e2ed59
|
refs/heads/master
| 2020-03-30T00:56:34.105000 | 2018-10-02T14:19:27 | 2018-10-02T14:19:27 | 150,551,509 | 0 | 1 | null | false | 2018-10-02T14:19:29 | 2018-09-27T08:06:24 | 2018-10-01T07:33:14 | 2018-10-02T14:19:28 | 18,860 | 0 | 1 | 2 |
Java
| false | null |
package install.sinapse;
import java.util.ArrayList;
public class Cuadro {
private ArrayList<Cmc> CMC;
public Cuadro(){}
public Cuadro(ArrayList<Cmc> c)
{
CMC = c;
}
public ArrayList<Cmc> getCuadros()
{
return CMC;
}
}
|
UTF-8
|
Java
| 263 |
java
|
Cuadro.java
|
Java
|
[] | null |
[] |
package install.sinapse;
import java.util.ArrayList;
public class Cuadro {
private ArrayList<Cmc> CMC;
public Cuadro(){}
public Cuadro(ArrayList<Cmc> c)
{
CMC = c;
}
public ArrayList<Cmc> getCuadros()
{
return CMC;
}
}
| 263 | 0.612167 | 0.612167 | 21 | 10.523809 | 12.085485 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
10
|
6196b51391878328167cc90fe1ad20b4a49f0082
| 4,449,586,125,045 |
629aec83c5a2b0010d287db6d821ba5a137fa0c5
|
/app/src/main/java/shaunaksharma/app/quotesoverdogs/MainActivity.java
|
a7c729c2848234e577c4009aa1f953f8f677d268
|
[] |
no_license
|
shaunaksharma/QuotesOverDogs
|
https://github.com/shaunaksharma/QuotesOverDogs
|
09fdaf4d7395b014cfb19d2ce99c2e2a8a206c9d
|
b8f068ef68afa9ecf8498b272ee0b0446bf75892
|
refs/heads/master
| 2020-05-14T22:50:57.179000 | 2019-08-28T17:00:06 | 2019-08-28T17:00:06 | 181,986,408 | 0 | 0 | null | false | 2019-08-28T22:30:07 | 2019-04-18T00:09:45 | 2019-08-28T16:53:58 | 2019-08-28T17:00:07 | 3,727 | 0 | 0 | 0 |
Java
| false | false |
package shaunaksharma.app.quotesoverdogs;
import android.Manifest;
import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.constraint.ConstraintLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.os.AsyncTask;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.acra.ACRA;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.Random;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
final int REQUEST_WRITE_STORAGE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button mainButton = findViewById(R.id.mainbutton);
Button randomQuote = findViewById(R.id.randomQuote);
Button randomFont = findViewById(R.id.randomFont);
Button randomImage = findViewById(R.id.randomImage);
Typeface amatic = Typeface.createFromAsset(getAssets(), "font/amaticsc.ttf");
Typeface courgette = Typeface.createFromAsset(getAssets(), "font/courgette.ttf");
Typeface laila = Typeface.createFromAsset(getAssets(), "font/laila.ttf");
Typeface merriweather = Typeface.createFromAsset(getAssets(), "font/merriweather.ttf");
Typeface dosis = Typeface.createFromAsset(getAssets(), "font/dosis.ttf");
Typeface opensans = Typeface.createFromAsset(getAssets(), "font/opensans.ttf");
Typeface cinzel = Typeface.createFromAsset(getAssets(), "font/cinzel.ttf");
Typeface ptserif = Typeface.createFromAsset(getAssets(), "font/ptserif.ttf");
final Typeface[] fonts = {amatic, courgette, laila, merriweather, dosis, opensans, cinzel, ptserif};
//Initialize retrofit for image API and make the initial request.
Retrofit.Builder imageBuilder = new Retrofit.Builder()
.baseUrl("https://random.dog/")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retroImage = imageBuilder.build();
final ImageClient mainImageClient = retroImage.create(ImageClient.class);
//Initial image setup done.
requestNewImageLink(mainImageClient);
//Initialize retrofit for quotes API and make the initial request.
Retrofit.Builder quotesBuilder = new Retrofit.Builder()
.baseUrl("https://api.forismatic.com/api/1.0/")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retroQuote = quotesBuilder.build();
final QuoteClient mainQuoteClient = retroQuote.create(QuoteClient.class);
//initial quote setup done.
requestNewQuoteLink(mainQuoteClient);
//Initial font setup done.
randomizeFont(fonts);
//Set listener fot 'Refresh All' button. Randomize image, quote, font.
mainButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestNewImageLink(mainImageClient);
requestNewQuoteLink(mainQuoteClient);
randomizeFont(fonts);
}
});
randomQuote.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
requestNewQuoteLink(mainQuoteClient);
}
});
randomImage.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
requestNewImageLink(mainImageClient);
}
});
randomFont.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
randomizeFont(fonts);
}
});
}
//AsyncTask in order to retrieve image from link. Way simpler with Glide, but I wanted to try AsyncTask.
class setImage extends AsyncTask<String, Void, Bitmap>
{
@Override
protected void onPreExecute()
{
ProgressBar progress = findViewById(R.id.progressBar);
progress.setVisibility(View.VISIBLE);
ImageView mainImage = findViewById(R.id.mainimage);
mainImage.setForeground(new ColorDrawable(0x80000000));
TextView mainText = findViewById(R.id.mainTextView);
mainText.setForeground(new ColorDrawable(0x80000000));
}
@Override
protected Bitmap doInBackground(String... links)//gets image, converts to bitmap, crops to a square and returns the bitmap
{
Bitmap mainViewBMP = null;
try
{
URL link = new URL(links[0]);
mainViewBMP = BitmapFactory.decodeStream(link.openConnection().getInputStream());
mainViewBMP = cropToSquare(mainViewBMP);
}
catch(MalformedURLException e)
{
//Log.d("MalformedURLException", e.getMessage());
handleBug(e);
}
catch(IOException e)
{
//Log.d("IOException", e.getMessage());
handleBug(e);
}
return mainViewBMP;
}
@Override
protected void onPostExecute(Bitmap mainviewbmp)//image bitmap is ready, set image
{
ProgressBar progress = findViewById(R.id.progressBar);
progress.setVisibility(View.INVISIBLE);
ImageView mainImage = findViewById(R.id.mainimage);
mainImage.setImageBitmap(mainviewbmp);
mainImage.setForeground(null);
mainImage.setDrawingCacheEnabled(true);
Palette main_palette = Palette.from(mainImage.getDrawingCache()).generate();//palette generated, ready to examine for colors
mainImage.setDrawingCacheEnabled(false);
int darkvibe = main_palette.getDarkMutedColor(99);
if(darkvibe == 99) { darkvibe = main_palette.getDarkVibrantColor(99); }
if(darkvibe == 99) { darkvibe = main_palette.getDominantColor(99); }//failsafe method since DarkMuted and DarkVibrant are not always available
TextView mainText = findViewById(R.id.mainTextView);
mainText.setBackgroundColor(darkvibe);//set the color on quote area background
mainText.setForeground(null);
transitionBackground(darkvibe);
TextView watermark = findViewById(R.id.watermark);
watermark.setBackgroundColor(darkvibe);//set the color on watermark background(watermark remains hidden unless image is exported)
}
}
public Bitmap cropToSquare(Bitmap bitmap)//crops bitmaps to squares
{
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = (height > width) ? width : height;
int newHeight = (height > width)? height - ( height - width) : height;
int cropW = (width - height) / 2;
cropW = (cropW < 0)? 0: cropW;
int cropH = (height - width) / 2;
cropH = (cropH < 0)? 0: cropH;
Bitmap cropImg = Bitmap.createBitmap(bitmap, cropW, cropH, newWidth, newHeight);
return cropImg;
}
public void requestNewImageLink(final ImageClient inputImageClient)//makes a request for a new image link, then calls setImage on the link
{
Call<ImageResponseContent> call = inputImageClient.getImage();
call.enqueue(new Callback<ImageResponseContent>() {
@Override
public void onResponse(Call<ImageResponseContent> call, Response<ImageResponseContent> response) {
String imageUrl = response.body().getUrl();
if(!(imageUrl.substring(imageUrl.length() - 3).equals("jpg")))//make sure link is for an image and not a gif/mp4 video.
{
requestNewImageLink(inputImageClient);
}
else
{
new setImage().execute(imageUrl);//set the image using the link
}
}
@Override
public void onFailure(Call<ImageResponseContent> call, Throwable t) {
//Log.d("ImageLinkBug", t.getMessage());
handleBug(new Exception(t));
}
});
}
public void requestNewQuoteLink(final QuoteClient inputQuoteClient)//requests a new quote and sets the quote in the textView.
{
Call<QuoteResponseContent> call = inputQuoteClient.getQuote();
call.enqueue(new Callback<QuoteResponseContent>() {
@Override
public void onResponse(Call<QuoteResponseContent> call, Response<QuoteResponseContent> response) {
TextView mainText = findViewById(R.id.mainTextView);
if(response.body().getQuoteAuthor().equals("Joseph Stalin") || response.body().getQuoteAuthor().equals("Donald Trump"))
{
requestNewQuoteLink(inputQuoteClient);
return;
}
mainText.setText(response.body().getQuoteText() + "\n - " + response.body().getQuoteAuthor());
}
@Override
public void onFailure(Call<QuoteResponseContent> call, Throwable t) {
//Log.d("QuoteLinkBug", t.getMessage());
handleBug(new Exception(t));
}
});
}
public void randomizeFont(Typeface[] fontarr)//sets a random font for the quote
{
Random rand = new Random();
int n = rand.nextInt(8);
TextView mainText = findViewById(R.id.mainTextView);
mainText.setTypeface(fontarr[n]);
}
public void handleBug(Exception e)//Simple bug handler. Allows user to send a bug report through email.
{
new AlertDialog.Builder(MainActivity.this)//inform the user that an error has occurred
.setTitle("Oops!")
.setMessage("Something went wrong. Send crash report through email? (Don't worry, the report will be created automatically!)")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ACRA.getErrorReporter().handleSilentException(e);
}
})
.setNegativeButton(android.R.string.no, null)
.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_export) {//set up export
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
//no permission to write to external storage, request the user for permission
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_STORAGE);
}
else
{
//permission has already been granted, export the image
exportImage();
}
return true;
}
if (id == R.id.action_about) {
//open about activity
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_WRITE_STORAGE: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//as of now, this is only called when user exports image, hence upon receiving permission, export image
exportImage();
} else {
//inform the user that permission is needed for export through a Toast.
Toast.makeText(MainActivity.this, "Could not export image without storage permissions.", Toast.LENGTH_LONG).show();
}
return;
}
}
}
public void exportImage()
{
final ImageView mainImage = findViewById(R.id.mainimage);
final ConstraintLayout mainContent = findViewById(R.id.contentLayout);
final TextView watermark = findViewById(R.id.watermark);
watermark.setAlpha(1f);//make watermark visible before exporting the image
mainContent.setDrawingCacheEnabled(true);
mainContent.buildDrawingCache();
mainImage.setDrawingCacheEnabled(true);
mainImage.buildDrawingCache();
Bitmap exportBMP = Bitmap.createBitmap(mainContent.getWidth(), mainContent.getHeight(), Bitmap.Config.ARGB_8888);//create the bitmap of the correct size
Canvas canvas = new Canvas(exportBMP);
mainContent.draw(canvas);//draw everything from the parent view (that holds the image, quote, and watermark) into the exportBMP bitmap
//Dynamic filename setup. Filename wil be generated with date and time.
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
File mainFolder = new File(Environment.getExternalStorageDirectory() + "/QuotesOverDogs");//the directory in which the images shall be stored
File expimage = new File(mainFolder.getAbsolutePath()+"/QuotesOverDogs" + day+"_"+month+"_"+year+"_"+hour+"_"+minute+"_"+second+".png");//set dynamic image name
if(!mainFolder.exists()){mainFolder.mkdir();}//if the directory QuotesOverDogs does not exist, create one
try {
if(!expimage.exists())
{
expimage.createNewFile();//create the image file
}
}
catch(IOException e){
//Log.d("IOException2", e.getMessage());
handleBug(e);
}
try
{
FileOutputStream output = new FileOutputStream(expimage);
exportBMP.compress(Bitmap.CompressFormat.PNG, 100, output);//convert the exportBMP to a png file
output.close();
}
catch(IOException e)
{
//Log.d("IOException3", e.getMessage());
handleBug(e);
}
watermark.setAlpha(0f);//set watermark to invisible again
mainContent.setDrawingCacheEnabled(false);
mainContent.destroyDrawingCache();
mainImage.setDrawingCacheEnabled(false);
mainImage.destroyDrawingCache();
Toast.makeText(MainActivity.this, "Image exported to folder QuotesOverDogs", Toast.LENGTH_LONG).show();
}
public void transitionBackground(int colorTo)
{
ConstraintLayout topLayout = findViewById(R.id.topLayout);
LinearLayout buttonLayout = findViewById(R.id.buttonLayout);
int currColor = Color.TRANSPARENT;
Drawable background = topLayout.getBackground();
currColor = ((ColorDrawable) background).getColor();
String hexColor = String.format("#%06X", (0xFFFFFF & colorTo));
String hexColorNew = "#66"+hexColor.substring(1);
int colorToFinal = Color.parseColor(hexColorNew);
ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), currColor, colorToFinal);
colorAnimation.setDuration(500); // milliseconds
colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
topLayout.setBackgroundColor((int) animator.getAnimatedValue());
}
});
colorAnimation.start();
}
}
|
UTF-8
|
Java
| 17,471 |
java
|
MainActivity.java
|
Java
|
[
{
"context": " if(response.body().getQuoteAuthor().equals(\"Joseph Stalin\") || response.body().getQuoteAuthor().equals(\"Don",
"end": 10116,
"score": 0.9998837113380432,
"start": 10103,
"tag": "NAME",
"value": "Joseph Stalin"
},
{
"context": "lin\") || response.body().getQuoteAuthor().equals(\"Donald Trump\"))\n {\n requestN",
"end": 10175,
"score": 0.9998747110366821,
"start": 10163,
"tag": "NAME",
"value": "Donald Trump"
}
] | null |
[] |
package shaunaksharma.app.quotesoverdogs;
import android.Manifest;
import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.constraint.ConstraintLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.os.AsyncTask;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.acra.ACRA;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.Random;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
final int REQUEST_WRITE_STORAGE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button mainButton = findViewById(R.id.mainbutton);
Button randomQuote = findViewById(R.id.randomQuote);
Button randomFont = findViewById(R.id.randomFont);
Button randomImage = findViewById(R.id.randomImage);
Typeface amatic = Typeface.createFromAsset(getAssets(), "font/amaticsc.ttf");
Typeface courgette = Typeface.createFromAsset(getAssets(), "font/courgette.ttf");
Typeface laila = Typeface.createFromAsset(getAssets(), "font/laila.ttf");
Typeface merriweather = Typeface.createFromAsset(getAssets(), "font/merriweather.ttf");
Typeface dosis = Typeface.createFromAsset(getAssets(), "font/dosis.ttf");
Typeface opensans = Typeface.createFromAsset(getAssets(), "font/opensans.ttf");
Typeface cinzel = Typeface.createFromAsset(getAssets(), "font/cinzel.ttf");
Typeface ptserif = Typeface.createFromAsset(getAssets(), "font/ptserif.ttf");
final Typeface[] fonts = {amatic, courgette, laila, merriweather, dosis, opensans, cinzel, ptserif};
//Initialize retrofit for image API and make the initial request.
Retrofit.Builder imageBuilder = new Retrofit.Builder()
.baseUrl("https://random.dog/")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retroImage = imageBuilder.build();
final ImageClient mainImageClient = retroImage.create(ImageClient.class);
//Initial image setup done.
requestNewImageLink(mainImageClient);
//Initialize retrofit for quotes API and make the initial request.
Retrofit.Builder quotesBuilder = new Retrofit.Builder()
.baseUrl("https://api.forismatic.com/api/1.0/")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retroQuote = quotesBuilder.build();
final QuoteClient mainQuoteClient = retroQuote.create(QuoteClient.class);
//initial quote setup done.
requestNewQuoteLink(mainQuoteClient);
//Initial font setup done.
randomizeFont(fonts);
//Set listener fot 'Refresh All' button. Randomize image, quote, font.
mainButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestNewImageLink(mainImageClient);
requestNewQuoteLink(mainQuoteClient);
randomizeFont(fonts);
}
});
randomQuote.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
requestNewQuoteLink(mainQuoteClient);
}
});
randomImage.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
requestNewImageLink(mainImageClient);
}
});
randomFont.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
randomizeFont(fonts);
}
});
}
//AsyncTask in order to retrieve image from link. Way simpler with Glide, but I wanted to try AsyncTask.
class setImage extends AsyncTask<String, Void, Bitmap>
{
@Override
protected void onPreExecute()
{
ProgressBar progress = findViewById(R.id.progressBar);
progress.setVisibility(View.VISIBLE);
ImageView mainImage = findViewById(R.id.mainimage);
mainImage.setForeground(new ColorDrawable(0x80000000));
TextView mainText = findViewById(R.id.mainTextView);
mainText.setForeground(new ColorDrawable(0x80000000));
}
@Override
protected Bitmap doInBackground(String... links)//gets image, converts to bitmap, crops to a square and returns the bitmap
{
Bitmap mainViewBMP = null;
try
{
URL link = new URL(links[0]);
mainViewBMP = BitmapFactory.decodeStream(link.openConnection().getInputStream());
mainViewBMP = cropToSquare(mainViewBMP);
}
catch(MalformedURLException e)
{
//Log.d("MalformedURLException", e.getMessage());
handleBug(e);
}
catch(IOException e)
{
//Log.d("IOException", e.getMessage());
handleBug(e);
}
return mainViewBMP;
}
@Override
protected void onPostExecute(Bitmap mainviewbmp)//image bitmap is ready, set image
{
ProgressBar progress = findViewById(R.id.progressBar);
progress.setVisibility(View.INVISIBLE);
ImageView mainImage = findViewById(R.id.mainimage);
mainImage.setImageBitmap(mainviewbmp);
mainImage.setForeground(null);
mainImage.setDrawingCacheEnabled(true);
Palette main_palette = Palette.from(mainImage.getDrawingCache()).generate();//palette generated, ready to examine for colors
mainImage.setDrawingCacheEnabled(false);
int darkvibe = main_palette.getDarkMutedColor(99);
if(darkvibe == 99) { darkvibe = main_palette.getDarkVibrantColor(99); }
if(darkvibe == 99) { darkvibe = main_palette.getDominantColor(99); }//failsafe method since DarkMuted and DarkVibrant are not always available
TextView mainText = findViewById(R.id.mainTextView);
mainText.setBackgroundColor(darkvibe);//set the color on quote area background
mainText.setForeground(null);
transitionBackground(darkvibe);
TextView watermark = findViewById(R.id.watermark);
watermark.setBackgroundColor(darkvibe);//set the color on watermark background(watermark remains hidden unless image is exported)
}
}
public Bitmap cropToSquare(Bitmap bitmap)//crops bitmaps to squares
{
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = (height > width) ? width : height;
int newHeight = (height > width)? height - ( height - width) : height;
int cropW = (width - height) / 2;
cropW = (cropW < 0)? 0: cropW;
int cropH = (height - width) / 2;
cropH = (cropH < 0)? 0: cropH;
Bitmap cropImg = Bitmap.createBitmap(bitmap, cropW, cropH, newWidth, newHeight);
return cropImg;
}
public void requestNewImageLink(final ImageClient inputImageClient)//makes a request for a new image link, then calls setImage on the link
{
Call<ImageResponseContent> call = inputImageClient.getImage();
call.enqueue(new Callback<ImageResponseContent>() {
@Override
public void onResponse(Call<ImageResponseContent> call, Response<ImageResponseContent> response) {
String imageUrl = response.body().getUrl();
if(!(imageUrl.substring(imageUrl.length() - 3).equals("jpg")))//make sure link is for an image and not a gif/mp4 video.
{
requestNewImageLink(inputImageClient);
}
else
{
new setImage().execute(imageUrl);//set the image using the link
}
}
@Override
public void onFailure(Call<ImageResponseContent> call, Throwable t) {
//Log.d("ImageLinkBug", t.getMessage());
handleBug(new Exception(t));
}
});
}
public void requestNewQuoteLink(final QuoteClient inputQuoteClient)//requests a new quote and sets the quote in the textView.
{
Call<QuoteResponseContent> call = inputQuoteClient.getQuote();
call.enqueue(new Callback<QuoteResponseContent>() {
@Override
public void onResponse(Call<QuoteResponseContent> call, Response<QuoteResponseContent> response) {
TextView mainText = findViewById(R.id.mainTextView);
if(response.body().getQuoteAuthor().equals("<NAME>") || response.body().getQuoteAuthor().equals("<NAME>"))
{
requestNewQuoteLink(inputQuoteClient);
return;
}
mainText.setText(response.body().getQuoteText() + "\n - " + response.body().getQuoteAuthor());
}
@Override
public void onFailure(Call<QuoteResponseContent> call, Throwable t) {
//Log.d("QuoteLinkBug", t.getMessage());
handleBug(new Exception(t));
}
});
}
public void randomizeFont(Typeface[] fontarr)//sets a random font for the quote
{
Random rand = new Random();
int n = rand.nextInt(8);
TextView mainText = findViewById(R.id.mainTextView);
mainText.setTypeface(fontarr[n]);
}
public void handleBug(Exception e)//Simple bug handler. Allows user to send a bug report through email.
{
new AlertDialog.Builder(MainActivity.this)//inform the user that an error has occurred
.setTitle("Oops!")
.setMessage("Something went wrong. Send crash report through email? (Don't worry, the report will be created automatically!)")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ACRA.getErrorReporter().handleSilentException(e);
}
})
.setNegativeButton(android.R.string.no, null)
.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_export) {//set up export
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
//no permission to write to external storage, request the user for permission
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_STORAGE);
}
else
{
//permission has already been granted, export the image
exportImage();
}
return true;
}
if (id == R.id.action_about) {
//open about activity
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_WRITE_STORAGE: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//as of now, this is only called when user exports image, hence upon receiving permission, export image
exportImage();
} else {
//inform the user that permission is needed for export through a Toast.
Toast.makeText(MainActivity.this, "Could not export image without storage permissions.", Toast.LENGTH_LONG).show();
}
return;
}
}
}
public void exportImage()
{
final ImageView mainImage = findViewById(R.id.mainimage);
final ConstraintLayout mainContent = findViewById(R.id.contentLayout);
final TextView watermark = findViewById(R.id.watermark);
watermark.setAlpha(1f);//make watermark visible before exporting the image
mainContent.setDrawingCacheEnabled(true);
mainContent.buildDrawingCache();
mainImage.setDrawingCacheEnabled(true);
mainImage.buildDrawingCache();
Bitmap exportBMP = Bitmap.createBitmap(mainContent.getWidth(), mainContent.getHeight(), Bitmap.Config.ARGB_8888);//create the bitmap of the correct size
Canvas canvas = new Canvas(exportBMP);
mainContent.draw(canvas);//draw everything from the parent view (that holds the image, quote, and watermark) into the exportBMP bitmap
//Dynamic filename setup. Filename wil be generated with date and time.
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
File mainFolder = new File(Environment.getExternalStorageDirectory() + "/QuotesOverDogs");//the directory in which the images shall be stored
File expimage = new File(mainFolder.getAbsolutePath()+"/QuotesOverDogs" + day+"_"+month+"_"+year+"_"+hour+"_"+minute+"_"+second+".png");//set dynamic image name
if(!mainFolder.exists()){mainFolder.mkdir();}//if the directory QuotesOverDogs does not exist, create one
try {
if(!expimage.exists())
{
expimage.createNewFile();//create the image file
}
}
catch(IOException e){
//Log.d("IOException2", e.getMessage());
handleBug(e);
}
try
{
FileOutputStream output = new FileOutputStream(expimage);
exportBMP.compress(Bitmap.CompressFormat.PNG, 100, output);//convert the exportBMP to a png file
output.close();
}
catch(IOException e)
{
//Log.d("IOException3", e.getMessage());
handleBug(e);
}
watermark.setAlpha(0f);//set watermark to invisible again
mainContent.setDrawingCacheEnabled(false);
mainContent.destroyDrawingCache();
mainImage.setDrawingCacheEnabled(false);
mainImage.destroyDrawingCache();
Toast.makeText(MainActivity.this, "Image exported to folder QuotesOverDogs", Toast.LENGTH_LONG).show();
}
public void transitionBackground(int colorTo)
{
ConstraintLayout topLayout = findViewById(R.id.topLayout);
LinearLayout buttonLayout = findViewById(R.id.buttonLayout);
int currColor = Color.TRANSPARENT;
Drawable background = topLayout.getBackground();
currColor = ((ColorDrawable) background).getColor();
String hexColor = String.format("#%06X", (0xFFFFFF & colorTo));
String hexColorNew = "#66"+hexColor.substring(1);
int colorToFinal = Color.parseColor(hexColorNew);
ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), currColor, colorToFinal);
colorAnimation.setDuration(500); // milliseconds
colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
topLayout.setBackgroundColor((int) animator.getAnimatedValue());
}
});
colorAnimation.start();
}
}
| 17,458 | 0.639689 | 0.635567 | 434 | 39.258064 | 34.56781 | 168 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.640553 | false | false |
10
|
0317032472d7e24b6cec28cb0b74b0806eac224e
| 12,128,987,648,675 |
2dafa1bc8436d282c552cb1cb55df69ef70d9dbc
|
/jsure-client-eclipse/src/com/surelogic/jsure/client/eclipse/views/metrics/statewrt/StateWrtElementProject.java
|
d5a8b1f2d20f1dfb408d980e1ef21f0a8ab7b5dd
|
[] |
no_license
|
surelogic/jsure
|
https://github.com/surelogic/jsure
|
99c47d195674234b688d08a4b03e506b3a235620
|
184d698991d0fbb8f73735b5aab2c5051d2518fd
|
refs/heads/master
| 2021-05-01T00:15:53.632000 | 2016-05-27T02:35:14 | 2016-05-27T02:35:14 | 50,687,249 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.surelogic.jsure.client.eclipse.views.metrics.statewrt;
import org.eclipse.swt.graphics.Image;
import com.surelogic.common.ui.SLImages;
public final class StateWrtElementProject extends StateWrtElement {
protected StateWrtElementProject(StateWrtElementScan parent, String projectName) {
super(parent, projectName);
}
@Override
public Image getImage() {
return SLImages.getImageForProject(f_label);
}
}
|
UTF-8
|
Java
| 453 |
java
|
StateWrtElementProject.java
|
Java
|
[] | null |
[] |
package com.surelogic.jsure.client.eclipse.views.metrics.statewrt;
import org.eclipse.swt.graphics.Image;
import com.surelogic.common.ui.SLImages;
public final class StateWrtElementProject extends StateWrtElement {
protected StateWrtElementProject(StateWrtElementScan parent, String projectName) {
super(parent, projectName);
}
@Override
public Image getImage() {
return SLImages.getImageForProject(f_label);
}
}
| 453 | 0.757174 | 0.757174 | 17 | 24.647058 | 27.388149 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.411765 | false | false |
10
|
43529eb3838613a96c267dcd17b4f2495667afc9
| 15,865,609,197,316 |
020d93365ed97530ae35731c0fd3428377a422a5
|
/app/src/main/java/com/jtangopro/Tango.java
|
6b2266b7137c1b64e69c892248dca89f09e1ad52
|
[] |
no_license
|
helloword-git/JTangoPro
|
https://github.com/helloword-git/JTangoPro
|
ae01f8ad0ef59b5abda91c3607b8ab24131f71e8
|
97c4d3ff7a7908febe5d9a2c85d8f6f2b521a9b8
|
refs/heads/master
| 2022-11-24T05:53:12.586000 | 2020-08-04T09:44:14 | 2020-08-04T09:44:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.jtangopro;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* 词条属性类
* 使用字典保存各个属性
*/
public class Tango implements Serializable {
private Map<String, String> m = new HashMap<>();
public Tango(Map<String, String> m_){
Iterator it = m_.entrySet().iterator();
while(it.hasNext()){
Map.Entry entry = (Map.Entry) it.next();
String key = (String) entry.getKey();
m.put(key,m_.get(key));
}
}
public void set(String key, String val){
m.put(key,val);
}
public String get(String key){
return m.get(key);
}
}
|
UTF-8
|
Java
| 711 |
java
|
Tango.java
|
Java
|
[] | null |
[] |
package com.jtangopro;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* 词条属性类
* 使用字典保存各个属性
*/
public class Tango implements Serializable {
private Map<String, String> m = new HashMap<>();
public Tango(Map<String, String> m_){
Iterator it = m_.entrySet().iterator();
while(it.hasNext()){
Map.Entry entry = (Map.Entry) it.next();
String key = (String) entry.getKey();
m.put(key,m_.get(key));
}
}
public void set(String key, String val){
m.put(key,val);
}
public String get(String key){
return m.get(key);
}
}
| 711 | 0.590308 | 0.590308 | 32 | 20.28125 | 17.850481 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.53125 | false | false |
10
|
d3b6a3fb6a10e1fd546efce0bf88bf631ffbd139
| 19,129,784,345,142 |
35ef309f7ae3814f35f94cf8ab97e9d9df2b0284
|
/AlgorithimsProjects/src/com/datastructure/MergeOverlappingIntervals.java
|
d6e07635711a37f43cceb3506a22219279bda95f
|
[] |
no_license
|
mdfraz13/workspace
|
https://github.com/mdfraz13/workspace
|
8db03f88942b2bd24957c6c4c8b5039ec7cbc2d0
|
12b645f2702ec11dcbdec44ad3ad4061c7ed38ff
|
refs/heads/master
| 2021-06-10T15:06:35.379000 | 2021-05-28T18:08:25 | 2021-05-28T18:08:25 | 181,201,315 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.datastructure;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Stack;
/**
* [1,4] [3,6] [8,10] []
* @author Faraz
*
*/
public class MergeOverlappingIntervals {
public static void main(String[] args) {
int[][] input = {
{1,4},{3,4},{3,6},{5,7},{8,10}
};
List<Interval> lst = new ArrayList<>();
for(int[] r : input) {
Interval i = new Interval();
i.start = r[0];
i.end = r[1];
lst.add(i);
}
Collections.sort(lst, (Comparator<? super Interval>) (Interval i1,Interval i2) -> i1.start - i2.start );
//System.out.println(lst.toString());
Stack<Interval> stack = new Stack<>();
List<Interval> newlist = new ArrayList<>();
stack.add(lst.get(0));
for(Interval x : lst) {
if(x.start < stack.peek().end) {
Interval t = stack.pop();
t.end = x.end; // update the end
stack.push(t);
}else {
//Interval t = x;
stack.push(x);
}
}
while(!stack.isEmpty()) {
newlist.add(stack.pop());
}
Collections.sort(newlist, (Comparator<? super Interval>) (Interval i1,Interval i2) -> i1.start - i2.start );
System.out.println(newlist.toString());
}
//private static void
}
class Interval{
int start;
int end;
@Override
public String toString() {
return "Interval [start=" + start + ", end=" + end + "]";
}
}
|
UTF-8
|
Java
| 1,391 |
java
|
MergeOverlappingIntervals.java
|
Java
|
[
{
"context": "il.Stack;\n\n/**\n * [1,4] [3,6] [8,10] []\n * @author Faraz\n *\n */\npublic class MergeOverlappingIntervals {\n\t",
"end": 208,
"score": 0.9997348785400391,
"start": 203,
"tag": "NAME",
"value": "Faraz"
}
] | null |
[] |
package com.datastructure;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Stack;
/**
* [1,4] [3,6] [8,10] []
* @author Faraz
*
*/
public class MergeOverlappingIntervals {
public static void main(String[] args) {
int[][] input = {
{1,4},{3,4},{3,6},{5,7},{8,10}
};
List<Interval> lst = new ArrayList<>();
for(int[] r : input) {
Interval i = new Interval();
i.start = r[0];
i.end = r[1];
lst.add(i);
}
Collections.sort(lst, (Comparator<? super Interval>) (Interval i1,Interval i2) -> i1.start - i2.start );
//System.out.println(lst.toString());
Stack<Interval> stack = new Stack<>();
List<Interval> newlist = new ArrayList<>();
stack.add(lst.get(0));
for(Interval x : lst) {
if(x.start < stack.peek().end) {
Interval t = stack.pop();
t.end = x.end; // update the end
stack.push(t);
}else {
//Interval t = x;
stack.push(x);
}
}
while(!stack.isEmpty()) {
newlist.add(stack.pop());
}
Collections.sort(newlist, (Comparator<? super Interval>) (Interval i1,Interval i2) -> i1.start - i2.start );
System.out.println(newlist.toString());
}
//private static void
}
class Interval{
int start;
int end;
@Override
public String toString() {
return "Interval [start=" + start + ", end=" + end + "]";
}
}
| 1,391 | 0.60532 | 0.584472 | 67 | 19.761194 | 21.294725 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.223881 | false | false |
10
|
842b9a810a39a2122ce2cc137e14a6a24ac94afd
| 26,749,056,326,633 |
57167433a127b329f7c6b375d8c3eef2b34096cf
|
/src/qwe.java
|
2aa2eb2c6d13ecc45af5ed07f09234cd61bf3319
|
[] |
no_license
|
Lake3L/Quest-about-Hackers
|
https://github.com/Lake3L/Quest-about-Hackers
|
729529a0570bd63f9ca4b9c345d98daf089fef88
|
8951e5620917ca3a5e0cbaec4ca712740320858f
|
refs/heads/master
| 2023-02-18T06:27:53.559000 | 2021-01-18T14:23:08 | 2021-01-18T14:23:08 | 322,328,310 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.Scanner;
public class qwe {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = "";
boolean running = true;
sc.nextLine();
while(running){
for(int i = 0; i<30; i++){
input = sc.nextLine();
TextPart.nextLine(i, input);
if(input.equals("//quit")) running = false;
}
}
//Для теста миниигр
MagicSquare magicSquare = new MagicSquare();
magicSquare.getAnswer();
Sudoku sudoku = new Sudoku();
sudoku.getAnswer();
GuessPassword guessPassword = new GuessPassword();
guessPassword.show_coincidences();
}
}
|
UTF-8
|
Java
| 754 |
java
|
qwe.java
|
Java
|
[] | null |
[] |
import java.util.Scanner;
public class qwe {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = "";
boolean running = true;
sc.nextLine();
while(running){
for(int i = 0; i<30; i++){
input = sc.nextLine();
TextPart.nextLine(i, input);
if(input.equals("//quit")) running = false;
}
}
//Для теста миниигр
MagicSquare magicSquare = new MagicSquare();
magicSquare.getAnswer();
Sudoku sudoku = new Sudoku();
sudoku.getAnswer();
GuessPassword guessPassword = new GuessPassword();
guessPassword.show_coincidences();
}
}
| 754 | 0.539919 | 0.535859 | 24 | 29.791666 | 16.373198 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.708333 | false | false |
10
|
87861d7b882cfd37f26d9bab3fb777e37281042b
| 33,457,795,243,232 |
e8b64332df55a0a551112ac3d19a3e78aaea0d2b
|
/app/src/main/java/percept/myplan/POJO/SidaSummary.java
|
60146c925a178018d06743af59e65f1eb1a8a78f
|
[] |
no_license
|
niravPercept/MyPlan
|
https://github.com/niravPercept/MyPlan
|
e670e51b4df71881abaa979cfe1605a3d7b04b28
|
74996c53f9f87a13f8e14b2c2b01f60190bfc014
|
refs/heads/master
| 2020-04-12T05:41:14.061000 | 2017-06-01T04:13:29 | 2017-06-01T04:13:29 | 63,421,827 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package percept.myplan.POJO;
import com.google.gson.annotations.SerializedName;
public class SidaSummary {
@SerializedName("week_number")
private String Week_Number;
@SerializedName("avg_perc")
private String avg_perc;
@SerializedName("avg_score")
private String Avg_Score;
@SerializedName("month_number")
private String monthNumber;
@SerializedName("year")
private String year;
public SidaSummary(String week_Number, String avg_Score, String monthNumber, String year) {
Week_Number = week_Number;
Avg_Score = avg_Score;
this.monthNumber = monthNumber;
this.year = year;
}
public String getWeek_Number() {
return Week_Number;
}
public void setWeek_Number(String week_Number) {
Week_Number = week_Number;
}
public String getAvg_Score() {
return Avg_Score;
}
public void setAvg_Score(String avg_Score) {
Avg_Score = avg_Score;
}
public String getMonthNumber() {
return monthNumber;
}
public void setMonthNumber(String monthNumber) {
this.monthNumber = monthNumber;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getAvg_perc() {
return avg_perc;
}
public void setAvg_perc(String avg_perc) {
this.avg_perc = avg_perc;
}
}
|
UTF-8
|
Java
| 1,436 |
java
|
SidaSummary.java
|
Java
|
[] | null |
[] |
package percept.myplan.POJO;
import com.google.gson.annotations.SerializedName;
public class SidaSummary {
@SerializedName("week_number")
private String Week_Number;
@SerializedName("avg_perc")
private String avg_perc;
@SerializedName("avg_score")
private String Avg_Score;
@SerializedName("month_number")
private String monthNumber;
@SerializedName("year")
private String year;
public SidaSummary(String week_Number, String avg_Score, String monthNumber, String year) {
Week_Number = week_Number;
Avg_Score = avg_Score;
this.monthNumber = monthNumber;
this.year = year;
}
public String getWeek_Number() {
return Week_Number;
}
public void setWeek_Number(String week_Number) {
Week_Number = week_Number;
}
public String getAvg_Score() {
return Avg_Score;
}
public void setAvg_Score(String avg_Score) {
Avg_Score = avg_Score;
}
public String getMonthNumber() {
return monthNumber;
}
public void setMonthNumber(String monthNumber) {
this.monthNumber = monthNumber;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getAvg_perc() {
return avg_perc;
}
public void setAvg_perc(String avg_perc) {
this.avg_perc = avg_perc;
}
}
| 1,436 | 0.630223 | 0.630223 | 63 | 21.793652 | 18.711815 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.380952 | false | false |
10
|
968254eb7424d0cf3e7a936e69535e61bd14b2ee
| 31,104,153,165,263 |
ec32ff271058f361948a475c72a118aa2a3180a1
|
/src/main/java/com/great/school/controllers/FeeTransactionController.java
|
46f29781f9512f9c263d904f776e6cd1b557e39e
|
[] |
no_license
|
CateNjeri/sms-api
|
https://github.com/CateNjeri/sms-api
|
f4af10b35f6da80e583320b127c79bddde6e0aa5
|
44a5ca6bbf6233e93aaedd50a02a2142de758a80
|
refs/heads/master
| 2020-03-27T15:34:29.596000 | 2018-08-30T09:23:55 | 2018-08-30T09:23:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.great.school.controllers;
import com.great.school.models.data.FeeTransaction;
import com.great.school.services.FeeTransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
/**
* Created by Kibet on 25-Nov-17.
*/
@RestController
@RequestMapping("/fees/transactions")
public class FeeTransactionController {
@Autowired
FeeTransactionService feeTransactionService;
@PostMapping
public ResponseEntity<FeeTransaction> create(@Valid @RequestBody FeeTransaction feeTransaction) {
return ResponseEntity.ok(feeTransactionService.add(feeTransaction));
}
@PutMapping("/{id}")
public ResponseEntity<FeeTransaction> update(@PathVariable long id, @Valid @RequestBody FeeTransaction feeTransaction) {
return ResponseEntity.ok(feeTransactionService.add(feeTransaction));
}
@GetMapping
public ResponseEntity<List<FeeTransaction>> all() {
return ResponseEntity.ok(feeTransactionService.all());
}
}
|
UTF-8
|
Java
| 1,146 |
java
|
FeeTransactionController.java
|
Java
|
[
{
"context": "n.Valid;\nimport java.util.List;\n\n/**\n * Created by Kibet on 25-Nov-17.\n */\n@RestController\n@RequestMapping",
"end": 387,
"score": 0.9985286593437195,
"start": 382,
"tag": "USERNAME",
"value": "Kibet"
}
] | null |
[] |
package com.great.school.controllers;
import com.great.school.models.data.FeeTransaction;
import com.great.school.services.FeeTransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
/**
* Created by Kibet on 25-Nov-17.
*/
@RestController
@RequestMapping("/fees/transactions")
public class FeeTransactionController {
@Autowired
FeeTransactionService feeTransactionService;
@PostMapping
public ResponseEntity<FeeTransaction> create(@Valid @RequestBody FeeTransaction feeTransaction) {
return ResponseEntity.ok(feeTransactionService.add(feeTransaction));
}
@PutMapping("/{id}")
public ResponseEntity<FeeTransaction> update(@PathVariable long id, @Valid @RequestBody FeeTransaction feeTransaction) {
return ResponseEntity.ok(feeTransactionService.add(feeTransaction));
}
@GetMapping
public ResponseEntity<List<FeeTransaction>> all() {
return ResponseEntity.ok(feeTransactionService.all());
}
}
| 1,146 | 0.773124 | 0.769634 | 36 | 30.833334 | 30.939457 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.361111 | false | false |
10
|
054abe8d2f2f4b46b2179425372ffd21ebf898f0
| 24,404,004,185,304 |
aa469cbc3b7b427f94e0ea36892a0794fdd9ab1e
|
/src/main/java/com/viniciusDias/cursomc/repositories/ProdutoRepository.java
|
eb3735cef713cf9bf6731ecdd9eb1e6aeada5790
|
[] |
no_license
|
viniciusteixeiradias/cursomc
|
https://github.com/viniciusteixeiradias/cursomc
|
44b0c9d5179c5e0a79fcc515a5fcacddb7520ea8
|
e1ffeec8e7161ca911bc7a46fa4cbe12e07ee02f
|
refs/heads/master
| 2023-04-10T03:04:46.732000 | 2021-04-25T22:22:03 | 2021-04-25T22:22:03 | 361,004,135 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.viniciusDias.cursomc.repositories;
import com.viniciusDias.cursomc.domain.Produto;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProdutoRepository extends JpaRepository<Produto, Integer>{
}
|
UTF-8
|
Java
| 301 |
java
|
ProdutoRepository.java
|
Java
|
[] | null |
[] |
package com.viniciusDias.cursomc.repositories;
import com.viniciusDias.cursomc.domain.Produto;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProdutoRepository extends JpaRepository<Produto, Integer>{
}
| 301 | 0.850498 | 0.850498 | 11 | 26.363636 | 27.877239 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false |
10
|
ac99e7f0d2005c9d27adea5494380df855710415
| 31,765,578,133,873 |
3c8f642ce9091d5795ab6a41b96b84196142e531
|
/caishunpay/caishunuser/src/main/java/com/trade/util/RSASignature.java
|
7390c3c3857c0bdf07b41531f74c8e20cf7d54ae
|
[] |
no_license
|
bluelzx/xiying
|
https://github.com/bluelzx/xiying
|
1e82d112203bc65a797405a30c706837338b3509
|
42b60a841354ae94d3cdb594b08f9cd5327460d4
|
refs/heads/master
| 2020-04-06T23:47:48.911000 | 2018-05-27T10:58:08 | 2018-05-27T10:58:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Decompiled with CFR 0_124.
*/
package com.trade.util;
import com.trade.util.Base64;
import com.trade.util.RSAUtils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Reader;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RSASignature {
public static final String SIGN_ALGORITHMS = "SHA1WithRSA";
public static String sign(String content, String privateKey, String encode) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
Signature signature = Signature.getInstance("SHA1WithRSA");
signature.initSign(priKey);
signature.update(content.getBytes(encode));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String sign(String content, String privateKey) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
Signature signature = Signature.getInstance("SHA1WithRSA");
signature.initSign(priKey);
signature.update(content.getBytes());
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) throws Exception {
String sign = RSASignature.sign("&Transfer&DF2017051500000296893621&C1800000002&0.01&CMBCHINA&6214830202948815&\u53f6\u5efa\u6587&B2C&&PAYER&true&\u7ed3\u7b97\u6b3e", RSASignature.loadPrivateKeyByFile(String.valueOf(RSAUtils.absolutePath) + "/cert/helibao/gypay_private_key_to_helibao.pem"));
System.out.println("sign:" + sign);
}
public static boolean doCheck(String content, String sign, String publicKey, String encode) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64.decode(publicKey);
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
Signature signature = Signature.getInstance("SHA1WithRSA");
signature.initVerify(pubKey);
signature.update(content.getBytes(encode));
boolean bverify = signature.verify(Base64.decode(sign));
return bverify;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static boolean doCheck(String content, String sign, String publicKey) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64.decode(publicKey);
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
Signature signature = Signature.getInstance("SHA1WithRSA");
signature.initVerify(pubKey);
signature.update(content.getBytes());
boolean bverify = signature.verify(Base64.decode(sign));
return bverify;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static String loadPrivateKeyByFile(String path) throws Exception {
try {
BufferedReader br = new BufferedReader(new FileReader(path));
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
if (readLine.charAt(0) == '-') continue;
sb.append(readLine);
}
br.close();
return sb.toString();
} catch (IOException e) {
throw new Exception("\u79c1\u94a5\u6570\u636e\u8bfb\u53d6\u9519\u8bef");
} catch (NullPointerException e) {
throw new Exception("\u79c1\u94a5\u8f93\u5165\u6d41\u4e3a\u7a7a");
}
}
}
|
UTF-8
|
Java
| 4,492 |
java
|
RSASignature.java
|
Java
|
[] | null |
[] |
/*
* Decompiled with CFR 0_124.
*/
package com.trade.util;
import com.trade.util.Base64;
import com.trade.util.RSAUtils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Reader;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RSASignature {
public static final String SIGN_ALGORITHMS = "SHA1WithRSA";
public static String sign(String content, String privateKey, String encode) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
Signature signature = Signature.getInstance("SHA1WithRSA");
signature.initSign(priKey);
signature.update(content.getBytes(encode));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String sign(String content, String privateKey) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
Signature signature = Signature.getInstance("SHA1WithRSA");
signature.initSign(priKey);
signature.update(content.getBytes());
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) throws Exception {
String sign = RSASignature.sign("&Transfer&DF2017051500000296893621&C1800000002&0.01&CMBCHINA&6214830202948815&\u53f6\u5efa\u6587&B2C&&PAYER&true&\u7ed3\u7b97\u6b3e", RSASignature.loadPrivateKeyByFile(String.valueOf(RSAUtils.absolutePath) + "/cert/helibao/gypay_private_key_to_helibao.pem"));
System.out.println("sign:" + sign);
}
public static boolean doCheck(String content, String sign, String publicKey, String encode) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64.decode(publicKey);
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
Signature signature = Signature.getInstance("SHA1WithRSA");
signature.initVerify(pubKey);
signature.update(content.getBytes(encode));
boolean bverify = signature.verify(Base64.decode(sign));
return bverify;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static boolean doCheck(String content, String sign, String publicKey) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64.decode(publicKey);
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
Signature signature = Signature.getInstance("SHA1WithRSA");
signature.initVerify(pubKey);
signature.update(content.getBytes());
boolean bverify = signature.verify(Base64.decode(sign));
return bverify;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static String loadPrivateKeyByFile(String path) throws Exception {
try {
BufferedReader br = new BufferedReader(new FileReader(path));
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
if (readLine.charAt(0) == '-') continue;
sb.append(readLine);
}
br.close();
return sb.toString();
} catch (IOException e) {
throw new Exception("\u79c1\u94a5\u6570\u636e\u8bfb\u53d6\u9519\u8bef");
} catch (NullPointerException e) {
throw new Exception("\u79c1\u94a5\u8f93\u5165\u6d41\u4e3a\u7a7a");
}
}
}
| 4,492 | 0.640917 | 0.606411 | 111 | 39.468468 | 35.943855 | 300 | false | false | 0 | 0 | 48 | 0.020036 | 0 | 0 | 0.684685 | false | false |
10
|
0256ca87b0dab5313610b5c82c843f6074d10a86
| 14,499,809,600,797 |
aca55726908f182ffac45ba7720729420a495491
|
/testingDSL/webPageContainers4Testing/dev/GoogleAnalyticsElement.java
|
f39684faa230917ff8de87bb98c4615763178dfb
|
[] |
no_license
|
murali-projects/k12-automation
|
https://github.com/murali-projects/k12-automation
|
c20548510416235716b3c190b7b576aeb308fd39
|
b792b163d30afddd73abb7c30e4fc4f24f982f0c
|
refs/heads/master
| 2021-01-18T21:30:37.546000 | 2013-04-19T10:57:37 | 2013-04-19T10:57:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package webPageContainers4Testing.dev;
public class GoogleAnalyticsElement extends BaseDevPageContainer {
protected String locator = properties.get("google_analytics_element");
protected String javascriptLocator = properties.get("google_analytics_javascript_element");
public GoogleAnalyticsElement() throws Exception {
super();
}
public boolean isPresent() {
return selenium.isElementPresent(locator);
}
public Number getJavaScriptBlockCount() {
return selenium.getXpathCount(javascriptLocator);
}
}
|
UTF-8
|
Java
| 526 |
java
|
GoogleAnalyticsElement.java
|
Java
|
[] | null |
[] |
package webPageContainers4Testing.dev;
public class GoogleAnalyticsElement extends BaseDevPageContainer {
protected String locator = properties.get("google_analytics_element");
protected String javascriptLocator = properties.get("google_analytics_javascript_element");
public GoogleAnalyticsElement() throws Exception {
super();
}
public boolean isPresent() {
return selenium.isElementPresent(locator);
}
public Number getJavaScriptBlockCount() {
return selenium.getXpathCount(javascriptLocator);
}
}
| 526 | 0.788973 | 0.787072 | 21 | 24.095238 | 28.430206 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.190476 | false | false |
10
|
af1823e0b1ac2fc1f8115607d06cc08159dfcc44
| 8,134,668,080,876 |
d8b70a9fc63dee52403979191afaa68383402ff0
|
/src/main/java/org/example/array/MoveZeros.java
|
a8a6af1df7dcce3659dca6e9ffd00bfa7fb32be7
|
[] |
no_license
|
niuniu-doc/BlogComments
|
https://github.com/niuniu-doc/BlogComments
|
e46843693c35854e31c71ec04481cbf1c32862b9
|
4cf80035b437ed682b5b151544d0ef1940ee3e85
|
refs/heads/master
| 2021-04-12T14:01:29.385000 | 2021-04-07T01:43:40 | 2021-04-07T01:43:40 | 249,082,550 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.example.array;
import java.util.Arrays;
/**
* 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
*
* 示例:
*
* 输入: [0,1,0,3,12]
* 输出: [1,3,12,0,0]
* 说明:
*
* 必须在原数组上操作,不能拷贝额外的数组。
* 尽量减少操作次数。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/move-zeroes
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class MoveZeros {
public static void main(String[] args) {
Solution solution = new MoveZeros().new Solution();
int[] origin = new int[]{0,1,0,3,12};
int[] res = solution.moveZeros(origin);
System.out.println(Arrays.toString(res));
}
class Solution {
public int[] moveZeros(int[] nums) {
int curr = 0, i; // cur is next none zero digit
for (i = 0; i < nums.length; i++) {
if (nums[i] == 0) continue; // if nums[i]==0, judge next digit
if (i != curr) { // if cur==i, all before digit more than zero
nums[curr] = nums[i];
nums[i] = 0;
}
curr++;
}
return nums;
}
}
}
|
UTF-8
|
Java
| 1,353 |
java
|
MoveZeros.java
|
Java
|
[] | null |
[] |
package org.example.array;
import java.util.Arrays;
/**
* 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
*
* 示例:
*
* 输入: [0,1,0,3,12]
* 输出: [1,3,12,0,0]
* 说明:
*
* 必须在原数组上操作,不能拷贝额外的数组。
* 尽量减少操作次数。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/move-zeroes
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class MoveZeros {
public static void main(String[] args) {
Solution solution = new MoveZeros().new Solution();
int[] origin = new int[]{0,1,0,3,12};
int[] res = solution.moveZeros(origin);
System.out.println(Arrays.toString(res));
}
class Solution {
public int[] moveZeros(int[] nums) {
int curr = 0, i; // cur is next none zero digit
for (i = 0; i < nums.length; i++) {
if (nums[i] == 0) continue; // if nums[i]==0, judge next digit
if (i != curr) { // if cur==i, all before digit more than zero
nums[curr] = nums[i];
nums[i] = 0;
}
curr++;
}
return nums;
}
}
}
| 1,353 | 0.519317 | 0.497754 | 45 | 23.733334 | 21.766846 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.644444 | false | false |
10
|
d6f940b5931dbb3c3d403471979ae7b70fd499aa
| 16,088,947,518,392 |
a37220beb80050e4c77d45ee15896e3cd1c9799c
|
/src/main/java/com/prandium/controller/UserController.java
|
b12c87b60677a4cfad48cd9bac338596e5c8c9b8
|
[] |
no_license
|
akshaygurao/Happy-Meals
|
https://github.com/akshaygurao/Happy-Meals
|
61200cd87a82855b0bcab45996394f7c426f06d3
|
60bfe624cda03bc4b8b890fe6317981d7e9e7324
|
refs/heads/master
| 2023-02-22T19:33:31.678000 | 2021-05-12T07:25:37 | 2021-05-12T07:25:37 | 130,827,565 | 0 | 0 | null | false | 2023-02-22T07:11:31 | 2018-04-24T09:11:55 | 2021-05-12T07:25:40 | 2023-02-22T07:11:30 | 7,411 | 0 | 0 | 8 |
Java
| false | false |
package com.prandium.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.prandium.dao.RestaurantDAO;
import com.prandium.dao.UserDAO;
import com.prandium.exception.UserException;
import com.prandium.filter.XSSFilter;
import com.prandium.pojo.Restaurant;
import com.prandium.pojo.User;
import com.prandium.validator.UserValidator;
/**
* Handles requests for the application home page.
*/
@Controller
@RequestMapping("/user/*")
public class UserController {
@Autowired
@Qualifier("userDao")
UserDAO userDao;
@Autowired
@Qualifier("restaurantDao")
RestaurantDAO restaurantDao;
@Autowired
@Qualifier("userValidator")
UserValidator validator;
@InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView goHome() {
return new ModelAndView("home");
}
@RequestMapping(value = "/user/login", method = RequestMethod.GET)
protected String getloginUser(HttpServletRequest request) throws Exception {
return "";
}
@RequestMapping(value = "/user/login", method = RequestMethod.POST)
protected String loginUser(HttpServletRequest request) throws Exception {
HttpSession session = (HttpSession) request.getSession();
try {
System.out.print("loginUser");
String tempUsername = request.getParameter("username");
String tempPassword = request.getParameter("password");
String username = XSSFilter.removeXSS(tempUsername);
String password = XSSFilter.removeXSS(tempPassword);
User u = userDao.get(username, password);
if (u == null) {
System.out.println("UserName/Password does not exist");
session.setAttribute("errorMessage", "UserName/Password does not exist");
return "error";
}
List<Restaurant> restaurantList = restaurantDao.getAllRestaurants();
session.setAttribute("restaurantList", restaurantList);
session.setAttribute("user", u);
session.setAttribute("username", u.getUsername());
if (u.getType().equalsIgnoreCase("U")) {
return "user-home";
} else if (u.getType().equalsIgnoreCase("A")) {
return "admin-home";
} else {
return "owner-home";
}
} catch (UserException e) {
System.out.println("Exception: " + e.getMessage());
session.setAttribute("errorMessage", "error while login");
return "error";
}
}
@RequestMapping(value = "/user/register", method = RequestMethod.GET)
protected ModelAndView registerUser() throws Exception {
System.out.print("registerUser");
return new ModelAndView("register-user", "user", new User());
}
@RequestMapping(value = "/user/register", method = RequestMethod.POST)
protected ModelAndView registerNewUser(HttpServletRequest request, @ModelAttribute("user") User user,
BindingResult result) throws Exception {
validator.validate(user, result);
if (result.hasErrors()) {
return new ModelAndView("register-user", "user", user);
}
try {
String tempUsername = user.getUsername();
String tempPassword = user.getPassword();
String tempFirstName = user.getFirstName();
String tempLastName = user.getLastName();
String username = XSSFilter.removeXSS(tempUsername);
String password = XSSFilter.removeXSS(tempPassword);
String firstName = XSSFilter.removeXSS(tempFirstName);
String lastName = XSSFilter.removeXSS(tempLastName);
user.setUsername(username);
user.setPassword(password);
user.setFirstName(firstName);
user.setLastName(lastName);
System.out.print("registerNewUser");
user.setType("U");
User u = userDao.register(user);
request.getSession().setAttribute("user", u);
return new ModelAndView("home", "user", u);
} catch (UserException e) {
System.out.println("Exception: " + e.getMessage());
return new ModelAndView("error", "errorMessage", "error while login");
}
}
@RequestMapping(value = "/user/register-owners", method = RequestMethod.GET)
protected ModelAndView registerOwner() throws Exception {
System.out.print("registerOwner");
return new ModelAndView("register-owners", "user", new User());
}
@RequestMapping(value = "/user/register-owners", method = RequestMethod.POST)
protected ModelAndView registerNewOwner(HttpServletRequest request, @ModelAttribute("user") User user,
BindingResult result) throws Exception {
validator.validate(user, result);
if (result.hasErrors()) {
return new ModelAndView("register-owners", "user", user);
}
try {
String tempUsername = user.getUsername();
String tempPassword = user.getPassword();
String tempFirstName = user.getFirstName();
String tempLastName = user.getLastName();
String username = XSSFilter.removeXSS(tempUsername);
String password = XSSFilter.removeXSS(tempPassword);
String firstName = XSSFilter.removeXSS(tempFirstName);
String lastName = XSSFilter.removeXSS(tempLastName);
user.setUsername(username);
user.setPassword(password);
user.setFirstName(firstName);
user.setLastName(lastName);
System.out.print("registerNewUser");
user.setType("O");
User u = userDao.register(user);
request.getSession().setAttribute("user", u);
return new ModelAndView("home", "user", u);
} catch (UserException e) {
System.out.println("Exception: " + e.getMessage());
return new ModelAndView("error", "errorMessage", "error while login");
}
}
@RequestMapping(value = "/user/settings", method = RequestMethod.GET)
protected ModelAndView getSettings(HttpServletRequest request) throws Exception {
System.out.print("Account settings (GET)");
User user = (User) request.getSession().getAttribute("user");
return new ModelAndView("edit-profile", "user", user);
}
@RequestMapping(value = "/user/settings", method = RequestMethod.POST)
protected ModelAndView updateSettings(HttpServletRequest request, @ModelAttribute("user") User user,
BindingResult result) throws Exception {
System.out.print("Account settings (POST)");
validator.validate(user, result);
// if (result.hasErrors()) {
// System.out.println("Got Errors");
// return new ModelAndView("edit-profile", "user", user);
// }
//
try {
User u = userDao.updateSettings(user);
request.getSession().setAttribute("user", u);
return new ModelAndView("account-success");
} catch (UserException e) {
System.out.println("Exception: " + e.getMessage());
return new ModelAndView("error", "errorMessage", "error while login");
}
}
@RequestMapping(value = "/user/viewUsers", method = RequestMethod.GET)
protected ModelAndView getAllUsers(HttpServletRequest request) throws Exception {
System.out.print("Get all Users (GET)");
User user = (User) request.getSession().getAttribute("user");
if (user.getType().equalsIgnoreCase("A")) {
List<User> userList = userDao.getAll();
return new ModelAndView("view-all-users", "userList", userList);
} else {
return new ModelAndView("access");
}
}
@RequestMapping(value = "/user/viewUsers", method = RequestMethod.POST)
protected ModelAndView setAllUsers(HttpServletRequest request) throws Exception {
System.out.print("Get all Users (POST)");
User user = (User) request.getSession().getAttribute("user");
if (user.getType().equalsIgnoreCase("A")) {
List<User> userList = userDao.getAll();
return new ModelAndView("view-all-users", "userList", userList);
} else {
return new ModelAndView("access");
}
}
@RequestMapping(value = "/user/viewRestaurants", method = RequestMethod.GET)
protected ModelAndView getAllRestaurants(HttpServletRequest request) throws Exception {
System.out.print("Get all restaurants (GET)");
User user = (User) request.getSession().getAttribute("user");
if (user.getType().equalsIgnoreCase("A")) {
List<Restaurant> restaurantList = restaurantDao.getAllRestaurants();
return new ModelAndView("view-all-rest", "restaurantList", restaurantList);
} else {
return new ModelAndView("access");
}
}
@RequestMapping(value = "/user/viewRestaurants", method = RequestMethod.POST)
protected ModelAndView setAllRestaurants(HttpServletRequest request) throws Exception {
System.out.print("Get all restaurants (POST)");
User user = (User) request.getSession().getAttribute("user");
if (user.getType().equalsIgnoreCase("A")) {
List<Restaurant> restaurantList = restaurantDao.getAllRestaurants();
return new ModelAndView("view-all-rest", "restaurantList", restaurantList);
} else {
return new ModelAndView("access");
}
}
@RequestMapping(value = "/user/deleteUser", method = RequestMethod.GET)
protected ModelAndView getDeleteUser(HttpServletRequest request) throws Exception {
System.out.print("Delete user (GET)");
String username = request.getParameter("username");
User user = (User) request.getSession().getAttribute("user");
if (user.getType().equalsIgnoreCase("A")) {
User u = userDao.getUser(username);
userDao.delete(u);
List<User> userList = userDao.getAll();
return new ModelAndView("view-all-users", "userList", userList);
} else {
return new ModelAndView("access");
}
}
}
|
UTF-8
|
Java
| 9,713 |
java
|
UserController.java
|
Java
|
[
{
"context": "ter.removeXSS(tempLastName);\n\n\t\t\tuser.setUsername(username);\n\t\t\tuser.setPassword(password);\n\t\t\tuser.setFirst",
"end": 4031,
"score": 0.9991893768310547,
"start": 4023,
"tag": "USERNAME",
"value": "username"
},
{
"context": "\t\tuser.setUsername(username);\n\t\t\tuser.setPassword(password);\n\t\t\tuser.setFirstName(firstName);\n\t\t\tuser.setLas",
"end": 4062,
"score": 0.9991258382797241,
"start": 4054,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "\t\tuser.setUsername(username);\n\t\t\tuser.setPassword(password);\n\t\t\tuser.setFirstName(firstName);\n\t\t\tuser.setLas",
"end": 5577,
"score": 0.9974079728126526,
"start": 5569,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "GET)\");\n\t\tString username = request.getParameter(\"username\");\n\t\tUser user = (User) request.getSession().getA",
"end": 9368,
"score": 0.816078245639801,
"start": 9360,
"tag": "USERNAME",
"value": "username"
}
] | null |
[] |
package com.prandium.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.prandium.dao.RestaurantDAO;
import com.prandium.dao.UserDAO;
import com.prandium.exception.UserException;
import com.prandium.filter.XSSFilter;
import com.prandium.pojo.Restaurant;
import com.prandium.pojo.User;
import com.prandium.validator.UserValidator;
/**
* Handles requests for the application home page.
*/
@Controller
@RequestMapping("/user/*")
public class UserController {
@Autowired
@Qualifier("userDao")
UserDAO userDao;
@Autowired
@Qualifier("restaurantDao")
RestaurantDAO restaurantDao;
@Autowired
@Qualifier("userValidator")
UserValidator validator;
@InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView goHome() {
return new ModelAndView("home");
}
@RequestMapping(value = "/user/login", method = RequestMethod.GET)
protected String getloginUser(HttpServletRequest request) throws Exception {
return "";
}
@RequestMapping(value = "/user/login", method = RequestMethod.POST)
protected String loginUser(HttpServletRequest request) throws Exception {
HttpSession session = (HttpSession) request.getSession();
try {
System.out.print("loginUser");
String tempUsername = request.getParameter("username");
String tempPassword = request.getParameter("password");
String username = XSSFilter.removeXSS(tempUsername);
String password = XSSFilter.removeXSS(tempPassword);
User u = userDao.get(username, password);
if (u == null) {
System.out.println("UserName/Password does not exist");
session.setAttribute("errorMessage", "UserName/Password does not exist");
return "error";
}
List<Restaurant> restaurantList = restaurantDao.getAllRestaurants();
session.setAttribute("restaurantList", restaurantList);
session.setAttribute("user", u);
session.setAttribute("username", u.getUsername());
if (u.getType().equalsIgnoreCase("U")) {
return "user-home";
} else if (u.getType().equalsIgnoreCase("A")) {
return "admin-home";
} else {
return "owner-home";
}
} catch (UserException e) {
System.out.println("Exception: " + e.getMessage());
session.setAttribute("errorMessage", "error while login");
return "error";
}
}
@RequestMapping(value = "/user/register", method = RequestMethod.GET)
protected ModelAndView registerUser() throws Exception {
System.out.print("registerUser");
return new ModelAndView("register-user", "user", new User());
}
@RequestMapping(value = "/user/register", method = RequestMethod.POST)
protected ModelAndView registerNewUser(HttpServletRequest request, @ModelAttribute("user") User user,
BindingResult result) throws Exception {
validator.validate(user, result);
if (result.hasErrors()) {
return new ModelAndView("register-user", "user", user);
}
try {
String tempUsername = user.getUsername();
String tempPassword = user.getPassword();
String tempFirstName = user.getFirstName();
String tempLastName = user.getLastName();
String username = XSSFilter.removeXSS(tempUsername);
String password = XSSFilter.removeXSS(tempPassword);
String firstName = XSSFilter.removeXSS(tempFirstName);
String lastName = XSSFilter.removeXSS(tempLastName);
user.setUsername(username);
user.setPassword(<PASSWORD>);
user.setFirstName(firstName);
user.setLastName(lastName);
System.out.print("registerNewUser");
user.setType("U");
User u = userDao.register(user);
request.getSession().setAttribute("user", u);
return new ModelAndView("home", "user", u);
} catch (UserException e) {
System.out.println("Exception: " + e.getMessage());
return new ModelAndView("error", "errorMessage", "error while login");
}
}
@RequestMapping(value = "/user/register-owners", method = RequestMethod.GET)
protected ModelAndView registerOwner() throws Exception {
System.out.print("registerOwner");
return new ModelAndView("register-owners", "user", new User());
}
@RequestMapping(value = "/user/register-owners", method = RequestMethod.POST)
protected ModelAndView registerNewOwner(HttpServletRequest request, @ModelAttribute("user") User user,
BindingResult result) throws Exception {
validator.validate(user, result);
if (result.hasErrors()) {
return new ModelAndView("register-owners", "user", user);
}
try {
String tempUsername = user.getUsername();
String tempPassword = user.getPassword();
String tempFirstName = user.getFirstName();
String tempLastName = user.getLastName();
String username = XSSFilter.removeXSS(tempUsername);
String password = XSSFilter.removeXSS(tempPassword);
String firstName = XSSFilter.removeXSS(tempFirstName);
String lastName = XSSFilter.removeXSS(tempLastName);
user.setUsername(username);
user.setPassword(<PASSWORD>);
user.setFirstName(firstName);
user.setLastName(lastName);
System.out.print("registerNewUser");
user.setType("O");
User u = userDao.register(user);
request.getSession().setAttribute("user", u);
return new ModelAndView("home", "user", u);
} catch (UserException e) {
System.out.println("Exception: " + e.getMessage());
return new ModelAndView("error", "errorMessage", "error while login");
}
}
@RequestMapping(value = "/user/settings", method = RequestMethod.GET)
protected ModelAndView getSettings(HttpServletRequest request) throws Exception {
System.out.print("Account settings (GET)");
User user = (User) request.getSession().getAttribute("user");
return new ModelAndView("edit-profile", "user", user);
}
@RequestMapping(value = "/user/settings", method = RequestMethod.POST)
protected ModelAndView updateSettings(HttpServletRequest request, @ModelAttribute("user") User user,
BindingResult result) throws Exception {
System.out.print("Account settings (POST)");
validator.validate(user, result);
// if (result.hasErrors()) {
// System.out.println("Got Errors");
// return new ModelAndView("edit-profile", "user", user);
// }
//
try {
User u = userDao.updateSettings(user);
request.getSession().setAttribute("user", u);
return new ModelAndView("account-success");
} catch (UserException e) {
System.out.println("Exception: " + e.getMessage());
return new ModelAndView("error", "errorMessage", "error while login");
}
}
@RequestMapping(value = "/user/viewUsers", method = RequestMethod.GET)
protected ModelAndView getAllUsers(HttpServletRequest request) throws Exception {
System.out.print("Get all Users (GET)");
User user = (User) request.getSession().getAttribute("user");
if (user.getType().equalsIgnoreCase("A")) {
List<User> userList = userDao.getAll();
return new ModelAndView("view-all-users", "userList", userList);
} else {
return new ModelAndView("access");
}
}
@RequestMapping(value = "/user/viewUsers", method = RequestMethod.POST)
protected ModelAndView setAllUsers(HttpServletRequest request) throws Exception {
System.out.print("Get all Users (POST)");
User user = (User) request.getSession().getAttribute("user");
if (user.getType().equalsIgnoreCase("A")) {
List<User> userList = userDao.getAll();
return new ModelAndView("view-all-users", "userList", userList);
} else {
return new ModelAndView("access");
}
}
@RequestMapping(value = "/user/viewRestaurants", method = RequestMethod.GET)
protected ModelAndView getAllRestaurants(HttpServletRequest request) throws Exception {
System.out.print("Get all restaurants (GET)");
User user = (User) request.getSession().getAttribute("user");
if (user.getType().equalsIgnoreCase("A")) {
List<Restaurant> restaurantList = restaurantDao.getAllRestaurants();
return new ModelAndView("view-all-rest", "restaurantList", restaurantList);
} else {
return new ModelAndView("access");
}
}
@RequestMapping(value = "/user/viewRestaurants", method = RequestMethod.POST)
protected ModelAndView setAllRestaurants(HttpServletRequest request) throws Exception {
System.out.print("Get all restaurants (POST)");
User user = (User) request.getSession().getAttribute("user");
if (user.getType().equalsIgnoreCase("A")) {
List<Restaurant> restaurantList = restaurantDao.getAllRestaurants();
return new ModelAndView("view-all-rest", "restaurantList", restaurantList);
} else {
return new ModelAndView("access");
}
}
@RequestMapping(value = "/user/deleteUser", method = RequestMethod.GET)
protected ModelAndView getDeleteUser(HttpServletRequest request) throws Exception {
System.out.print("Delete user (GET)");
String username = request.getParameter("username");
User user = (User) request.getSession().getAttribute("user");
if (user.getType().equalsIgnoreCase("A")) {
User u = userDao.getUser(username);
userDao.delete(u);
List<User> userList = userDao.getAll();
return new ModelAndView("view-all-users", "userList", userList);
} else {
return new ModelAndView("access");
}
}
}
| 9,717 | 0.733141 | 0.733141 | 293 | 32.150169 | 27.005207 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.221843 | false | false |
10
|
2e51716673fdeedfa3070ad14cfe3a7183b8dd0c
| 16,088,947,515,281 |
7f9fee07fcd214ae3da6dc7ad9fb948e1d20ff65
|
/threads/src/main/java/com/threads/thread/jdk/semaphore/MySemaphore.java
|
524e452f72de53278e55ed9ede5b4ff3ad5e30bb
|
[] |
no_license
|
opop32165455/zeroBeginning
|
https://github.com/opop32165455/zeroBeginning
|
d2ac5c4c4a641fe59904b23491df8ae5419bde75
|
8d6b1bb548f3ee72fa2695f9826404deaaab7720
|
refs/heads/master
| 2023-07-06T05:52:02.183000 | 2023-01-28T09:03:41 | 2023-01-28T09:03:41 | 320,766,486 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.threads.thread.jdk.semaphore;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import static java.lang.Thread.currentThread;
/**
* @author zhangxuecheng4441
* @date 2021/5/17/017 12:00
*/
@Slf4j
public class MySemaphore extends Semaphore {
private static final long serialVersionUID = 3184061773358565644L;
/**
* 定义线程安全的、存放Thread类型的队列 todo 此处可以是其他线程安全的集合
*/
private final ConcurrentLinkedQueue<Thread> queue = new ConcurrentLinkedQueue<>();
int parallelCount;
public MySemaphore(int permits) {
super(permits);
}
public MySemaphore(int permits, boolean fair) {
super(permits, fair);
}
@Override
public void acquire() throws InterruptedException {
super.acquire();
// 线程成功获取许可证,将其放入队列中
this.queue.add(currentThread());
}
@Override
public void acquireUninterruptibly() {
super.acquireUninterruptibly();
// 线程成功获取许可证,将其放入队列中
this.queue.add(currentThread());
}
@Override
public boolean tryAcquire() {
final boolean acquired = super.tryAcquire();
if (acquired) {
// 线程成功获取许可证,将其放入队列中
this.queue.add(currentThread());
}
return acquired;
}
@Override
public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException {
final boolean acquired = super.tryAcquire(timeout, unit);
if (acquired) {
// 线程成功获取许可证,将其放入队列中
this.queue.add(currentThread());
}
return acquired;
}
@Override
public void release() {
final Thread currentThread = currentThread();
// 当队列中不存在该线程时,调用release方法将会被忽略
if (!this.queue.contains(currentThread)) {
return;
}
super.release();
// 成功释放,并且将当前线程从队列中剔除
this.queue.remove(currentThread);
}
@Override
public void acquire(int permits) throws InterruptedException {
super.acquire(permits);
// 线程成功获取许可证,将其放入队列中
this.queue.add(currentThread());
}
@Override
public void acquireUninterruptibly(int permits) {
super.acquireUninterruptibly(permits);
// 线程成功获取许可证,将其放入队列中
this.queue.add(currentThread());
}
@Override
public boolean tryAcquire(int permits) {
boolean acquired = super.tryAcquire(permits);
if (acquired) {
// 线程成功获取许可证,将其放入队列中
this.queue.add(currentThread());
}
return acquired;
}
@Override
public boolean tryAcquire(int permits, long timeout, TimeUnit unit) throws InterruptedException {
boolean acquired = super.tryAcquire(permits, timeout, unit);
if (acquired) {
// 线程成功获取许可证,将其放入队列中
this.queue.add(currentThread());
}
return acquired;
}
@Override
public void release(int permits) {
final Thread currentThread = currentThread();
// 当队列中不存在该线程时,调用release方法将会被忽略
if (!this.queue.contains(currentThread)) {
return;
}
super.release(permits);
// 成功释放,并且将当前线程从队列中剔除
this.queue.remove(currentThread);
}
}
|
UTF-8
|
Java
| 3,802 |
java
|
MySemaphore.java
|
Java
|
[
{
"context": "ic java.lang.Thread.currentThread;\n\n/**\n * @author zhangxuecheng4441\n * @date 2021/5/17/017 12:00\n */\n@Slf4j\npublic cl",
"end": 286,
"score": 0.9985631108283997,
"start": 269,
"tag": "USERNAME",
"value": "zhangxuecheng4441"
}
] | null |
[] |
package com.threads.thread.jdk.semaphore;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import static java.lang.Thread.currentThread;
/**
* @author zhangxuecheng4441
* @date 2021/5/17/017 12:00
*/
@Slf4j
public class MySemaphore extends Semaphore {
private static final long serialVersionUID = 3184061773358565644L;
/**
* 定义线程安全的、存放Thread类型的队列 todo 此处可以是其他线程安全的集合
*/
private final ConcurrentLinkedQueue<Thread> queue = new ConcurrentLinkedQueue<>();
int parallelCount;
public MySemaphore(int permits) {
super(permits);
}
public MySemaphore(int permits, boolean fair) {
super(permits, fair);
}
@Override
public void acquire() throws InterruptedException {
super.acquire();
// 线程成功获取许可证,将其放入队列中
this.queue.add(currentThread());
}
@Override
public void acquireUninterruptibly() {
super.acquireUninterruptibly();
// 线程成功获取许可证,将其放入队列中
this.queue.add(currentThread());
}
@Override
public boolean tryAcquire() {
final boolean acquired = super.tryAcquire();
if (acquired) {
// 线程成功获取许可证,将其放入队列中
this.queue.add(currentThread());
}
return acquired;
}
@Override
public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException {
final boolean acquired = super.tryAcquire(timeout, unit);
if (acquired) {
// 线程成功获取许可证,将其放入队列中
this.queue.add(currentThread());
}
return acquired;
}
@Override
public void release() {
final Thread currentThread = currentThread();
// 当队列中不存在该线程时,调用release方法将会被忽略
if (!this.queue.contains(currentThread)) {
return;
}
super.release();
// 成功释放,并且将当前线程从队列中剔除
this.queue.remove(currentThread);
}
@Override
public void acquire(int permits) throws InterruptedException {
super.acquire(permits);
// 线程成功获取许可证,将其放入队列中
this.queue.add(currentThread());
}
@Override
public void acquireUninterruptibly(int permits) {
super.acquireUninterruptibly(permits);
// 线程成功获取许可证,将其放入队列中
this.queue.add(currentThread());
}
@Override
public boolean tryAcquire(int permits) {
boolean acquired = super.tryAcquire(permits);
if (acquired) {
// 线程成功获取许可证,将其放入队列中
this.queue.add(currentThread());
}
return acquired;
}
@Override
public boolean tryAcquire(int permits, long timeout, TimeUnit unit) throws InterruptedException {
boolean acquired = super.tryAcquire(permits, timeout, unit);
if (acquired) {
// 线程成功获取许可证,将其放入队列中
this.queue.add(currentThread());
}
return acquired;
}
@Override
public void release(int permits) {
final Thread currentThread = currentThread();
// 当队列中不存在该线程时,调用release方法将会被忽略
if (!this.queue.contains(currentThread)) {
return;
}
super.release(permits);
// 成功释放,并且将当前线程从队列中剔除
this.queue.remove(currentThread);
}
}
| 3,802 | 0.627262 | 0.615199 | 127 | 25.094488 | 21.385267 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.370079 | false | false |
10
|
3c6c9c880f9bed1d4d5d475f73aef94d1043e94d
| 21,732,534,542,350 |
bf4c98ad14e9a16bcb23eeb88af464fa79de37f2
|
/src/model/entities/Airport.java
|
c92c372a34963396ad43ea0963900cd1813361e8
|
[] |
no_license
|
KwasnikMaciej/TicketReservationSystem
|
https://github.com/KwasnikMaciej/TicketReservationSystem
|
940c850397435b7284c14f420a4ce27a18e8f68a
|
ab0e15f0605d900f9bd1298f829ecc44b78ea06b
|
refs/heads/master
| 2021-01-10T16:48:11.959000 | 2016-03-11T16:51:14 | 2016-03-11T16:51:14 | 53,680,322 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package model.entities;
import java.io.Serializable;
import java.lang.Integer;
import java.lang.String;
import javax.persistence.*;
@Entity
public class Airport implements Serializable {
@Transient
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String IATAcode;
private String city;
private String name;
public Airport() {
super();
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getIATAcode() {
return IATAcode;
}
public void setIATAcode(String iATAcode) {
IATAcode = iATAcode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return city + ", " + name + " [" + IATAcode + "]";
}
public String toStringForFlight() {
return name + " (" + IATAcode + ")";
}
}
|
UTF-8
|
Java
| 1,054 |
java
|
Airport.java
|
Java
|
[] | null |
[] |
package model.entities;
import java.io.Serializable;
import java.lang.Integer;
import java.lang.String;
import javax.persistence.*;
@Entity
public class Airport implements Serializable {
@Transient
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String IATAcode;
private String city;
private String name;
public Airport() {
super();
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getIATAcode() {
return IATAcode;
}
public void setIATAcode(String iATAcode) {
IATAcode = iATAcode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return city + ", " + name + " [" + IATAcode + "]";
}
public String toStringForFlight() {
return name + " (" + IATAcode + ")";
}
}
| 1,054 | 0.683112 | 0.682163 | 57 | 17.491228 | 14.607284 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.333333 | false | false |
10
|
d6eaad7352491449a566f46a17d39ca43b213a39
| 8,512,625,208,008 |
70f7bbdfa2aeb927e1717db310bb7df816d9c230
|
/src/main/java/net/sublime/warehouse/model/Product.java
|
a329628c2d9461bca9c8e315d824b739b77cd666
|
[] |
no_license
|
Atoiebai/e-warehouse
|
https://github.com/Atoiebai/e-warehouse
|
ead52d7c955a044248302c1c736c12b6a596e6c5
|
caac925f44470024a0c3464494518a558c0ccb22
|
refs/heads/master
| 2023-03-21T12:58:43.801000 | 2021-02-19T21:15:45 | 2021-02-19T21:15:45 | 336,786,885 | 1 | 0 | null | false | 2021-02-19T21:15:45 | 2021-02-07T12:56:38 | 2021-02-13T20:07:46 | 2021-02-19T21:15:45 | 47 | 0 | 0 | 0 |
Java
| false | false |
package net.sublime.warehouse.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@Column(nullable = false)
String name;
@Column(nullable = false)
long price;
@JsonIgnore
@Column(nullable = false)
boolean archived = false;
}
|
UTF-8
|
Java
| 694 |
java
|
Product.java
|
Java
|
[] | null |
[] |
package net.sublime.warehouse.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@Column(nullable = false)
String name;
@Column(nullable = false)
long price;
@JsonIgnore
@Column(nullable = false)
boolean archived = false;
}
| 694 | 0.760807 | 0.760807 | 33 | 20.030304 | 17.880894 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.393939 | false | false |
10
|
b0027acc02bf210ae427ac241b6e881e4b09ff7e
| 8,512,625,207,289 |
10a2a8dc540b109aca685100832f52047ad5de53
|
/test1/mycalc/src/main/java/local/lessons/mycalc/NumeredButton.java
|
c10926ef6e5b15977890384f96fccf6806c5c2c7
|
[] |
no_license
|
lesnikyan/android_course
|
https://github.com/lesnikyan/android_course
|
ec816d23cbe4ef4b27cbd3ca3bc89af6aebcaddb
|
146fcda1fa64617f31ee44b50d79b8a5ff7b2bd2
|
refs/heads/master
| 2020-03-29T13:17:01.999000 | 2015-05-11T22:10:10 | 2015-05-11T22:10:10 | 33,244,394 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package local.lessons.mycalc;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;
import android.widget.RemoteViews;
/**
* Created by Less on 14.03.2015.
*/
@RemoteViews.RemoteView
public class NumeredButton extends Button {
private int val;
public NumeredButton(Context context, AttributeSet attributes){
super(context, attributes);
}
public void setVal(int val){
this. val = val;
}
public int getVal(){
return val;
}
public void incVal(){
val++;
}
}
|
UTF-8
|
Java
| 574 |
java
|
NumeredButton.java
|
Java
|
[
{
"context": "ort android.widget.RemoteViews;\n\n/**\n * Created by Less on 14.03.2015.\n */\n@RemoteViews.RemoteView\npublic",
"end": 185,
"score": 0.9150065183639526,
"start": 181,
"tag": "USERNAME",
"value": "Less"
}
] | null |
[] |
package local.lessons.mycalc;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;
import android.widget.RemoteViews;
/**
* Created by Less on 14.03.2015.
*/
@RemoteViews.RemoteView
public class NumeredButton extends Button {
private int val;
public NumeredButton(Context context, AttributeSet attributes){
super(context, attributes);
}
public void setVal(int val){
this. val = val;
}
public int getVal(){
return val;
}
public void incVal(){
val++;
}
}
| 574 | 0.665505 | 0.651568 | 32 | 16.9375 | 16.55094 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false |
10
|
450b4dec48b41a33bc3e063d0e95eb825ccc0545
| 32,049,046,020,391 |
67e7b49c7ea7d3b556dcdda981c02154552c1132
|
/reptiles-src/common/EntityTortoise.java
|
d8a68d36de210d5c3422e7a4a748445392aacfad
|
[] |
no_license
|
Kash-117/reptiles
|
https://github.com/Kash-117/reptiles
|
5ca10faa7900c6e00d32dcbc17e15c1b244c8d6d
|
c52da05430c45ecf6d50fb0b22480d247d2062f7
|
refs/heads/master
| 2016-12-28T09:47:33.569000 | 2013-06-10T21:02:30 | 2013-06-10T21:02:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
//
// This work is licensed under the Creative Commons
// Attribution-ShareAlike 3.0 Unported License. To view a copy of this
// license, visit http://creativecommons.org/licenses/by-sa/3.0/
//
package reptiles.common;
import java.util.*;
import net.minecraft.entity.EntityAgeable;
import net.minecraft.entity.passive.EntityAnimal;
import net.minecraft.world.World;
public class EntityTortoise extends EntityTurtle {
public EntityTortoise(World world) {
super(world);
texture = "/mob/gtortoise2-32.png";
setSize(1.5F, 1.5F);
moveSpeed = 0.4F;
}
public EntityAnimal spawnBabyAnimal(EntityAgeable entityageable) {
EntityTortoise t = new EntityTortoise(worldObj);
if (isTamed()) {
t.setOwner(getOwnerName());
t.setTamed(true);
}
System.out.printf("Spawned entity of type %s", getClass().toString());
return t;
}
}
|
UTF-8
|
Java
| 865 |
java
|
EntityTortoise.java
|
Java
|
[] | null |
[] |
//
// This work is licensed under the Creative Commons
// Attribution-ShareAlike 3.0 Unported License. To view a copy of this
// license, visit http://creativecommons.org/licenses/by-sa/3.0/
//
package reptiles.common;
import java.util.*;
import net.minecraft.entity.EntityAgeable;
import net.minecraft.entity.passive.EntityAnimal;
import net.minecraft.world.World;
public class EntityTortoise extends EntityTurtle {
public EntityTortoise(World world) {
super(world);
texture = "/mob/gtortoise2-32.png";
setSize(1.5F, 1.5F);
moveSpeed = 0.4F;
}
public EntityAnimal spawnBabyAnimal(EntityAgeable entityageable) {
EntityTortoise t = new EntityTortoise(worldObj);
if (isTamed()) {
t.setOwner(getOwnerName());
t.setTamed(true);
}
System.out.printf("Spawned entity of type %s", getClass().toString());
return t;
}
}
| 865 | 0.717919 | 0.70289 | 34 | 24.441177 | 23.509937 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.176471 | false | false |
10
|
173069f3a01ea0734c7627c3f273b3b78096d575
| 36,155,034,732,492 |
5052aded7e9182cf31019243b4c1c5368ad821a2
|
/CrackingTheCodingInterview/src/main/java/ch1/Q16.java
|
66b0eabde02691cbda5a3751a32282e473ddc9a1
|
[
"Apache-2.0"
] |
permissive
|
richmnus/sandbox
|
https://github.com/richmnus/sandbox
|
ef7a01d4435e1abfa8b72cd23e9432ae77dce373
|
d58c8375a7b001eba3e11d77b74435d13b959635
|
refs/heads/master
| 2020-04-06T06:59:42.925000 | 2016-08-18T16:38:18 | 2016-08-18T16:38:18 | 62,914,674 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ch1;
public class Q16 {
int[][] rotate(int[][] shape) {
return null;
}
}
|
UTF-8
|
Java
| 92 |
java
|
Q16.java
|
Java
|
[] | null |
[] |
package ch1;
public class Q16 {
int[][] rotate(int[][] shape) {
return null;
}
}
| 92 | 0.554348 | 0.521739 | 10 | 8.2 | 10.127192 | 32 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.9 | false | false |
10
|
72700ac12b123ce25de10855ea4fb30a3a2f9033
| 38,293,928,430,712 |
eb1af80e8a8d20330b6459bdeadc0526dd6925a1
|
/app/src/main/java/com/zhonghong/hlbelogistics/core/home/Fragments/BuyerInfoFragment.java
|
07734fe80e95178a55310d25c14813a535d51901
|
[] |
no_license
|
qq742571766/Shang-TongBao
|
https://github.com/qq742571766/Shang-TongBao
|
d23c4d6dd4f6e284016fd6ca611cbfde49cb7afb
|
310d12e7063b4060edea32711d0549d9ad75e152
|
refs/heads/master
| 2021-01-20T16:04:11.546000 | 2017-05-11T07:43:27 | 2017-05-11T07:43:27 | 90,812,221 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.zhonghong.hlbelogistics.core.home.Fragments;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.zhonghong.hlbelogistics.R;
import com.zhonghong.hlbelogistics.bean.Buyer;
import com.zhonghong.hlbelogistics.core.home.Activitys.Buyers_details_Activity;
import com.zhonghong.hlbelogistics.core.home.Adapter.BuyerInfoAdapter;
import com.zhonghong.hlbelogistics.ui.PullToRefreshBase;
import com.zhonghong.hlbelogistics.ui.PullToRefreshListView;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
/**
* Created by Administrator on 2017/3/1.
*/
public class BuyerInfoFragment extends Fragment {
private ListView mListView;
private PullToRefreshListView pull_refresh_listView;
private BuyerInfoAdapter BIAdapter;
private ArrayList<Buyer> buyerArrayList ;
private int page_num = 1;
private LinkedList<String> mListItems;
private SimpleDateFormat mDateFormat = new SimpleDateFormat("MM-dd HH:mm");
private boolean mIsStart = true;
private int mCurIndex = 0;
private static final int mLoadDataCount = 100;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_buyerinfo,container,false);
init(view);
return view;
}
private void init(View view) {
pull_refresh_listView = (PullToRefreshListView) view.findViewById(R.id.pull_refresh_listView);
pull_refresh_listView.setPullLoadEnabled(false);
pull_refresh_listView.setScrollLoadEnabled(true);
mListView = pull_refresh_listView.getRefreshableView();
mCurIndex = mLoadDataCount;
buyerArrayList = new ArrayList<>();
for (int i=0 ;i<10;i++)
{
Buyer buyer = new Buyer();
buyer.setId("i"+i);
buyer.setDealed_num("i"+i);
buyer.setGd_title("i"+i);
buyer.setPrice("i"+i);
buyer.setPrice_type("i"+i);
buyer.setReleas_time("i"+i);
buyer.setTotal("i"+i);
buyerArrayList.add(buyer);
}
BIAdapter = new BuyerInfoAdapter(buyerArrayList);
mListView.setAdapter(BIAdapter);
// mListView.setOnItemClickListener(new MyOnItemClickListener());
pull_refresh_listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
mIsStart = true;
new GetDataTask().execute();
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
mIsStart = false;
new GetDataTask().execute();
}
});
}
// private class MyOnItemClickListener implements AdapterView.OnItemClickListener{
//
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Intent intent=new Intent(getActivity(), Buyers_details_Activity.class);
// startActivity(intent);
// }
// }
private class GetDataTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
return null;
}
@Override
protected void onPostExecute(Void result) {
boolean hasMoreData = true;
if (mIsStart) {
Buyer buyer = new Buyer();
buyer.setId("i"+page_num);
buyer.setDealed_num("i"+page_num);
buyer.setGd_title("i"+page_num);
buyer.setPrice("i"+page_num);
buyer.setPrice_type("i"+page_num);
buyer.setReleas_time("i"+page_num);
buyer.setTotal("i"+page_num);
buyerArrayList.add(0,buyer);
} else {
if (page_num<5)
{
Buyer buyer = new Buyer();
buyer.setId("i"+page_num);
buyer.setDealed_num("i"+page_num);
buyer.setGd_title("i"+page_num);
buyer.setPrice("i"+page_num);
buyer.setPrice_type("i"+page_num);
buyer.setReleas_time("i"+page_num);
buyer.setTotal("i"+page_num);
buyerArrayList.add(buyer);
}else
{
hasMoreData = false;
}
}
BIAdapter.notifyDataSetChanged();
pull_refresh_listView.onPullDownRefreshComplete();
pull_refresh_listView.onPullUpRefreshComplete();
pull_refresh_listView.setHasMoreData(hasMoreData);
setLastUpdateTime();
page_num++;
super.onPostExecute(result);
}
}
private void setLastUpdateTime() {
String text = formatDateTime(System.currentTimeMillis());
pull_refresh_listView.setLastUpdatedLabel(text);
}
private String formatDateTime(long time) {
if (0 == time) {
return "";
}
return mDateFormat.format(new Date(time));
}
}
|
UTF-8
|
Java
| 5,855 |
java
|
BuyerInfoFragment.java
|
Java
|
[] | null |
[] |
package com.zhonghong.hlbelogistics.core.home.Fragments;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.zhonghong.hlbelogistics.R;
import com.zhonghong.hlbelogistics.bean.Buyer;
import com.zhonghong.hlbelogistics.core.home.Activitys.Buyers_details_Activity;
import com.zhonghong.hlbelogistics.core.home.Adapter.BuyerInfoAdapter;
import com.zhonghong.hlbelogistics.ui.PullToRefreshBase;
import com.zhonghong.hlbelogistics.ui.PullToRefreshListView;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
/**
* Created by Administrator on 2017/3/1.
*/
public class BuyerInfoFragment extends Fragment {
private ListView mListView;
private PullToRefreshListView pull_refresh_listView;
private BuyerInfoAdapter BIAdapter;
private ArrayList<Buyer> buyerArrayList ;
private int page_num = 1;
private LinkedList<String> mListItems;
private SimpleDateFormat mDateFormat = new SimpleDateFormat("MM-dd HH:mm");
private boolean mIsStart = true;
private int mCurIndex = 0;
private static final int mLoadDataCount = 100;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_buyerinfo,container,false);
init(view);
return view;
}
private void init(View view) {
pull_refresh_listView = (PullToRefreshListView) view.findViewById(R.id.pull_refresh_listView);
pull_refresh_listView.setPullLoadEnabled(false);
pull_refresh_listView.setScrollLoadEnabled(true);
mListView = pull_refresh_listView.getRefreshableView();
mCurIndex = mLoadDataCount;
buyerArrayList = new ArrayList<>();
for (int i=0 ;i<10;i++)
{
Buyer buyer = new Buyer();
buyer.setId("i"+i);
buyer.setDealed_num("i"+i);
buyer.setGd_title("i"+i);
buyer.setPrice("i"+i);
buyer.setPrice_type("i"+i);
buyer.setReleas_time("i"+i);
buyer.setTotal("i"+i);
buyerArrayList.add(buyer);
}
BIAdapter = new BuyerInfoAdapter(buyerArrayList);
mListView.setAdapter(BIAdapter);
// mListView.setOnItemClickListener(new MyOnItemClickListener());
pull_refresh_listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
mIsStart = true;
new GetDataTask().execute();
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
mIsStart = false;
new GetDataTask().execute();
}
});
}
// private class MyOnItemClickListener implements AdapterView.OnItemClickListener{
//
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Intent intent=new Intent(getActivity(), Buyers_details_Activity.class);
// startActivity(intent);
// }
// }
private class GetDataTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
return null;
}
@Override
protected void onPostExecute(Void result) {
boolean hasMoreData = true;
if (mIsStart) {
Buyer buyer = new Buyer();
buyer.setId("i"+page_num);
buyer.setDealed_num("i"+page_num);
buyer.setGd_title("i"+page_num);
buyer.setPrice("i"+page_num);
buyer.setPrice_type("i"+page_num);
buyer.setReleas_time("i"+page_num);
buyer.setTotal("i"+page_num);
buyerArrayList.add(0,buyer);
} else {
if (page_num<5)
{
Buyer buyer = new Buyer();
buyer.setId("i"+page_num);
buyer.setDealed_num("i"+page_num);
buyer.setGd_title("i"+page_num);
buyer.setPrice("i"+page_num);
buyer.setPrice_type("i"+page_num);
buyer.setReleas_time("i"+page_num);
buyer.setTotal("i"+page_num);
buyerArrayList.add(buyer);
}else
{
hasMoreData = false;
}
}
BIAdapter.notifyDataSetChanged();
pull_refresh_listView.onPullDownRefreshComplete();
pull_refresh_listView.onPullUpRefreshComplete();
pull_refresh_listView.setHasMoreData(hasMoreData);
setLastUpdateTime();
page_num++;
super.onPostExecute(result);
}
}
private void setLastUpdateTime() {
String text = formatDateTime(System.currentTimeMillis());
pull_refresh_listView.setLastUpdatedLabel(text);
}
private String formatDateTime(long time) {
if (0 == time) {
return "";
}
return mDateFormat.format(new Date(time));
}
}
| 5,855 | 0.610931 | 0.607173 | 172 | 33.040699 | 24.970531 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.616279 | false | false |
10
|
5f90bc3f0fa63edf71ffc9ea1cd66a920d3692a8
| 33,105,607,952,466 |
ed65ab4008762c2dc205ec3430d6c06b0c30b3d7
|
/src/main/GameLauncher.java
|
ace51db68a29537c47ef3e936ab243bfdecb0d21
|
[] |
no_license
|
MrEqu/Java_Checkers
|
https://github.com/MrEqu/Java_Checkers
|
0e841b4e5b6a2d6be1686621ad782745b5f3b488
|
bf38a785d5c1af3758a6f3cd34e500125fb673ed
|
refs/heads/master
| 2021-01-21T03:38:20.683000 | 2013-04-16T15:18:07 | 2013-04-16T15:18:07 | 36,811,768 | 1 | 0 | null | true | 2015-06-03T15:14:11 | 2015-06-03T15:14:10 | 2014-04-16T17:05:48 | 2013-04-16T15:19:01 | 19,355 | 0 | 0 | 0 | null | null | null |
package main;
import javax.swing.SwingWorker;
public class GameLauncher extends SwingWorker{
int mode = -1;
/**
* Constructor method to set the 'Mode' of the game from a given integer, 1 or 2, to decide the number of Human Players.
* @param mode Integer value, 1 or 2, of the number of human players- the remainder will be AI.
*/
public GameLauncher(int mode) {
this.mode = mode;
}
/**
* Run method for the game's Thread. Initializes and plays the game in its own thread.
*/
public void runGame() {
Game game = Game.getInstance();
game.initialize(mode);
game.play();
}
@Override
protected String doInBackground() throws Exception {
runGame();
return "Start game";
}
}
|
UTF-8
|
Java
| 739 |
java
|
GameLauncher.java
|
Java
|
[] | null |
[] |
package main;
import javax.swing.SwingWorker;
public class GameLauncher extends SwingWorker{
int mode = -1;
/**
* Constructor method to set the 'Mode' of the game from a given integer, 1 or 2, to decide the number of Human Players.
* @param mode Integer value, 1 or 2, of the number of human players- the remainder will be AI.
*/
public GameLauncher(int mode) {
this.mode = mode;
}
/**
* Run method for the game's Thread. Initializes and plays the game in its own thread.
*/
public void runGame() {
Game game = Game.getInstance();
game.initialize(mode);
game.play();
}
@Override
protected String doInBackground() throws Exception {
runGame();
return "Start game";
}
}
| 739 | 0.663058 | 0.656292 | 31 | 21.838709 | 29.811338 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.354839 | false | false |
10
|
c4a71b039277022d5931ddcccf73baefb6803af1
| 23,338,852,327,800 |
c107e325dfd1bc9ad1c5e8ef01e30f1fab2d7e75
|
/src/Square/Square.java
|
573f1917ead475e393e7084ed34fc0f4cb3e2ed7
|
[] |
no_license
|
AzizovMarat/YandexAlgorithmsCourse
|
https://github.com/AzizovMarat/YandexAlgorithmsCourse
|
94f2fcdec62a00663babe6458fff1b5a4a107a35
|
b0ee0fc89b6b55e227ce92254743f25069be8f79
|
refs/heads/master
| 2023-06-22T20:39:15.094000 | 2021-07-05T14:22:25 | 2021-07-05T14:22:25 | 382,816,025 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Square;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Square {
public static void main(String[] args) throws IOException {
long t, n, m;
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
n = Long.parseLong(reader.readLine());
m = Long.parseLong(reader.readLine());
t = Long.parseLong(reader.readLine());
}
long min = Math.min(n, m);
long max = Math.max(n, m);
long right = min + 1;
long left = 0;
System.out.println(rBinSearch(left, right, t, min, max));
}
public static long rBinSearch(long left, long right, long t, long min, long max) {
long currLength = (left + right + 1) / 2;
while (left != right) {
if (check(currLength, t, min, max)) {
left = currLength;
} else {
right = currLength - 1;
}
currLength = (left + right + 1) / 2;
}
return currLength;
}
public static boolean check(long curr, long t, long min, long max) {
if (curr * 2 >= min) return false;
long res = curr * min * 2 + curr * (max - 2 * curr) * 2;
if (res < 1) return false;
return res <= t;
}
}
|
UTF-8
|
Java
| 1,332 |
java
|
Square.java
|
Java
|
[] | null |
[] |
package Square;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Square {
public static void main(String[] args) throws IOException {
long t, n, m;
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
n = Long.parseLong(reader.readLine());
m = Long.parseLong(reader.readLine());
t = Long.parseLong(reader.readLine());
}
long min = Math.min(n, m);
long max = Math.max(n, m);
long right = min + 1;
long left = 0;
System.out.println(rBinSearch(left, right, t, min, max));
}
public static long rBinSearch(long left, long right, long t, long min, long max) {
long currLength = (left + right + 1) / 2;
while (left != right) {
if (check(currLength, t, min, max)) {
left = currLength;
} else {
right = currLength - 1;
}
currLength = (left + right + 1) / 2;
}
return currLength;
}
public static boolean check(long curr, long t, long min, long max) {
if (curr * 2 >= min) return false;
long res = curr * min * 2 + curr * (max - 2 * curr) * 2;
if (res < 1) return false;
return res <= t;
}
}
| 1,332 | 0.53979 | 0.530781 | 44 | 29.295454 | 23.812315 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.909091 | false | false |
10
|
805088ae9e0ca0eb406870b37abc42b2bd990f47
| 13,357,348,335,392 |
3c905d04f4a7b5867cceeb56279de98f103cd691
|
/SistemaAgendamentoPOO20181/src/processamento/classes/EquipamentoGenerico.java
|
5c115b3c96805281d0aca8efb2c5caa5618bf00a
|
[] |
no_license
|
helder-rangel/projetopoo20181
|
https://github.com/helder-rangel/projetopoo20181
|
17a14264f2c102c6999f29f1b2a9b99e315f9af9
|
8054aa2d7e7e7776cc5d997a52a5173b7f8bd4c8
|
refs/heads/master
| 2020-08-11T05:16:07.028000 | 2018-07-26T10:42:34 | 2018-07-26T10:42:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package processamento.classes;
import java.util.Scanner;
public class EquipamentoGenerico {
private Integer mesas;
private Integer cadeiras;
private Integer lixeiras;
private Integer quadros;
//Construtores
public EquipamentoGenerico(Integer mesas, Integer cadeiras, Integer lixeiras, Integer quadros) {
super();
this.mesas = mesas;
this.cadeiras = cadeiras;
this.lixeiras = lixeiras;
this.quadros = quadros;
}
public EquipamentoGenerico() {
super();
}
//Getters and Setters
public Integer getMesas() {
return mesas;
}
public Integer getCadeiras() {
return cadeiras;
}
public Integer getLixeiras() {
return lixeiras;
}
public Integer getQuadros() {
return quadros;
}
private void setMesas(Integer mesas) {
this.mesas = mesas;
}
private void setCadeiras(Integer cadeiras) {
this.cadeiras = cadeiras;
}
private void setLixeiras(Integer lixeiras) {
this.lixeiras = lixeiras;
}
private void setQuadros(Integer quadros) {
this.quadros = quadros;
}
//toString
@Override
public String toString() {
return "EquipamentoGenerico [mesas=" + mesas + ", cadeiras=" + cadeiras + ", lixeiras=" + lixeiras
+ ", quadros=" + quadros + "]";
}
//hashCode
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((cadeiras == null) ? 0 : cadeiras.hashCode());
result = prime * result + ((lixeiras == null) ? 0 : lixeiras.hashCode());
result = prime * result + ((mesas == null) ? 0 : mesas.hashCode());
result = prime * result + ((quadros == null) ? 0 : quadros.hashCode());
return result;
}
//equals
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EquipamentoGenerico other = (EquipamentoGenerico) obj;
if (cadeiras == null) {
if (other.cadeiras != null)
return false;
} else if (!cadeiras.equals(other.cadeiras))
return false;
if (lixeiras == null) {
if (other.lixeiras != null)
return false;
} else if (!lixeiras.equals(other.lixeiras))
return false;
if (mesas == null) {
if (other.mesas != null)
return false;
} else if (!mesas.equals(other.mesas))
return false;
if (quadros == null) {
if (other.quadros != null)
return false;
} else if (!quadros.equals(other.quadros))
return false;
return true;
}
//Metodos
/**
* Metodo privado (lerInteiro), é feito para garantir a leitura de um inteiro e retorna um Integer com tal informação.
* @return tclin.nextInt Integer
*/
private Integer lerInteiro() {
Scanner tclin = new Scanner(System.in);
while(!tclin.hasNextInt()) {
System.out.print("Digite um numero inteiro: ");
tclin.nextInt();
}
return tclin.nextInt();
}
/**
* Metodo (criarEquipamentoGenerico), é feito para preencher os dados do objeto da classe EquipamentoGenerico, não precisando colocar os dados no construtor da classe
* @return void
*/
public void criarEquipamentoGenerico() {
System.out.print("Digite a quantidade de Mesas: ");
setMesas(lerInteiro() );
System.out.print("Digite a quantidade de Cadeiras: ");
setCadeiras(lerInteiro() );
System.out.print("Digite a quantidade de Lixeiras: ");
setLixeiras(lerInteiro() );
System.out.print("Digite a quantidade de Quadros: ");
setQuadros(lerInteiro() );
}
}
|
ISO-8859-1
|
Java
| 3,430 |
java
|
EquipamentoGenerico.java
|
Java
|
[] | null |
[] |
package processamento.classes;
import java.util.Scanner;
public class EquipamentoGenerico {
private Integer mesas;
private Integer cadeiras;
private Integer lixeiras;
private Integer quadros;
//Construtores
public EquipamentoGenerico(Integer mesas, Integer cadeiras, Integer lixeiras, Integer quadros) {
super();
this.mesas = mesas;
this.cadeiras = cadeiras;
this.lixeiras = lixeiras;
this.quadros = quadros;
}
public EquipamentoGenerico() {
super();
}
//Getters and Setters
public Integer getMesas() {
return mesas;
}
public Integer getCadeiras() {
return cadeiras;
}
public Integer getLixeiras() {
return lixeiras;
}
public Integer getQuadros() {
return quadros;
}
private void setMesas(Integer mesas) {
this.mesas = mesas;
}
private void setCadeiras(Integer cadeiras) {
this.cadeiras = cadeiras;
}
private void setLixeiras(Integer lixeiras) {
this.lixeiras = lixeiras;
}
private void setQuadros(Integer quadros) {
this.quadros = quadros;
}
//toString
@Override
public String toString() {
return "EquipamentoGenerico [mesas=" + mesas + ", cadeiras=" + cadeiras + ", lixeiras=" + lixeiras
+ ", quadros=" + quadros + "]";
}
//hashCode
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((cadeiras == null) ? 0 : cadeiras.hashCode());
result = prime * result + ((lixeiras == null) ? 0 : lixeiras.hashCode());
result = prime * result + ((mesas == null) ? 0 : mesas.hashCode());
result = prime * result + ((quadros == null) ? 0 : quadros.hashCode());
return result;
}
//equals
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EquipamentoGenerico other = (EquipamentoGenerico) obj;
if (cadeiras == null) {
if (other.cadeiras != null)
return false;
} else if (!cadeiras.equals(other.cadeiras))
return false;
if (lixeiras == null) {
if (other.lixeiras != null)
return false;
} else if (!lixeiras.equals(other.lixeiras))
return false;
if (mesas == null) {
if (other.mesas != null)
return false;
} else if (!mesas.equals(other.mesas))
return false;
if (quadros == null) {
if (other.quadros != null)
return false;
} else if (!quadros.equals(other.quadros))
return false;
return true;
}
//Metodos
/**
* Metodo privado (lerInteiro), é feito para garantir a leitura de um inteiro e retorna um Integer com tal informação.
* @return tclin.nextInt Integer
*/
private Integer lerInteiro() {
Scanner tclin = new Scanner(System.in);
while(!tclin.hasNextInt()) {
System.out.print("Digite um numero inteiro: ");
tclin.nextInt();
}
return tclin.nextInt();
}
/**
* Metodo (criarEquipamentoGenerico), é feito para preencher os dados do objeto da classe EquipamentoGenerico, não precisando colocar os dados no construtor da classe
* @return void
*/
public void criarEquipamentoGenerico() {
System.out.print("Digite a quantidade de Mesas: ");
setMesas(lerInteiro() );
System.out.print("Digite a quantidade de Cadeiras: ");
setCadeiras(lerInteiro() );
System.out.print("Digite a quantidade de Lixeiras: ");
setLixeiras(lerInteiro() );
System.out.print("Digite a quantidade de Quadros: ");
setQuadros(lerInteiro() );
}
}
| 3,430 | 0.668321 | 0.666277 | 158 | 20.677216 | 24.16852 | 167 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.867089 | false | false |
10
|
cfe3052a123aafb48488cb3b6c350ca242f97392
| 17,712,445,165,539 |
58bcb7e79c7f92afecd62e0fc7d0df25b1de2587
|
/src/pieces/Pawn.java
|
68a2e393fa42d5ea2367a3c16e61e0d1b101c9b0
|
[] |
no_license
|
katerina-raztsvetnikova/Kasparov-Tron-Week3
|
https://github.com/katerina-raztsvetnikova/Kasparov-Tron-Week3
|
943a0872584c35a0bcdbff530adb4ac4c7d8a8a8
|
17dd02f9242cb0f856d374b902d511f3cfa6893e
|
refs/heads/master
| 2020-12-21T21:01:21.200000 | 2020-01-27T18:11:35 | 2020-01-27T18:11:35 | 236,555,425 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pieces;
public class Pawn extends Piece {
public Pawn(String inputColor, int row, int col) {
super(inputColor, row, col);
this.power = 1;
this.id = 1;
}
public boolean isMovePosible(int moveRow, int moveCol) {
int moveRowCoeficient = (this.row - moveRow);
int moveColCoeficient = (this.col - moveCol);
boolean isRowMovementPosible = (moveRowCoeficient == 1);
boolean isColMovementPosible = (moveColCoeficient == 0);
return isRowMovementPosible &&
isColMovementPosible;
}
public void move(int moveRow, int moveCol) {
if(this.isMovePosible(moveRow, moveCol)) {
this.row = moveRow;
this.col = moveCol;
}
}
public void attack(int attackRow, int attackCol) {
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
if ((attackRow == (this.row + i)) && (attackCol == (this.col + j))) {
System.out.println("It's pawn attack.");
}
if ((attackRow == (this.row - i)) && (attackCol == (this.col + j))) {
System.out.println("It's pawn attack.");
}
if ((attackRow == (this.row - i)) && (attackCol == (this.col - j))) {
System.out.println("It's pawn attack.");
}
if ((attackRow == (this.row + i)) && (attackCol == (this.col - j))) {
System.out.println("It's pawn attack.");
} else {
System.out.println("Invalid attack.");
}
}
}
}
}
|
UTF-8
|
Java
| 1,748 |
java
|
Pawn.java
|
Java
|
[] | null |
[] |
package pieces;
public class Pawn extends Piece {
public Pawn(String inputColor, int row, int col) {
super(inputColor, row, col);
this.power = 1;
this.id = 1;
}
public boolean isMovePosible(int moveRow, int moveCol) {
int moveRowCoeficient = (this.row - moveRow);
int moveColCoeficient = (this.col - moveCol);
boolean isRowMovementPosible = (moveRowCoeficient == 1);
boolean isColMovementPosible = (moveColCoeficient == 0);
return isRowMovementPosible &&
isColMovementPosible;
}
public void move(int moveRow, int moveCol) {
if(this.isMovePosible(moveRow, moveCol)) {
this.row = moveRow;
this.col = moveCol;
}
}
public void attack(int attackRow, int attackCol) {
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
if ((attackRow == (this.row + i)) && (attackCol == (this.col + j))) {
System.out.println("It's pawn attack.");
}
if ((attackRow == (this.row - i)) && (attackCol == (this.col + j))) {
System.out.println("It's pawn attack.");
}
if ((attackRow == (this.row - i)) && (attackCol == (this.col - j))) {
System.out.println("It's pawn attack.");
}
if ((attackRow == (this.row + i)) && (attackCol == (this.col - j))) {
System.out.println("It's pawn attack.");
} else {
System.out.println("Invalid attack.");
}
}
}
}
}
| 1,748 | 0.467963 | 0.462243 | 57 | 28.596491 | 27.142805 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.526316 | false | false |
10
|
49c67f6acce659a1a357e9232c646a467f474a6c
| 7,395,933,685,156 |
8614c330200db00a9e4f99dbba80b846cecf4958
|
/LeetcodeProblems/Indeed/RootLeafMinCost.java
|
89865e306793d21afb30e77783d959ecc5e42922
|
[] |
no_license
|
sjwangzju/leetcode
|
https://github.com/sjwangzju/leetcode
|
0b8d26de6d2ef1c88e6fe46affb2e480f99703b2
|
5145edb3fbec01c0fd50d0700d69248e9db2e96c
|
refs/heads/master
| 2021-06-15T18:21:39.016000 | 2019-12-20T18:50:33 | 2019-12-20T18:50:33 | 130,455,572 | 5 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Indeed;
import java.util.LinkedList;
import java.util.List;
public class RootLeafMinCost {
public static class Node {
List<Edge> edges;
public Node() {
this.edges = new LinkedList<>();
}
}
public static class Edge {
Node endNode;
int cost;
public Edge(Node end, int cost) {
this.endNode = end;
this.cost = cost;
}
}
int min = Integer.MAX_VALUE;
public List<Edge> minCost(Node root) {
if (root == null) return null;
List<Edge> res = new LinkedList<>();
List<Edge> tmp = new LinkedList<>();
dfs(res, tmp, root, 0);
return res;
}
public void dfs(List<Edge> res, List<Edge> tmp, Node n, int curCost) {
if (n == null) {
return;
}
if (n.edges.size() == 0) {
if (curCost < min) {
min = curCost;
res.clear();
res.addAll(tmp);
}
return;
}
List<Edge> list = n.edges;
for (Edge e: list) {
tmp.add(e);
dfs(res, tmp, e.endNode, curCost + e.cost);
tmp.remove(tmp.size() - 1);
}
}
public static void main(String[] args) {
Node n1 = new Node();
Node n21 = new Node();
Node n22 = new Node();
Node n23 = new Node();
Node n31 = new Node();
Node n32 = new Node();
Edge e1 = new Edge(n21, -15);
Edge e2 = new Edge(n22, -5);
Edge e3 = new Edge(n23, 10);
Edge e4 = new Edge(n31, -1);
Edge e5 = new Edge(n32, 30);
n1.edges.add(e1);
n1.edges.add(e2);
n1.edges.add(e3);
n21.edges.add(e4);
n21.edges.add(e5);
List<Edge> list = new RootLeafMinCost().minCost(n1);
for (Edge e: list) {
System.out.println(e.cost);
}
}
}
|
UTF-8
|
Java
| 1,941 |
java
|
RootLeafMinCost.java
|
Java
|
[] | null |
[] |
package Indeed;
import java.util.LinkedList;
import java.util.List;
public class RootLeafMinCost {
public static class Node {
List<Edge> edges;
public Node() {
this.edges = new LinkedList<>();
}
}
public static class Edge {
Node endNode;
int cost;
public Edge(Node end, int cost) {
this.endNode = end;
this.cost = cost;
}
}
int min = Integer.MAX_VALUE;
public List<Edge> minCost(Node root) {
if (root == null) return null;
List<Edge> res = new LinkedList<>();
List<Edge> tmp = new LinkedList<>();
dfs(res, tmp, root, 0);
return res;
}
public void dfs(List<Edge> res, List<Edge> tmp, Node n, int curCost) {
if (n == null) {
return;
}
if (n.edges.size() == 0) {
if (curCost < min) {
min = curCost;
res.clear();
res.addAll(tmp);
}
return;
}
List<Edge> list = n.edges;
for (Edge e: list) {
tmp.add(e);
dfs(res, tmp, e.endNode, curCost + e.cost);
tmp.remove(tmp.size() - 1);
}
}
public static void main(String[] args) {
Node n1 = new Node();
Node n21 = new Node();
Node n22 = new Node();
Node n23 = new Node();
Node n31 = new Node();
Node n32 = new Node();
Edge e1 = new Edge(n21, -15);
Edge e2 = new Edge(n22, -5);
Edge e3 = new Edge(n23, 10);
Edge e4 = new Edge(n31, -1);
Edge e5 = new Edge(n32, 30);
n1.edges.add(e1);
n1.edges.add(e2);
n1.edges.add(e3);
n21.edges.add(e4);
n21.edges.add(e5);
List<Edge> list = new RootLeafMinCost().minCost(n1);
for (Edge e: list) {
System.out.println(e.cost);
}
}
}
| 1,941 | 0.473467 | 0.447707 | 83 | 22.385542 | 16.187777 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.686747 | false | false |
10
|
742f62e55da1a725a6e70a02c18b6c68313bb6bf
| 8,143,258,015,865 |
8d2b4690852e6a70b3d3d537fdde049710de1142
|
/helloDemo/src/com/fhzc/stream/TestPredicate.java
|
2a2f142c5b2ace4076febe44d35ffb97b0a7b133
|
[] |
no_license
|
calmDJ/jdk8
|
https://github.com/calmDJ/jdk8
|
fe3fd07461fbcc80a8d8911866136ba1bffcae77
|
db2de86e4db88ee3ea9fd25e431436da99dee919
|
refs/heads/master
| 2020-09-10T20:52:48.489000 | 2019-11-15T03:04:47 | 2019-11-15T03:04:47 | 221,831,728 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.fhzc.stream;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TestPredicate {
List<Employee> emps = Arrays.asList(
new Employee(102, "李四", 59, 6666.66),
new Employee(101, "张三", 18, 9999.99),
new Employee(103, "王五", 28, 3333.33),
new Employee(104, "赵六", 8, 7777.77),
new Employee(104, "赵六", 8, 7777.77),
new Employee(104, "赵六", 8, 7777.77),
new Employee(105, "田七", 38, 5555.55)
);
// 需求:获取公司中工资大于 5000 的员工信息
@Test
public void test1(){
List<Employee> list = new ArrayList<>();
for (Employee emp : emps) {
if (emp.getSalary() > 5000) {
list.add(emp);
}
}
System.out.println(list);
}
public List<Employee> filterEmployee(List<Employee> emps, MyPredicate<Employee> mp){
List<Employee> list = new ArrayList<>();
for (Employee employee : emps) {
if(mp.test(employee)){
list.add(employee);
}
}
return list;
}
//策略模式
//匿名内部类
@Test
public void test2(){
List<Employee> list =
filterEmployee(emps, new MyPredicate<Employee>() {
@Override
public boolean test(Employee employee) {
return employee.getSalary() > 5000;
}
});
for (Employee employee : list) {
System.out.println(employee);
}
}
//lambda表达式
@Test
public void test3(){
List<Employee> list =
filterEmployee(emps, employee -> employee.getSalary() > 5000);
for (Employee employee : list) {
System.out.println(employee);
}
}
@Test
public void test4(){
emps.stream()
.filter(employee -> employee.getSalary() > 5000)
.map(Employee::getSalary)
.sorted()
.forEach(System.out::println);
}
}
|
UTF-8
|
Java
| 2,136 |
java
|
TestPredicate.java
|
Java
|
[
{
"context": "s = Arrays.asList(\n new Employee(102, \"李四\", 59, 6666.66),\n new Employee(101, \"张三",
"end": 230,
"score": 0.9997605085372925,
"start": 228,
"tag": "NAME",
"value": "李四"
},
{
"context": "李四\", 59, 6666.66),\n new Employee(101, \"张三\", 18, 9999.99),\n new Employee(103, \"王五",
"end": 280,
"score": 0.999684751033783,
"start": 278,
"tag": "NAME",
"value": "张三"
},
{
"context": "张三\", 18, 9999.99),\n new Employee(103, \"王五\", 28, 3333.33),\n new Employee(104, \"赵六",
"end": 330,
"score": 0.9996178150177002,
"start": 328,
"tag": "NAME",
"value": "王五"
},
{
"context": "王五\", 28, 3333.33),\n new Employee(104, \"赵六\", 8, 7777.77),\n new Employee(104, \"赵六\"",
"end": 380,
"score": 0.9983227252960205,
"start": 378,
"tag": "NAME",
"value": "赵六"
},
{
"context": "\"赵六\", 8, 7777.77),\n new Employee(104, \"赵六\", 8, 7777.77),\n new Employee(104, \"赵六\"",
"end": 429,
"score": 0.9983951449394226,
"start": 427,
"tag": "NAME",
"value": "赵六"
},
{
"context": "\"赵六\", 8, 7777.77),\n new Employee(104, \"赵六\", 8, 7777.77),\n new Employee(105, \"田七\"",
"end": 478,
"score": 0.9981825351715088,
"start": 476,
"tag": "NAME",
"value": "赵六"
},
{
"context": "\"赵六\", 8, 7777.77),\n new Employee(105, \"田七\", 38, 5555.55)\n );\n// 需求:获取公司中工资大于 5000 的员工",
"end": 527,
"score": 0.9988734126091003,
"start": 525,
"tag": "NAME",
"value": "田七"
}
] | null |
[] |
package com.fhzc.stream;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TestPredicate {
List<Employee> emps = Arrays.asList(
new Employee(102, "李四", 59, 6666.66),
new Employee(101, "张三", 18, 9999.99),
new Employee(103, "王五", 28, 3333.33),
new Employee(104, "赵六", 8, 7777.77),
new Employee(104, "赵六", 8, 7777.77),
new Employee(104, "赵六", 8, 7777.77),
new Employee(105, "田七", 38, 5555.55)
);
// 需求:获取公司中工资大于 5000 的员工信息
@Test
public void test1(){
List<Employee> list = new ArrayList<>();
for (Employee emp : emps) {
if (emp.getSalary() > 5000) {
list.add(emp);
}
}
System.out.println(list);
}
public List<Employee> filterEmployee(List<Employee> emps, MyPredicate<Employee> mp){
List<Employee> list = new ArrayList<>();
for (Employee employee : emps) {
if(mp.test(employee)){
list.add(employee);
}
}
return list;
}
//策略模式
//匿名内部类
@Test
public void test2(){
List<Employee> list =
filterEmployee(emps, new MyPredicate<Employee>() {
@Override
public boolean test(Employee employee) {
return employee.getSalary() > 5000;
}
});
for (Employee employee : list) {
System.out.println(employee);
}
}
//lambda表达式
@Test
public void test3(){
List<Employee> list =
filterEmployee(emps, employee -> employee.getSalary() > 5000);
for (Employee employee : list) {
System.out.println(employee);
}
}
@Test
public void test4(){
emps.stream()
.filter(employee -> employee.getSalary() > 5000)
.map(Employee::getSalary)
.sorted()
.forEach(System.out::println);
}
}
| 2,136 | 0.517073 | 0.469268 | 77 | 25.623377 | 19.836369 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.623377 | false | false |
10
|
df4442ecb92a6f90909e53b1c0eafb719dbfee64
| 25,202,868,121,933 |
dc83ad32419999b5c2122dd215c3cfa408171e91
|
/精灵1/src/com/kikyou/spirit/GameLayer.java
|
44002f5e71d58a2b3239a069f858b57ccc3df1bd
|
[] |
no_license
|
Kikyou645559030/AndroidApp
|
https://github.com/Kikyou645559030/AndroidApp
|
bbc55b33a846a0565603b3a5722e09945ccab25a
|
fa832597828572962ff613836e10df0b648c209e
|
refs/heads/master
| 2021-01-22T09:33:24.754000 | 2015-07-15T10:08:41 | 2015-07-15T10:08:41 | 38,040,530 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.kikyou.spirit;
import org.cocos2d.actions.interval.CCJumpBy;
import org.cocos2d.actions.interval.CCMoveBy;
import org.cocos2d.layers.CCLayer;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.types.CGPoint;
/**
* 布景层-向量的计算
* Created by Liu_Zhichao on 2014/12/1 0001.
*/
public class GameLayer extends CCLayer{
/**
* 精灵
*/
CCSprite sprite1;
CCSprite sprite2;
/**
* 初始化精灵
*/
public GameLayer(){
sprite1 = CCSprite.sprite("player.png");
sprite2 = CCSprite.sprite("player.png");
this.addChild(sprite1);
this.addChild(sprite2);
CGPoint point = CGPoint.ccp(200,400);
sprite1.setPosition(point);
sprite2.setPosition(point);
/**
* CCMoveBy表示的是从原来的位置移动多少向量,是在原来的坐标基础上移动,就是
* CCMoveTo表示从当前位置移动到指定的位置(坐标)
*/
CGPoint targetPoint = CGPoint.ccp(100,100);
CCMoveBy moveBy = CCMoveBy.action(1,targetPoint);
sprite1.runAction(moveBy);
CGPoint jumpPoint = CGPoint.ccp(100,200);
CCJumpBy jumpBy = CCJumpBy.action(3,jumpPoint,300,4);
sprite2.runAction(jumpBy);
/*
CGPoint point1 = CGPoint.ccp(0,200);
//向量的加法运算
CGPoint addPoint = CGPoint.ccpAdd(point,point1);
sprite1.setPosition(addPoint);
CGPoint point2 = CGPoint.ccp(0,300);
//向量的减法运算
CGPoint subPoint = CGPoint.ccpSub(addPoint,point2);
sprite1.setPosition(subPoint);
//向量的乘法运算,除法运算就是乘以小数
CGPoint multPoint = CGPoint.ccpMult(subPoint,2);
sprite1.setPosition(multPoint);
//计算单位向量
CGPoint newPoint = CGPoint.ccpNormalize(point);
sprite2.setPosition(newPoint);*/
}
}
|
UTF-8
|
Java
| 1,711 |
java
|
GameLayer.java
|
Java
|
[
{
"context": "s2d.types.CGPoint;\n\n/**\n * 布景层-向量的计算\n * Created by Liu_Zhichao on 2014/12/1 0001.\n */\npublic class Game",
"end": 258,
"score": 0.8160303831100464,
"start": 256,
"tag": "USERNAME",
"value": "Li"
},
{
"context": ".types.CGPoint;\n\n/**\n * 布景层-向量的计算\n * Created by Liu_Zhichao on 2014/12/1 0001.\n */\npublic class GameL",
"end": 259,
"score": 0.6981498003005981,
"start": 258,
"tag": "NAME",
"value": "u"
},
{
"context": "types.CGPoint;\n\n/**\n * 布景层-向量的计算\n * Created by Liu_Zhichao on 2014/12/1 0001.\n */\npublic class GameLa",
"end": 259,
"score": 0.6644272804260254,
"start": 259,
"tag": "USERNAME",
"value": ""
},
{
"context": "ypes.CGPoint;\n\n/**\n * 布景层-向量的计算\n * Created by Liu_Zhichao on 2014/12/1 0001.\n */\npublic class GameLayer ext",
"end": 267,
"score": 0.9130325317382812,
"start": 260,
"tag": "NAME",
"value": "Zhichao"
}
] | null |
[] |
package com.kikyou.spirit;
import org.cocos2d.actions.interval.CCJumpBy;
import org.cocos2d.actions.interval.CCMoveBy;
import org.cocos2d.layers.CCLayer;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.types.CGPoint;
/**
* 布景层-向量的计算
* Created by Liu_Zhichao on 2014/12/1 0001.
*/
public class GameLayer extends CCLayer{
/**
* 精灵
*/
CCSprite sprite1;
CCSprite sprite2;
/**
* 初始化精灵
*/
public GameLayer(){
sprite1 = CCSprite.sprite("player.png");
sprite2 = CCSprite.sprite("player.png");
this.addChild(sprite1);
this.addChild(sprite2);
CGPoint point = CGPoint.ccp(200,400);
sprite1.setPosition(point);
sprite2.setPosition(point);
/**
* CCMoveBy表示的是从原来的位置移动多少向量,是在原来的坐标基础上移动,就是
* CCMoveTo表示从当前位置移动到指定的位置(坐标)
*/
CGPoint targetPoint = CGPoint.ccp(100,100);
CCMoveBy moveBy = CCMoveBy.action(1,targetPoint);
sprite1.runAction(moveBy);
CGPoint jumpPoint = CGPoint.ccp(100,200);
CCJumpBy jumpBy = CCJumpBy.action(3,jumpPoint,300,4);
sprite2.runAction(jumpBy);
/*
CGPoint point1 = CGPoint.ccp(0,200);
//向量的加法运算
CGPoint addPoint = CGPoint.ccpAdd(point,point1);
sprite1.setPosition(addPoint);
CGPoint point2 = CGPoint.ccp(0,300);
//向量的减法运算
CGPoint subPoint = CGPoint.ccpSub(addPoint,point2);
sprite1.setPosition(subPoint);
//向量的乘法运算,除法运算就是乘以小数
CGPoint multPoint = CGPoint.ccpMult(subPoint,2);
sprite1.setPosition(multPoint);
//计算单位向量
CGPoint newPoint = CGPoint.ccpNormalize(point);
sprite2.setPosition(newPoint);*/
}
}
| 1,711 | 0.725946 | 0.681486 | 64 | 22.546875 | 18.03896 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.828125 | false | false |
10
|
55af9044093f20b9182ffcd36320262df03e88b3
| 21,741,124,496,554 |
1c30efa3180f5a4fcba99c12b55d92b6f5bf6333
|
/src/main/java/generated/wlyjt/czknj/nxbdo/wxict/ixrvd/Class002102.java
|
38f86ca838c7b7e8587bd777e85fab2243e40bf0
|
[] |
no_license
|
mojira/MojirAI.git
|
https://github.com/mojira/MojirAI.git
|
e4adc643511d943620e364ce46719bd02392484d
|
5934d64874e54fddabb16826dfb5af397988825c
|
refs/heads/main
| 2021-06-09T15:12:12.938000 | 2021-04-01T21:30:16 | 2021-04-01T21:30:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package generated.wlyjt.czknj.nxbdo.wxict.ixrvd;
import helpers.Config;
import helpers.Context;
import helpers.BullshifierException;
import java.util.*;
import java.util.logging.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.text.SimpleDateFormat;
public class Class002102
{
public static final Logger logger = LoggerFactory.getLogger(Class002102.class);
public static final int classId = 2102;
public static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
public static void method000(Context context) throws Exception
{
int methodId = 0;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 2102, 0);
// Start of fake locals generator
Set<Object> root = new HashSet<Object>();
boolean valZbbyqivsccd = true;
root.add(valZbbyqivsccd);
int valDdadvcpzgiy = 101;
root.add(valDdadvcpzgiy);
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class002102.method000 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class002102.method000 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method000MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method000MethodToCall)
{
case (0): generated.rlpmt.lplho.gpmrf.giykp.wopwf.Class008108.method003(context); return;
case (1): generated.gvmrx.uexhr.zvoqc.mmgwt.nntop.Class009484.method000(context); return;
case (2): generated.mypch.bsiqe.hfnok.vootg.jesmf.Class003108.method005(context); return;
case (3): generated.aghot.ytokc.udhgt.evwwm.ljcbt.Class001539.method005(context); return;
case (4): generated.mcrok.ovjkt.ffvny.ywlsg.xoypv.Class006132.method001(context); return;
case (5): generated.aryqf.fceyr.qwchn.xskdi.dynsu.Class005480.method002(context); return;
case (6): generated.qitbf.tmnuk.kjezh.nwrwk.bwiyy.Class008650.method003(context); return;
case (7): generated.wfmtq.mqzdo.lhqhu.nmtqp.kkxdi.Class009914.method007(context); return;
case (8): generated.zcofn.uuueg.ckukr.usgmc.drvcc.Class008730.method005(context); return;
case (9): generated.tjxjm.oayhz.crvmu.sarmu.syieb.Class006700.method000(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method001(Context context) throws Exception
{
int methodId = 1;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 2102, 1);
// Start of fake locals generator
Map<Object, Object> root = new HashMap();
boolean mapValKeafqkejcxc = false;
boolean mapKeyDbucvqxcqcw = true;
root.put("mapValKeafqkejcxc","mapKeyDbucvqxcqcw" );
int mapValBgdefaschmp = 547;
long mapKeyKnvniahtlqt = 4188442117699818462L;
root.put("mapValBgdefaschmp","mapKeyKnvniahtlqt" );
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class002102.method001 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class002102.method001 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method001MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method001MethodToCall)
{
case (0): generated.sdsbd.vuzay.wggeh.lerya.aaknh.Class008824.method002(context); return;
case (1): generated.eqpfc.hxukm.mbjpz.aldcx.iibgb.Class005266.method004(context); return;
case (2): generated.dhdrq.fhdjw.cvwmp.eqepo.jgccb.Class001847.method000(context); return;
case (3): generated.ihjsl.kfqhx.euoyc.lpldu.pdkqr.Class007086.method006(context); return;
case (4): generated.mkatg.ykccs.ezuil.qbozx.wemmd.Class000947.method002(context); return;
case (5): generated.vxgyn.jbmkv.hhmzn.xveun.eeeno.Class009715.method006(context); return;
case (6): generated.qoqwv.wngrf.hpnyh.iiwuw.adizq.Class009088.method003(context); return;
case (7): generated.vjetl.jzxvv.oizsa.ujayk.jyled.Class000751.method005(context); return;
case (8): generated.vxfoc.yteiy.wwhea.vqfsx.bywca.Class000665.method009(context); return;
case (9): generated.froqi.kwzqp.hxnvl.vzpqh.yuzlt.Class004573.method007(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method002(Context context) throws Exception
{
int methodId = 2;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 2102, 2);
// Start of fake locals generator
Object[] root = new Object[2];
int valGhtxkifglmd = 778;
root[0] = valGhtxkifglmd;
for (int i = 1; i < 2; i++)
{
root[i] = Config.get().getRandom().nextInt(1000);
}
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class002102.method002 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class002102.method002 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method002MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method002MethodToCall)
{
case (0): generated.xlhdh.fgyyz.xtbtv.grqof.yajww.Class000194.method002(context); return;
case (1): generated.vhhxs.cvwmf.ighco.uhaph.nqenw.Class009400.method009(context); return;
case (2): generated.fcdjo.ksafz.llyis.vinid.wndvz.Class009677.method006(context); return;
case (3): generated.zpajo.azjsc.ptorx.emskj.dugtj.Class003396.method004(context); return;
case (4): generated.vmgdz.lrldb.hfuqo.obano.evccu.Class002070.method005(context); return;
case (5): generated.gdlsz.uncnu.lxldv.wsvuz.tzxhy.Class008073.method003(context); return;
case (6): generated.crjxw.ayydm.ugcgc.opvyt.ichzo.Class004904.method006(context); return;
case (7): generated.ffxro.awqqf.ruidg.idxvp.viyrv.Class007212.method009(context); return;
case (8): generated.wjjae.bsbdj.clorm.dhuxx.sgvtw.Class002886.method006(context); return;
case (9): generated.wlgql.okzvo.sarix.hktfs.mxyyn.Class003275.method000(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method003(Context context) throws Exception
{
int methodId = 3;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 2102, 3);
// Start of fake locals generator
Map<Object, Object> root = new HashMap();
String mapValHitefcfcoqm = "StrBgnqubgcpwt";
long mapKeyDtkboemkcxr = 9017545038932032496L;
root.put("mapValHitefcfcoqm","mapKeyDtkboemkcxr" );
int mapValYxhtobjraph = 634;
int mapKeyHwaehfriyiq = 298;
root.put("mapValYxhtobjraph","mapKeyHwaehfriyiq" );
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class002102.method003 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class002102.method003 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method003MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method003MethodToCall)
{
case (0): generated.iuiuv.gnydo.dxdzg.lxzsc.pxbsd.Class000422.method002(context); return;
case (1): generated.msqsy.mpywa.lggnl.bckqk.wuckg.Class004034.method005(context); return;
case (2): generated.ixyia.opvnt.bkiir.ffuvk.uqmdj.Class008001.method004(context); return;
case (3): generated.pifpv.jxehi.vtvdi.drmxi.rcvrr.Class006363.method000(context); return;
case (4): generated.sugci.nhybv.tueid.rddvl.ztbtd.Class004711.method002(context); return;
case (5): generated.pkuzv.shrpc.psgrl.qexsi.wpvfv.Class001938.method008(context); return;
case (6): generated.epfqk.cgpfo.ixxfz.crwli.wkdxg.Class001444.method008(context); return;
case (7): generated.cflst.ehhmd.nfgty.vnnjf.budtk.Class006216.method005(context); return;
case (8): generated.amcty.xkgpx.dqwzv.vywne.vlyxt.Class001243.method002(context); return;
case (9): generated.iofwl.kskof.dwnig.xybqv.qeqcm.Class002370.method009(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method004(Context context) throws Exception
{
int methodId = 4;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 2102, 4);
// Start of fake locals generator
List<Object> root = new LinkedList<Object>();
boolean valGxdxcasacgo = false;
root.add(valGxdxcasacgo);
int valRfeyteqfifh = 339;
root.add(valRfeyteqfifh);
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class002102.method004 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class002102.method004 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method004MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method004MethodToCall)
{
case (0): generated.shqzh.wuzis.rvnoa.clqfm.sxdsr.Class003366.method007(context); return;
case (1): generated.ydfey.jowfu.oumnm.bjqxj.eluwr.Class006608.method002(context); return;
case (2): generated.xtsaa.usudb.bthko.hhoar.rbsgp.Class008043.method006(context); return;
case (3): generated.sfkod.xuisd.xcbdw.fejvp.jgtee.Class002893.method000(context); return;
case (4): generated.iuvog.oxaox.hxmgv.xwoxi.omrmr.Class002089.method005(context); return;
case (5): generated.kmiij.phhxn.wamro.cbspq.xmtrt.Class006498.method004(context); return;
case (6): generated.hbazj.ntoyh.gasjh.yhppv.pihyp.Class004745.method001(context); return;
case (7): generated.utlvz.ciovt.ckcmj.tavls.navhg.Class002194.method002(context); return;
case (8): generated.plprp.myxhc.rkqpl.gbumu.rbama.Class004495.method006(context); return;
case (9): generated.ivkba.ivjkb.tbnru.qlnhy.lupci.Class006299.method003(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method005(Context context) throws Exception
{
int methodId = 5;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 2102, 5);
// Start of fake locals generator
Map<Object, Object> root = new HashMap();
int mapValEocfikipkqz = 146;
int mapKeyNcvfcdmpqzz = 315;
root.put("mapValEocfikipkqz","mapKeyNcvfcdmpqzz" );
String mapValStkguohoxaw = "StrWjsweaspvjw";
int mapKeyPlhzhqgauru = 403;
root.put("mapValStkguohoxaw","mapKeyPlhzhqgauru" );
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class002102.method005 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class002102.method005 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method005MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method005MethodToCall)
{
case (0): generated.momli.oxzic.czkxr.zeygn.qahgc.Class001327.method000(context); return;
case (1): generated.ryvnm.jjdjs.irmqb.jifzb.sjzlr.Class006558.method007(context); return;
case (2): generated.bvbhu.iqxys.wgzpi.ivzdn.kcgxb.Class001183.method006(context); return;
case (3): generated.vdxlo.flopr.fkeze.chzai.iyotg.Class004975.method001(context); return;
case (4): generated.smmex.undgm.mplsk.izjxk.egnwo.Class006481.method009(context); return;
case (5): generated.qegce.xfjkz.oxpga.zdarj.hgwzz.Class006280.method004(context); return;
case (6): generated.sqqct.umkpo.anneg.xszkp.yjvpa.Class006958.method000(context); return;
case (7): generated.atnyj.qruoo.bgjxi.csiga.heyve.Class008854.method003(context); return;
case (8): generated.xkxbz.rpkyj.zxdlk.fhfku.ashay.Class000969.method004(context); return;
case (9): generated.tvihh.kkfub.uwqmv.nrcgk.lgxmw.Class004809.method003(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method006(Context context) throws Exception
{
int methodId = 6;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 2102, 6);
// Start of fake locals generator
Map<Object, Object> root = new HashMap();
long mapValNhrzcemzkhh = -5908662913819155299L;
String mapKeyDeikvyyssjm = "StrTncqryevixb";
root.put("mapValNhrzcemzkhh","mapKeyDeikvyyssjm" );
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class002102.method006 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class002102.method006 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method006MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method006MethodToCall)
{
case (0): generated.wfptx.rhjom.hqknh.ypwme.txiss.Class006389.method008(context); return;
case (1): generated.pjhan.kjyqd.tyfnr.xwvhe.hxqbo.Class001982.method001(context); return;
case (2): generated.rkwge.xcohq.accuw.chpof.jrbut.Class009441.method007(context); return;
case (3): generated.xukde.qdadi.utwng.azdyw.pujeb.Class002844.method001(context); return;
case (4): generated.luxpz.qifmg.dcfhi.ykyhq.iwbrz.Class003983.method009(context); return;
case (5): generated.lxhug.szqhz.mlytn.ifvpa.prmel.Class006660.method009(context); return;
case (6): generated.jkgdv.vosen.extij.zvfqa.lckek.Class004292.method002(context); return;
case (7): generated.qzgcu.raeqh.abbqd.nqedk.zwhht.Class005305.method005(context); return;
case (8): generated.prnns.pfvfp.krdsy.uwtld.sgutk.Class007036.method006(context); return;
case (9): generated.xjxns.mbqnj.tlujn.msovq.ibblu.Class007996.method006(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method007(Context context) throws Exception
{
int methodId = 7;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 2102, 7);
// Start of fake locals generator
Object[] root = new Object[4];
long valHpwwidkvuyj = 6617135366264693821L;
root[0] = valHpwwidkvuyj;
for (int i = 1; i < 4; i++)
{
root[i] = Config.get().getRandom().nextInt(1000);
}
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class002102.method007 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class002102.method007 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method007MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method007MethodToCall)
{
case (0): generated.ibcss.qmpnr.himpa.adydd.unlxk.Class002573.method009(context); return;
case (1): generated.nmmjv.tqxzh.doxhd.epvmn.pjqzc.Class008816.method001(context); return;
case (2): generated.xpqjz.avdzp.cmeeo.abftw.jrpie.Class003832.method005(context); return;
case (3): generated.obbaq.tlann.pwmgk.qcrvi.sbbos.Class005079.method002(context); return;
case (4): generated.aoqbj.dsnsg.klklp.udqiv.wbohw.Class007218.method006(context); return;
case (5): generated.emlui.vcqwr.cmrsi.rrxda.ijnni.Class009319.method006(context); return;
case (6): generated.rmqxf.elwzo.xqahp.lyadz.aeyce.Class007824.method001(context); return;
case (7): generated.bqqfh.abfdx.xrvaf.layge.hagog.Class002384.method008(context); return;
case (8): generated.cflst.ehhmd.nfgty.vnnjf.budtk.Class006216.method000(context); return;
case (9): generated.dheyj.pphha.obtvc.gxpvu.mrfpl.Class002232.method009(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method008(Context context) throws Exception
{
int methodId = 8;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 2102, 8);
// Start of fake locals generator
List<Object> root = new LinkedList<Object>();
int valQytrdnqwell = 462;
root.add(valQytrdnqwell);
String valKjuduwbfjkz = "StrWfrvoetpmjv";
root.add(valKjuduwbfjkz);
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class002102.method008 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class002102.method008 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method008MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method008MethodToCall)
{
case (0): generated.dagfl.qubwq.jkqtw.tpjcf.hxfjy.Class003881.method003(context); return;
case (1): generated.seefz.ptwmp.blrdw.frfvd.izhrd.Class009126.method009(context); return;
case (2): generated.ownib.ghlux.mecyc.phkrc.bteqk.Class009820.method000(context); return;
case (3): generated.zqxep.qwrma.oelnk.mbvto.qnldc.Class006265.method003(context); return;
case (4): generated.nkpzx.acehj.amnul.nsqoh.dzigc.Class005506.method008(context); return;
case (5): generated.mwdlr.urxky.hnsoh.snuie.kaiyv.Class005714.method004(context); return;
case (6): generated.xgtku.emhep.zubkd.tpdpq.uiepf.Class003935.method006(context); return;
case (7): generated.metry.npsxq.idyvw.gfbrr.pudzr.Class004355.method001(context); return;
case (8): generated.gxdbk.clcun.kmlym.axvrr.pcdfa.Class008385.method003(context); return;
case (9): generated.mapkq.xqasn.kkcid.conov.cgakp.Class006266.method000(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method009(Context context) throws Exception
{
int methodId = 9;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 2102, 9);
// Start of fake locals generator
Map<Object, Object> root = new HashMap();
long mapValEdrnvysjxpu = 7430313492284377625L;
long mapKeyTwfinmwrvcc = 7821265693434104518L;
root.put("mapValEdrnvysjxpu","mapKeyTwfinmwrvcc" );
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class002102.method009 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class002102.method009 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method009MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method009MethodToCall)
{
case (0): generated.aatng.hzwmb.ovdnd.btkrb.zeeqq.Class000908.method006(context); return;
case (1): generated.tdkfj.lchcb.byjsq.mabch.ocqkz.Class000456.method002(context); return;
case (2): generated.lsgio.dmbyx.nkxmd.sdedo.vjzpg.Class007154.method009(context); return;
case (3): generated.eeekg.nksqq.cwznv.bpsdh.iekqu.Class003689.method002(context); return;
case (4): generated.dvrhh.mvftm.kliga.kotpn.gvjml.Class000889.method001(context); return;
case (5): generated.hbrqn.dnuwm.kaxjc.lylku.hlfqw.Class002503.method003(context); return;
case (6): generated.szdbi.rdrjr.mzhqx.oqwtu.oseva.Class009381.method001(context); return;
case (7): generated.ovpug.ahmkf.sfvur.ezdpr.muiny.Class005087.method008(context); return;
case (8): generated.zcuzq.vbxlp.vbcpw.hpxti.yvrhk.Class006831.method005(context); return;
case (9): generated.kwugr.vznow.udvsb.vkwhz.jednd.Class002775.method008(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
}
|
UTF-8
|
Java
| 34,170 |
java
|
Class002102.java
|
Java
|
[
{
"context": "= \"StrBgnqubgcpwt\";\n\t\t\n\t\tlong mapKeyDtkboemkcxr = 9017545038932032496L;\n\t\t\n\t\troot.put(\"mapValHitefcfcoqm\",\"mapKeyDtkboem",
"end": 11021,
"score": 0.9804520606994629,
"start": 11001,
"tag": "KEY",
"value": "9017545038932032496L"
},
{
"context": "62913819155299L;\n\t\t\n\t\tString mapKeyDeikvyyssjm = \"StrTncqryevixb\";\n\t\t\n\t\troot.put(\"mapValNhrzcemzkhh\",\"mapKeyDeikvy",
"end": 21224,
"score": 0.8396108150482178,
"start": 21210,
"tag": "KEY",
"value": "StrTncqryevixb"
}
] | null |
[] |
package generated.wlyjt.czknj.nxbdo.wxict.ixrvd;
import helpers.Config;
import helpers.Context;
import helpers.BullshifierException;
import java.util.*;
import java.util.logging.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.text.SimpleDateFormat;
public class Class002102
{
public static final Logger logger = LoggerFactory.getLogger(Class002102.class);
public static final int classId = 2102;
public static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
public static void method000(Context context) throws Exception
{
int methodId = 0;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 2102, 0);
// Start of fake locals generator
Set<Object> root = new HashSet<Object>();
boolean valZbbyqivsccd = true;
root.add(valZbbyqivsccd);
int valDdadvcpzgiy = 101;
root.add(valDdadvcpzgiy);
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class002102.method000 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class002102.method000 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method000MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method000MethodToCall)
{
case (0): generated.rlpmt.lplho.gpmrf.giykp.wopwf.Class008108.method003(context); return;
case (1): generated.gvmrx.uexhr.zvoqc.mmgwt.nntop.Class009484.method000(context); return;
case (2): generated.mypch.bsiqe.hfnok.vootg.jesmf.Class003108.method005(context); return;
case (3): generated.aghot.ytokc.udhgt.evwwm.ljcbt.Class001539.method005(context); return;
case (4): generated.mcrok.ovjkt.ffvny.ywlsg.xoypv.Class006132.method001(context); return;
case (5): generated.aryqf.fceyr.qwchn.xskdi.dynsu.Class005480.method002(context); return;
case (6): generated.qitbf.tmnuk.kjezh.nwrwk.bwiyy.Class008650.method003(context); return;
case (7): generated.wfmtq.mqzdo.lhqhu.nmtqp.kkxdi.Class009914.method007(context); return;
case (8): generated.zcofn.uuueg.ckukr.usgmc.drvcc.Class008730.method005(context); return;
case (9): generated.tjxjm.oayhz.crvmu.sarmu.syieb.Class006700.method000(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method001(Context context) throws Exception
{
int methodId = 1;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 2102, 1);
// Start of fake locals generator
Map<Object, Object> root = new HashMap();
boolean mapValKeafqkejcxc = false;
boolean mapKeyDbucvqxcqcw = true;
root.put("mapValKeafqkejcxc","mapKeyDbucvqxcqcw" );
int mapValBgdefaschmp = 547;
long mapKeyKnvniahtlqt = 4188442117699818462L;
root.put("mapValBgdefaschmp","mapKeyKnvniahtlqt" );
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class002102.method001 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class002102.method001 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method001MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method001MethodToCall)
{
case (0): generated.sdsbd.vuzay.wggeh.lerya.aaknh.Class008824.method002(context); return;
case (1): generated.eqpfc.hxukm.mbjpz.aldcx.iibgb.Class005266.method004(context); return;
case (2): generated.dhdrq.fhdjw.cvwmp.eqepo.jgccb.Class001847.method000(context); return;
case (3): generated.ihjsl.kfqhx.euoyc.lpldu.pdkqr.Class007086.method006(context); return;
case (4): generated.mkatg.ykccs.ezuil.qbozx.wemmd.Class000947.method002(context); return;
case (5): generated.vxgyn.jbmkv.hhmzn.xveun.eeeno.Class009715.method006(context); return;
case (6): generated.qoqwv.wngrf.hpnyh.iiwuw.adizq.Class009088.method003(context); return;
case (7): generated.vjetl.jzxvv.oizsa.ujayk.jyled.Class000751.method005(context); return;
case (8): generated.vxfoc.yteiy.wwhea.vqfsx.bywca.Class000665.method009(context); return;
case (9): generated.froqi.kwzqp.hxnvl.vzpqh.yuzlt.Class004573.method007(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method002(Context context) throws Exception
{
int methodId = 2;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 2102, 2);
// Start of fake locals generator
Object[] root = new Object[2];
int valGhtxkifglmd = 778;
root[0] = valGhtxkifglmd;
for (int i = 1; i < 2; i++)
{
root[i] = Config.get().getRandom().nextInt(1000);
}
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class002102.method002 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class002102.method002 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method002MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method002MethodToCall)
{
case (0): generated.xlhdh.fgyyz.xtbtv.grqof.yajww.Class000194.method002(context); return;
case (1): generated.vhhxs.cvwmf.ighco.uhaph.nqenw.Class009400.method009(context); return;
case (2): generated.fcdjo.ksafz.llyis.vinid.wndvz.Class009677.method006(context); return;
case (3): generated.zpajo.azjsc.ptorx.emskj.dugtj.Class003396.method004(context); return;
case (4): generated.vmgdz.lrldb.hfuqo.obano.evccu.Class002070.method005(context); return;
case (5): generated.gdlsz.uncnu.lxldv.wsvuz.tzxhy.Class008073.method003(context); return;
case (6): generated.crjxw.ayydm.ugcgc.opvyt.ichzo.Class004904.method006(context); return;
case (7): generated.ffxro.awqqf.ruidg.idxvp.viyrv.Class007212.method009(context); return;
case (8): generated.wjjae.bsbdj.clorm.dhuxx.sgvtw.Class002886.method006(context); return;
case (9): generated.wlgql.okzvo.sarix.hktfs.mxyyn.Class003275.method000(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method003(Context context) throws Exception
{
int methodId = 3;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 2102, 3);
// Start of fake locals generator
Map<Object, Object> root = new HashMap();
String mapValHitefcfcoqm = "StrBgnqubgcpwt";
long mapKeyDtkboemkcxr = 9017545038932032496L;
root.put("mapValHitefcfcoqm","mapKeyDtkboemkcxr" );
int mapValYxhtobjraph = 634;
int mapKeyHwaehfriyiq = 298;
root.put("mapValYxhtobjraph","mapKeyHwaehfriyiq" );
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class002102.method003 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class002102.method003 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method003MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method003MethodToCall)
{
case (0): generated.iuiuv.gnydo.dxdzg.lxzsc.pxbsd.Class000422.method002(context); return;
case (1): generated.msqsy.mpywa.lggnl.bckqk.wuckg.Class004034.method005(context); return;
case (2): generated.ixyia.opvnt.bkiir.ffuvk.uqmdj.Class008001.method004(context); return;
case (3): generated.pifpv.jxehi.vtvdi.drmxi.rcvrr.Class006363.method000(context); return;
case (4): generated.sugci.nhybv.tueid.rddvl.ztbtd.Class004711.method002(context); return;
case (5): generated.pkuzv.shrpc.psgrl.qexsi.wpvfv.Class001938.method008(context); return;
case (6): generated.epfqk.cgpfo.ixxfz.crwli.wkdxg.Class001444.method008(context); return;
case (7): generated.cflst.ehhmd.nfgty.vnnjf.budtk.Class006216.method005(context); return;
case (8): generated.amcty.xkgpx.dqwzv.vywne.vlyxt.Class001243.method002(context); return;
case (9): generated.iofwl.kskof.dwnig.xybqv.qeqcm.Class002370.method009(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method004(Context context) throws Exception
{
int methodId = 4;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 2102, 4);
// Start of fake locals generator
List<Object> root = new LinkedList<Object>();
boolean valGxdxcasacgo = false;
root.add(valGxdxcasacgo);
int valRfeyteqfifh = 339;
root.add(valRfeyteqfifh);
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class002102.method004 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class002102.method004 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method004MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method004MethodToCall)
{
case (0): generated.shqzh.wuzis.rvnoa.clqfm.sxdsr.Class003366.method007(context); return;
case (1): generated.ydfey.jowfu.oumnm.bjqxj.eluwr.Class006608.method002(context); return;
case (2): generated.xtsaa.usudb.bthko.hhoar.rbsgp.Class008043.method006(context); return;
case (3): generated.sfkod.xuisd.xcbdw.fejvp.jgtee.Class002893.method000(context); return;
case (4): generated.iuvog.oxaox.hxmgv.xwoxi.omrmr.Class002089.method005(context); return;
case (5): generated.kmiij.phhxn.wamro.cbspq.xmtrt.Class006498.method004(context); return;
case (6): generated.hbazj.ntoyh.gasjh.yhppv.pihyp.Class004745.method001(context); return;
case (7): generated.utlvz.ciovt.ckcmj.tavls.navhg.Class002194.method002(context); return;
case (8): generated.plprp.myxhc.rkqpl.gbumu.rbama.Class004495.method006(context); return;
case (9): generated.ivkba.ivjkb.tbnru.qlnhy.lupci.Class006299.method003(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method005(Context context) throws Exception
{
int methodId = 5;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 2102, 5);
// Start of fake locals generator
Map<Object, Object> root = new HashMap();
int mapValEocfikipkqz = 146;
int mapKeyNcvfcdmpqzz = 315;
root.put("mapValEocfikipkqz","mapKeyNcvfcdmpqzz" );
String mapValStkguohoxaw = "StrWjsweaspvjw";
int mapKeyPlhzhqgauru = 403;
root.put("mapValStkguohoxaw","mapKeyPlhzhqgauru" );
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class002102.method005 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class002102.method005 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method005MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method005MethodToCall)
{
case (0): generated.momli.oxzic.czkxr.zeygn.qahgc.Class001327.method000(context); return;
case (1): generated.ryvnm.jjdjs.irmqb.jifzb.sjzlr.Class006558.method007(context); return;
case (2): generated.bvbhu.iqxys.wgzpi.ivzdn.kcgxb.Class001183.method006(context); return;
case (3): generated.vdxlo.flopr.fkeze.chzai.iyotg.Class004975.method001(context); return;
case (4): generated.smmex.undgm.mplsk.izjxk.egnwo.Class006481.method009(context); return;
case (5): generated.qegce.xfjkz.oxpga.zdarj.hgwzz.Class006280.method004(context); return;
case (6): generated.sqqct.umkpo.anneg.xszkp.yjvpa.Class006958.method000(context); return;
case (7): generated.atnyj.qruoo.bgjxi.csiga.heyve.Class008854.method003(context); return;
case (8): generated.xkxbz.rpkyj.zxdlk.fhfku.ashay.Class000969.method004(context); return;
case (9): generated.tvihh.kkfub.uwqmv.nrcgk.lgxmw.Class004809.method003(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method006(Context context) throws Exception
{
int methodId = 6;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 2102, 6);
// Start of fake locals generator
Map<Object, Object> root = new HashMap();
long mapValNhrzcemzkhh = -5908662913819155299L;
String mapKeyDeikvyyssjm = "<KEY>";
root.put("mapValNhrzcemzkhh","mapKeyDeikvyyssjm" );
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class002102.method006 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class002102.method006 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method006MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method006MethodToCall)
{
case (0): generated.wfptx.rhjom.hqknh.ypwme.txiss.Class006389.method008(context); return;
case (1): generated.pjhan.kjyqd.tyfnr.xwvhe.hxqbo.Class001982.method001(context); return;
case (2): generated.rkwge.xcohq.accuw.chpof.jrbut.Class009441.method007(context); return;
case (3): generated.xukde.qdadi.utwng.azdyw.pujeb.Class002844.method001(context); return;
case (4): generated.luxpz.qifmg.dcfhi.ykyhq.iwbrz.Class003983.method009(context); return;
case (5): generated.lxhug.szqhz.mlytn.ifvpa.prmel.Class006660.method009(context); return;
case (6): generated.jkgdv.vosen.extij.zvfqa.lckek.Class004292.method002(context); return;
case (7): generated.qzgcu.raeqh.abbqd.nqedk.zwhht.Class005305.method005(context); return;
case (8): generated.prnns.pfvfp.krdsy.uwtld.sgutk.Class007036.method006(context); return;
case (9): generated.xjxns.mbqnj.tlujn.msovq.ibblu.Class007996.method006(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method007(Context context) throws Exception
{
int methodId = 7;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 2102, 7);
// Start of fake locals generator
Object[] root = new Object[4];
long valHpwwidkvuyj = 6617135366264693821L;
root[0] = valHpwwidkvuyj;
for (int i = 1; i < 4; i++)
{
root[i] = Config.get().getRandom().nextInt(1000);
}
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class002102.method007 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class002102.method007 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method007MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method007MethodToCall)
{
case (0): generated.ibcss.qmpnr.himpa.adydd.unlxk.Class002573.method009(context); return;
case (1): generated.nmmjv.tqxzh.doxhd.epvmn.pjqzc.Class008816.method001(context); return;
case (2): generated.xpqjz.avdzp.cmeeo.abftw.jrpie.Class003832.method005(context); return;
case (3): generated.obbaq.tlann.pwmgk.qcrvi.sbbos.Class005079.method002(context); return;
case (4): generated.aoqbj.dsnsg.klklp.udqiv.wbohw.Class007218.method006(context); return;
case (5): generated.emlui.vcqwr.cmrsi.rrxda.ijnni.Class009319.method006(context); return;
case (6): generated.rmqxf.elwzo.xqahp.lyadz.aeyce.Class007824.method001(context); return;
case (7): generated.bqqfh.abfdx.xrvaf.layge.hagog.Class002384.method008(context); return;
case (8): generated.cflst.ehhmd.nfgty.vnnjf.budtk.Class006216.method000(context); return;
case (9): generated.dheyj.pphha.obtvc.gxpvu.mrfpl.Class002232.method009(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method008(Context context) throws Exception
{
int methodId = 8;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 2102, 8);
// Start of fake locals generator
List<Object> root = new LinkedList<Object>();
int valQytrdnqwell = 462;
root.add(valQytrdnqwell);
String valKjuduwbfjkz = "StrWfrvoetpmjv";
root.add(valKjuduwbfjkz);
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class002102.method008 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class002102.method008 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method008MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method008MethodToCall)
{
case (0): generated.dagfl.qubwq.jkqtw.tpjcf.hxfjy.Class003881.method003(context); return;
case (1): generated.seefz.ptwmp.blrdw.frfvd.izhrd.Class009126.method009(context); return;
case (2): generated.ownib.ghlux.mecyc.phkrc.bteqk.Class009820.method000(context); return;
case (3): generated.zqxep.qwrma.oelnk.mbvto.qnldc.Class006265.method003(context); return;
case (4): generated.nkpzx.acehj.amnul.nsqoh.dzigc.Class005506.method008(context); return;
case (5): generated.mwdlr.urxky.hnsoh.snuie.kaiyv.Class005714.method004(context); return;
case (6): generated.xgtku.emhep.zubkd.tpdpq.uiepf.Class003935.method006(context); return;
case (7): generated.metry.npsxq.idyvw.gfbrr.pudzr.Class004355.method001(context); return;
case (8): generated.gxdbk.clcun.kmlym.axvrr.pcdfa.Class008385.method003(context); return;
case (9): generated.mapkq.xqasn.kkcid.conov.cgakp.Class006266.method000(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method009(Context context) throws Exception
{
int methodId = 9;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 2102, 9);
// Start of fake locals generator
Map<Object, Object> root = new HashMap();
long mapValEdrnvysjxpu = 7430313492284377625L;
long mapKeyTwfinmwrvcc = 7821265693434104518L;
root.put("mapValEdrnvysjxpu","mapKeyTwfinmwrvcc" );
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class002102.method009 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class002102.method009 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method009MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method009MethodToCall)
{
case (0): generated.aatng.hzwmb.ovdnd.btkrb.zeeqq.Class000908.method006(context); return;
case (1): generated.tdkfj.lchcb.byjsq.mabch.ocqkz.Class000456.method002(context); return;
case (2): generated.lsgio.dmbyx.nkxmd.sdedo.vjzpg.Class007154.method009(context); return;
case (3): generated.eeekg.nksqq.cwznv.bpsdh.iekqu.Class003689.method002(context); return;
case (4): generated.dvrhh.mvftm.kliga.kotpn.gvjml.Class000889.method001(context); return;
case (5): generated.hbrqn.dnuwm.kaxjc.lylku.hlfqw.Class002503.method003(context); return;
case (6): generated.szdbi.rdrjr.mzhqx.oqwtu.oseva.Class009381.method001(context); return;
case (7): generated.ovpug.ahmkf.sfvur.ezdpr.muiny.Class005087.method008(context); return;
case (8): generated.zcuzq.vbxlp.vbcpw.hpxti.yvrhk.Class006831.method005(context); return;
case (9): generated.kwugr.vznow.udvsb.vkwhz.jednd.Class002775.method008(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
}
| 34,161 | 0.714399 | 0.66851 | 1,022 | 32.434441 | 34.893677 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.014677 | false | false |
10
|
297b93568b67d00f5d5ffefab60fbd2720813316
| 7,567,732,411,303 |
01cf07f9e3a373bbdbc4c2936d5beed9f06df589
|
/src/Assignment_3_2.java
|
60dc53fb3c2be1ae73a77c3c7aba119ba068f77c
|
[] |
no_license
|
nguyendangtritoan/OOP_course
|
https://github.com/nguyendangtritoan/OOP_course
|
d57f1e20595ff1527e0b74ec73325a115756e03a
|
28b1792b79569d531b2076784f025decd6660c62
|
refs/heads/master
| 2022-03-26T10:42:15.165000 | 2019-12-09T17:03:43 | 2019-12-09T17:03:43 | 212,534,523 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.HashMap;
import java.util.Scanner;
public class Assignment_3_2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<Integer,Double> product = new HashMap<>();
Scanner sc = new Scanner(System.in);
product.put(1, 150.3);
product.put(2, 43.5);
product.put(3, 54.1);
product.put(50, 45.0);
product.put(100, 12.5);
do {
System.out.print("Give the product number to see price: ");
System.out.println("( To stop input 0 )");
int i = sc.nextInt();
if (i!=0) {
if(product.containsKey(i))
System.out.println(product.get(i));
else System.out.println("Not found");
}
else break;
}while (true);
}
}
|
UTF-8
|
Java
| 851 |
java
|
Assignment_3_2.java
|
Java
|
[] | null |
[] |
import java.util.HashMap;
import java.util.Scanner;
public class Assignment_3_2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<Integer,Double> product = new HashMap<>();
Scanner sc = new Scanner(System.in);
product.put(1, 150.3);
product.put(2, 43.5);
product.put(3, 54.1);
product.put(50, 45.0);
product.put(100, 12.5);
do {
System.out.print("Give the product number to see price: ");
System.out.println("( To stop input 0 )");
int i = sc.nextInt();
if (i!=0) {
if(product.containsKey(i))
System.out.println(product.get(i));
else System.out.println("Not found");
}
else break;
}while (true);
}
}
| 851 | 0.522914 | 0.490012 | 28 | 29.392857 | 18.773727 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.785714 | false | false |
10
|
ac99e740a60503788ea8ab7b5ebf4d8dabda544b
| 26,826,365,749,369 |
240e1ec3ee43b0c1cefdf2110b57985fab56948c
|
/app-spring/src/test/java/io/ibigdata/app/spring/introduce/TestIntroduce.java
|
c7a3af655795639601257ad600126c6a889ae851
|
[] |
no_license
|
zlj0123/ibigdata
|
https://github.com/zlj0123/ibigdata
|
10c827ab35bfea74357355f2fd377afec0ea2c2b
|
5d1176296b8366147bf233378b881813756061e2
|
refs/heads/master
| 2018-01-03T15:32:52.748000 | 2016-11-11T07:32:59 | 2016-11-11T07:32:59 | 71,433,713 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package io.ibigdata.app.spring.introduce;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestIntroduce {
@Test
public void testIntroduce() {
String configPath = "APPLICATION_INTRODUCE_BEAN.xml";
@SuppressWarnings("resource")
ApplicationContext ctx = new ClassPathXmlApplicationContext(configPath);
ForumService forumService = (ForumService)ctx.getBean("forumService");
forumService.removeForum(10);
forumService.removeTopic(1022);
Monitorable moniterable = (Monitorable)forumService;
moniterable.setMonitorActive(true);
forumService.removeForum(10);
forumService.removeTopic(1022);
}
}
|
UTF-8
|
Java
| 774 |
java
|
TestIntroduce.java
|
Java
|
[] | null |
[] |
package io.ibigdata.app.spring.introduce;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestIntroduce {
@Test
public void testIntroduce() {
String configPath = "APPLICATION_INTRODUCE_BEAN.xml";
@SuppressWarnings("resource")
ApplicationContext ctx = new ClassPathXmlApplicationContext(configPath);
ForumService forumService = (ForumService)ctx.getBean("forumService");
forumService.removeForum(10);
forumService.removeTopic(1022);
Monitorable moniterable = (Monitorable)forumService;
moniterable.setMonitorActive(true);
forumService.removeForum(10);
forumService.removeTopic(1022);
}
}
| 774 | 0.762274 | 0.74677 | 22 | 34.227272 | 24.646467 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.045455 | false | false |
10
|
18e3451de96ea7d1f367cd1d02b94afd4cc70810
| 30,975,304,172,734 |
0ef3e696ca0f6d88d921ed89ad626aa7f94897f3
|
/src/main/java/lionsmobile/com/MM6/MM6_1/MM6_04/MM6_04ServiceImpl.java
|
30fa9332bdbd85d0c9676142ee1e2f8b36f57072
|
[] |
no_license
|
pentium4/bokjuri
|
https://github.com/pentium4/bokjuri
|
3e70f1f0bf8c4f1537eac9f68b6990c9d0f09c83
|
2de175e625ca25cf822ee1bd4387a73f7d65657e
|
refs/heads/master
| 2021-01-12T07:58:27.245000 | 2017-01-14T09:43:03 | 2017-01-14T09:43:03 | 77,064,836 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package lionsmobile.com.MM6.MM6_1.MM6_04;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import egovframework.rte.fdl.cmmn.AbstractServiceImpl;
@Service
public class MM6_04ServiceImpl extends AbstractServiceImpl implements MM6_04Service{
@Autowired
private MM6_04DAO dao;
@Override
public List<MM6_04VO_MENU> selectMenuList(MM6_04VO_PARAM vo) throws Exception {
return (List<MM6_04VO_MENU>)dao.selectMenuList(vo);
}
@Override
public List<MM6_04VO_MEMBER> selectMemberList(MM6_04VO_PARAM vo) throws Exception {
return (List<MM6_04VO_MEMBER>)dao.selectMemberList(vo);
}
}
|
UTF-8
|
Java
| 674 |
java
|
MM6_04ServiceImpl.java
|
Java
|
[] | null |
[] |
package lionsmobile.com.MM6.MM6_1.MM6_04;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import egovframework.rte.fdl.cmmn.AbstractServiceImpl;
@Service
public class MM6_04ServiceImpl extends AbstractServiceImpl implements MM6_04Service{
@Autowired
private MM6_04DAO dao;
@Override
public List<MM6_04VO_MENU> selectMenuList(MM6_04VO_PARAM vo) throws Exception {
return (List<MM6_04VO_MENU>)dao.selectMenuList(vo);
}
@Override
public List<MM6_04VO_MEMBER> selectMemberList(MM6_04VO_PARAM vo) throws Exception {
return (List<MM6_04VO_MEMBER>)dao.selectMemberList(vo);
}
}
| 674 | 0.795252 | 0.746291 | 23 | 28.304348 | 29.568542 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.913043 | false | false |
10
|
4ca39905ce8387857f9b9af208062e9579cf754d
| 30,030,411,396,355 |
1303ee0a02950aad1fa36493fdf285d062ffc62c
|
/tsr/src/th/co/thiensurat/fragments/complain/ComplainDetailFragment.java
|
4902ecf1ae6eef637ad74f7c559872a797130682
|
[] |
no_license
|
it-thiensurat/tsr-android
|
https://github.com/it-thiensurat/tsr-android
|
bd996bc1aae6c298f353d31086fad7c2c8a8106c
|
6547b0c80c3bc2eceedc2df549066f3e8dc26e1b
|
refs/heads/master
| 2023-07-10T01:50:03.884000 | 2023-06-27T10:19:31 | 2023-06-27T10:19:31 | 194,594,260 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package th.co.thiensurat.fragments.complain;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import th.co.bighead.utilities.BHFragment;
import th.co.bighead.utilities.BHParcelable;
import th.co.bighead.utilities.BHPreference;
import th.co.bighead.utilities.BHSpinnerAdapter;
import th.co.bighead.utilities.BHUtilities;
import th.co.bighead.utilities.annotation.InjectView;
import th.co.thiensurat.R;
import th.co.thiensurat.business.controller.BackgroundProcess;
import th.co.thiensurat.business.controller.TSRController;
import th.co.thiensurat.data.controller.ComplainController;
import th.co.thiensurat.data.controller.ContractController;
import th.co.thiensurat.data.controller.DatabaseHelper;
import th.co.thiensurat.data.controller.EmployeeController;
import th.co.thiensurat.data.controller.EmployeeDetailController;
import th.co.thiensurat.data.controller.ProblemController;
import th.co.thiensurat.data.info.ComplainInfo;
import th.co.thiensurat.data.info.ContractInfo;
import th.co.thiensurat.data.info.EmployeeDetailInfo;
import th.co.thiensurat.data.info.EmployeeInfo;
import th.co.thiensurat.data.info.ProblemInfo;
import th.co.thiensurat.data.info.TeamInfo;
import th.co.thiensurat.service.TSRService;
import th.co.thiensurat.service.data.GetTeamByIDInputInfo;
public class ComplainDetailFragment extends BHFragment {
public static class Data extends BHParcelable {
public String RefNo;
}
private Data data;
@InjectView
TextView textViewContractNumber, textViewName, textViewIDcard, textContractDate, textViewEmpName, textViewProductSerialNumber, textViewProductName, textViewNote, textViewProblem, textViewLeaderName;
@InjectView
Spinner spinnerProblem;
@InjectView
EditText editTextNote;
private ContractInfo contract;
private List<ProblemInfo> problemList;
private ProblemInfo selectedProblem;
ProblemAdapter problemAdapter;
@Override
protected int titleID() {
return R.string.title_complain;
}
@Override
protected int fragmentID() {
return R.layout.fragment_complain_detail;
}
@Override
protected int[] processButtons() {
return new int[]{R.string.button_back, R.string.button_confirm};
}
@Override
protected void onCreateViewSuccess(Bundle savedInstanceState) {
data = getData();
if (problemList == null) {
problemList = new ArrayList<ProblemInfo>();
} else {
problemList.clear();
}
problemAdapter = new ProblemAdapter(activity, R.layout.spinner_item_problem, problemList);
spinnerProblem.setAdapter(problemAdapter);
spinnerProblem.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
selectedProblem = (ProblemInfo) adapterView.getItemAtPosition(position);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
bindData();
textViewNote.setVisibility(View.GONE);
textViewProblem.setVisibility(View.GONE);
}
private void bindData() {
(new BackgroundProcess(activity) {
boolean isOwnTeam = false;
EmployeeInfo SaleInfo;
EmployeeInfo TeamHeadInfo;
@Override
protected void before() {
if (BHPreference.sourceSystem().equals(EmployeeController.SourceSystem.Sale.toString())) {
isOwnTeam = true;
}
if (problemList == null) {
problemList = new ArrayList<ProblemInfo>();
} else {
problemList.clear();
}
}
@Override
protected void calling() {
/* Fixed - [BHPROJ-0024-418] :: เปลี่ยนเครื่อง เพิ่มการค้นหา STATUS = 'F' */
// List<ContractInfo> contractListTemp = new ContractController().getContractListByRefNoOrSearchText(BHPreference.organizationCode(), ContractInfo.ContractStatus.NORMAL.toString(), null, data.RefNo);
List<ContractInfo> contractListTemp = new ContractController().getContractListByRefNoOrSearchText(BHPreference.organizationCode(), null, data.RefNo);
if (contractListTemp != null && contractListTemp.size() > 0) {
contract = contractListTemp.get(0);
if (contract.SaleEmployeeName == null || contract.SaleEmployeeName.trim().isEmpty()) {
// import employee
// TSRController.importEmployeeByEmployeeCode(contract.OrganizationCode, contract.SaleEmployeeCode, contract.SaleTeamCode);
SaleInfo = new EmployeeController().getEmployeeByID(contract.SaleEmployeeCode);
if (contract.SaleLeaderName == null || contract.SaleLeaderName.trim().isEmpty()) {
EmployeeDetailInfo TeamHead = new EmployeeDetailController().getTeamHeadDetailByTeamCode(contract.OrganizationCode, contract.SaleTeamCode);
if (TeamHead == null) {
GetTeamByIDInputInfo team = new GetTeamByIDInputInfo();
team.Code = contract.SaleTeamCode;
TeamInfo output = TSRService.getTeamByID(team, false).Info;
if (output != null && output.TeamHeadCode != null) {
// TSRController.importEmployeeByEmployeeCode(contract.OrganizationCode, output.TeamHeadCode, contract.SaleTeamCode);
TeamHeadInfo = new EmployeeController().getEmployeeByID(output.TeamHeadCode);
}
} else {
TeamHeadInfo = new EmployeeController().getEmployeeByID(TeamHead.EmployeeCode);
}
}
}
}
List<ProblemInfo> problemListTemp = getProblemByProblemType(BHPreference.organizationCode(), ProblemController.ProblemType.Complain.toString());
if (problemListTemp != null && problemListTemp.size() > 0) {
problemList.addAll(problemListTemp);
}
}
@Override
protected void after() {
if (contract != null) {
textViewContractNumber.setText(contract.CONTNO);
textViewName.setText(contract.CustomerFullName);
textViewIDcard.setText(contract.IDCard);
textContractDate.setText(BHUtilities.dateFormat(contract.EFFDATE));
textViewProductSerialNumber.setText(contract.ProductSerialNumber);
textViewProductName.setText(contract.ProductName);
if (contract.SaleEmployeeName == null || contract.SaleEmployeeName.trim().isEmpty()) {
textViewEmpName.setText(String.format("%s %s", contract.SaleCode, SaleInfo != null ? SaleInfo.FullName() : ""));
} else {
textViewEmpName.setText(String.format("%s %s", contract.SaleCode, contract.SaleEmployeeName));
}
if (contract.SaleLeaderName == null || contract.SaleLeaderName.trim().isEmpty()) {
textViewLeaderName.setText(String.format("ทีม %s %s", contract.SaleTeamCode, TeamHeadInfo != null ? TeamHeadInfo.FullName() : ""));
} else {
textViewLeaderName.setText(String.format("ทีม %s %s", contract.SaleTeamCode, contract.SaleLeaderName));
}
if (problemAdapter != null) {
problemAdapter.notifyDataSetChanged();
}
if (problemList != null && problemList.size() > 0 && selectedProblem == null) {
spinnerProblem.setSelection(0);
}
}
}
}).start();
}
public class ProblemAdapter extends BHSpinnerAdapter<ProblemInfo> {
public ProblemAdapter(Context context, int resource, List<ProblemInfo> objects) {
super(context, resource, objects);
}
@Override
protected void setupView(TextView tv, ProblemInfo item) {
tv.setText(item.ProblemName);
}
}
@Override
public void onProcessButtonClicked(int buttonID) {
switch (buttonID) {
case R.string.button_confirm:
if (selectedProblem != null) {
final String title = "แจ้งปัญหา";
String message = "ยืนยันการแจ้งปัญหา เรื่อง: " + selectedProblem.ProblemName;
AlertDialog.Builder setupAlert = new AlertDialog.Builder(activity).setTitle(title).setMessage(message)
.setPositiveButton(getResources().getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
addComplain();
}
})
.setNegativeButton(getResources().getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
}
});
setupAlert.show();
} else {
BHUtilities.alertDialog(activity, "กรุณาเลือกรายการ", "เลือกสาเหตุที่จะแจ้งปัญหา").show();
}
break;
case R.string.button_back:
showLastView();
break;
default:
break;
}
}
private void addComplain() {
(new BackgroundProcess(activity) {
ComplainInfo complain;
@Override
protected void calling() {
//REQUEST
complain = new ComplainInfo();
complain.ComplainID = DatabaseHelper.getUUID();
complain.OrganizationCode = BHPreference.organizationCode();
complain.RefNo = contract.RefNo;
complain.Status = ComplainController.ComplainStatus.REQUEST.toString();
complain.RequestProblemID = selectedProblem.ProblemID;
complain.RequestDetail = editTextNote.getText().toString();
complain.RequestDate = new Date();
complain.RequestBy = BHPreference.employeeID();
complain.RequestTeamCode = BHPreference.teamCode();
complain.CreateDate = new Date();
complain.CreateBy = BHPreference.employeeID();
complain.LastUpdateDate = new Date();
complain.LastUpdateBy = BHPreference.employeeID();
complain.TaskType = ComplainController.TaskType.Other.toString();
complain.ComplainPaperID = new TSRController().getAutoGenerateDocumentID(TSRController.DocumentGenType.Complain, BHPreference.SubTeamCode(), BHPreference.saleCode());
// Fixed - [BHPROJ-0016-777] :: [Meeting@BH-28/12/2558] 5. [Android-การบันทึก Transaction ใหม่] ในการบันทึก Transaction ต่าง ๆ ให้บันทึก Version ของโครงสร้างปัจจุบัน (Field TreeHistoryID) จาก ตาราง EmployeeDetail ลงไปด้วย
complain.RequestEmployeeLevelPath = BHPreference.currentTreeHistoryID();
TSRController.addComplainStatusREQUEST(complain, true);
}
@Override
protected void after() {
AlertDialog.Builder builder = BHUtilities.builderDialog(activity, "บันทึก", "แจ้งปัญหาการใช้งานเรียบร้อยแล้ว");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ComplainPrintFragment.Data data = new ComplainPrintFragment.Data();
data.ComplainID = complain.ComplainID;
ComplainPrintFragment fragment = BHFragment.newInstance(ComplainPrintFragment.class, data);
showNextView(fragment);
}
});
builder.show();
}
}).start();
}
}
|
UTF-8
|
Java
| 13,518 |
java
|
ComplainDetailFragment.java
|
Java
|
[] | null |
[] |
package th.co.thiensurat.fragments.complain;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import th.co.bighead.utilities.BHFragment;
import th.co.bighead.utilities.BHParcelable;
import th.co.bighead.utilities.BHPreference;
import th.co.bighead.utilities.BHSpinnerAdapter;
import th.co.bighead.utilities.BHUtilities;
import th.co.bighead.utilities.annotation.InjectView;
import th.co.thiensurat.R;
import th.co.thiensurat.business.controller.BackgroundProcess;
import th.co.thiensurat.business.controller.TSRController;
import th.co.thiensurat.data.controller.ComplainController;
import th.co.thiensurat.data.controller.ContractController;
import th.co.thiensurat.data.controller.DatabaseHelper;
import th.co.thiensurat.data.controller.EmployeeController;
import th.co.thiensurat.data.controller.EmployeeDetailController;
import th.co.thiensurat.data.controller.ProblemController;
import th.co.thiensurat.data.info.ComplainInfo;
import th.co.thiensurat.data.info.ContractInfo;
import th.co.thiensurat.data.info.EmployeeDetailInfo;
import th.co.thiensurat.data.info.EmployeeInfo;
import th.co.thiensurat.data.info.ProblemInfo;
import th.co.thiensurat.data.info.TeamInfo;
import th.co.thiensurat.service.TSRService;
import th.co.thiensurat.service.data.GetTeamByIDInputInfo;
public class ComplainDetailFragment extends BHFragment {
public static class Data extends BHParcelable {
public String RefNo;
}
private Data data;
@InjectView
TextView textViewContractNumber, textViewName, textViewIDcard, textContractDate, textViewEmpName, textViewProductSerialNumber, textViewProductName, textViewNote, textViewProblem, textViewLeaderName;
@InjectView
Spinner spinnerProblem;
@InjectView
EditText editTextNote;
private ContractInfo contract;
private List<ProblemInfo> problemList;
private ProblemInfo selectedProblem;
ProblemAdapter problemAdapter;
@Override
protected int titleID() {
return R.string.title_complain;
}
@Override
protected int fragmentID() {
return R.layout.fragment_complain_detail;
}
@Override
protected int[] processButtons() {
return new int[]{R.string.button_back, R.string.button_confirm};
}
@Override
protected void onCreateViewSuccess(Bundle savedInstanceState) {
data = getData();
if (problemList == null) {
problemList = new ArrayList<ProblemInfo>();
} else {
problemList.clear();
}
problemAdapter = new ProblemAdapter(activity, R.layout.spinner_item_problem, problemList);
spinnerProblem.setAdapter(problemAdapter);
spinnerProblem.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
selectedProblem = (ProblemInfo) adapterView.getItemAtPosition(position);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
bindData();
textViewNote.setVisibility(View.GONE);
textViewProblem.setVisibility(View.GONE);
}
private void bindData() {
(new BackgroundProcess(activity) {
boolean isOwnTeam = false;
EmployeeInfo SaleInfo;
EmployeeInfo TeamHeadInfo;
@Override
protected void before() {
if (BHPreference.sourceSystem().equals(EmployeeController.SourceSystem.Sale.toString())) {
isOwnTeam = true;
}
if (problemList == null) {
problemList = new ArrayList<ProblemInfo>();
} else {
problemList.clear();
}
}
@Override
protected void calling() {
/* Fixed - [BHPROJ-0024-418] :: เปลี่ยนเครื่อง เพิ่มการค้นหา STATUS = 'F' */
// List<ContractInfo> contractListTemp = new ContractController().getContractListByRefNoOrSearchText(BHPreference.organizationCode(), ContractInfo.ContractStatus.NORMAL.toString(), null, data.RefNo);
List<ContractInfo> contractListTemp = new ContractController().getContractListByRefNoOrSearchText(BHPreference.organizationCode(), null, data.RefNo);
if (contractListTemp != null && contractListTemp.size() > 0) {
contract = contractListTemp.get(0);
if (contract.SaleEmployeeName == null || contract.SaleEmployeeName.trim().isEmpty()) {
// import employee
// TSRController.importEmployeeByEmployeeCode(contract.OrganizationCode, contract.SaleEmployeeCode, contract.SaleTeamCode);
SaleInfo = new EmployeeController().getEmployeeByID(contract.SaleEmployeeCode);
if (contract.SaleLeaderName == null || contract.SaleLeaderName.trim().isEmpty()) {
EmployeeDetailInfo TeamHead = new EmployeeDetailController().getTeamHeadDetailByTeamCode(contract.OrganizationCode, contract.SaleTeamCode);
if (TeamHead == null) {
GetTeamByIDInputInfo team = new GetTeamByIDInputInfo();
team.Code = contract.SaleTeamCode;
TeamInfo output = TSRService.getTeamByID(team, false).Info;
if (output != null && output.TeamHeadCode != null) {
// TSRController.importEmployeeByEmployeeCode(contract.OrganizationCode, output.TeamHeadCode, contract.SaleTeamCode);
TeamHeadInfo = new EmployeeController().getEmployeeByID(output.TeamHeadCode);
}
} else {
TeamHeadInfo = new EmployeeController().getEmployeeByID(TeamHead.EmployeeCode);
}
}
}
}
List<ProblemInfo> problemListTemp = getProblemByProblemType(BHPreference.organizationCode(), ProblemController.ProblemType.Complain.toString());
if (problemListTemp != null && problemListTemp.size() > 0) {
problemList.addAll(problemListTemp);
}
}
@Override
protected void after() {
if (contract != null) {
textViewContractNumber.setText(contract.CONTNO);
textViewName.setText(contract.CustomerFullName);
textViewIDcard.setText(contract.IDCard);
textContractDate.setText(BHUtilities.dateFormat(contract.EFFDATE));
textViewProductSerialNumber.setText(contract.ProductSerialNumber);
textViewProductName.setText(contract.ProductName);
if (contract.SaleEmployeeName == null || contract.SaleEmployeeName.trim().isEmpty()) {
textViewEmpName.setText(String.format("%s %s", contract.SaleCode, SaleInfo != null ? SaleInfo.FullName() : ""));
} else {
textViewEmpName.setText(String.format("%s %s", contract.SaleCode, contract.SaleEmployeeName));
}
if (contract.SaleLeaderName == null || contract.SaleLeaderName.trim().isEmpty()) {
textViewLeaderName.setText(String.format("ทีม %s %s", contract.SaleTeamCode, TeamHeadInfo != null ? TeamHeadInfo.FullName() : ""));
} else {
textViewLeaderName.setText(String.format("ทีม %s %s", contract.SaleTeamCode, contract.SaleLeaderName));
}
if (problemAdapter != null) {
problemAdapter.notifyDataSetChanged();
}
if (problemList != null && problemList.size() > 0 && selectedProblem == null) {
spinnerProblem.setSelection(0);
}
}
}
}).start();
}
public class ProblemAdapter extends BHSpinnerAdapter<ProblemInfo> {
public ProblemAdapter(Context context, int resource, List<ProblemInfo> objects) {
super(context, resource, objects);
}
@Override
protected void setupView(TextView tv, ProblemInfo item) {
tv.setText(item.ProblemName);
}
}
@Override
public void onProcessButtonClicked(int buttonID) {
switch (buttonID) {
case R.string.button_confirm:
if (selectedProblem != null) {
final String title = "แจ้งปัญหา";
String message = "ยืนยันการแจ้งปัญหา เรื่อง: " + selectedProblem.ProblemName;
AlertDialog.Builder setupAlert = new AlertDialog.Builder(activity).setTitle(title).setMessage(message)
.setPositiveButton(getResources().getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
addComplain();
}
})
.setNegativeButton(getResources().getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
}
});
setupAlert.show();
} else {
BHUtilities.alertDialog(activity, "กรุณาเลือกรายการ", "เลือกสาเหตุที่จะแจ้งปัญหา").show();
}
break;
case R.string.button_back:
showLastView();
break;
default:
break;
}
}
private void addComplain() {
(new BackgroundProcess(activity) {
ComplainInfo complain;
@Override
protected void calling() {
//REQUEST
complain = new ComplainInfo();
complain.ComplainID = DatabaseHelper.getUUID();
complain.OrganizationCode = BHPreference.organizationCode();
complain.RefNo = contract.RefNo;
complain.Status = ComplainController.ComplainStatus.REQUEST.toString();
complain.RequestProblemID = selectedProblem.ProblemID;
complain.RequestDetail = editTextNote.getText().toString();
complain.RequestDate = new Date();
complain.RequestBy = BHPreference.employeeID();
complain.RequestTeamCode = BHPreference.teamCode();
complain.CreateDate = new Date();
complain.CreateBy = BHPreference.employeeID();
complain.LastUpdateDate = new Date();
complain.LastUpdateBy = BHPreference.employeeID();
complain.TaskType = ComplainController.TaskType.Other.toString();
complain.ComplainPaperID = new TSRController().getAutoGenerateDocumentID(TSRController.DocumentGenType.Complain, BHPreference.SubTeamCode(), BHPreference.saleCode());
// Fixed - [BHPROJ-0016-777] :: [Meeting@BH-28/12/2558] 5. [Android-การบันทึก Transaction ใหม่] ในการบันทึก Transaction ต่าง ๆ ให้บันทึก Version ของโครงสร้างปัจจุบัน (Field TreeHistoryID) จาก ตาราง EmployeeDetail ลงไปด้วย
complain.RequestEmployeeLevelPath = BHPreference.currentTreeHistoryID();
TSRController.addComplainStatusREQUEST(complain, true);
}
@Override
protected void after() {
AlertDialog.Builder builder = BHUtilities.builderDialog(activity, "บันทึก", "แจ้งปัญหาการใช้งานเรียบร้อยแล้ว");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ComplainPrintFragment.Data data = new ComplainPrintFragment.Data();
data.ComplainID = complain.ComplainID;
ComplainPrintFragment fragment = BHFragment.newInstance(ComplainPrintFragment.class, data);
showNextView(fragment);
}
});
builder.show();
}
}).start();
}
}
| 13,518 | 0.605259 | 0.603119 | 284 | 45.063381 | 40.953377 | 237 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.679577 | false | false |
10
|
0d9d9c3c4c2cfaecc7e409886dbef2eb5b985f96
| 28,286,654,645,033 |
7df2d99e1bc425c4ffa6982da27ffe9d0421a78c
|
/app/src/main/java/org/ucomplex/ucomplex/Modules/RoleSelect/RoleModel.java
|
3570d1a0de28c784dc464c4e7a8f3f142c8e50df
|
[] |
no_license
|
Sermilion/uComplexAndroid
|
https://github.com/Sermilion/uComplexAndroid
|
2240e6080a25093bf9002fef7b817dd89621b7ef
|
e2ef28a80a640c09a7c71d1ae7a8f2df9027a474
|
refs/heads/master
| 2021-01-18T22:34:29.126000 | 2017-02-07T20:03:38 | 2017-02-07T20:03:38 | 72,567,037 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.ucomplex.ucomplex.Modules.RoleSelect;
import android.os.Bundle;
import net.oneread.aghanim.components.utility.MVPCallback;
import net.oneread.aghanim.mvp.abstractmvp.MVPAbstractModelRecycler;
import net.oneread.aghanim.mvp.recyclermvp.MVPModelRecycler;
import org.ucomplex.ucomplex.CommonDependencies.Constants;
import org.ucomplex.ucomplex.Domain.Users.Role;
import org.ucomplex.ucomplex.Domain.Users.UserInterface;
import org.ucomplex.ucomplex.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* ---------------------------------------------------
* Created by Sermilion on 08/11/2016.
* Project: uComplex_v_2
* ---------------------------------------------------
* <a href="http://www.ucomplex.org">ucomplex.org</a>
* <a href="http://www.github.com/sermilion>github</a>
* ---------------------------------------------------
*/
public class RoleModel extends MVPAbstractModelRecycler<UserInterface, List<RoleItem>> implements MVPModelRecycler<UserInterface, List<RoleItem>> {
private int[] roleIcons = {
R.drawable.role_select_1,
R.drawable.role_select_2,
R.drawable.role_select_3,
R.drawable.role_select_4,
R.drawable.role_select_5};
public RoleModel() {
}
@Override
public void loadData(MVPCallback<List<RoleItem>> mvpCallback, Bundle... bundles) {
UserInterface user = bundles[0].getParcelable(Constants.EXTRA_KEY_USER);
mvpCallback.onSuccess(processJson(user));
}
@Override
public List<RoleItem> processJson(UserInterface user) {
List<RoleItem> roles = new ArrayList<>();
if (user!=null) {
Random random = new Random();
for (int i = 0; i < user.getRoles().size(); i++) {
Role role = user.getRoles().get(i);
String roleStr = "";
if (role.getType() == 3) {
roleStr = mContext.getResources().getString(R.string.prepodvatel);
} else if (role.getType() == 4) {
roleStr = mContext.getResources().getString(R.string.student);
} else if (role.getType() == 0) {
roleStr = mContext.getResources().getString(R.string.sotrudnik);
} else if (role.getType() == 3) {
roleStr = mContext.getResources().getString(R.string.prepodvatel);
}
int index = random.nextInt(5);
roles.add(new RoleItem(roleIcons[index], roleStr));
}
}
return roles;
}
}
|
UTF-8
|
Java
| 2,601 |
java
|
RoleModel.java
|
Java
|
[
{
"context": "------------------------------------\n * Created by Sermilion on 08/11/2016.\n * Project: uComplex_v_2\n * ------",
"end": 624,
"score": 0.9995102286338806,
"start": 615,
"tag": "NAME",
"value": "Sermilion"
},
{
"context": "complex.org</a>\n * <a href=\"http://www.github.com/sermilion>github</a>\n * -----------------------------------",
"end": 817,
"score": 0.9996933937072754,
"start": 808,
"tag": "USERNAME",
"value": "sermilion"
}
] | null |
[] |
package org.ucomplex.ucomplex.Modules.RoleSelect;
import android.os.Bundle;
import net.oneread.aghanim.components.utility.MVPCallback;
import net.oneread.aghanim.mvp.abstractmvp.MVPAbstractModelRecycler;
import net.oneread.aghanim.mvp.recyclermvp.MVPModelRecycler;
import org.ucomplex.ucomplex.CommonDependencies.Constants;
import org.ucomplex.ucomplex.Domain.Users.Role;
import org.ucomplex.ucomplex.Domain.Users.UserInterface;
import org.ucomplex.ucomplex.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* ---------------------------------------------------
* Created by Sermilion on 08/11/2016.
* Project: uComplex_v_2
* ---------------------------------------------------
* <a href="http://www.ucomplex.org">ucomplex.org</a>
* <a href="http://www.github.com/sermilion>github</a>
* ---------------------------------------------------
*/
public class RoleModel extends MVPAbstractModelRecycler<UserInterface, List<RoleItem>> implements MVPModelRecycler<UserInterface, List<RoleItem>> {
private int[] roleIcons = {
R.drawable.role_select_1,
R.drawable.role_select_2,
R.drawable.role_select_3,
R.drawable.role_select_4,
R.drawable.role_select_5};
public RoleModel() {
}
@Override
public void loadData(MVPCallback<List<RoleItem>> mvpCallback, Bundle... bundles) {
UserInterface user = bundles[0].getParcelable(Constants.EXTRA_KEY_USER);
mvpCallback.onSuccess(processJson(user));
}
@Override
public List<RoleItem> processJson(UserInterface user) {
List<RoleItem> roles = new ArrayList<>();
if (user!=null) {
Random random = new Random();
for (int i = 0; i < user.getRoles().size(); i++) {
Role role = user.getRoles().get(i);
String roleStr = "";
if (role.getType() == 3) {
roleStr = mContext.getResources().getString(R.string.prepodvatel);
} else if (role.getType() == 4) {
roleStr = mContext.getResources().getString(R.string.student);
} else if (role.getType() == 0) {
roleStr = mContext.getResources().getString(R.string.sotrudnik);
} else if (role.getType() == 3) {
roleStr = mContext.getResources().getString(R.string.prepodvatel);
}
int index = random.nextInt(5);
roles.add(new RoleItem(roleIcons[index], roleStr));
}
}
return roles;
}
}
| 2,601 | 0.588235 | 0.580161 | 71 | 35.633804 | 29.108946 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.507042 | false | false |
10
|
e3098d723a0873cb2b23f42833a8cd503f60144e
| 29,274,497,126,975 |
341d828a009a672f432d1c90387950f56dc1db6f
|
/Learn-java-Spring-MVC/Spring-mvc/src/main/java/com/laptrinhjavaweb/service/impl/CatalogService.java
|
a2a00c78ef7dc5f899a923423ac6f2218af8504c
|
[] |
no_license
|
ThangHuynh99/Spring-MVC-ttclothesShop
|
https://github.com/ThangHuynh99/Spring-MVC-ttclothesShop
|
d94ba9ed03bbe44cc11c105aeee9143a81ceb3a9
|
55f5d9a33a7ebff123df234af8dcb228dc2f74f7
|
refs/heads/master
| 2023-07-07T07:09:46.171000 | 2021-08-07T13:32:39 | 2021-08-07T13:32:39 | 349,434,861 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.laptrinhjavaweb.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.laptrinhjavaweb.converter.CatalogConverter;
import com.laptrinhjavaweb.dto.CatalogDTO;
import com.laptrinhjavaweb.entity.CatalogEntity;
import com.laptrinhjavaweb.repository.CatalogRepository;
import com.laptrinhjavaweb.service.ICatalogService;
@Service
public class CatalogService implements ICatalogService {
@Autowired
private CatalogRepository catalogRepository;
@Autowired
private CatalogConverter converter;
@Override
public List<CatalogDTO> findAll() {
List<CatalogEntity> catalogEntity = catalogRepository.findAll();
List<CatalogDTO> catalogDTO = new ArrayList<>();
//convert entity sang dto
for(CatalogEntity item: catalogEntity) {
catalogDTO.add(converter.toDTO(item));
}
return catalogDTO;
}
}
|
UTF-8
|
Java
| 1,001 |
java
|
CatalogService.java
|
Java
|
[] | null |
[] |
package com.laptrinhjavaweb.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.laptrinhjavaweb.converter.CatalogConverter;
import com.laptrinhjavaweb.dto.CatalogDTO;
import com.laptrinhjavaweb.entity.CatalogEntity;
import com.laptrinhjavaweb.repository.CatalogRepository;
import com.laptrinhjavaweb.service.ICatalogService;
@Service
public class CatalogService implements ICatalogService {
@Autowired
private CatalogRepository catalogRepository;
@Autowired
private CatalogConverter converter;
@Override
public List<CatalogDTO> findAll() {
List<CatalogEntity> catalogEntity = catalogRepository.findAll();
List<CatalogDTO> catalogDTO = new ArrayList<>();
//convert entity sang dto
for(CatalogEntity item: catalogEntity) {
catalogDTO.add(converter.toDTO(item));
}
return catalogDTO;
}
}
| 1,001 | 0.813187 | 0.813187 | 36 | 26.805555 | 22.155787 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.166667 | false | false |
10
|
b16f7a5e2c3ff0554ebaf9490cf60c0a688240ed
| 1,039,382,117,372 |
6712044ffb39b5d507308d1a0c6ad9290f557ac4
|
/vertx-config-redis/src/main/java/io/vertx/config/redis/RedisConfigStore.java
|
54eeb5c33cf7d92cf78544f78239cd9947cdd1d2
|
[
"Apache-2.0"
] |
permissive
|
vert-x3/vertx-config
|
https://github.com/vert-x3/vertx-config
|
5e6f7a38f922bc806067cefee6ee427dbb938f7c
|
f650b9c19601883805df624b627fc99066ecb6b4
|
refs/heads/master
| 2023-08-20T17:41:52.486000 | 2023-08-01T11:01:17 | 2023-08-01T11:01:17 | 75,085,823 | 55 | 86 |
Apache-2.0
| false | 2023-07-31T14:42:13 | 2016-11-29T13:51:02 | 2023-05-21T04:54:58 | 2023-07-19T14:41:33 | 1,653 | 51 | 67 | 27 |
Java
| false | false |
/*
* Copyright (c) 2014 Red Hat, Inc. and others
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
package io.vertx.config.redis;
import io.vertx.config.spi.ConfigStore;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonObject;
import io.vertx.redis.client.*;
/**
* An implementation of configuration store reading hash from Redis.
*
* @author <a href="http://escoffier.me">Clement Escoffier</a>
*/
public class RedisConfigStore implements ConfigStore {
private final Redis redis;
private final String field;
public RedisConfigStore(Vertx vertx, JsonObject config) {
this.field = config.getString("key", "configuration");
this.redis = Redis.createClient(vertx, new RedisOptions(config));
}
@Override
public Future<Void> close() {
redis.close();
return Future.succeededFuture();
}
@Override
public Future<Buffer> get() {
return redis.send(Request.cmd(Command.HGETALL).arg(field))
.map(resp -> {
JsonObject result = new JsonObject();
for (String key : resp.getKeys()) {
result.put(key, resp.get(key).toString());
}
return result.toBuffer();
});
}
}
|
UTF-8
|
Java
| 1,765 |
java
|
RedisConfigStore.java
|
Java
|
[
{
"context": "edis.\n *\n * @author <a href=\"http://escoffier.me\">Clement Escoffier</a>\n */\npublic class RedisConfigStore implements ",
"end": 1010,
"score": 0.9998049736022949,
"start": 993,
"tag": "NAME",
"value": "Clement Escoffier"
}
] | null |
[] |
/*
* Copyright (c) 2014 Red Hat, Inc. and others
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
package io.vertx.config.redis;
import io.vertx.config.spi.ConfigStore;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonObject;
import io.vertx.redis.client.*;
/**
* An implementation of configuration store reading hash from Redis.
*
* @author <a href="http://escoffier.me"><NAME></a>
*/
public class RedisConfigStore implements ConfigStore {
private final Redis redis;
private final String field;
public RedisConfigStore(Vertx vertx, JsonObject config) {
this.field = config.getString("key", "configuration");
this.redis = Redis.createClient(vertx, new RedisOptions(config));
}
@Override
public Future<Void> close() {
redis.close();
return Future.succeededFuture();
}
@Override
public Future<Buffer> get() {
return redis.send(Request.cmd(Command.HGETALL).arg(field))
.map(resp -> {
JsonObject result = new JsonObject();
for (String key : resp.getKeys()) {
result.put(key, resp.get(key).toString());
}
return result.toBuffer();
});
}
}
| 1,754 | 0.70085 | 0.696317 | 59 | 28.915255 | 25.753254 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.457627 | false | false |
10
|
656b92c52a3cf0d85499a06d45e11281c61eab39
| 27,023,934,251,926 |
bb245b695a9736d8302b38a7691d69ba8e859a60
|
/Algo/src/Main/Main_리모컨.java
|
615ecf4d13df0453b9340411217c4712bd85685f
|
[] |
no_license
|
wrjym/algorithm
|
https://github.com/wrjym/algorithm
|
bee42f3b1a4710b3996ae3da403805b456f7c747
|
a8feb2de4fb1e779afc185bb66e3a64bec338d43
|
refs/heads/master
| 2020-06-23T12:50:09.675000 | 2019-11-01T00:54:56 | 2019-11-01T00:54:56 | 198,628,920 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Main;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Scanner;
public class Main_리모컨{
static String channelStr;
static int channel;
static int n;
static int []tmp;
static int []seq;
static int []num;
static int count = 0;
static int ans = 0;
static boolean b = false;
public static void main(String[] args) throws Exception{
System.setIn(new FileInputStream("rs/1107.txt"));
Scanner sc = new Scanner(System.in);
channelStr = sc.nextLine();
channel = Integer.parseInt(channelStr);
n = sc.nextInt();
tmp = new int[10];
ans = Integer.MAX_VALUE;
num = new int[tmp.length-n];
seq = new int[channelStr.length()+1];
for(int i=0; i<n; i++) {
tmp[sc.nextInt()] = 1;
}
int cnt = 0;
for(int i=0; i<tmp.length; i++) {
if(tmp[i] == 0) {
num[cnt++] = i;
}
}
for(int i=0; i<=250000; i++) {
checks((channel-i));
checks((channel+i));
if(b){
break ;
}
}
ans = Math.min(ans, Math.abs(channel-100));
System.out.println(ans);
sc.close();
}
private static void checks(int now) {
// System.out.println(now);
if(now < 0){
return ;
}
String tmp = now+"";
for(int i=0; i<num.length; i++) {
tmp = tmp.replace((num[i]+""), "");
}
if(tmp.equals("")) {
ans = Math.min(ans, Math.abs(channel-now)+(now+"").length());
// System.out.println("함수 : " + ans);
b = true;
}
}
}
|
UTF-8
|
Java
| 1,398 |
java
|
Main_리모컨.java
|
Java
|
[] | null |
[] |
package Main;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Scanner;
public class Main_리모컨{
static String channelStr;
static int channel;
static int n;
static int []tmp;
static int []seq;
static int []num;
static int count = 0;
static int ans = 0;
static boolean b = false;
public static void main(String[] args) throws Exception{
System.setIn(new FileInputStream("rs/1107.txt"));
Scanner sc = new Scanner(System.in);
channelStr = sc.nextLine();
channel = Integer.parseInt(channelStr);
n = sc.nextInt();
tmp = new int[10];
ans = Integer.MAX_VALUE;
num = new int[tmp.length-n];
seq = new int[channelStr.length()+1];
for(int i=0; i<n; i++) {
tmp[sc.nextInt()] = 1;
}
int cnt = 0;
for(int i=0; i<tmp.length; i++) {
if(tmp[i] == 0) {
num[cnt++] = i;
}
}
for(int i=0; i<=250000; i++) {
checks((channel-i));
checks((channel+i));
if(b){
break ;
}
}
ans = Math.min(ans, Math.abs(channel-100));
System.out.println(ans);
sc.close();
}
private static void checks(int now) {
// System.out.println(now);
if(now < 0){
return ;
}
String tmp = now+"";
for(int i=0; i<num.length; i++) {
tmp = tmp.replace((num[i]+""), "");
}
if(tmp.equals("")) {
ans = Math.min(ans, Math.abs(channel-now)+(now+"").length());
// System.out.println("함수 : " + ans);
b = true;
}
}
}
| 1,398 | 0.597983 | 0.579251 | 65 | 20.353846 | 14.69739 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.476923 | false | false |
10
|
fc4a2cc36a80ee3332d6ec0c8c6eed567b688bfc
| 15,238,543,999,147 |
b2810bdfafc7fb3f72d5625c593eb088450e6846
|
/condition/FinalCondition.java
|
82bcb454677efd65f6ecf56adc796ed0521a98c2
|
[] |
no_license
|
ElgersNiels/Subset-Sum-Iterator
|
https://github.com/ElgersNiels/Subset-Sum-Iterator
|
119e31b97c3c88b52bdc72f2118ec7fe0af96355
|
4e5cb22396b522d9f1e80e80c7bdcb66b10eb61b
|
refs/heads/master
| 2021-08-18T19:59:38.623000 | 2017-11-23T18:39:14 | 2017-11-23T18:39:14 | 103,564,868 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package condition;
import java.util.List;
public interface FinalCondition<T> extends Condition<T> {
boolean sat(List<T> ts);
}
|
UTF-8
|
Java
| 130 |
java
|
FinalCondition.java
|
Java
|
[] | null |
[] |
package condition;
import java.util.List;
public interface FinalCondition<T> extends Condition<T> {
boolean sat(List<T> ts);
}
| 130 | 0.753846 | 0.753846 | 7 | 17.571428 | 18.980118 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false |
10
|
46959fb6dbac9a1b946d7b749df022ea1dc38cb1
| 30,296,699,326,351 |
23d0ff45a1a07f7e1210a2c9ec2528ff9eae5c8a
|
/hndl-activitySys/src/main/java/com/hndl/cn/activity/sys/business/library/vo/HappyLibraryHeadDataVo.java
|
2e95917f2a2dc13bd966dbb08eb8c5f3ede1b7b9
|
[] |
no_license
|
moutainhigh/hndl-platfrom
|
https://github.com/moutainhigh/hndl-platfrom
|
e7a6ee302bce88eaef51316dd94300d248068ad4
|
02cc84f8fef8cf2bf32fa6f30a7b51bf7d53a448
|
refs/heads/master
| 2022-03-20T19:07:26.610000 | 2019-09-04T06:22:26 | 2019-09-04T06:22:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.hndl.cn.activity.sys.business.library.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @Classname 赵俊凯
* @Description TODO
* @Date 2019/3/31 17:59
* @Created by 湖南达联
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class HappyLibraryHeadDataVo implements Serializable {
private String starName;
private String groupName;
private Long startTime;//开始时间
private Long endTime;//结束时间
private Integer version;//版本
private Long nowVoteCount;//每天用户投票次数
private Long starSumCount;//总次数
}
|
UTF-8
|
Java
| 705 |
java
|
HappyLibraryHeadDataVo.java
|
Java
|
[
{
"context": "\n\nimport java.io.Serializable;\n\n/**\n * @Classname 赵俊凯\n * @Description TODO\n * @Date 2019/3/31 17:59\n * ",
"end": 217,
"score": 0.9998469352722168,
"start": 214,
"tag": "NAME",
"value": "赵俊凯"
},
{
"context": "tion TODO\n * @Date 2019/3/31 17:59\n * @Created by 湖南达联\n */\n@Data\n@Builder\n@NoArgsConstructor\n@AllArgsCon",
"end": 283,
"score": 0.7040623426437378,
"start": 279,
"tag": "NAME",
"value": "湖南达联"
}
] | null |
[] |
package com.hndl.cn.activity.sys.business.library.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @Classname 赵俊凯
* @Description TODO
* @Date 2019/3/31 17:59
* @Created by 湖南达联
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class HappyLibraryHeadDataVo implements Serializable {
private String starName;
private String groupName;
private Long startTime;//开始时间
private Long endTime;//结束时间
private Integer version;//版本
private Long nowVoteCount;//每天用户投票次数
private Long starSumCount;//总次数
}
| 705 | 0.750385 | 0.733436 | 36 | 17.027779 | 16.479763 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.361111 | false | false |
10
|
def8d1ba0c3519293895f82ab09a8e2da0039a08
| 28,819,230,578,873 |
497a2ec4fc2f277b3c730c2f7fcc1e7f00543fc5
|
/TPE/CondGeneroUnico.java
|
6c22e29ac370daadc5d0ca2323038fec0c4bb156
|
[] |
no_license
|
GeroMendy/Programacion-2---TPE
|
https://github.com/GeroMendy/Programacion-2---TPE
|
a33415304eaf4533e42fa8b0af189f95c3987c5e
|
0aabb51f216e32ba82edd36e33a9087e40f79615
|
refs/heads/master
| 2020-07-31T14:45:41.136000 | 2019-09-24T15:48:02 | 2019-09-24T15:48:02 | 210,640,633 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package TPE;
import java.util.Vector;
public class CondGeneroUnico extends CondGeneros{
public CondGeneroUnico(Vector<String>generos) {
super(generos);
}
public CondGeneroUnico(Cliente cliente) {
super(cliente);
}
public boolean cumple(Pelicula p) {
if(g!=null) {
if(g.size()!=0) {
boolean cumple = false;
int i=0;
while(i<g.size()&&!cumple) {
cumple = p.contieneGenero(g.elementAt(i));
i++;
}
return cumple;
}
}
return true;
}
}
|
UTF-8
|
Java
| 486 |
java
|
CondGeneroUnico.java
|
Java
|
[] | null |
[] |
package TPE;
import java.util.Vector;
public class CondGeneroUnico extends CondGeneros{
public CondGeneroUnico(Vector<String>generos) {
super(generos);
}
public CondGeneroUnico(Cliente cliente) {
super(cliente);
}
public boolean cumple(Pelicula p) {
if(g!=null) {
if(g.size()!=0) {
boolean cumple = false;
int i=0;
while(i<g.size()&&!cumple) {
cumple = p.contieneGenero(g.elementAt(i));
i++;
}
return cumple;
}
}
return true;
}
}
| 486 | 0.639918 | 0.635802 | 27 | 17 | 15.700909 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.333333 | false | false |
10
|
037e4627cd755eede1df40b54d9d9e315330000f
| 910,533,095,271 |
00e72473bee6b901255f1b6cb7ff5ca234f7fd6b
|
/SFtoBoot_std190829_Spring_5_BBS_Sample/src/main/java/com/sample/app/pds/model/PdsDTO.java
|
ae1c2b8294c14d53822da01b6093e6359c4791b6
|
[] |
no_license
|
HyeongJunMin/springboot
|
https://github.com/HyeongJunMin/springboot
|
7e70be9f75d6f35632e8c9d2833e9b7e4b929fa0
|
63250c54267c5a67b687906f7f34ad6aa8691a56
|
refs/heads/master
| 2021-06-17T10:24:28.908000 | 2019-11-05T03:47:07 | 2019-11-05T03:47:07 | 197,293,405 | 1 | 3 | null | false | 2021-04-26T19:28:32 | 2019-07-17T01:38:05 | 2019-11-05T03:47:16 | 2021-04-26T19:28:32 | 8,133 | 1 | 3 | 7 |
JavaScript
| false | false |
package com.sample.app.pds.model;
import java.io.Serializable;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class PdsDTO implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int rnum;
private int seq;
private String id;
private String title;
private String content;
private String filename;// 업로드된 파일 이름(저장하기위해 바뀐) 사실 오리지널 이름이 있어야함
private String origin_filename;
private int readcount;
private int downcount;// 다운 수
private String regdate;// 등록일
//No Args Constructor
@Builder
public PdsDTO() {}
// 유저 입력값만 받는 생성자
@Builder
public PdsDTO(String id, String title, String content, String filename, String origin_filename) {
this.id = id;
this.title = title;
this.content = content;
this.filename = filename;
this.origin_filename = origin_filename;
}
// 수정용 생성자
@Builder
public PdsDTO(int seq, String id, String title, String content, String filename, String origin_filename) {
this.seq = seq;
this.id = id;
this.title = title;
this.content = content;
this.filename = filename;
this.origin_filename = origin_filename;
}
//All arguments constructor
@Builder
public PdsDTO(int seq, String id, String title, String content, String filename, String origin_filename,
int readcount, int downcount, String regdate) {
super();
this.seq = seq;
this.id = id;
this.title = title;
this.content = content;
this.filename = filename;
this.origin_filename = origin_filename;
this.readcount = readcount;
this.downcount = downcount;
this.regdate = regdate;
}
//All arguments constructor + rnum
@Builder
public PdsDTO(int rnum, int seq, String id, String title, String content, String filename, String origin_filename,
int readcount, int downcount, String regdate) {
super();
this.rnum = rnum;
this.seq = seq;
this.id = id;
this.title = title;
this.content = content;
this.filename = filename;
this.origin_filename = origin_filename;
this.readcount = readcount;
this.downcount = downcount;
this.regdate = regdate;
}
}
|
UTF-8
|
Java
| 2,258 |
java
|
PdsDTO.java
|
Java
|
[] | null |
[] |
package com.sample.app.pds.model;
import java.io.Serializable;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class PdsDTO implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int rnum;
private int seq;
private String id;
private String title;
private String content;
private String filename;// 업로드된 파일 이름(저장하기위해 바뀐) 사실 오리지널 이름이 있어야함
private String origin_filename;
private int readcount;
private int downcount;// 다운 수
private String regdate;// 등록일
//No Args Constructor
@Builder
public PdsDTO() {}
// 유저 입력값만 받는 생성자
@Builder
public PdsDTO(String id, String title, String content, String filename, String origin_filename) {
this.id = id;
this.title = title;
this.content = content;
this.filename = filename;
this.origin_filename = origin_filename;
}
// 수정용 생성자
@Builder
public PdsDTO(int seq, String id, String title, String content, String filename, String origin_filename) {
this.seq = seq;
this.id = id;
this.title = title;
this.content = content;
this.filename = filename;
this.origin_filename = origin_filename;
}
//All arguments constructor
@Builder
public PdsDTO(int seq, String id, String title, String content, String filename, String origin_filename,
int readcount, int downcount, String regdate) {
super();
this.seq = seq;
this.id = id;
this.title = title;
this.content = content;
this.filename = filename;
this.origin_filename = origin_filename;
this.readcount = readcount;
this.downcount = downcount;
this.regdate = regdate;
}
//All arguments constructor + rnum
@Builder
public PdsDTO(int rnum, int seq, String id, String title, String content, String filename, String origin_filename,
int readcount, int downcount, String regdate) {
super();
this.rnum = rnum;
this.seq = seq;
this.id = id;
this.title = title;
this.content = content;
this.filename = filename;
this.origin_filename = origin_filename;
this.readcount = readcount;
this.downcount = downcount;
this.regdate = regdate;
}
}
| 2,258 | 0.711235 | 0.710771 | 88 | 23.477272 | 22.792032 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.295455 | false | false |
10
|
f9f84c357c2b373496b2a17d6039c8eac0179e83
| 3,719,441,706,564 |
db009f41bd031815294cbd1831e972b31d7d5ff6
|
/SelectionCommittee/src/main/java/by/training/nc/dev3/entities/Faculty.java
|
0f19ffca8f47e80d922ee5ab05541186b33fb61b
|
[] |
no_license
|
yalov4uk/Selection-committee-1
|
https://github.com/yalov4uk/Selection-committee-1
|
4055bffdbdb22faf7019afd7361cc7417713fa1c
|
9509a9f4a58699481719e9f83597cdee40fcba14
|
refs/heads/master
| 2021-06-24T19:44:06.839000 | 2017-04-26T18:36:34 | 2017-04-26T18:36:34 | null | 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 by.training.nc.dev3.entities;
import by.training.nc.dev3.abstracts.Entity;
import java.util.ArrayList;
import java.util.List;
/**
* @author Valera Yalov4uk
*/
public class Faculty extends Entity {
private static int count = 0;
private String name;
private int maxSize;
private List<SubjectName> requiredSubjects;
private List<User> registeredUsers;
public Faculty() {
super(count++);
this.requiredSubjects = new ArrayList<>();
this.registeredUsers = new ArrayList<>();
}
public Faculty(String name, int maxSize) {
super(count++);
this.name = name;
this.maxSize = maxSize;
this.requiredSubjects = new ArrayList<>();
this.registeredUsers = new ArrayList<>();
}
public Faculty(String name, int maxSize, List<SubjectName> requiredSubjects) {
super(count++);
this.name = name;
this.maxSize = maxSize;
this.requiredSubjects = requiredSubjects;
this.registeredUsers = new ArrayList<>();
}
public Faculty(int id, int maxSize, String name) {
super(id);
this.name = name;
this.maxSize = maxSize;
this.requiredSubjects = new ArrayList<>();
this.registeredUsers = new ArrayList<>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMaxSize() {
return maxSize;
}
public void setMaxSize(int maxSize) {
this.maxSize = maxSize;
}
/**
* @return
*/
public List<SubjectName> getRequiredSubjects() {
return requiredSubjects;
}
/**
* @param requiredSubjects
*/
public void setRequiredSubjects(List<SubjectName> requiredSubjects) {
this.requiredSubjects = requiredSubjects;
}
/**
* @return
*/
public List<User> getRegisteredUsers() {
return registeredUsers;
}
/**
* @param registeredUsers
*/
public void setRegisteredEntrants(List<User> registeredUsers) {
this.registeredUsers = registeredUsers;
}
@Override
public String toString() {
return "Faculty{" +
super.toString() +
", name='" + name + '\'' +
", maxSize=" + maxSize +
", requiredSubjects=" + requiredSubjects +
", registeredUsers=" + registeredUsers +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if ((!(o instanceof Faculty))) return false;
if (!super.equals(o)) return false;
Faculty faculty = (Faculty) o;
if (maxSize != faculty.maxSize) return false;
if (name != faculty.name) return false;
if (requiredSubjects != null ? !requiredSubjects.equals(faculty.requiredSubjects) : faculty.requiredSubjects != null)
return false;
return registeredUsers != null ? registeredUsers.equals(faculty.registeredUsers) : faculty.registeredUsers == null;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + maxSize;
result = 31 * result + (requiredSubjects != null ? requiredSubjects.hashCode() : 0);
result = 31 * result + (registeredUsers != null ? registeredUsers.hashCode() : 0);
return result;
}
}
|
UTF-8
|
Java
| 3,685 |
java
|
Faculty.java
|
Java
|
[
{
"context": ".ArrayList;\nimport java.util.List;\n\n/**\n * @author Valera Yalov4uk\n */\npublic class Faculty extends Entity {\n\n pr",
"end": 352,
"score": 0.9998618364334106,
"start": 337,
"tag": "NAME",
"value": "Valera Yalov4uk"
}
] | 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 by.training.nc.dev3.entities;
import by.training.nc.dev3.abstracts.Entity;
import java.util.ArrayList;
import java.util.List;
/**
* @author <NAME>
*/
public class Faculty extends Entity {
private static int count = 0;
private String name;
private int maxSize;
private List<SubjectName> requiredSubjects;
private List<User> registeredUsers;
public Faculty() {
super(count++);
this.requiredSubjects = new ArrayList<>();
this.registeredUsers = new ArrayList<>();
}
public Faculty(String name, int maxSize) {
super(count++);
this.name = name;
this.maxSize = maxSize;
this.requiredSubjects = new ArrayList<>();
this.registeredUsers = new ArrayList<>();
}
public Faculty(String name, int maxSize, List<SubjectName> requiredSubjects) {
super(count++);
this.name = name;
this.maxSize = maxSize;
this.requiredSubjects = requiredSubjects;
this.registeredUsers = new ArrayList<>();
}
public Faculty(int id, int maxSize, String name) {
super(id);
this.name = name;
this.maxSize = maxSize;
this.requiredSubjects = new ArrayList<>();
this.registeredUsers = new ArrayList<>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMaxSize() {
return maxSize;
}
public void setMaxSize(int maxSize) {
this.maxSize = maxSize;
}
/**
* @return
*/
public List<SubjectName> getRequiredSubjects() {
return requiredSubjects;
}
/**
* @param requiredSubjects
*/
public void setRequiredSubjects(List<SubjectName> requiredSubjects) {
this.requiredSubjects = requiredSubjects;
}
/**
* @return
*/
public List<User> getRegisteredUsers() {
return registeredUsers;
}
/**
* @param registeredUsers
*/
public void setRegisteredEntrants(List<User> registeredUsers) {
this.registeredUsers = registeredUsers;
}
@Override
public String toString() {
return "Faculty{" +
super.toString() +
", name='" + name + '\'' +
", maxSize=" + maxSize +
", requiredSubjects=" + requiredSubjects +
", registeredUsers=" + registeredUsers +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if ((!(o instanceof Faculty))) return false;
if (!super.equals(o)) return false;
Faculty faculty = (Faculty) o;
if (maxSize != faculty.maxSize) return false;
if (name != faculty.name) return false;
if (requiredSubjects != null ? !requiredSubjects.equals(faculty.requiredSubjects) : faculty.requiredSubjects != null)
return false;
return registeredUsers != null ? registeredUsers.equals(faculty.registeredUsers) : faculty.registeredUsers == null;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + maxSize;
result = 31 * result + (requiredSubjects != null ? requiredSubjects.hashCode() : 0);
result = 31 * result + (registeredUsers != null ? registeredUsers.hashCode() : 0);
return result;
}
}
| 3,676 | 0.6 | 0.595929 | 135 | 26.296297 | 24.918259 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.459259 | false | false |
10
|
65656b4e20d912fd289bdf2cfd5b68733f0c85f1
| 4,612,794,906,122 |
3fae644fef1f49558e4226ebc08e12e3ba7be5d2
|
/src/com/testyantra/webelementmethods/HandlingMultipleWindows.java
|
47f9cb1d2eccab60b756210a32ddf85fc6fe68ef
|
[] |
no_license
|
HemaGaikwad/TrialRep
|
https://github.com/HemaGaikwad/TrialRep
|
752581bde65cfc051320de1a5fdbfca43704a864
|
4bd7ee171d8c9d6ea51e138d6083fc474c99b0b9
|
refs/heads/master
| 2021-08-20T05:59:51.885000 | 2017-11-28T10:55:42 | 2017-11-28T10:55:42 | 112,321,114 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.testyantra.webelementmethods;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class HandlingMultipleWindows {
public static WebDriver driver=null;
public static void handleMultipleWindows()
{
String ParentWindow = driver.getWindowHandle();
driver.findElement(By.xpath("//a[text() = 'thesitewizard.com']")).click();
Set<String> handles = driver.getWindowHandles();
for(String handle1: handles)
{
System.out.println(handle1);
String Url = driver.switchTo().window(handle1).getCurrentUrl();
System.out.println(Url);
}
driver.switchTo().window(ParentWindow);
System.out.println(driver.getCurrentUrl());
}
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","./Driver/chromedriver.exe");
driver = new ChromeDriver();
driver.get("file:///C:/Users/TYSS/Desktop/SamplePage.html");
handleMultipleWindows();
}
}
|
UTF-8
|
Java
| 1,039 |
java
|
HandlingMultipleWindows.java
|
Java
|
[] | null |
[] |
package com.testyantra.webelementmethods;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class HandlingMultipleWindows {
public static WebDriver driver=null;
public static void handleMultipleWindows()
{
String ParentWindow = driver.getWindowHandle();
driver.findElement(By.xpath("//a[text() = 'thesitewizard.com']")).click();
Set<String> handles = driver.getWindowHandles();
for(String handle1: handles)
{
System.out.println(handle1);
String Url = driver.switchTo().window(handle1).getCurrentUrl();
System.out.println(Url);
}
driver.switchTo().window(ParentWindow);
System.out.println(driver.getCurrentUrl());
}
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","./Driver/chromedriver.exe");
driver = new ChromeDriver();
driver.get("file:///C:/Users/TYSS/Desktop/SamplePage.html");
handleMultipleWindows();
}
}
| 1,039 | 0.709336 | 0.706448 | 37 | 26.081081 | 23.452515 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.783784 | false | false |
10
|
c1a4c6ba129bfb92454f510370ab482ff30bfba3
| 19,250,043,447,787 |
6d686c58203d1ffbcd4e8fb29005d76fad326a1c
|
/app/src/main/java/com/finalexam/capstone1/mypage/MypageActivity.java
|
7accc14731ae99e63576b2a7120efc85a4de3b62
|
[] |
no_license
|
JMine97/traveler_limits
|
https://github.com/JMine97/traveler_limits
|
78f441ee7f004c532cecde3d075e7546251be50a
|
185b6dfd61eb329a414ddb42031229720e0ea6f3
|
refs/heads/master
| 2023-04-27T08:30:00.439000 | 2021-05-28T11:15:16 | 2021-05-28T11:15:16 | 371,254,138 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.finalexam.capstone1.mypage;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import com.finalexam.capstone1.PreferenceManager;
import com.finalexam.capstone1.R;
import com.finalexam.capstone1.alarm.MyAlarmsActivity;
import com.finalexam.capstone1.login.LoginActivity;
import com.finalexam.capstone1.login.MainActivity;
import java.util.ArrayList;
public class MypageActivity extends Activity {
private ArrayList<String> list_menu;
private BaseAdapter_mypage adapter;
private ListView mListView;
private ImageButton btn_home, btn_profile;
private TextView login, email, birth;
private String id, st_email, st_birth;
private String CurState = "CheckAlarm"; //알람 조회 페이지에서 뒤로가기로 이동할 구간을 구분하기 위함
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mypage_profile);
getWindow().setWindowAnimations(0); //화면전환 효과 제거
email = (TextView) findViewById(R.id.email);
birth = (TextView) findViewById(R.id.birth);
mListView = (ListView) findViewById(R.id.list_mypage);
btn_home = (ImageButton)findViewById(R.id.btn_mp_home);
btn_profile = (ImageButton)findViewById(R.id.btn_mp_profile);
login=(TextView) findViewById(R.id.login);
PreferenceManager pref = new PreferenceManager(this);
id = pref.getValue("id", null);
st_email = pref.getValue("e_mail", null);
st_birth = pref.getValue("date_of_birth", null);
Intent intent = getIntent();
/*id = intent.getStringExtra("id");
st_email = intent.getStringExtra("e_mail");
st_birth = intent.getStringExtra("date_of_birth");
password = intent.getStringExtra("password");
*/
if(id!=null) {
login.setText(id+"님 안녕하세요");
login.setOnClickListener(null);
email.setText(st_email);
birth.setText(st_birth);
}
else {
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), LoginActivity.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
finish();
}
});
}
list_menu = new ArrayList<String>();
if(id!=null){
list_menu.add("개인정보"); list_menu.add("알람설정");
list_menu.add("알람목록"); list_menu.add("로그아웃");
}
adapter = new BaseAdapter_mypage(this, list_menu);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Toast.makeText(getApplicationContext(), i+"번째 id="+l, Toast.LENGTH_SHORT).show();
if(i == 0){ // 개인정보
Intent intent = new Intent(view.getContext(), MemberInfoActivity.class);
startActivity(intent);
finish();
}
else if(i == 1){ // 알람설정
}
else if (i == 2) { // 알람목록
Intent intent = new Intent(view.getContext(), MyAlarmsActivity.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
/*intent.putExtra("id", id);
intent.putExtra("password", password);
intent.putExtra("e_mail", st_email);
intent.putExtra("date_of_birth", st_birth);
*/
intent.putExtra("CurState", CurState);
startActivity(intent);
finish();
}
else if(i==3){ // 로그아웃
AlertDialog.Builder alert = new AlertDialog.Builder(MypageActivity.this);
alert.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); //닫기
}
});
alert.setPositiveButton("네", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
PreferenceManager pref = new PreferenceManager(MypageActivity.this);
pref.clear();
Intent intent = getIntent();
startActivity(intent);
finish();
}
});
alert.setMessage("정말 로그아웃하시겠습니까?");
alert.show();
}
}
});
btn_home.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MypageActivity.this, MainActivity.class);
/*intent.putExtra("id", id);
intent.putExtra("password", password);
intent.putExtra("e_mail", st_email);
intent.putExtra("date_of_birth", st_birth);
*/
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
finish();
}
});
btn_profile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "You're looking mypage already", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onBackPressed() {
//Intent intent = new Intent(MypageActivity.this, MainActivity.class);
//startActivity(intent);
finish();
}
class BaseAdapter_mypage extends BaseAdapter {
private ArrayList<String> list;
private Context context;
BaseAdapter_mypage(Context context, ArrayList<String> data) {
this.context = context;
this.list = data;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int i) {
return list.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.mypage_profile_listitem, viewGroup, false);
}
final String str = list.get(i);
TextView tv = (TextView) view.findViewById(R.id.tv_mypage_list);
tv.setText(str);
return view;
}
}
}
|
UTF-8
|
Java
| 8,048 |
java
|
MypageActivity.java
|
Java
|
[
{
"context": "irth\");\n password = intent.getStringExtra(\"password\");\n */\n if(id!=null) {\n ",
"end": 2259,
"score": 0.9976632595062256,
"start": 2251,
"tag": "PASSWORD",
"value": "password"
},
{
"context": ");\n intent.putExtra(\"password\", password);\n intent.putExtra(\"e_mail\", s",
"end": 4224,
"score": 0.9963749051094055,
"start": 4216,
"tag": "PASSWORD",
"value": "password"
},
{
"context": ", id);\n intent.putExtra(\"password\", password);\n intent.putExtra(\"e_mail\", st_em",
"end": 5957,
"score": 0.9987927079200745,
"start": 5949,
"tag": "PASSWORD",
"value": "password"
}
] | null |
[] |
package com.finalexam.capstone1.mypage;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import com.finalexam.capstone1.PreferenceManager;
import com.finalexam.capstone1.R;
import com.finalexam.capstone1.alarm.MyAlarmsActivity;
import com.finalexam.capstone1.login.LoginActivity;
import com.finalexam.capstone1.login.MainActivity;
import java.util.ArrayList;
public class MypageActivity extends Activity {
private ArrayList<String> list_menu;
private BaseAdapter_mypage adapter;
private ListView mListView;
private ImageButton btn_home, btn_profile;
private TextView login, email, birth;
private String id, st_email, st_birth;
private String CurState = "CheckAlarm"; //알람 조회 페이지에서 뒤로가기로 이동할 구간을 구분하기 위함
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mypage_profile);
getWindow().setWindowAnimations(0); //화면전환 효과 제거
email = (TextView) findViewById(R.id.email);
birth = (TextView) findViewById(R.id.birth);
mListView = (ListView) findViewById(R.id.list_mypage);
btn_home = (ImageButton)findViewById(R.id.btn_mp_home);
btn_profile = (ImageButton)findViewById(R.id.btn_mp_profile);
login=(TextView) findViewById(R.id.login);
PreferenceManager pref = new PreferenceManager(this);
id = pref.getValue("id", null);
st_email = pref.getValue("e_mail", null);
st_birth = pref.getValue("date_of_birth", null);
Intent intent = getIntent();
/*id = intent.getStringExtra("id");
st_email = intent.getStringExtra("e_mail");
st_birth = intent.getStringExtra("date_of_birth");
password = intent.getStringExtra("<PASSWORD>");
*/
if(id!=null) {
login.setText(id+"님 안녕하세요");
login.setOnClickListener(null);
email.setText(st_email);
birth.setText(st_birth);
}
else {
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), LoginActivity.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
finish();
}
});
}
list_menu = new ArrayList<String>();
if(id!=null){
list_menu.add("개인정보"); list_menu.add("알람설정");
list_menu.add("알람목록"); list_menu.add("로그아웃");
}
adapter = new BaseAdapter_mypage(this, list_menu);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Toast.makeText(getApplicationContext(), i+"번째 id="+l, Toast.LENGTH_SHORT).show();
if(i == 0){ // 개인정보
Intent intent = new Intent(view.getContext(), MemberInfoActivity.class);
startActivity(intent);
finish();
}
else if(i == 1){ // 알람설정
}
else if (i == 2) { // 알람목록
Intent intent = new Intent(view.getContext(), MyAlarmsActivity.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
/*intent.putExtra("id", id);
intent.putExtra("password", <PASSWORD>);
intent.putExtra("e_mail", st_email);
intent.putExtra("date_of_birth", st_birth);
*/
intent.putExtra("CurState", CurState);
startActivity(intent);
finish();
}
else if(i==3){ // 로그아웃
AlertDialog.Builder alert = new AlertDialog.Builder(MypageActivity.this);
alert.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); //닫기
}
});
alert.setPositiveButton("네", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
PreferenceManager pref = new PreferenceManager(MypageActivity.this);
pref.clear();
Intent intent = getIntent();
startActivity(intent);
finish();
}
});
alert.setMessage("정말 로그아웃하시겠습니까?");
alert.show();
}
}
});
btn_home.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MypageActivity.this, MainActivity.class);
/*intent.putExtra("id", id);
intent.putExtra("password", <PASSWORD>);
intent.putExtra("e_mail", st_email);
intent.putExtra("date_of_birth", st_birth);
*/
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
finish();
}
});
btn_profile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "You're looking mypage already", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onBackPressed() {
//Intent intent = new Intent(MypageActivity.this, MainActivity.class);
//startActivity(intent);
finish();
}
class BaseAdapter_mypage extends BaseAdapter {
private ArrayList<String> list;
private Context context;
BaseAdapter_mypage(Context context, ArrayList<String> data) {
this.context = context;
this.list = data;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int i) {
return list.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.mypage_profile_listitem, viewGroup, false);
}
final String str = list.get(i);
TextView tv = (TextView) view.findViewById(R.id.tv_mypage_list);
tv.setText(str);
return view;
}
}
}
| 8,054 | 0.560529 | 0.55913 | 216 | 35.402779 | 26.009254 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.726852 | false | false |
10
|
1e37d3c968312faccc935b1b23fd898e45d92a61
| 19,250,043,444,918 |
8a8f91a50d0a8203df994a41b77b8bea951af1b9
|
/ccmillennium/src/zw/co/telecel/akm/webservice/ccb/client/TestNum.java
|
6aeba9b47b644bb16e30a73da2f957b3efc1a81e
|
[] |
no_license
|
ebridgevas/vasgw
|
https://github.com/ebridgevas/vasgw
|
d138bfa177d763d2efd5a46560af5975e6e39845
|
62bf2d9a1872fd270f0a7cfee6c558762b057362
|
refs/heads/master
| 2020-04-28T00:51:36.298000 | 2014-03-24T09:05:38 | 2014-03-24T09:05:38 | 18,056,792 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package zw.co.telecel.akm.webservice.ccb.client;
/**
*
* @author matsaudzaa
*/
public class TestNum {
public static void main(String [] args){
try{
ChangeCOS change = new ChangeCOS(); //0738836137 737730520
CheckNumber check = new CheckNumber();
boolean result = check.isPrepaid("263734266605");
// change.changeCOS("2777Millenium", "263737730520");
//change.changeCOS("TEL_COS", "263738836139");
System.out.println("state : "+result);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 765 |
java
|
TestNum.java
|
Java
|
[
{
"context": ".akm.webservice.ccb.client;\r\n\r\n/**\r\n *\r\n * @author matsaudzaa\r\n */\r\npublic class TestNum {\r\n public static",
"end": 186,
"score": 0.9929271936416626,
"start": 176,
"tag": "USERNAME",
"value": "matsaudzaa"
}
] | null |
[] |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package zw.co.telecel.akm.webservice.ccb.client;
/**
*
* @author matsaudzaa
*/
public class TestNum {
public static void main(String [] args){
try{
ChangeCOS change = new ChangeCOS(); //0738836137 737730520
CheckNumber check = new CheckNumber();
boolean result = check.isPrepaid("263734266605");
// change.changeCOS("2777Millenium", "263737730520");
//change.changeCOS("TEL_COS", "263738836139");
System.out.println("state : "+result);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
| 765 | 0.554248 | 0.477124 | 27 | 26.333334 | 23.303156 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false |
10
|
aad2b6011486450ff684feff5f944f8b9070dfa9
| 36,395,552,873,153 |
e0f81ca84f953c8e5d641fbd5fc1244acd5a8101
|
/framework-toolkit/framework-toolkit-cli/src/main/java/com/rnkrsoft/framework/toolkit/cli/CommandDefine.java
|
a48e3f9a46bdbf5f2f75aa1bb672be576c5c8475
|
[] |
no_license
|
rnkrsoft/framework
|
https://github.com/rnkrsoft/framework
|
c2a5a984623d75217be69da959f18f2791ec3d31
|
eb00a2a6981e9a585ddf7215d2c9c531db0d501b
|
refs/heads/master
| 2020-03-25T05:26:30.721000 | 2019-09-20T09:58:56 | 2019-09-20T09:58:56 | 143,446,825 | 1 | 1 | null | false | 2020-10-04T08:07:01 | 2018-08-03T15:55:20 | 2020-10-04T08:06:26 | 2020-10-04T08:07:00 | 1,685 | 1 | 1 | 5 |
Java
| false | false |
package com.rnkrsoft.framework.toolkit.cli;
import com.rnkrsoft.message.MessageFormatter;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.*;
/**
* Created by rnkrsoft.com on 2017/1/4.
* 命令定义
*/
@ToString
public class CommandDefine {
@Setter
@Getter
String name;
@Setter
@Getter
String cmd;
/**
* 参数定义
*/
protected final Map<String, Option> options = new HashMap();
/**
* 别名
*/
protected final Map<String, String> alias = new HashMap();
@Setter
@Getter
protected String example;
@Setter
@Getter
protected String extrInfo;
/**
* 获取选项信息
*
* @param name 参数名
* @return 选项
*/
public Option getOption(String name) {
String longName = alias.get(name);
if (longName == null) {
longName = name;
}
Option option = options.get(longName);
if (option == null) {
throw new IllegalArgumentException("无效的参数");
} else {
return option;
}
}
/**
* 增加选项
*
* @param longName 长命名
* @param require 是否必须
* @param argNum 参数数目
* @return 对象
*/
public CommandDefine addOption(String longName, boolean require, int argNum, String desc, String example) {
return addOption(longName, longName, require, argNum, desc, example);
}
/**
* 增加选项
*
* @param longName 长命名
* @param shortName 短命名
* @param require 是否必须
* @param argNum 参数数目 如果为不确定,输入-1
* @return 对象
*/
public CommandDefine addOption(String longName, String shortName, boolean require, int argNum, String desc, String example, String ... defaultValue) {
Option option = new Option(longName, shortName, require, argNum, desc, example, Arrays.asList(defaultValue));
return addOption(option);
}
/**
* 增加选项
*
* @param option 选项
* @return 对象
*/
public CommandDefine addOption(Option option) {
String longName = option.longName;
String shortName = option.shortName;
if (longName == null) {
throw new NullPointerException("无效的长命名");
}
if (shortName == null) {
option.shortName = longName;
}
if (options.containsKey(longName)) {
return this;
}
String name = alias.get(shortName);
if (options.containsKey(name)) {
return this;
}
options.put(longName, option);
if (shortName != null && !shortName.isEmpty()) {
alias.put(shortName, longName);
}
return this;
}
/**
* 解析参数
*
* @return 处理完成
*/
boolean parseOptions(Command command, List<String> cmdArgs) {
Iterator<String> it = cmdArgs.iterator();
Map<String, List> tempArgs = new HashMap();
while (it.hasNext()) {
String opt = it.next();
if (opt.startsWith("-")) {
String argName = opt.substring(1);
Option option = getOption(argName);
int argNum = option.argNum;
if (argNum == 0) {
tempArgs.put(option.getLongName(), null);
} else if (argNum == 1) {
String arg = null;
if (it.hasNext()) {
arg = it.next();
} else {
throw new IllegalArgumentException("无效参数");
}
tempArgs.put(option.getLongName(), Arrays.asList(arg));
}else if(argNum == -1){
List<String> args = new ArrayList();
int count = 0;
String param = null;
while (it.hasNext() && !(param = it.next()).startsWith("-")) {
count++;
args.add(param);
}
tempArgs.put(option.getLongName(), args);
} else {
List<String> args = new ArrayList();
int count = 0;
String param = null;
while (it.hasNext() && !(param = it.next()).startsWith("-")) {
count++;
args.add(param);
}
if (count != option.argNum) {
System.out.println(MessageFormatter.format("无效参数:{}", command.getCmd()));
return false;
}
tempArgs.put(option.getLongName(), args);
}
continue;
}
}
for (Option option : options.values()) {
String longName = option.getLongName();
String shortName = option.getShortName();
List<String> values = null;
if(!tempArgs.containsKey(longName)){
if(tempArgs.containsKey(shortName)){
values = tempArgs.get(shortName);
}else {
if (option.isRequire()){
System.out.println(MessageFormatter.format("参数{}是必须输入的", longName));
return false;
}else {
values = option.getDefaultValue();
}
}
}else{
values = tempArgs.get(longName);
}
command.args.put(longName, values);
}
return true;
}
/**
* 解析命令
*
* @param cmd 命令字符串
* @return 处理完成
*/
public Command parseCommand(String cmd) {
String[] args = cmd.split(" ");
if (args.length == 0) {
return null;
}
Command command = new Command(args[0], this);
List<String> cmdArgs = Arrays.asList(args);
boolean success = parseOptions(command, cmdArgs);
if (success){
return command;
}else{
return null;
}
}
}
|
UTF-8
|
Java
| 6,296 |
java
|
CommandDefine.java
|
Java
|
[
{
"context": ".ToString;\n\nimport java.util.*;\n\n/**\n * Created by rnkrsoft.com on 2017/1/4.\n * 命令定义\n */\n@ToString\npublic class C",
"end": 211,
"score": 0.7979658842086792,
"start": 199,
"tag": "EMAIL",
"value": "rnkrsoft.com"
}
] | null |
[] |
package com.rnkrsoft.framework.toolkit.cli;
import com.rnkrsoft.message.MessageFormatter;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.*;
/**
* Created by <EMAIL> on 2017/1/4.
* 命令定义
*/
@ToString
public class CommandDefine {
@Setter
@Getter
String name;
@Setter
@Getter
String cmd;
/**
* 参数定义
*/
protected final Map<String, Option> options = new HashMap();
/**
* 别名
*/
protected final Map<String, String> alias = new HashMap();
@Setter
@Getter
protected String example;
@Setter
@Getter
protected String extrInfo;
/**
* 获取选项信息
*
* @param name 参数名
* @return 选项
*/
public Option getOption(String name) {
String longName = alias.get(name);
if (longName == null) {
longName = name;
}
Option option = options.get(longName);
if (option == null) {
throw new IllegalArgumentException("无效的参数");
} else {
return option;
}
}
/**
* 增加选项
*
* @param longName 长命名
* @param require 是否必须
* @param argNum 参数数目
* @return 对象
*/
public CommandDefine addOption(String longName, boolean require, int argNum, String desc, String example) {
return addOption(longName, longName, require, argNum, desc, example);
}
/**
* 增加选项
*
* @param longName 长命名
* @param shortName 短命名
* @param require 是否必须
* @param argNum 参数数目 如果为不确定,输入-1
* @return 对象
*/
public CommandDefine addOption(String longName, String shortName, boolean require, int argNum, String desc, String example, String ... defaultValue) {
Option option = new Option(longName, shortName, require, argNum, desc, example, Arrays.asList(defaultValue));
return addOption(option);
}
/**
* 增加选项
*
* @param option 选项
* @return 对象
*/
public CommandDefine addOption(Option option) {
String longName = option.longName;
String shortName = option.shortName;
if (longName == null) {
throw new NullPointerException("无效的长命名");
}
if (shortName == null) {
option.shortName = longName;
}
if (options.containsKey(longName)) {
return this;
}
String name = alias.get(shortName);
if (options.containsKey(name)) {
return this;
}
options.put(longName, option);
if (shortName != null && !shortName.isEmpty()) {
alias.put(shortName, longName);
}
return this;
}
/**
* 解析参数
*
* @return 处理完成
*/
boolean parseOptions(Command command, List<String> cmdArgs) {
Iterator<String> it = cmdArgs.iterator();
Map<String, List> tempArgs = new HashMap();
while (it.hasNext()) {
String opt = it.next();
if (opt.startsWith("-")) {
String argName = opt.substring(1);
Option option = getOption(argName);
int argNum = option.argNum;
if (argNum == 0) {
tempArgs.put(option.getLongName(), null);
} else if (argNum == 1) {
String arg = null;
if (it.hasNext()) {
arg = it.next();
} else {
throw new IllegalArgumentException("无效参数");
}
tempArgs.put(option.getLongName(), Arrays.asList(arg));
}else if(argNum == -1){
List<String> args = new ArrayList();
int count = 0;
String param = null;
while (it.hasNext() && !(param = it.next()).startsWith("-")) {
count++;
args.add(param);
}
tempArgs.put(option.getLongName(), args);
} else {
List<String> args = new ArrayList();
int count = 0;
String param = null;
while (it.hasNext() && !(param = it.next()).startsWith("-")) {
count++;
args.add(param);
}
if (count != option.argNum) {
System.out.println(MessageFormatter.format("无效参数:{}", command.getCmd()));
return false;
}
tempArgs.put(option.getLongName(), args);
}
continue;
}
}
for (Option option : options.values()) {
String longName = option.getLongName();
String shortName = option.getShortName();
List<String> values = null;
if(!tempArgs.containsKey(longName)){
if(tempArgs.containsKey(shortName)){
values = tempArgs.get(shortName);
}else {
if (option.isRequire()){
System.out.println(MessageFormatter.format("参数{}是必须输入的", longName));
return false;
}else {
values = option.getDefaultValue();
}
}
}else{
values = tempArgs.get(longName);
}
command.args.put(longName, values);
}
return true;
}
/**
* 解析命令
*
* @param cmd 命令字符串
* @return 处理完成
*/
public Command parseCommand(String cmd) {
String[] args = cmd.split(" ");
if (args.length == 0) {
return null;
}
Command command = new Command(args[0], this);
List<String> cmdArgs = Arrays.asList(args);
boolean success = parseOptions(command, cmdArgs);
if (success){
return command;
}else{
return null;
}
}
}
| 6,291 | 0.488264 | 0.485785 | 205 | 28.512196 | 23.49543 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.531707 | false | false |
10
|
5dcf67e89a5911d8443df4ffa21caaafbbb4c9b2
| 687,194,805,714 |
009d040f48a3ede3a5199614759409d59a808ffb
|
/security/security-provider/common-security-provider/src/main/java/uet/hungnh/config/AbstractSecurityConfig.java
|
dea46e4b573db03eff2604aa590c9fa5861684b0
|
[] |
no_license
|
hungnh/spring-boot-security
|
https://github.com/hungnh/spring-boot-security
|
55a6491e571d9573e6758218e37619b417c8a3b2
|
e08a1f54dff6b377b20c77f6765ddb300b790356
|
refs/heads/master
| 2020-04-21T18:44:40.487000 | 2016-09-19T07:26:26 | 2016-09-19T07:26:26 | 67,766,652 | 6 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package uet.hungnh.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import uet.hungnh.security.handler.CustomLogoutSuccessHandler;
import javax.servlet.http.HttpServletResponse;
import static uet.hungnh.security.constants.SecurityConstant.*;
public abstract class AbstractSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
protected String[] publicAPIs() {
return new String[]{
REGISTRATION_ENDPOINT, LOGIN_ENDPOINT,
LOGOUT_ENDPOINT, EMAIL_CONFIRMATION_ENDPOINT,
REQUEST_RESET_PASSWORD_ENDPOINT, RESET_PASSWORD_ENDPOINT
};
}
protected CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfig = new CorsConfiguration();
corsConfig.setAllowCredentials(true);
corsConfig.addAllowedOrigin("*");
corsConfig.addAllowedHeader("*");
corsConfig.addAllowedMethod("*");
corsConfigurationSource.registerCorsConfiguration("/**", corsConfig);
return corsConfigurationSource;
}
@Bean
public AuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return daoAuthenticationProvider;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationEntryPoint unauthorizedEntryPoint() {
return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
@Bean
public LogoutSuccessHandler logoutSuccessHandler() {
return new CustomLogoutSuccessHandler();
}
}
|
UTF-8
|
Java
| 2,894 |
java
|
AbstractSecurityConfig.java
|
Java
|
[] | null |
[] |
package uet.hungnh.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import uet.hungnh.security.handler.CustomLogoutSuccessHandler;
import javax.servlet.http.HttpServletResponse;
import static uet.hungnh.security.constants.SecurityConstant.*;
public abstract class AbstractSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
protected String[] publicAPIs() {
return new String[]{
REGISTRATION_ENDPOINT, LOGIN_ENDPOINT,
LOGOUT_ENDPOINT, EMAIL_CONFIRMATION_ENDPOINT,
REQUEST_RESET_PASSWORD_ENDPOINT, RESET_PASSWORD_ENDPOINT
};
}
protected CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfig = new CorsConfiguration();
corsConfig.setAllowCredentials(true);
corsConfig.addAllowedOrigin("*");
corsConfig.addAllowedHeader("*");
corsConfig.addAllowedMethod("*");
corsConfigurationSource.registerCorsConfiguration("/**", corsConfig);
return corsConfigurationSource;
}
@Bean
public AuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return daoAuthenticationProvider;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationEntryPoint unauthorizedEntryPoint() {
return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
@Bean
public LogoutSuccessHandler logoutSuccessHandler() {
return new CustomLogoutSuccessHandler();
}
}
| 2,894 | 0.78369 | 0.78369 | 68 | 41.558823 | 32.328907 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.632353 | false | false |
10
|
d1bf3ca68b1bb4c153f9364e77f1e45ef60d7b61
| 32,083,405,733,994 |
aea4b04eaf4bd039a407c1f8e867983873ad1286
|
/src/main/java/by/soft/testProject/questionnairePortal/dto/request/RegistrationUserRequestDto.java
|
4cbb3173dc003e17eb4b6b40df8c8adef5326113
|
[] |
no_license
|
HalapsikoN/Questionnaire-portal
|
https://github.com/HalapsikoN/Questionnaire-portal
|
2149cc93f2c9240857e0e41301ad76ecd516a57e
|
ae56dcdaa3b60246a07058e084f7b89000666f17
|
refs/heads/master
| 2021-03-29T10:48:33.859000 | 2020-03-30T19:38:31 | 2020-03-30T19:38:31 | 247,947,385 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package by.soft.testProject.questionnairePortal.dto.request;
import by.soft.testProject.questionnairePortal.entity.User;
import by.soft.testProject.questionnairePortal.exception.ErrorMessageConstants;
import lombok.Data;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
@Data
public class RegistrationUserRequestDto {
@NotNull(message = ErrorMessageConstants.INCORRECT_FIRST_NAME)
private String firstName;
@NotNull(message = ErrorMessageConstants.INCORRECT_LAST_NAME)
private String lastName;
@NotNull(message = ErrorMessageConstants.INCORRECT_PASSWORD)
@Pattern(regexp = ErrorMessageConstants.REGEX_PASSWORD, message = ErrorMessageConstants.INCORRECT_PASSWORD)
private String password;
@Email(message = ErrorMessageConstants.INCORRECT_EMAIL)
@NotNull(message = ErrorMessageConstants.INCORRECT_EMAIL)
private String email;
@NotNull(message = ErrorMessageConstants.INCORRECT_PHONE)
@Pattern(regexp = ErrorMessageConstants.REGEX_PHONE, message = ErrorMessageConstants.INCORRECT_PHONE)
private String phone;
@NotNull(message = ErrorMessageConstants.INCORRECT_ROLE)
private String role;
public User getUser() {
User user = new User();
user.setFirstName(firstName);
user.setLastName(lastName);
user.setPassword(password);
user.setEmail(email);
user.setPhone(phone);
return user;
}
public String getRole() {
return role.toUpperCase();
}
}
|
UTF-8
|
Java
| 1,570 |
java
|
RegistrationUserRequestDto.java
|
Java
|
[
{
"context": "User user = new User();\n user.setFirstName(firstName);\n user.setLastName(lastName);\n use",
"end": 1333,
"score": 0.9989345669746399,
"start": 1324,
"tag": "NAME",
"value": "firstName"
},
{
"context": "setFirstName(firstName);\n user.setLastName(lastName);\n user.setPassword(password);\n use",
"end": 1369,
"score": 0.9985983967781067,
"start": 1361,
"tag": "NAME",
"value": "lastName"
},
{
"context": "r.setLastName(lastName);\n user.setPassword(password);\n user.setEmail(email);\n user.setP",
"end": 1405,
"score": 0.9986268877983093,
"start": 1397,
"tag": "PASSWORD",
"value": "password"
}
] | null |
[] |
package by.soft.testProject.questionnairePortal.dto.request;
import by.soft.testProject.questionnairePortal.entity.User;
import by.soft.testProject.questionnairePortal.exception.ErrorMessageConstants;
import lombok.Data;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
@Data
public class RegistrationUserRequestDto {
@NotNull(message = ErrorMessageConstants.INCORRECT_FIRST_NAME)
private String firstName;
@NotNull(message = ErrorMessageConstants.INCORRECT_LAST_NAME)
private String lastName;
@NotNull(message = ErrorMessageConstants.INCORRECT_PASSWORD)
@Pattern(regexp = ErrorMessageConstants.REGEX_PASSWORD, message = ErrorMessageConstants.INCORRECT_PASSWORD)
private String password;
@Email(message = ErrorMessageConstants.INCORRECT_EMAIL)
@NotNull(message = ErrorMessageConstants.INCORRECT_EMAIL)
private String email;
@NotNull(message = ErrorMessageConstants.INCORRECT_PHONE)
@Pattern(regexp = ErrorMessageConstants.REGEX_PHONE, message = ErrorMessageConstants.INCORRECT_PHONE)
private String phone;
@NotNull(message = ErrorMessageConstants.INCORRECT_ROLE)
private String role;
public User getUser() {
User user = new User();
user.setFirstName(firstName);
user.setLastName(lastName);
user.setPassword(<PASSWORD>);
user.setEmail(email);
user.setPhone(phone);
return user;
}
public String getRole() {
return role.toUpperCase();
}
}
| 1,572 | 0.752229 | 0.752229 | 49 | 31.040817 | 27.932835 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.469388 | false | false |
10
|
047d23d68ec2d329c393fe79223d085bde8523d4
| 32,083,405,730,111 |
cc9a3fc52c5a5dba047d831a8c1578d646c7c032
|
/7주차/2번/BeerSelect.java
|
68b4a097c5a6052f15fbdb7b9168db5b17082a1e
|
[] |
no_license
|
jiwon4178/webProgramming
|
https://github.com/jiwon4178/webProgramming
|
d73df0d3929ccd8fe10a4ca669a3ceefdc4b2421
|
650de77e75851fd52134b71900af7d43d96616a5
|
refs/heads/master
| 2022-12-31T02:01:45.916000 | 2020-10-23T08:43:22 | 2020-10-23T08:43:22 | 294,652,260 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class BeerSelect
*/
@WebServlet("/PJW1")
public class BeerSelect extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public BeerSelect() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Beer Selection Advice<br>");
String c = request.getParameter("color");
out.println("<br>Got Beer Color<br>");
}
}
|
UTF-8
|
Java
| 1,388 |
java
|
BeerSelect.java
|
Java
|
[] | null |
[] |
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class BeerSelect
*/
@WebServlet("/PJW1")
public class BeerSelect extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public BeerSelect() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Beer Selection Advice<br>");
String c = request.getParameter("color");
out.println("<br>Got Beer Color<br>");
}
}
| 1,388 | 0.755764 | 0.753602 | 44 | 30.522728 | 30.390257 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.090909 | false | false |
10
|
ff79e0f0d4b59418c49afab03e848286acf7068d
| 35,321,811,060,068 |
e5aa5e735d53967862f3cac9ae71640dc85fa498
|
/cosmic-core/api/src/main/java/com/cloud/api/command/user/nat/ListIpForwardingRulesCmd.java
|
06259610de49c47a50f6c82c6cc789c834dc32ac
|
[
"Apache-2.0"
] |
permissive
|
MissionCriticalCloud/cosmic
|
https://github.com/MissionCriticalCloud/cosmic
|
93eb8e0fa4d7db63f0fd20d8181ed56ecfaab20b
|
094bdd3b9f23cc80824e194854c489ce782b6090
|
refs/heads/master
| 2023-06-22T16:20:25.140000 | 2022-12-08T15:19:54 | 2022-12-08T15:19:54 | 61,372,044 | 58 | 21 |
Apache-2.0
| false | 2023-09-05T22:00:45 | 2016-06-17T12:28:44 | 2023-08-06T02:21:24 | 2023-09-05T22:00:45 | 28,840 | 55 | 18 | 35 |
Java
| false | false |
package com.cloud.api.command.user.nat;
import com.cloud.api.APICommand;
import com.cloud.api.APICommandGroup;
import com.cloud.api.ApiConstants;
import com.cloud.api.BaseListProjectAndAccountResourcesCmd;
import com.cloud.api.Parameter;
import com.cloud.api.response.FirewallRuleResponse;
import com.cloud.api.response.IPAddressResponse;
import com.cloud.api.response.IpForwardingRuleResponse;
import com.cloud.api.response.ListResponse;
import com.cloud.api.response.UserVmResponse;
import com.cloud.legacymodel.network.FirewallRule;
import com.cloud.legacymodel.network.StaticNatRule;
import com.cloud.legacymodel.utils.Pair;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@APICommand(name = "listIpForwardingRules", group = APICommandGroup.NATService, description = "List the IP forwarding rules", responseObject = FirewallRuleResponse.class,
requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class ListIpForwardingRulesCmd extends BaseListProjectAndAccountResourcesCmd {
public static final Logger s_logger = LoggerFactory.getLogger(ListIpForwardingRulesCmd.class.getName());
private static final String s_name = "listipforwardingrulesresponse";
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@Parameter(name = ApiConstants.IP_ADDRESS_ID,
type = CommandType.UUID,
entityType = IPAddressResponse.class,
description = "list the rule belonging to this public IP address")
private Long publicIpAddressId;
@Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = FirewallRuleResponse.class, description = "Lists rule with the specified ID.")
private Long id;
@Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID,
type = CommandType.UUID,
entityType = UserVmResponse.class,
description = "Lists all rules applied to the specified VM.")
private Long vmId;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public Long getPublicIpAddressId() {
return publicIpAddressId;
}
public Long getId() {
return id;
}
public Long getVmId() {
return vmId;
}
@Override
public void execute() {
final Pair<List<? extends FirewallRule>, Integer> result =
_rulesService.searchStaticNatRules(publicIpAddressId, id, vmId, this.getStartIndex(), this.getPageSizeVal(), this.getAccountName(), this.getDomainId(),
this.getProjectId(), this.isRecursive(), this.listAll());
final ListResponse<IpForwardingRuleResponse> response = new ListResponse<>();
final List<IpForwardingRuleResponse> ipForwardingResponses = new ArrayList<>();
for (final FirewallRule rule : result.first()) {
final StaticNatRule staticNatRule = _rulesService.buildStaticNatRule(rule, false);
final IpForwardingRuleResponse resp = _responseGenerator.createIpForwardingRuleResponse(staticNatRule);
if (resp != null) {
ipForwardingResponses.add(resp);
}
}
response.setResponses(ipForwardingResponses, result.second());
response.setResponseName(getCommandName());
this.setResponseObject(response);
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public String getCommandName() {
return s_name;
}
}
|
UTF-8
|
Java
| 3,800 |
java
|
ListIpForwardingRulesCmd.java
|
Java
|
[] | null |
[] |
package com.cloud.api.command.user.nat;
import com.cloud.api.APICommand;
import com.cloud.api.APICommandGroup;
import com.cloud.api.ApiConstants;
import com.cloud.api.BaseListProjectAndAccountResourcesCmd;
import com.cloud.api.Parameter;
import com.cloud.api.response.FirewallRuleResponse;
import com.cloud.api.response.IPAddressResponse;
import com.cloud.api.response.IpForwardingRuleResponse;
import com.cloud.api.response.ListResponse;
import com.cloud.api.response.UserVmResponse;
import com.cloud.legacymodel.network.FirewallRule;
import com.cloud.legacymodel.network.StaticNatRule;
import com.cloud.legacymodel.utils.Pair;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@APICommand(name = "listIpForwardingRules", group = APICommandGroup.NATService, description = "List the IP forwarding rules", responseObject = FirewallRuleResponse.class,
requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class ListIpForwardingRulesCmd extends BaseListProjectAndAccountResourcesCmd {
public static final Logger s_logger = LoggerFactory.getLogger(ListIpForwardingRulesCmd.class.getName());
private static final String s_name = "listipforwardingrulesresponse";
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@Parameter(name = ApiConstants.IP_ADDRESS_ID,
type = CommandType.UUID,
entityType = IPAddressResponse.class,
description = "list the rule belonging to this public IP address")
private Long publicIpAddressId;
@Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = FirewallRuleResponse.class, description = "Lists rule with the specified ID.")
private Long id;
@Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID,
type = CommandType.UUID,
entityType = UserVmResponse.class,
description = "Lists all rules applied to the specified VM.")
private Long vmId;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public Long getPublicIpAddressId() {
return publicIpAddressId;
}
public Long getId() {
return id;
}
public Long getVmId() {
return vmId;
}
@Override
public void execute() {
final Pair<List<? extends FirewallRule>, Integer> result =
_rulesService.searchStaticNatRules(publicIpAddressId, id, vmId, this.getStartIndex(), this.getPageSizeVal(), this.getAccountName(), this.getDomainId(),
this.getProjectId(), this.isRecursive(), this.listAll());
final ListResponse<IpForwardingRuleResponse> response = new ListResponse<>();
final List<IpForwardingRuleResponse> ipForwardingResponses = new ArrayList<>();
for (final FirewallRule rule : result.first()) {
final StaticNatRule staticNatRule = _rulesService.buildStaticNatRule(rule, false);
final IpForwardingRuleResponse resp = _responseGenerator.createIpForwardingRuleResponse(staticNatRule);
if (resp != null) {
ipForwardingResponses.add(resp);
}
}
response.setResponses(ipForwardingResponses, result.second());
response.setResponseName(getCommandName());
this.setResponseObject(response);
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public String getCommandName() {
return s_name;
}
}
| 3,800 | 0.631842 | 0.631316 | 91 | 40.758244 | 35.801144 | 170 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.681319 | false | false |
10
|
235ff214b7d5b85d11dd8421532364bb1bf6428f
| 35,321,811,055,949 |
3628b8c1f38cd0ac27fa35d58e94757830a5932a
|
/src/Kantine.java
|
9fbe05e7e4c9645636b813e08fed5b9fb0d5fb89
|
[] |
no_license
|
Figueus/Kantine
|
https://github.com/Figueus/Kantine
|
0c6809eede49eb821c5ed87bb3fd4ea71db663ee
|
a2ee45d0b712eaefcc217bf9195a9891cc8ab69d
|
refs/heads/master
| 2020-05-18T02:55:06.616000 | 2015-01-21T09:01:47 | 2015-01-21T09:01:47 | 27,541,832 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Write a description of class Kantine here.
*
* @author Robert van Timmeren & Jan-Bert
* @version 1.9
*/
public class Kantine {
private Kassa kassa;
private KassaRij kassaRij;
private KantineAanbod kantineaanbod;
/**
* Constructor
*/
public Kantine()
{
kassaRij=new KassaRij();
kassa=new Kassa(kassaRij);
}
/**
* In deze methode kiest een Persoon met een dienblad
* de artikelen in artikelnamen.
* @param persoon
* @param artikelnamen
*/
public void loopPakSluitAan(Persoon persoon, String[] artikelnamen)
{
for(int i=0; i<artikelnamen.length; i++)
{
Artikel artikel = kantineaanbod.getArtikel(artikelnamen[i]);
persoon.getDienblad().voegToe(artikel);
kassaRij.sluitAchteraan(persoon);
}
}
/**
* Deze methode handelt de rij voor de kassa af.
*/
public void verwerkRijVoorKassa()
{
while(kassaRij.erIsEenRij())
{
kassa.rekenAf(kassaRij.eerstePersoonInRij());
kassaRij.verwijderUitRij(kassaRij.eerstePersoonInRij());
}
}
/**
* Een getter voor de private instantie
* variabele kassa in de klasse Kantine
*/
public Kassa getKassa()
{
return kassa;
}
/**
* methode om het kantine aanbod te setten in de variabele kantineaanbod.
*/
public void setKantineAanbod(KantineAanbod kantineaanbod)
{
this.kantineaanbod = kantineaanbod;
}
/**
* methode om het kantineaanbod object op te vragen.
*/
public KantineAanbod getKantineAanbod()
{
return this.kantineaanbod;
}
}
|
UTF-8
|
Java
| 1,721 |
java
|
Kantine.java
|
Java
|
[
{
"context": " description of class Kantine here.\n * \n * @author Robert van Timmeren & Jan-Bert\n * @version 1.9\n */\npublic class Kanti",
"end": 85,
"score": 0.9997631907463074,
"start": 66,
"tag": "NAME",
"value": "Robert van Timmeren"
},
{
"context": "Kantine here.\n * \n * @author Robert van Timmeren & Jan-Bert\n * @version 1.9\n */\npublic class Kantine {\n pr",
"end": 96,
"score": 0.9998505115509033,
"start": 88,
"tag": "NAME",
"value": "Jan-Bert"
}
] | null |
[] |
/**
* Write a description of class Kantine here.
*
* @author <NAME> & Jan-Bert
* @version 1.9
*/
public class Kantine {
private Kassa kassa;
private KassaRij kassaRij;
private KantineAanbod kantineaanbod;
/**
* Constructor
*/
public Kantine()
{
kassaRij=new KassaRij();
kassa=new Kassa(kassaRij);
}
/**
* In deze methode kiest een Persoon met een dienblad
* de artikelen in artikelnamen.
* @param persoon
* @param artikelnamen
*/
public void loopPakSluitAan(Persoon persoon, String[] artikelnamen)
{
for(int i=0; i<artikelnamen.length; i++)
{
Artikel artikel = kantineaanbod.getArtikel(artikelnamen[i]);
persoon.getDienblad().voegToe(artikel);
kassaRij.sluitAchteraan(persoon);
}
}
/**
* Deze methode handelt de rij voor de kassa af.
*/
public void verwerkRijVoorKassa()
{
while(kassaRij.erIsEenRij())
{
kassa.rekenAf(kassaRij.eerstePersoonInRij());
kassaRij.verwijderUitRij(kassaRij.eerstePersoonInRij());
}
}
/**
* Een getter voor de private instantie
* variabele kassa in de klasse Kantine
*/
public Kassa getKassa()
{
return kassa;
}
/**
* methode om het kantine aanbod te setten in de variabele kantineaanbod.
*/
public void setKantineAanbod(KantineAanbod kantineaanbod)
{
this.kantineaanbod = kantineaanbod;
}
/**
* methode om het kantineaanbod object op te vragen.
*/
public KantineAanbod getKantineAanbod()
{
return this.kantineaanbod;
}
}
| 1,708 | 0.597327 | 0.595584 | 75 | 21.946667 | 21.293438 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.226667 | false | false |
10
|
70dec529a55ade529ae020684ed5b0c1870c831f
| 6,863,357,789,363 |
1edf1423dbafd3fc6d82e475a77c0da2bec049c3
|
/app/src/main/java/letier/brandon/weatherapp/service/ForecastWebService.java
|
b8d9dd878d7197c9b1be3928b1a948f6338ca7dc
|
[] |
no_license
|
letiger/WeatherApp
|
https://github.com/letiger/WeatherApp
|
fbfaec6c8729d57f126faaf974d019990640b294
|
248042a5ff31a65405a7371cc4f1d3847dce28ea
|
refs/heads/master
| 2020-07-11T20:26:38.225000 | 2019-09-26T17:46:00 | 2019-09-26T17:46:00 | 128,891,645 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package letier.brandon.weatherapp.service;
import android.content.Context;
import io.reactivex.Observable;
import letier.brandon.weatherapp.service.model.Forecast;
import retrofit2.Response;
public interface ForecastWebService {
Observable<Response<Forecast>> getDailyForecast(Context context, String city);
Observable<Response<Forecast>> getDailyForecast(Context context, Double latitude, Double longitude);
}
|
UTF-8
|
Java
| 421 |
java
|
ForecastWebService.java
|
Java
|
[] | null |
[] |
package letier.brandon.weatherapp.service;
import android.content.Context;
import io.reactivex.Observable;
import letier.brandon.weatherapp.service.model.Forecast;
import retrofit2.Response;
public interface ForecastWebService {
Observable<Response<Forecast>> getDailyForecast(Context context, String city);
Observable<Response<Forecast>> getDailyForecast(Context context, Double latitude, Double longitude);
}
| 421 | 0.824228 | 0.821853 | 12 | 34.166668 | 32.145069 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false |
10
|
4bc723911b3bfbc945acc72c39c3e3047f796931
| 773,094,119,401 |
5850b875cf0cd9a92a81f30a2fc377134ca65a1a
|
/src/java/com/exposure101/ubik/event/type/CloseEditorEvent.java
|
d3c14d6b448722f49dd4b9510e86edcff8823dd0
|
[] |
no_license
|
schriste/ubik-shared
|
https://github.com/schriste/ubik-shared
|
744603ed0f4894e7980d47c3ac15f6c3d33f288d
|
5b44b022aa9935623b08f4da0ee57aa51ddf22b8
|
refs/heads/master
| 2016-08-09T08:31:25.374000 | 2015-05-28T02:12:41 | 2015-05-28T02:12:41 | 36,408,339 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.exposure101.ubik.event.type;
import com.exposure101.ubik.event.Event;
import com.exposure101.ubik.event.handler.CloseEditorEventHandler;
import com.exposure101.ubik.mvp.presenter.EditorPresenter;
public interface CloseEditorEvent {
class GroupLayer implements Event<CloseEditorEventHandler.GroupLayer> {
public static final Event.Type<CloseEditorEventHandler.GroupLayer> TYPE = new Event.Type<CloseEditorEventHandler.GroupLayer>() {
};
private EditorPresenter editorPresenter;
public GroupLayer(EditorPresenter editorPresenter) {
this.editorPresenter = editorPresenter;
}
public EditorPresenter getEditorPresenter() {
return editorPresenter;
}
@Override
public Event.Type<CloseEditorEventHandler.GroupLayer> getType() {
return TYPE;
}
@Override
public void dispatch(CloseEditorEventHandler.GroupLayer handler) {
handler.handle(this);
}
}
class Level implements Event<CloseEditorEventHandler.Level> {
public static final Event.Type<CloseEditorEventHandler.Level> TYPE = new Event.Type<CloseEditorEventHandler.Level>() {
};
private EditorPresenter editorPresenter;
public Level(EditorPresenter editorPresenter) {
this.editorPresenter = editorPresenter;
}
public EditorPresenter getEditorPresenter() {
return editorPresenter;
}
@Override
public Event.Type<CloseEditorEventHandler.Level> getType() {
return TYPE;
}
@Override
public void dispatch(com.exposure101.ubik.event.handler.CloseEditorEventHandler.Level handler) {
handler.handle(this);
}
}
}
|
UTF-8
|
Java
| 1,668 |
java
|
CloseEditorEvent.java
|
Java
|
[] | null |
[] |
package com.exposure101.ubik.event.type;
import com.exposure101.ubik.event.Event;
import com.exposure101.ubik.event.handler.CloseEditorEventHandler;
import com.exposure101.ubik.mvp.presenter.EditorPresenter;
public interface CloseEditorEvent {
class GroupLayer implements Event<CloseEditorEventHandler.GroupLayer> {
public static final Event.Type<CloseEditorEventHandler.GroupLayer> TYPE = new Event.Type<CloseEditorEventHandler.GroupLayer>() {
};
private EditorPresenter editorPresenter;
public GroupLayer(EditorPresenter editorPresenter) {
this.editorPresenter = editorPresenter;
}
public EditorPresenter getEditorPresenter() {
return editorPresenter;
}
@Override
public Event.Type<CloseEditorEventHandler.GroupLayer> getType() {
return TYPE;
}
@Override
public void dispatch(CloseEditorEventHandler.GroupLayer handler) {
handler.handle(this);
}
}
class Level implements Event<CloseEditorEventHandler.Level> {
public static final Event.Type<CloseEditorEventHandler.Level> TYPE = new Event.Type<CloseEditorEventHandler.Level>() {
};
private EditorPresenter editorPresenter;
public Level(EditorPresenter editorPresenter) {
this.editorPresenter = editorPresenter;
}
public EditorPresenter getEditorPresenter() {
return editorPresenter;
}
@Override
public Event.Type<CloseEditorEventHandler.Level> getType() {
return TYPE;
}
@Override
public void dispatch(com.exposure101.ubik.event.handler.CloseEditorEventHandler.Level handler) {
handler.handle(this);
}
}
}
| 1,668 | 0.726619 | 0.717626 | 60 | 26.799999 | 31.0273 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.266667 | false | false |
10
|
3fc7cb30eda4dda6a1b6ba13280cba1395684ddc
| 3,350,074,496,682 |
3ce811e60d04cb848cf5e0045c8adc9c2cbb7867
|
/src/main/java/falah/falah_api/repository/CommentRepository.java
|
befec52dcac54aeb2762639c780f99dbeac2560b
|
[] |
no_license
|
salekin01/testAPI
|
https://github.com/salekin01/testAPI
|
263ae9de2bbf6023dc3e95626d86117202a9ced9
|
8bb349a0509fb75601feea61a8843dbba12c17ba
|
refs/heads/master
| 2023-01-03T04:56:57.309000 | 2020-10-21T23:33:09 | 2020-10-21T23:33:09 | 305,820,274 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package falah.falah_api.repository;
import falah.falah_api.model.Comment;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface CommentRepository extends JpaRepository<Comment, Long> {
@Query("select c from Comment c where c.blog.blogId = :blogId")
public List<Comment> getCommentsByBlogId(@Param("blogId") long blogId);
//doesn't work
@Modifying(clearAutomatically=true, flushAutomatically=true)
@Query("delete from Comment c where c.blog.blogId = :blogId")
public void deleteCommentsByBlogId(@Param("blogId") long blogId);
}
|
UTF-8
|
Java
| 772 |
java
|
CommentRepository.java
|
Java
|
[] | null |
[] |
package falah.falah_api.repository;
import falah.falah_api.model.Comment;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface CommentRepository extends JpaRepository<Comment, Long> {
@Query("select c from Comment c where c.blog.blogId = :blogId")
public List<Comment> getCommentsByBlogId(@Param("blogId") long blogId);
//doesn't work
@Modifying(clearAutomatically=true, flushAutomatically=true)
@Query("delete from Comment c where c.blog.blogId = :blogId")
public void deleteCommentsByBlogId(@Param("blogId") long blogId);
}
| 772 | 0.782383 | 0.782383 | 20 | 37.599998 | 28.685188 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.55 | false | false |
10
|
5bf08524565edfb79833a56273a99a2818691b95
| 12,378,095,753,332 |
dbdd5f1caf4d5117560d3588aeec7950c3adbe9a
|
/src/Setup.java
|
d16a0977747e7bc3b270b053291644269d7bcd24
|
[] |
no_license
|
bzkxzol/FileCommands
|
https://github.com/bzkxzol/FileCommands
|
7435cde3bc30c23cc0fa51e136304c9146a72318
|
2c0bdad5b9c81d4a9b0ad8651ae90ecf234b16e3
|
refs/heads/master
| 2021-01-02T22:54:05.059000 | 2017-08-07T12:33:31 | 2017-08-07T12:33:31 | 99,416,565 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.io.*;
import java.nio.file.NoSuchFileException;
import java.util.concurrent.TimeUnit;
public class Setup {
protected static File MergeFiles(String fileName1, String fileName2) throws InterruptedException {
File file1 = new File (fileName1);
File file2 = new File (fileName2);
CheckFileExist (file1);
CheckFileExist (file2);
File mergedFile = new File ("Merged_" + fileName1.substring (0,fileName1.lastIndexOf (".")) + "_" + fileName2.substring (0,fileName2.lastIndexOf (".")) + ".txt" );
FromFileToFile (file1, mergedFile);
FromFileToFile (file2, mergedFile);
return mergedFile;
}
private static void FromFileToFile(File source, File dest) {
FileReader fr;
BufferedReader reader;
FileWriter fw;
String data;
try {
fw = new FileWriter (dest , true);
fr = new FileReader (source);
reader = new BufferedReader (fr);
while (true) {
data = reader.readLine ();
if (data != null)
fw.write (data + "\n");
else
break;
}
fw.close ();
fr.close ();
reader.close ();
} catch (IOException e) {
e.getMessage ();
}
}
private static void CheckFileExist(File name) throws InterruptedException {
try{
if(!name.isFile())
throw new NoSuchFileException("Файл не найден по указанному пути");
}catch (NoSuchFileException e){
System.out.println(e.getMessage());
TimeUnit.SECONDS.sleep(3);
System.exit(9);
}
}
}
|
UTF-8
|
Java
| 1,767 |
java
|
Setup.java
|
Java
|
[] | null |
[] |
import java.io.*;
import java.nio.file.NoSuchFileException;
import java.util.concurrent.TimeUnit;
public class Setup {
protected static File MergeFiles(String fileName1, String fileName2) throws InterruptedException {
File file1 = new File (fileName1);
File file2 = new File (fileName2);
CheckFileExist (file1);
CheckFileExist (file2);
File mergedFile = new File ("Merged_" + fileName1.substring (0,fileName1.lastIndexOf (".")) + "_" + fileName2.substring (0,fileName2.lastIndexOf (".")) + ".txt" );
FromFileToFile (file1, mergedFile);
FromFileToFile (file2, mergedFile);
return mergedFile;
}
private static void FromFileToFile(File source, File dest) {
FileReader fr;
BufferedReader reader;
FileWriter fw;
String data;
try {
fw = new FileWriter (dest , true);
fr = new FileReader (source);
reader = new BufferedReader (fr);
while (true) {
data = reader.readLine ();
if (data != null)
fw.write (data + "\n");
else
break;
}
fw.close ();
fr.close ();
reader.close ();
} catch (IOException e) {
e.getMessage ();
}
}
private static void CheckFileExist(File name) throws InterruptedException {
try{
if(!name.isFile())
throw new NoSuchFileException("Файл не найден по указанному пути");
}catch (NoSuchFileException e){
System.out.println(e.getMessage());
TimeUnit.SECONDS.sleep(3);
System.exit(9);
}
}
}
| 1,767 | 0.549741 | 0.53939 | 61 | 27.508196 | 28.673185 | 171 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.590164 | false | false |
10
|
a67a4d4d4c5e94c21c41ab883ff1db7de3896292
| 12,687,333,400,227 |
aeb14e5247558e2bf8f037a690de7069128ac7a0
|
/java/botanyMain/Crafting.java
|
9050147e3570ec71dc6d9d2ebee618d1d8b11d7e
|
[] |
no_license
|
LucasSchuetz/theBotonyMod
|
https://github.com/LucasSchuetz/theBotonyMod
|
15ce2fa597b497c2ebd825337661b632643cf72a
|
49472efa58236bf3edad70ea27dfa35cbe4c14d1
|
refs/heads/master
| 2021-01-17T16:13:18.227000 | 2014-09-29T01:48:35 | 2014-09-29T01:48:35 | 23,158,230 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package botanyMain;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.registry.GameRegistry;
/** Crafting Recipe Skeletons **
* Shapeless Recipe:
* GameRegistry.addShapelessRecipe(new ItemStack(Base.Blocks/Items, X, Y), new Object[]{
* new ItemStack(Items.whatever), new ItemStack(Blocks.whatever)
*
* -- Can use as many as necessary (up to 9 obviously), X = quantity, Y = metadata is needed. First
* parameter is what Items is returned (can return more than one!) and second is new object that contains
* whatever Blockss are used to make the output, can take more then one and use metadatas.
*
* Shaped Recipe:
* GameRegistry.addRecipe(new ItemStack(Base.Blocks/Items), new Object[]{
* "CRC",
* "RZR",
* "CRC",
* 'C', Items.whatever, 'R', Blocks.whatever, 'Z', new ItemStack(Base.whatever, X, Y)});
*
* -- Can use up to 9 as well, X = quantity, Y = metadata. Clearly laid out for easy to read. Shows
* the crafting table in a 3x3. First parameter is output, amount and metas CAN be included but are not
* required, second parameter is the crafting table part.
*
*/
public class Crafting
{
public static void addRecipes()
{
GameRegistry.addShapedRecipe(new ItemStack(Base.itemThornedBranch), new Object[]{
"ZXZ",
"YXY",
"ZXZ",
'Z', new ItemStack(Blocks.vine), 'Y', new ItemStack(Blocks.cactus), 'X', new ItemStack(Items.stick)});
GameRegistry.addShapedRecipe(new ItemStack(Base.itemVileFlesh), new Object[]{
"Z",
"Y",
"X",
'Z', new ItemStack(Items.potionitem, 1, 0), 'Y', new ItemStack(Base.itemMatter, 1, 3), 'X', new ItemStack(Items.rotten_flesh)});
GameRegistry.addShapedRecipe(new ItemStack(Base.blockSalvagedPlanks, 2), new Object[]{
"XX",
"XX",
'X', new ItemStack(Base.blockRottenPlanks)});
GameRegistry.addShapedRecipe(new ItemStack(Base.blockGemGlass, 2), new Object[]{
"XX",
"XX",
'X', new ItemStack(Base.itemMobPart, 1, 12)});
GameRegistry.addShapedRecipe(new ItemStack(Base.itemFangBlade, 2), new Object[]{
"X",
"X",
"Y",
'X', new ItemStack(Base.itemMobPart, 1, 7), 'Y', new ItemStack(Items.stick)});
GameRegistry.addShapedRecipe(new ItemStack(Base.blockGemGlass, 2), new Object[]{
"XX",
"XX",
'X', new ItemStack(Base.itemGemRootShard)});
GameRegistry.addShapelessRecipe(new ItemStack(Base.blockRottenPlanks, 4), new Object[]{
new ItemStack(Base.blockInfectedLog)});
GameRegistry.addShapelessRecipe(new ItemStack(Base.blockShroomWood, 4), new Object[]{
new ItemStack(Base.blockBlueMushroomStem)});
GameRegistry.addShapelessRecipe(new ItemStack(Base.itemMatter, 1, 3), new Object[]{
new ItemStack(Base.blockVileMushroom)});
GameRegistry.addShapelessRecipe(new ItemStack(Base.itemGemRootShard, 2), new Object[]{
new ItemStack(Base.blockGemRoot)});
BiologyCrafting();
SmeltingRecipes();
}
//Recipes for Photo mod module
public static void BiologyCrafting()
{
//Compost recipe loop for each metadata'ed mobPart
// 3 Paper, 3 Plant Greens, and 3 of any other mob part
for(int i = 0; i < 6; i++)
{
for(int j = 0; j < 6; j++)
{
for(int k = 0; k < 6; k++)
{
ItemStack iMobPart = new ItemStack(Base.itemMobPart, 1, i);
ItemStack jMobPart = new ItemStack(Base.itemMobPart, 1, j);
ItemStack kMobPart = new ItemStack(Base.itemMobPart, 1, k);
GameRegistry.addShapelessRecipe(new ItemStack(Base.itemCompost), new Object[]{
new ItemStack(Items.paper), new ItemStack(Items.paper), new ItemStack(Items.paper),
iMobPart, jMobPart, kMobPart,
new ItemStack(Base.itemMobPart, 1, 6), new ItemStack(Base.itemMobPart, 1, 5), new ItemStack(Base.itemMobPart, 1, 6)});
}
}
}
GameRegistry.addShapedRecipe(new ItemStack(Base.itemThornedBranch), new Object[]{
"ZXZ",
"YXY",
"ZXZ",
'Z', new ItemStack(Blocks.vine), 'Y', new ItemStack(Blocks.cactus), 'X', new ItemStack(Items.stick)});
GameRegistry.addShapedRecipe(new ItemStack(Base.itemStoneCrown), new Object[]{
"XYX",
"XZX",
"XXX",
'Y', new ItemStack(Blocks.soul_sand), 'Z', new ItemStack(Blocks.enchanting_table), 'X', new ItemStack(Blocks.stonebrick)});
GameRegistry.addShapedRecipe(new ItemStack(Base.blockCropStaff), new Object[]{
" Z",
" Y ",
"X ",
'X', new ItemStack(Base.itemThornedBranch), 'Y', new ItemStack(Items.slime_ball), 'Z', new ItemStack(Base.itemStoneCrown)});
GameRegistry.addShapedRecipe(new ItemStack(Base.blockLifeBasin), new Object[]{
"XWX",
"ZYZ",
"XVX",
'X', new ItemStack(Items.bone), 'Y', new ItemStack(Blocks.glass), 'Z', new ItemStack(Blocks.soul_sand),
'V', new ItemStack(Blocks.hopper), 'W', new ItemStack(Blocks.daylight_detector)});
GameRegistry.addShapelessRecipe(new ItemStack(Base.blockFungleGrass, 4), new Object[]{
new ItemStack(Blocks.dirt), new ItemStack(Blocks.dirt), new ItemStack(Blocks.dirt),
new ItemStack(Blocks.red_mushroom), new ItemStack(Blocks.red_mushroom), new ItemStack(Blocks.red_mushroom),
new ItemStack(Blocks.brown_mushroom), new ItemStack(Blocks.brown_mushroom), new ItemStack(Blocks.brown_mushroom)});
}
/**
* Smelting Recipe:
* GameRegistry.addSmelting(input, new ItemStack(output), exp);
*
* --- OTHER NOTES ---
* /-\Recipes also may allow for enchants in output and input but declaring it as a new variable (shown below)/-\
*
* -- ItemStack enchanted = new ItemStack(Items.pickaxeStone);
* -- enchanted.addEnchantment(Enchantment.sharpness, 2);
*
* 2 being the level of the enchant and sharpness being the enchant type. Enchants the Items declared about it.
* The Items, enchant, and level may be changed! These are only examples!
**/
public static void SmeltingRecipes()
{
GameRegistry.addSmelting(Base.itemCrabMorsel, new ItemStack(Base.itemCookedCrabMorsel), 0.2F);
}
}
|
UTF-8
|
Java
| 5,900 |
java
|
Crafting.java
|
Java
|
[] | null |
[] |
package botanyMain;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.registry.GameRegistry;
/** Crafting Recipe Skeletons **
* Shapeless Recipe:
* GameRegistry.addShapelessRecipe(new ItemStack(Base.Blocks/Items, X, Y), new Object[]{
* new ItemStack(Items.whatever), new ItemStack(Blocks.whatever)
*
* -- Can use as many as necessary (up to 9 obviously), X = quantity, Y = metadata is needed. First
* parameter is what Items is returned (can return more than one!) and second is new object that contains
* whatever Blockss are used to make the output, can take more then one and use metadatas.
*
* Shaped Recipe:
* GameRegistry.addRecipe(new ItemStack(Base.Blocks/Items), new Object[]{
* "CRC",
* "RZR",
* "CRC",
* 'C', Items.whatever, 'R', Blocks.whatever, 'Z', new ItemStack(Base.whatever, X, Y)});
*
* -- Can use up to 9 as well, X = quantity, Y = metadata. Clearly laid out for easy to read. Shows
* the crafting table in a 3x3. First parameter is output, amount and metas CAN be included but are not
* required, second parameter is the crafting table part.
*
*/
public class Crafting
{
public static void addRecipes()
{
GameRegistry.addShapedRecipe(new ItemStack(Base.itemThornedBranch), new Object[]{
"ZXZ",
"YXY",
"ZXZ",
'Z', new ItemStack(Blocks.vine), 'Y', new ItemStack(Blocks.cactus), 'X', new ItemStack(Items.stick)});
GameRegistry.addShapedRecipe(new ItemStack(Base.itemVileFlesh), new Object[]{
"Z",
"Y",
"X",
'Z', new ItemStack(Items.potionitem, 1, 0), 'Y', new ItemStack(Base.itemMatter, 1, 3), 'X', new ItemStack(Items.rotten_flesh)});
GameRegistry.addShapedRecipe(new ItemStack(Base.blockSalvagedPlanks, 2), new Object[]{
"XX",
"XX",
'X', new ItemStack(Base.blockRottenPlanks)});
GameRegistry.addShapedRecipe(new ItemStack(Base.blockGemGlass, 2), new Object[]{
"XX",
"XX",
'X', new ItemStack(Base.itemMobPart, 1, 12)});
GameRegistry.addShapedRecipe(new ItemStack(Base.itemFangBlade, 2), new Object[]{
"X",
"X",
"Y",
'X', new ItemStack(Base.itemMobPart, 1, 7), 'Y', new ItemStack(Items.stick)});
GameRegistry.addShapedRecipe(new ItemStack(Base.blockGemGlass, 2), new Object[]{
"XX",
"XX",
'X', new ItemStack(Base.itemGemRootShard)});
GameRegistry.addShapelessRecipe(new ItemStack(Base.blockRottenPlanks, 4), new Object[]{
new ItemStack(Base.blockInfectedLog)});
GameRegistry.addShapelessRecipe(new ItemStack(Base.blockShroomWood, 4), new Object[]{
new ItemStack(Base.blockBlueMushroomStem)});
GameRegistry.addShapelessRecipe(new ItemStack(Base.itemMatter, 1, 3), new Object[]{
new ItemStack(Base.blockVileMushroom)});
GameRegistry.addShapelessRecipe(new ItemStack(Base.itemGemRootShard, 2), new Object[]{
new ItemStack(Base.blockGemRoot)});
BiologyCrafting();
SmeltingRecipes();
}
//Recipes for Photo mod module
public static void BiologyCrafting()
{
//Compost recipe loop for each metadata'ed mobPart
// 3 Paper, 3 Plant Greens, and 3 of any other mob part
for(int i = 0; i < 6; i++)
{
for(int j = 0; j < 6; j++)
{
for(int k = 0; k < 6; k++)
{
ItemStack iMobPart = new ItemStack(Base.itemMobPart, 1, i);
ItemStack jMobPart = new ItemStack(Base.itemMobPart, 1, j);
ItemStack kMobPart = new ItemStack(Base.itemMobPart, 1, k);
GameRegistry.addShapelessRecipe(new ItemStack(Base.itemCompost), new Object[]{
new ItemStack(Items.paper), new ItemStack(Items.paper), new ItemStack(Items.paper),
iMobPart, jMobPart, kMobPart,
new ItemStack(Base.itemMobPart, 1, 6), new ItemStack(Base.itemMobPart, 1, 5), new ItemStack(Base.itemMobPart, 1, 6)});
}
}
}
GameRegistry.addShapedRecipe(new ItemStack(Base.itemThornedBranch), new Object[]{
"ZXZ",
"YXY",
"ZXZ",
'Z', new ItemStack(Blocks.vine), 'Y', new ItemStack(Blocks.cactus), 'X', new ItemStack(Items.stick)});
GameRegistry.addShapedRecipe(new ItemStack(Base.itemStoneCrown), new Object[]{
"XYX",
"XZX",
"XXX",
'Y', new ItemStack(Blocks.soul_sand), 'Z', new ItemStack(Blocks.enchanting_table), 'X', new ItemStack(Blocks.stonebrick)});
GameRegistry.addShapedRecipe(new ItemStack(Base.blockCropStaff), new Object[]{
" Z",
" Y ",
"X ",
'X', new ItemStack(Base.itemThornedBranch), 'Y', new ItemStack(Items.slime_ball), 'Z', new ItemStack(Base.itemStoneCrown)});
GameRegistry.addShapedRecipe(new ItemStack(Base.blockLifeBasin), new Object[]{
"XWX",
"ZYZ",
"XVX",
'X', new ItemStack(Items.bone), 'Y', new ItemStack(Blocks.glass), 'Z', new ItemStack(Blocks.soul_sand),
'V', new ItemStack(Blocks.hopper), 'W', new ItemStack(Blocks.daylight_detector)});
GameRegistry.addShapelessRecipe(new ItemStack(Base.blockFungleGrass, 4), new Object[]{
new ItemStack(Blocks.dirt), new ItemStack(Blocks.dirt), new ItemStack(Blocks.dirt),
new ItemStack(Blocks.red_mushroom), new ItemStack(Blocks.red_mushroom), new ItemStack(Blocks.red_mushroom),
new ItemStack(Blocks.brown_mushroom), new ItemStack(Blocks.brown_mushroom), new ItemStack(Blocks.brown_mushroom)});
}
/**
* Smelting Recipe:
* GameRegistry.addSmelting(input, new ItemStack(output), exp);
*
* --- OTHER NOTES ---
* /-\Recipes also may allow for enchants in output and input but declaring it as a new variable (shown below)/-\
*
* -- ItemStack enchanted = new ItemStack(Items.pickaxeStone);
* -- enchanted.addEnchantment(Enchantment.sharpness, 2);
*
* 2 being the level of the enchant and sharpness being the enchant type. Enchants the Items declared about it.
* The Items, enchant, and level may be changed! These are only examples!
**/
public static void SmeltingRecipes()
{
GameRegistry.addSmelting(Base.itemCrabMorsel, new ItemStack(Base.itemCookedCrabMorsel), 0.2F);
}
}
| 5,900 | 0.699831 | 0.692203 | 142 | 40.556339 | 39.079464 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.485915 | false | false |
10
|
0525cd0e4cae7da6dcac93cab2949e9565cd0999
| 24,627,342,480,144 |
857b63fad61d93b4c83add0c19cbba88e4ea5967
|
/Block.java
|
e0527abf00fecc29ff37fd8db68243ee5a993cbe
|
[] |
no_license
|
NassimBennouar/myJavaBlockchain
|
https://github.com/NassimBennouar/myJavaBlockchain
|
bd0f9368b4f708204137a297be7cfc2e653674e5
|
69896b6611cf66afeceb12ec8e2eef072d28fac2
|
refs/heads/master
| 2021-02-04T08:46:33.520000 | 2020-02-28T00:31:03 | 2020-02-28T00:31:03 | 243,645,288 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package myJavaBlockchain;
import java.security.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import org.json.JSONObject;
public class Block {
private static int currentIndex=0;
private static final int DIFFICULTY_THRESHOLD=Cryptools.MY_HASHFUNC_LENGTH-5;
private int id;
private String hash;
private String prevHash;
private long timestamp;
private String data;
private int nonce;
private ArrayList<Transaction> transactions;
public Block(String prevHash,String data) {
this.id=Block.currentIndex;
Block.currentIndex++;
this.prevHash=prevHash;
this.timestamp=new Date().getTime();
this.data=data;
this.nonce=0;
this.hash=this.calcHash();
this.transactions=new ArrayList<>();
}
public Block(String prevHash) {
this.id=Block.currentIndex;
Block.currentIndex++;
this.prevHash=prevHash;
this.timestamp=new Date().getTime();
this.data="";
this.nonce=0;
this.hash=this.calcHash();
this.transactions=new ArrayList<>();
}
public ArrayList<Transaction> getTransactions(){
return this.transactions;
}
public int getID() {
return this.id;
}
public String calcHash(){
return Cryptools.plainToSHA256(Integer.toString(this.id)+this.data+this.prevHash+Long.toString(this.timestamp)+Integer.toString(this.nonce));
}
public void mineBlock(int difficulty) { //Hashcash PoW
if(difficulty<1 || difficulty>DIFFICULTY_THRESHOLD)
throw new Error("The difficulty must be included between 0 and "+DIFFICULTY_THRESHOLD);
//Random r = new Random();
String zero="";
for(int i=0;i<difficulty;i++)
zero+="0";
do {
this.nonce++;
this.hash=this.calcHash();
//System.out.println(this.hash);
} while(!this.hash.substring(0, difficulty).equals(zero));
this.hash=this.calcHash();
System.out.println("Block mined dude :) "+this.hash);
}
public boolean addTransaction(Transaction transaction) {
if (transaction==null) //NUL NUL NUL!!!!!
return false;
if(this.prevHash != "0") { //Si le bloc précédent est po la génèse
if(transaction.process()!=true) {
System.err.println("Operation aborted : transaction failed");
return false;
}
}
this.transactions.add(transaction);
System.out.println("Success : Transaction added to block :) :D :) :D");
return true;
}
public JSONObject getJSONObject() {
JSONObject json=new JSONObject();
json.append("id", this.id);
json.append("timestamp", this.timestamp);
json.append("prevHash", this.prevHash);
json.append("hash", this.hash);
json.append("data", this.data);
json.append("nonce", this.nonce);
return json;
}
@Override
public String toString() {
return this.getJSONObject().toString();
}
public String getHash() {
return this.hash;
}
public String getPrevHash() {
return this.prevHash;
}
public int getNonce() {
return this.nonce;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Block other = (Block) obj;
if (id != other.id)
return false;
return true;
}
}
|
UTF-8
|
Java
| 3,275 |
java
|
Block.java
|
Java
|
[] | null |
[] |
package myJavaBlockchain;
import java.security.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import org.json.JSONObject;
public class Block {
private static int currentIndex=0;
private static final int DIFFICULTY_THRESHOLD=Cryptools.MY_HASHFUNC_LENGTH-5;
private int id;
private String hash;
private String prevHash;
private long timestamp;
private String data;
private int nonce;
private ArrayList<Transaction> transactions;
public Block(String prevHash,String data) {
this.id=Block.currentIndex;
Block.currentIndex++;
this.prevHash=prevHash;
this.timestamp=new Date().getTime();
this.data=data;
this.nonce=0;
this.hash=this.calcHash();
this.transactions=new ArrayList<>();
}
public Block(String prevHash) {
this.id=Block.currentIndex;
Block.currentIndex++;
this.prevHash=prevHash;
this.timestamp=new Date().getTime();
this.data="";
this.nonce=0;
this.hash=this.calcHash();
this.transactions=new ArrayList<>();
}
public ArrayList<Transaction> getTransactions(){
return this.transactions;
}
public int getID() {
return this.id;
}
public String calcHash(){
return Cryptools.plainToSHA256(Integer.toString(this.id)+this.data+this.prevHash+Long.toString(this.timestamp)+Integer.toString(this.nonce));
}
public void mineBlock(int difficulty) { //Hashcash PoW
if(difficulty<1 || difficulty>DIFFICULTY_THRESHOLD)
throw new Error("The difficulty must be included between 0 and "+DIFFICULTY_THRESHOLD);
//Random r = new Random();
String zero="";
for(int i=0;i<difficulty;i++)
zero+="0";
do {
this.nonce++;
this.hash=this.calcHash();
//System.out.println(this.hash);
} while(!this.hash.substring(0, difficulty).equals(zero));
this.hash=this.calcHash();
System.out.println("Block mined dude :) "+this.hash);
}
public boolean addTransaction(Transaction transaction) {
if (transaction==null) //NUL NUL NUL!!!!!
return false;
if(this.prevHash != "0") { //Si le bloc précédent est po la génèse
if(transaction.process()!=true) {
System.err.println("Operation aborted : transaction failed");
return false;
}
}
this.transactions.add(transaction);
System.out.println("Success : Transaction added to block :) :D :) :D");
return true;
}
public JSONObject getJSONObject() {
JSONObject json=new JSONObject();
json.append("id", this.id);
json.append("timestamp", this.timestamp);
json.append("prevHash", this.prevHash);
json.append("hash", this.hash);
json.append("data", this.data);
json.append("nonce", this.nonce);
return json;
}
@Override
public String toString() {
return this.getJSONObject().toString();
}
public String getHash() {
return this.hash;
}
public String getPrevHash() {
return this.prevHash;
}
public int getNonce() {
return this.nonce;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Block other = (Block) obj;
if (id != other.id)
return false;
return true;
}
}
| 3,275 | 0.692449 | 0.687557 | 141 | 22.198582 | 20.772739 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.156028 | false | false |
10
|
b6889d295bf3ec3fb8e7b473cd0d1b9ae39391e3
| 1,176,821,075,508 |
d6bcd74c26428f29cf793c33ce74653b9690b55c
|
/YourBook/src/exception/IllegalArgumentException.java
|
26c2aaba3be70a305d2d0f74ff0397083ae54d56
|
[] |
no_license
|
paolopetta/YourBook
|
https://github.com/paolopetta/YourBook
|
44cec3bd95c96e68cec45f9e057e9b501de653a6
|
0af1dcffe9c9cfc6b97dc774bbd1afb1dd1d69e9
|
refs/heads/master
| 2023-07-29T11:20:41.427000 | 2021-09-12T10:05:39 | 2021-09-12T10:05:39 | 303,450,391 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package exception;
import javax.servlet.ServletException;
public class IllegalArgumentException extends ServletException {
private static final long serialVersionUID = 1L;
public IllegalArgumentException() {
super();
}
public IllegalArgumentException(String message, Throwable rootCause) {
super(message, rootCause);
}
public IllegalArgumentException(String message) {
super(message);
}
public IllegalArgumentException(Throwable rootCause) {
super(rootCause);
}
}
|
UTF-8
|
Java
| 537 |
java
|
IllegalArgumentException.java
|
Java
|
[] | null |
[] |
package exception;
import javax.servlet.ServletException;
public class IllegalArgumentException extends ServletException {
private static final long serialVersionUID = 1L;
public IllegalArgumentException() {
super();
}
public IllegalArgumentException(String message, Throwable rootCause) {
super(message, rootCause);
}
public IllegalArgumentException(String message) {
super(message);
}
public IllegalArgumentException(Throwable rootCause) {
super(rootCause);
}
}
| 537 | 0.711359 | 0.709497 | 23 | 22.391304 | 23.658327 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.391304 | false | false |
10
|
ffe0fd4236c2db56c66a8fa51a8ec403f8c4d805
| 20,779,051,801,912 |
4a606b7a7babf5a9446045b1ff08985d237fa9a7
|
/src/main/java/org/lima/vertx/mod_was/handler/EBDataHandler.java
|
a08ba1af43c6e13112ce6f411bf71602f21a5c93
|
[] |
no_license
|
sungtaek/mod-was
|
https://github.com/sungtaek/mod-was
|
4092d1d5e8b602e032c9e48ac2c29f195d6ddcf7
|
773b63b335834e0bb29f71ee553c3574f8ca8943
|
refs/heads/master
| 2016-09-15T21:12:33.290000 | 2015-05-27T14:31:38 | 2015-05-27T14:31:38 | 35,374,993 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.lima.vertx.mod_was.handler;
import org.vertx.java.core.Handler;
import org.vertx.java.core.eventbus.Message;
public abstract class EBDataHandler<T> implements Handler<Message<T>>{
private Message<T> msg;
@Override
public void handle(Message<T> msg) {
this.msg = msg;
handleData(msg.body());
}
public void sendReply(T data) {
msg.reply(data);
}
public void sendFailure(int failureCode, String message) {
msg.fail(failureCode, message);
}
public abstract void handleData(T data);
}
|
UTF-8
|
Java
| 531 |
java
|
EBDataHandler.java
|
Java
|
[] | null |
[] |
package org.lima.vertx.mod_was.handler;
import org.vertx.java.core.Handler;
import org.vertx.java.core.eventbus.Message;
public abstract class EBDataHandler<T> implements Handler<Message<T>>{
private Message<T> msg;
@Override
public void handle(Message<T> msg) {
this.msg = msg;
handleData(msg.body());
}
public void sendReply(T data) {
msg.reply(data);
}
public void sendFailure(int failureCode, String message) {
msg.fail(failureCode, message);
}
public abstract void handleData(T data);
}
| 531 | 0.711864 | 0.711864 | 20 | 24.549999 | 20.123308 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.4 | false | false |
10
|
00cc776162faa053e8fdd968a7102073f41788a0
| 9,775,345,594,091 |
f41584418aed7f733c29f2ffdc4c32bba912ba1f
|
/ScheduleArray.java
|
0fa40ba24ec99497859a934eb94ab0c3b0a8e5f1
|
[] |
no_license
|
t-griggs/schedule-manager
|
https://github.com/t-griggs/schedule-manager
|
57a4814fe0041d45b81bfe915d67fd2d744630f2
|
988e4749629395f656e4bb39dacb13b4d99b0d44
|
refs/heads/master
| 2016-09-13T15:15:49.081000 | 2016-05-18T22:24:50 | 2016-05-18T22:24:50 | 58,881,933 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class ScheduleArray {
public static int length = 340;
public static int timeIncrement = 10;
public static String startTime = "9:00";
private Availability[] availabilty;
public Availability get(int index){
return availabilty[index];
}
public static int toScheduleIndex(Day day, int time){
int dayMultiplier = ScheduleArray.length / 5;
int timeVal = time - getIntTime(ScheduleArray.startTime);
int timeIndex = timeVal / ScheduleArray.timeIncrement;
switch(day){
case M: return timeIndex;
case T: return timeIndex + dayMultiplier;
case W: return timeIndex + dayMultiplier * 2;
case TH: return timeIndex + dayMultiplier * 3;
case F: return timeIndex + dayMultiplier * 4;
default: throw new IllegalArgumentException("Invalid day of the week entered: "
+ day);
}
}
private static int getIntTime(String time){
int intTime = 0;
if(time.length() == 4 ){ // e.g. 1:20
intTime+= 12 * 60; // military time adjustment
intTime+= Character.getNumericValue(time.charAt(0)) * 60;
intTime+= Character.getNumericValue(time.charAt(2)) * 10;
intTime+= Character.getNumericValue(time.charAt(3));
}
if(time.length() == 5 ){ // e.g. 12:15
intTime+= Character.getNumericValue(time.charAt(0)) * 60 * 10;
intTime+= Character.getNumericValue(time.charAt(1)) * 60;
intTime+= Character.getNumericValue(time.charAt(3)) * 10;
intTime+= Character.getNumericValue(time.charAt(4));
}
if(intTime ==0){
throw new IllegalArgumentException("Invalid time of day entered: "
+ time);
}
return intTime;
}
}
|
UTF-8
|
Java
| 1,578 |
java
|
ScheduleArray.java
|
Java
|
[] | null |
[] |
public class ScheduleArray {
public static int length = 340;
public static int timeIncrement = 10;
public static String startTime = "9:00";
private Availability[] availabilty;
public Availability get(int index){
return availabilty[index];
}
public static int toScheduleIndex(Day day, int time){
int dayMultiplier = ScheduleArray.length / 5;
int timeVal = time - getIntTime(ScheduleArray.startTime);
int timeIndex = timeVal / ScheduleArray.timeIncrement;
switch(day){
case M: return timeIndex;
case T: return timeIndex + dayMultiplier;
case W: return timeIndex + dayMultiplier * 2;
case TH: return timeIndex + dayMultiplier * 3;
case F: return timeIndex + dayMultiplier * 4;
default: throw new IllegalArgumentException("Invalid day of the week entered: "
+ day);
}
}
private static int getIntTime(String time){
int intTime = 0;
if(time.length() == 4 ){ // e.g. 1:20
intTime+= 12 * 60; // military time adjustment
intTime+= Character.getNumericValue(time.charAt(0)) * 60;
intTime+= Character.getNumericValue(time.charAt(2)) * 10;
intTime+= Character.getNumericValue(time.charAt(3));
}
if(time.length() == 5 ){ // e.g. 12:15
intTime+= Character.getNumericValue(time.charAt(0)) * 60 * 10;
intTime+= Character.getNumericValue(time.charAt(1)) * 60;
intTime+= Character.getNumericValue(time.charAt(3)) * 10;
intTime+= Character.getNumericValue(time.charAt(4));
}
if(intTime ==0){
throw new IllegalArgumentException("Invalid time of day entered: "
+ time);
}
return intTime;
}
}
| 1,578 | 0.695184 | 0.666033 | 51 | 29.921568 | 23.718813 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.372549 | false | false |
10
|
57935e277e486ed03c7c44c775a23f08d714fecf
| 13,993,003,475,493 |
31677e002c27aeb016c8cb244c63ab5071ae54b3
|
/df-dev/data-fabric-aggregate/data-fabric-reference/src/main/java/com/hsbc/gbm/datafabric/support/reference/ReferenceableStream.java
|
d4233de7a59e78fd739856b243b054210ffe28b2
|
[] |
no_license
|
mileyd/df
|
https://github.com/mileyd/df
|
0d1e1385ffb3d67829124df85734f23014be0e6f
|
b3b493c395cd37ee0374a204f64dd955821be04e
|
refs/heads/master
| 2016-06-05T06:56:09.301000 | 2015-06-06T21:25:50 | 2015-06-06T21:25:50 | 36,993,848 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* HSBC Bank : Fixed Income
*/
package com.hsbc.gbm.datafabric.support.reference;
import java.util.Iterator;
import java.util.Properties;
import com.hsbc.gbm.datafabric.api.DataVersion;
import com.hsbc.gbm.datafabric.api.Referenceable;
import com.hsbc.gbm.datafabric.api.View;
import com.hsbc.gbm.datafabric.api.predicate.DFPredicate;
import com.hsbc.gbm.datafabric.api.predicate.Extractor;
import com.hsbc.gbm.datafabric.api.snapshot.Snapshot;
public interface ReferenceableStream<T> {
T serialize(Referenceable ref);
Iterator<Referenceable> deserialize(T node);
Properties internalMeta(T node);
String dataFabricVersion(T node);
<K, V> View<K, V> deserializeView(T node);
<K, V> Snapshot<K, V> deserializeSnapshot(T node);
<V> DFPredicate<V> deserializeDFPredicate(T node);
<V> DataVersion<V> deserializeDataVersion(T node);
<S, D> Extractor<S, D> deserializeExtractor(T node);
<K, V> T serialize(View<K, V> view);
<K, V> T serialize(Snapshot<K, V> snapshot);
<S, D> T serialize(Extractor<S, D> extractor);
<V> T serialize(DFPredicate<V> predicate);
<V> T serialize(DataVersion<V> dataVersion);
boolean isValidReference(T node);
long now();
}
|
UTF-8
|
Java
| 1,185 |
java
|
ReferenceableStream.java
|
Java
|
[] | null |
[] |
/**
* HSBC Bank : Fixed Income
*/
package com.hsbc.gbm.datafabric.support.reference;
import java.util.Iterator;
import java.util.Properties;
import com.hsbc.gbm.datafabric.api.DataVersion;
import com.hsbc.gbm.datafabric.api.Referenceable;
import com.hsbc.gbm.datafabric.api.View;
import com.hsbc.gbm.datafabric.api.predicate.DFPredicate;
import com.hsbc.gbm.datafabric.api.predicate.Extractor;
import com.hsbc.gbm.datafabric.api.snapshot.Snapshot;
public interface ReferenceableStream<T> {
T serialize(Referenceable ref);
Iterator<Referenceable> deserialize(T node);
Properties internalMeta(T node);
String dataFabricVersion(T node);
<K, V> View<K, V> deserializeView(T node);
<K, V> Snapshot<K, V> deserializeSnapshot(T node);
<V> DFPredicate<V> deserializeDFPredicate(T node);
<V> DataVersion<V> deserializeDataVersion(T node);
<S, D> Extractor<S, D> deserializeExtractor(T node);
<K, V> T serialize(View<K, V> view);
<K, V> T serialize(Snapshot<K, V> snapshot);
<S, D> T serialize(Extractor<S, D> extractor);
<V> T serialize(DFPredicate<V> predicate);
<V> T serialize(DataVersion<V> dataVersion);
boolean isValidReference(T node);
long now();
}
| 1,185 | 0.745992 | 0.745992 | 49 | 23.183674 | 22.074709 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.081633 | false | false |
10
|
44760e30f21cc08f7a00a62f2adabd0d211dffb3
| 31,370,441,159,696 |
8816fe7f46a0b1e4a3b4a9502c9adfa9494dc484
|
/JFCU/src/main/java/uk/org/merg/jfcu/modulemodel/Type.java
|
1c8fd52f1681ee793f77167eae27f4ddaf0e1174
|
[] |
no_license
|
MERG-DEV/JFCU
|
https://github.com/MERG-DEV/JFCU
|
3a6ba300a298b072e1465a102b0dc65c4f81a60d
|
84186f8c83b97c4edcde2bce9d18510b888b84c4
|
refs/heads/master
| 2022-03-25T15:02:46.873000 | 2019-12-18T11:18:57 | 2019-12-18T11:18:57 | 106,045,378 | 1 | 1 | null | false | 2019-12-18T11:18:59 | 2017-10-06T20:02:40 | 2019-12-08T08:23:46 | 2019-12-18T11:18:58 | 716 | 0 | 1 | 0 |
Java
| false | false |
package uk.org.merg.jfcu.modulemodel;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import uk.org.merg.jfcu.layoutmodel.Module;
@XmlRootElement
public class Type {
private String ui;
@XmlElementRef(name="choice", required=false)
private Choice choice;
@XmlElementRef(name="integer", required=false)
private MyInteger integer;
private String cellEditor;
public String getUi() {
return ui;
}
@XmlElement
public void setUi(String ui) {
this.ui = ui;
}
public Choice getChoice() {
return choice;
}
@XmlElement(name="choice")
public void setNvChoice(Choice choice) {
this.choice = choice;
}
public MyInteger getInteger() {
return integer;
}
@XmlElement(name="integer")
public void setNvInteger(MyInteger integer) {
this.integer = integer;
}
public String getCellEditor() {
return cellEditor;
}
@XmlElement(name="celleditor")
public void setNvCellEditor(String cellEditor) {
this.cellEditor = cellEditor;
}
public String getValue(Module module, int id, int bitmask) {
if (module.getNvs() == null) return "NO NVs";
Integer ip = module.getNvs().get(id);
if (ip == null) return "No NV";
Byte nvVal = ip.byteValue();
byte b = (byte) (nvVal & bitmask);
if (integer != null) {
return ""+b;
}
if (choice != null) {
for (Item nvi : choice.getItems()) {
if (nvi.getValue() == b) return nvi.getSetting();
}
return "Invalid";
}
return "Unknown";
}
}
|
UTF-8
|
Java
| 1,531 |
java
|
Type.java
|
Java
|
[] | null |
[] |
package uk.org.merg.jfcu.modulemodel;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import uk.org.merg.jfcu.layoutmodel.Module;
@XmlRootElement
public class Type {
private String ui;
@XmlElementRef(name="choice", required=false)
private Choice choice;
@XmlElementRef(name="integer", required=false)
private MyInteger integer;
private String cellEditor;
public String getUi() {
return ui;
}
@XmlElement
public void setUi(String ui) {
this.ui = ui;
}
public Choice getChoice() {
return choice;
}
@XmlElement(name="choice")
public void setNvChoice(Choice choice) {
this.choice = choice;
}
public MyInteger getInteger() {
return integer;
}
@XmlElement(name="integer")
public void setNvInteger(MyInteger integer) {
this.integer = integer;
}
public String getCellEditor() {
return cellEditor;
}
@XmlElement(name="celleditor")
public void setNvCellEditor(String cellEditor) {
this.cellEditor = cellEditor;
}
public String getValue(Module module, int id, int bitmask) {
if (module.getNvs() == null) return "NO NVs";
Integer ip = module.getNvs().get(id);
if (ip == null) return "No NV";
Byte nvVal = ip.byteValue();
byte b = (byte) (nvVal & bitmask);
if (integer != null) {
return ""+b;
}
if (choice != null) {
for (Item nvi : choice.getItems()) {
if (nvi.getValue() == b) return nvi.getSetting();
}
return "Invalid";
}
return "Unknown";
}
}
| 1,531 | 0.691705 | 0.691705 | 72 | 20.263889 | 17.164234 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.652778 | false | false |
10
|
e78cde8b01ec3af584d0b27ac75198437ad398ac
| 1,640,677,544,235 |
49e1ff6d44dda3998fd0bf9aea1c0e0f6d9e8175
|
/dddsample_javaee/src/main/java/com/dliu/dddsample/domain/model/cargo/Leg.java
|
fa7e2d1c3aa43c85a761b925aff45c4870883f23
|
[] |
no_license
|
davidlzs/dddsample_javaee
|
https://github.com/davidlzs/dddsample_javaee
|
e98bbf8c86f80148321dada7a8d04d8565cdb9f4
|
e5bb19ba37c17b89b1377626f324197ad4e1d394
|
refs/heads/master
| 2021-01-10T21:05:58.569000 | 2014-03-04T02:46:05 | 2014-03-04T02:46:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.dliu.dddsample.domain.model.cargo;
import com.dliu.dddsample.domain.model.location.Location;
import com.dliu.dddsample.domain.model.voyage.Voyage;
import org.apache.commons.lang.Validate;
import java.util.Date;
/**
* Created by IntelliJ IDEA.
*/
public class Leg {
private Voyage voyage;
private Location loadLocation;
private Location unloadLocation;
private Date loadTime;
private Date unloadTime;
public Leg(Voyage voyage, Location loadLocation, Location unloadLocation, Date loadTime, Date unloadTime) {
Validate.noNullElements(new Object[] {voyage, loadLocation, unloadLocation, loadTime, unloadTime});
this.voyage = voyage;
this.loadLocation = loadLocation;
this.unloadLocation = unloadLocation;
this.loadTime = loadTime;
this.unloadTime = unloadTime;
}
public Voyage voyage() {
return voyage;
}
public Location loadLocation() {
return loadLocation;
}
public Location unloadLocation() {
return unloadLocation;
}
public Date loadTime() {
return loadTime;
}
public Date unloadTime() {
return unloadTime;
}
}
|
UTF-8
|
Java
| 1,192 |
java
|
Leg.java
|
Java
|
[] | null |
[] |
package com.dliu.dddsample.domain.model.cargo;
import com.dliu.dddsample.domain.model.location.Location;
import com.dliu.dddsample.domain.model.voyage.Voyage;
import org.apache.commons.lang.Validate;
import java.util.Date;
/**
* Created by IntelliJ IDEA.
*/
public class Leg {
private Voyage voyage;
private Location loadLocation;
private Location unloadLocation;
private Date loadTime;
private Date unloadTime;
public Leg(Voyage voyage, Location loadLocation, Location unloadLocation, Date loadTime, Date unloadTime) {
Validate.noNullElements(new Object[] {voyage, loadLocation, unloadLocation, loadTime, unloadTime});
this.voyage = voyage;
this.loadLocation = loadLocation;
this.unloadLocation = unloadLocation;
this.loadTime = loadTime;
this.unloadTime = unloadTime;
}
public Voyage voyage() {
return voyage;
}
public Location loadLocation() {
return loadLocation;
}
public Location unloadLocation() {
return unloadLocation;
}
public Date loadTime() {
return loadTime;
}
public Date unloadTime() {
return unloadTime;
}
}
| 1,192 | 0.683725 | 0.683725 | 48 | 23.833334 | 24.264458 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.604167 | false | false |
10
|
6f74e97117d908f6a17a0e435ff0e091fb0816f0
| 9,955,734,208,486 |
5225c1ed193a6cb686188daa08e33aaf0bbf084c
|
/src/gov/nasa/Calculator.java
|
e1666e907c52fd8a99ada8fb67d5c1b960555e16
|
[] |
no_license
|
TehGreatCat/JavaCourse
|
https://github.com/TehGreatCat/JavaCourse
|
3af0b08bc6102bbad55c742d893527d28a9ae9f0
|
2b5edb9bea0487323ddcb6ef4799c4d1441cf848
|
refs/heads/master
| 2020-01-24T20:53:12.978000 | 2016-11-15T21:58:54 | 2016-11-15T21:58:54 | 73,853,778 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package gov.nasa;
public class Calculator {
private Processor amplifier;
private Processor summator;
private Processor contractor;
private Processor divider;
public Calculator(Processor amplifier, Processor summator, Processor divider, Processor contractor) {
this.amplifier = amplifier;
this.summator = summator;
this.contractor = contractor;
this.divider = divider;
}
public Eenteger sum(Eenteger a, Eenteger b){
return summator.process(a, b);
}
public Eenteger mult(Eenteger a, Eenteger b) {
return amplifier.process(a, b);
}
public Eenteger divd(Eenteger a, Eenteger b) {
return divider.process(a, b);
}
public Eenteger contr(Eenteger a, Eenteger b) {
return contractor.process(a, b);
}
}
|
UTF-8
|
Java
| 820 |
java
|
Calculator.java
|
Java
|
[] | null |
[] |
package gov.nasa;
public class Calculator {
private Processor amplifier;
private Processor summator;
private Processor contractor;
private Processor divider;
public Calculator(Processor amplifier, Processor summator, Processor divider, Processor contractor) {
this.amplifier = amplifier;
this.summator = summator;
this.contractor = contractor;
this.divider = divider;
}
public Eenteger sum(Eenteger a, Eenteger b){
return summator.process(a, b);
}
public Eenteger mult(Eenteger a, Eenteger b) {
return amplifier.process(a, b);
}
public Eenteger divd(Eenteger a, Eenteger b) {
return divider.process(a, b);
}
public Eenteger contr(Eenteger a, Eenteger b) {
return contractor.process(a, b);
}
}
| 820 | 0.659756 | 0.659756 | 32 | 24.625 | 23.128378 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false |
10
|
8cf1521923e641b5cb14e6cb305c0e19d66f32d2
| 18,562,848,722,213 |
d83310dca5e5cf173338aeff56a720a0fcf6ae1e
|
/l011_Heap/Heap creation/heapSort.java
|
15c5ed2e2bd1eaa64154550fdaf746f8b1efcaa6
|
[] |
no_license
|
annukamat/pepcoding_DS
|
https://github.com/annukamat/pepcoding_DS
|
a46667b8fd8a81b3a1392f6e2e901ae3bd3c4e3e
|
8135b5b70495cc4d46ba831ebf3a53dd5cfb6dff
|
refs/heads/master
| 2023-05-05T01:43:08.219000 | 2021-05-09T05:18:36 | 2021-05-09T05:18:36 | 347,165,614 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class heapSort {
public static void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static boolean compareTo(int a, int b, boolean isMax){
if(isMax) return a > b;
else return a < b;
}
public static void heapify(int pi, int[] arr, int li, boolean isMax){
int maxIdx = pi;
int lci = 2 * pi + 1;
int rci = 2 * pi + 2;
if()
}
}
|
UTF-8
|
Java
| 479 |
java
|
heapSort.java
|
Java
|
[] | null |
[] |
public class heapSort {
public static void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static boolean compareTo(int a, int b, boolean isMax){
if(isMax) return a > b;
else return a < b;
}
public static void heapify(int pi, int[] arr, int li, boolean isMax){
int maxIdx = pi;
int lci = 2 * pi + 1;
int rci = 2 * pi + 2;
if()
}
}
| 479 | 0.498956 | 0.490605 | 21 | 21.809525 | 20.504631 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false |
10
|
f0af0bc05df9d9802278deca4c02f1f374cd3e3e
| 953,482,740,484 |
2b58332190757831b1d0874f2db5d8351f10bd14
|
/services/src/main/java/org/keycloak/services/managers/AuditManager.java
|
5aa416775ffa7e93bfcf595a5057c0c4693c3de1
|
[
"Apache-2.0"
] |
permissive
|
cardosogabriel/keycloak
|
https://github.com/cardosogabriel/keycloak
|
769765b1e5341564fa3ee2a63b8c880af3baffed
|
4a5ea08a2a399e5b570111b020a8ec8617485620
|
refs/heads/master
| 2017-04-29T11:07:34.275000 | 2014-08-13T13:42:09 | 2014-08-13T13:42:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.keycloak.services.managers;
import org.jboss.logging.Logger;
import org.keycloak.ClientConnection;
import org.keycloak.audit.Audit;
import org.keycloak.audit.AuditListener;
import org.keycloak.audit.AuditProvider;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import java.util.LinkedList;
import java.util.List;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class AuditManager {
private Logger log = Logger.getLogger(AuditManager.class);
private RealmModel realm;
private KeycloakSession session;
private ClientConnection clientConnection;
public AuditManager(RealmModel realm, KeycloakSession session, ClientConnection clientConnection) {
this.realm = realm;
this.session = session;
this.clientConnection = clientConnection;
}
public Audit createAudit() {
List<AuditListener> listeners = new LinkedList<AuditListener>();
if (realm.isAuditEnabled()) {
AuditProvider auditProvider = session.getProvider(AuditProvider.class);
if (auditProvider != null) {
listeners.add(auditProvider);
} else {
log.error("Audit enabled, but no audit provider configured");
}
}
if (realm.getAuditListeners() != null) {
for (String id : realm.getAuditListeners()) {
AuditListener listener = session.getProvider(AuditListener.class, id);
if (listener != null) {
listeners.add(listener);
} else {
log.error("Audit listener '" + id + "' registered, but not found");
}
}
}
return new Audit(listeners, realm, clientConnection.getRemoteAddr());
}
}
|
UTF-8
|
Java
| 1,832 |
java
|
AuditManager.java
|
Java
|
[
{
"context": "t java.util.List;\n\n/**\n * @author <a href=\"mailto:sthorger@redhat.com\">Stian Thorgersen</a>\n */\npublic class AuditManag",
"end": 414,
"score": 0.9998964071273804,
"start": 395,
"tag": "EMAIL",
"value": "sthorger@redhat.com"
},
{
"context": "*\n * @author <a href=\"mailto:sthorger@redhat.com\">Stian Thorgersen</a>\n */\npublic class AuditManager {\n\n private ",
"end": 432,
"score": 0.9998559355735779,
"start": 416,
"tag": "NAME",
"value": "Stian Thorgersen"
}
] | null |
[] |
package org.keycloak.services.managers;
import org.jboss.logging.Logger;
import org.keycloak.ClientConnection;
import org.keycloak.audit.Audit;
import org.keycloak.audit.AuditListener;
import org.keycloak.audit.AuditProvider;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import java.util.LinkedList;
import java.util.List;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public class AuditManager {
private Logger log = Logger.getLogger(AuditManager.class);
private RealmModel realm;
private KeycloakSession session;
private ClientConnection clientConnection;
public AuditManager(RealmModel realm, KeycloakSession session, ClientConnection clientConnection) {
this.realm = realm;
this.session = session;
this.clientConnection = clientConnection;
}
public Audit createAudit() {
List<AuditListener> listeners = new LinkedList<AuditListener>();
if (realm.isAuditEnabled()) {
AuditProvider auditProvider = session.getProvider(AuditProvider.class);
if (auditProvider != null) {
listeners.add(auditProvider);
} else {
log.error("Audit enabled, but no audit provider configured");
}
}
if (realm.getAuditListeners() != null) {
for (String id : realm.getAuditListeners()) {
AuditListener listener = session.getProvider(AuditListener.class, id);
if (listener != null) {
listeners.add(listener);
} else {
log.error("Audit listener '" + id + "' registered, but not found");
}
}
}
return new Audit(listeners, realm, clientConnection.getRemoteAddr());
}
}
| 1,810 | 0.645196 | 0.645196 | 57 | 31.14035 | 26.928391 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.561404 | false | false |
10
|
efc698ac082469747dc57ecfe7391a371c8b5858
| 22,265,110,527,890 |
12998e1b57e9e3926d6870fc1f1cdced5b54e83f
|
/idsbase/src/main/java/cn_rt/idsbase/netbean/ShotScreenPresent.java
|
e30fe2b0dc332f70d9f40e59dfbb2091cb67eeea
|
[] |
no_license
|
lwh4444/rtbase
|
https://github.com/lwh4444/rtbase
|
084ab8382af5931237d329e448e81b87f8d302b5
|
f6144b33cc7d2edaadf44bbcf399bab01f1cef4b
|
refs/heads/master
| 2022-12-04T02:27:41.612000 | 2020-08-20T07:09:05 | 2020-08-20T07:09:05 | 288,926,905 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cn_rt.idsbase.netbean;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import java.io.File;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
/**
* Created by ${zml} on 2019/6/27.
*/
public class ShotScreenPresent extends BasePresenter implements ShotScreenContract.Presenter {
private BaseView view;
public ShotScreenPresent(BaseView mview, Context ctx) {
super(ctx);
this.view = mview;
}
@SuppressLint("CheckResult")
@Override
public void getInfo(String num, File files) {
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), files);
MultipartBody.Part body =
MultipartBody.Part.createFormData("screenShot", files.getName(), requestFile);
mService.shotScreen(num, body)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<String>() {
@Override
public void accept(String stringBaseResponse) throws Exception {
Log.d("---", stringBaseResponse);
}
});
}
}
|
UTF-8
|
Java
| 1,411 |
java
|
ShotScreenPresent.java
|
Java
|
[
{
"context": "y;\nimport okhttp3.RequestBody;\n\n\n/**\n * Created by ${zml} on 2019/6/27.\n */\npublic class ShotScreenPresent ",
"end": 402,
"score": 0.8798492550849915,
"start": 397,
"tag": "USERNAME",
"value": "${zml"
}
] | null |
[] |
package cn_rt.idsbase.netbean;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import java.io.File;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
/**
* Created by ${zml} on 2019/6/27.
*/
public class ShotScreenPresent extends BasePresenter implements ShotScreenContract.Presenter {
private BaseView view;
public ShotScreenPresent(BaseView mview, Context ctx) {
super(ctx);
this.view = mview;
}
@SuppressLint("CheckResult")
@Override
public void getInfo(String num, File files) {
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), files);
MultipartBody.Part body =
MultipartBody.Part.createFormData("screenShot", files.getName(), requestFile);
mService.shotScreen(num, body)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<String>() {
@Override
public void accept(String stringBaseResponse) throws Exception {
Log.d("---", stringBaseResponse);
}
});
}
}
| 1,411 | 0.659107 | 0.65202 | 50 | 27.219999 | 26.905977 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
10
|
fd349840c71ca790b77b695f1e96f54beb13e580
| 31,542,239,830,063 |
aab012090e8318487db50f9432e51aa88b0902a9
|
/src/Gameplay/Model/Wonder/Wonder.java
|
640d5f529884aebf31a536455c326b91a200fbff
|
[] |
no_license
|
Jcvarela/OOPTeam14
|
https://github.com/Jcvarela/OOPTeam14
|
f127e1cb47a127b489e2f80b01f6addee67a564d
|
50f8da684f09c8d23da8fcd72d2c9f4b9b28702d
|
refs/heads/master
| 2021-06-16T02:04:49.749000 | 2017-04-30T00:32:12 | 2017-04-30T00:32:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Gameplay.Model.Wonder;
import Gameplay.Model.Actions.WonderAction.IrrigationWonderAction;
import Gameplay.Model.Actions.WonderAction.WonderAction;
/**
* Created by Willie on 4/17/2017.
*/
public class Wonder {
Brick[] bricks;
WonderAction[] wonderActions;
int counter = 0;
public Wonder() {
bricks = new Brick[61];
wonderActions = new WonderAction[61];
wonderActions[44] = new IrrigationWonderAction();
}
public void addBrick(Brick brick) {
bricks[counter] = brick;
if (wonderActions[counter] != null)
wonderActions[counter].execute();
counter++;
}
}
|
UTF-8
|
Java
| 655 |
java
|
Wonder.java
|
Java
|
[
{
"context": "ions.WonderAction.WonderAction;\n\n/**\n * Created by Willie on 4/17/2017.\n */\npublic class Wonder {\n\n Bric",
"end": 181,
"score": 0.9857718348503113,
"start": 175,
"tag": "NAME",
"value": "Willie"
}
] | null |
[] |
package Gameplay.Model.Wonder;
import Gameplay.Model.Actions.WonderAction.IrrigationWonderAction;
import Gameplay.Model.Actions.WonderAction.WonderAction;
/**
* Created by Willie on 4/17/2017.
*/
public class Wonder {
Brick[] bricks;
WonderAction[] wonderActions;
int counter = 0;
public Wonder() {
bricks = new Brick[61];
wonderActions = new WonderAction[61];
wonderActions[44] = new IrrigationWonderAction();
}
public void addBrick(Brick brick) {
bricks[counter] = brick;
if (wonderActions[counter] != null)
wonderActions[counter].execute();
counter++;
}
}
| 655 | 0.653435 | 0.632061 | 28 | 22.392857 | 20.077242 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false |
10
|
285312484a2adb09044b4a67d7706598737c3ac0
| 20,263,655,702,694 |
4d48e1c36cac8197fde138f064b8475edc1c8d5b
|
/app/src/main/java/com/andshine/app/entity/SimpleEntity.java
|
053c579143684911170b76c89eecd5435495ed5c
|
[] |
no_license
|
andShine/app_base
|
https://github.com/andShine/app_base
|
467bda4faabce4fa1b40590325ed2b317ead1e1e
|
1c3ced062f94e9b42a330b5faff8269402060963
|
refs/heads/master
| 2021-09-16T01:29:50.726000 | 2018-06-14T09:34:27 | 2018-06-14T09:34:27 | 114,231,229 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.andshine.app.entity;
/**
* 基本数据类型
* Created by liu on 2017/12/14.
*/
public class SimpleEntity {
public boolean status;
public String msg;
public BaseEntity toBaseEntity() {
BaseEntity baseEntity = new BaseEntity();
baseEntity.status = status;
baseEntity.msg = msg;
return baseEntity;
}
}
|
UTF-8
|
Java
| 368 |
java
|
SimpleEntity.java
|
Java
|
[
{
"context": ".andshine.app.entity;\n\n/**\n * 基本数据类型\n * Created by liu on 2017/12/14.\n */\n\npublic class SimpleEntity {\n ",
"end": 65,
"score": 0.9809228181838989,
"start": 62,
"tag": "USERNAME",
"value": "liu"
}
] | null |
[] |
package com.andshine.app.entity;
/**
* 基本数据类型
* Created by liu on 2017/12/14.
*/
public class SimpleEntity {
public boolean status;
public String msg;
public BaseEntity toBaseEntity() {
BaseEntity baseEntity = new BaseEntity();
baseEntity.status = status;
baseEntity.msg = msg;
return baseEntity;
}
}
| 368 | 0.63764 | 0.615169 | 19 | 17.736841 | 15.680501 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false |
10
|
6be6db6614df1ecf16771120525025b4eda35d3d
| 9,491,877,755,944 |
e7e83db1ca7b702bed203819e7319fca9b0fbfc4
|
/app/src/androidTest/java/com/example/photogalleryproject3/UITest.java
|
de25058e6bd41746bfafde7bbbca6d07c148f4e0
|
[] |
no_license
|
wmcconnell1234/PhotoGalleryProject
|
https://github.com/wmcconnell1234/PhotoGalleryProject
|
843bb7eb50bfb8eac9cb013ee241ee13ded24422
|
f14befc4adeabe895cc6c76920289ea4389acd9f
|
refs/heads/master
| 2021-05-17T15:13:05.678000 | 2020-04-19T00:38:17 | 2020-04-19T00:38:17 | 250,838,005 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright 2015, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.photogalleryproject3;
import android.app.Activity;
import androidx.test.espresso.action.ViewActions;
import androidx.test.espresso.matcher.ViewMatchers;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static androidx.test.espresso.action.ViewActions.replaceText;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
/**
* Basic tests showcasing simple view matchers and actions like {@link ViewMatchers#withId},
* {@link ViewActions#click} and {@link ViewActions#typeText}.
* <p>
* Note that there is no need to tell Espresso that a view is in a different {@link Activity}.
*/
@RunWith(AndroidJUnit4.class)
@LargeTest
//make tests run in alphabetical order
//https://stackoverflow.com/questions/25308301/test-order-with-espresso
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class UITest
{
///**
// * Use {@link ActivityScenarioRule} to create and launch the activity under test, and close it
// * after test completes. This is a replacement for {@link androidx.test.rule.ActivityTestRule}.
//*/
@Rule public ActivityScenarioRule<com.example.photogalleryproject3.MainActivity> activityScenarioRule
= new ActivityScenarioRule<>(com.example.photogalleryproject3.MainActivity.class);
@Test
public void TestCaptionSearch()
{
//The test assumes that 2 pictures have been taken already!!
//Note: the test starts on the RIGHTMOST (earliest) picture.
try{Thread.sleep(1000);}catch(Exception e){}
//Enter a caption "Caption1"
onView(withId(R.id.editTextCaption)).perform(replaceText("Caption1"), closeSoftKeyboard());
try{Thread.sleep(1000);}catch(Exception e){}
//Press Save
onView(withId(R.id.buttonSaveCaption)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
//Press left
onView(withId(R.id.buttonLeft)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
//Enter another caption "Caption2"
onView(withId(R.id.editTextCaption)).perform(replaceText("Caption2"), closeSoftKeyboard());
try{Thread.sleep(1000);}catch(Exception e){}
//Press Save
onView(withId(R.id.buttonSaveCaption)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
//Press left (to show it does nothing)
onView(withId(R.id.buttonLeft)).perform(click());
//Press right three times (to show attempting to move too far to the right does nothing)
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
//Press Search
onView(withId(R.id.btnSnap2)).perform(click());
//In the search window Enter a string "1"
onView(withId(R.id.search_Captions)).perform(typeText("1"), closeSoftKeyboard());
//In the search window Press Search
onView(withId(R.id.button)).perform(click());
//Press right (it should do nothing)
onView(withId(R.id.buttonRight)).perform(click());
//Press left twice (it should do nothing)
onView(withId(R.id.buttonLeft)).perform(click());
onView(withId(R.id.buttonLeft)).perform(click());
//Verify that the result contains "1"
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption1")));
try{Thread.sleep(2000);}catch(Exception e){}
//Clear the search for the next test
onView(withId(R.id.btnSnap2)).perform(click());
onView(withId(R.id.button)).perform(click());
}
@Test
public void TestFolders()
{
//The test assumes that 2 pictures have been taken already!!
//It also assumes the previous test has been run, so that the pictures are called Caption1 and Caption2.
//It also assumes that it's on the main screen of the photo gallery app.
try{Thread.sleep(1000);}catch(Exception e){}
//add picture called Caption1 to Folder 1
onView(withId(R.id.btnAddToFolder)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.textViewFolder1)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
//Now go to Folder 1
onView(withId(R.id.btnFolderView)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.textViewFolder1)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
//Press left (it should do nothing)
onView(withId(R.id.buttonLeft)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
//Press right twice (it should do nothing)
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
//Verify that Caption1 is in Folder1
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption1")));
try{Thread.sleep(1000);}catch(Exception e){}
}
@Test
public void TestLocationSearch()
{
//The test assumes that at least one picture containing location information has been taken already!!
//It also assumes the previous test has been run, so that the first picture to show up in the search will be Caption1.
// UI test for sprint 2. IL
// Testing Valid Equivalence Class, entering a range that's within 90 >= TopLeft.Lat >= BottomRight.Lat >= -90
// and -180 <= TopLeft.Long <= BottomRight.Long <= 180
//Press Search
onView(withId(R.id.btnSnap2)).perform(click());
//In the location search window Enter the desire search for upper bound latitude
onView(withId(R.id.search_fromLatitude)).perform(typeText("49.300000"), closeSoftKeyboard());
//In the location search window Enter the desire search for lower bound latitude
onView(withId(R.id.search_toLatitude)).perform(typeText("49.100000"), closeSoftKeyboard());
//In the location search window Enter the desire search for upper bound longitude
onView(withId(R.id.search_fromLongitude)).perform(typeText("-122.000000"), closeSoftKeyboard());
//In the location search window Enter the desire search for lower bound longitude
onView(withId(R.id.search_toLongitude)).perform(typeText("-124.000000"), closeSoftKeyboard());
//In the search window Press Search to go back to main activity
onView(withId(R.id.button)).perform(click());
// I can't verify the result because pictures on my specific phone has no location information, no matter what I tried.
// I enabled "save location" already
//Uncommented WM - works on my phone
//Verify that there is a result
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption1")));
try{Thread.sleep(1000);}catch(Exception e){}
//to Test InValid Equivalence Class: At least one of TopLeft.Lat, TopLeft.Long, BottomRight.Left, BottomRight.Long is null;
//Press Search
onView(withId(R.id.btnSnap2)).perform(click());
//---------------------------------The NULL -------------------------------//
onView(withId(R.id.search_fromLatitude)).perform(typeText(""), closeSoftKeyboard());
//In the location search window Enter the desire search for lower bound latitude
onView(withId(R.id.search_toLatitude)).perform(typeText("49.100000"), closeSoftKeyboard());
//In the location search window Enter the desire search for upper bound longitude
onView(withId(R.id.search_fromLongitude)).perform(typeText("-122.000000"), closeSoftKeyboard());
//In the location search window Enter the desire search for lower bound longitude
onView(withId(R.id.search_toLongitude)).perform(typeText("-124.000000"), closeSoftKeyboard());
//In the search window Press Search to go back to main activity
onView(withId(R.id.button)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
//Added WM - Verify that there is a result
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption1")));
onView(withId(R.id.buttonLeft)).perform(click());
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption2")));
//to Test InValid Equivalence Class: TopLeft.Lat < BottomRight.Lat; or TopLeft.Long > BottomRight.Long
//Press Search
onView(withId(R.id.btnSnap2)).perform(click());
//-------------------------The Top Lat should be greater, but a smaller value is entered--------//
onView(withId(R.id.search_fromLatitude)).perform(typeText("49.300000"), closeSoftKeyboard());
//-------------------------The lower Lat should be smaller, but a bigger value is entered--------//
onView(withId(R.id.search_toLatitude)).perform(typeText("55.100000"), closeSoftKeyboard());
//In the location search window Enter the desire search for upper bound longitude
onView(withId(R.id.search_fromLongitude)).perform(typeText("-122.000000"), closeSoftKeyboard());
//In the location search window Enter the desire search for lower bound longitude
onView(withId(R.id.search_toLongitude)).perform(typeText("-124.000000"), closeSoftKeyboard());
//In the search window Press Search to go back to main activity
onView(withId(R.id.button)).perform(click());
//Added WM - Verify that there is no result
onView(withId(R.id.editTextCaption)).check(matches(withText("No files found")));
try{Thread.sleep(1000);}catch(Exception e){}
}
//Note: this test is time sensitive. Must re-enter the dates below every time you run this test with a different
//set of pictures. WM
//Note 2: Must enter the dates such that the earlier picture (labelled "Caption1" above) is caught. WM
@Test
public void TestTimeSearch()
{
// Test for Valid Equivalence Class: MinDate <= StartDate <= EndDate <= MaxDate.
//Press Search
onView(withId(R.id.btnSnap2)).perform(click());
//In the Time search window Enter the desire search for StartDate in yyyyMMdd_hhmmss format
onView(withId(R.id.search_fromDate)).perform(typeText("20200418_170450"), closeSoftKeyboard());
//In the location search window Enter the desire search for lower bound latitude
onView(withId(R.id.search_toDate)).perform(typeText("20200418_172413"), closeSoftKeyboard());
//In the search window Press Search to go back to main activity
onView(withId(R.id.button)).perform(click());
//Verify that there is a result
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption1"))); // modified WM "valid")));
//Press left to cycle through the pictures matching search
onView(withId(R.id.buttonLeft)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.buttonLeft)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.buttonLeft)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.buttonLeft)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
// Test for InValid Equivalence Class: StartDate = null; EndDate = null; or EndDate < StartDate.
// If any of the Time search is Null, the app will display all the pictures.
//----------------------------- Test for StartDate = null--------------------------------
//Press Search
onView(withId(R.id.btnSnap2)).perform(click());
//------------------TEST FOR StartDATE NULL ------------------------------//
onView(withId(R.id.search_fromDate)).perform(typeText(""), closeSoftKeyboard());
//In the location search window Enter the desire search for lower bound latitude
onView(withId(R.id.search_toDate)).perform(typeText("20501212_010101"), closeSoftKeyboard());
//In the search window Press Search to go back to main activity
onView(withId(R.id.button)).perform(click());
//Press left to cycle through the pictures matching search
onView(withId(R.id.buttonLeft)).perform(click());
onView(withId(R.id.buttonLeft)).perform(click());
//onView(withId(R.id.buttonLeft)).perform(click()); //commented out WM
//onView(withId(R.id.buttonLeft)).perform(click()); //commented out WM
//added WM: at this point we should be on the later picture ("Caption2").
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption2")));
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
//added WM: at this point we should be on the earlier picture ("Caption1").
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption1")));
// --------------------------Test for EndDate = null----------------------------//
//Press Search
onView(withId(R.id.btnSnap2)).perform(click());
//In the Time search window Enter the desire search for StartDate in yyyyMMdd_hhmmss format
onView(withId(R.id.search_fromDate)).perform(typeText("20501212_010101"), closeSoftKeyboard());
//------------------TEST FOR EndDATE NULL ------------------------------//
onView(withId(R.id.search_toDate)).perform(typeText(""), closeSoftKeyboard());
//In the search window Press Search to go back to main activity
onView(withId(R.id.button)).perform(click());
//Press left to cycle through the pictures matching search
onView(withId(R.id.buttonLeft)).perform(click());
onView(withId(R.id.buttonLeft)).perform(click());
//onView(withId(R.id.buttonLeft)).perform(click()); //commented out WM
//onView(withId(R.id.buttonLeft)).perform(click()); //commented out WM
//added WM: at this point we should be on the later picture ("Caption2").
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption2")));
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
//added WM: at this point we should be on the earlier picture ("Caption1").
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption1")));
// --------------------------Test for EndDate < StartDate----------------------------//
//Press Search
onView(withId(R.id.btnSnap2)).perform(click());
//In the Time search window Enter the desire search for StartDate in yyyyMMdd_hhmmss format
onView(withId(R.id.search_fromDate)).perform(typeText("20200412_104601"), closeSoftKeyboard());
//---------------------- 10:44:04------------ smaller than 10:46:01 ---------------------//
onView(withId(R.id.search_toDate)).perform(typeText("20200412_104401"), closeSoftKeyboard());
//In the search window Press Search to go back to main activity
onView(withId(R.id.button)).perform(click());
/* commented out WM
//Press left to cycle through the pictures matching search
onView(withId(R.id.buttonLeft)).perform(click());
onView(withId(R.id.buttonLeft)).perform(click());
onView(withId(R.id.buttonLeft)).perform(click());
onView(withId(R.id.buttonLeft)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
*/
//added WM: there should be no results
onView(withId(R.id.editTextCaption)).check(matches(withText("No files found")));
}
//The test fails because when the UI Test is installed, there is nothing in Folder 1,
//even though when the app is run (not as a UI Test), the face is in Folder 1.
//Test run manually works fine. WM
/*
@Test
public void TestFaceRecognition()
{
//The test assumes that 2 pictures with faces is already in the app
// The face of one of the picture needs to be fairly big proportional to the width of photo, bigger than 0.1 of the
// width of photo
//For another face of the other photo, the face width need to be smaller than 0.1 of the width of photo
//WM Modifications, april 18:
//The big face is the first picture taken (labelled as "Caption1" in the above tests),
//The small face is the second picture taken (labelled as "Caption2" in the above tests)
//Now go to Folder 1
onView(withId(R.id.btnFolderView)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.textViewFolder1)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
//Verify that the picture in folder 1 is the face that is bigger than 0.1 width of photo
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption1"))); // modified WM "FaceWithin0.1")));
//Press left (it should do nothing)
onView(withId(R.id.buttonLeft)).perform(click());
}
*/
@Test
public void TestScan()
{
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.scanbtn)).perform(click());
}
@Test
public void TestShare() // testing the function of sharing photo to social media
{
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.btnShare)).perform(click());
}
@Test
public void zTestDelete() //tests run in alphabetical order, and this one must be last
{
//The test assumes that 2 pictures have been taken already!!
//and that it is on the main screen of the photo gallery app.
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.btnDelete)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.btnDelete)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.editTextCaption)).check(matches(withText("No files found")));
try{Thread.sleep(2000);}catch(Exception e){}
}
}
|
UTF-8
|
Java
| 20,013 |
java
|
UITest.java
|
Java
|
[] | null |
[] |
/*
* Copyright 2015, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.photogalleryproject3;
import android.app.Activity;
import androidx.test.espresso.action.ViewActions;
import androidx.test.espresso.matcher.ViewMatchers;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static androidx.test.espresso.action.ViewActions.replaceText;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
/**
* Basic tests showcasing simple view matchers and actions like {@link ViewMatchers#withId},
* {@link ViewActions#click} and {@link ViewActions#typeText}.
* <p>
* Note that there is no need to tell Espresso that a view is in a different {@link Activity}.
*/
@RunWith(AndroidJUnit4.class)
@LargeTest
//make tests run in alphabetical order
//https://stackoverflow.com/questions/25308301/test-order-with-espresso
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class UITest
{
///**
// * Use {@link ActivityScenarioRule} to create and launch the activity under test, and close it
// * after test completes. This is a replacement for {@link androidx.test.rule.ActivityTestRule}.
//*/
@Rule public ActivityScenarioRule<com.example.photogalleryproject3.MainActivity> activityScenarioRule
= new ActivityScenarioRule<>(com.example.photogalleryproject3.MainActivity.class);
@Test
public void TestCaptionSearch()
{
//The test assumes that 2 pictures have been taken already!!
//Note: the test starts on the RIGHTMOST (earliest) picture.
try{Thread.sleep(1000);}catch(Exception e){}
//Enter a caption "Caption1"
onView(withId(R.id.editTextCaption)).perform(replaceText("Caption1"), closeSoftKeyboard());
try{Thread.sleep(1000);}catch(Exception e){}
//Press Save
onView(withId(R.id.buttonSaveCaption)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
//Press left
onView(withId(R.id.buttonLeft)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
//Enter another caption "Caption2"
onView(withId(R.id.editTextCaption)).perform(replaceText("Caption2"), closeSoftKeyboard());
try{Thread.sleep(1000);}catch(Exception e){}
//Press Save
onView(withId(R.id.buttonSaveCaption)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
//Press left (to show it does nothing)
onView(withId(R.id.buttonLeft)).perform(click());
//Press right three times (to show attempting to move too far to the right does nothing)
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
//Press Search
onView(withId(R.id.btnSnap2)).perform(click());
//In the search window Enter a string "1"
onView(withId(R.id.search_Captions)).perform(typeText("1"), closeSoftKeyboard());
//In the search window Press Search
onView(withId(R.id.button)).perform(click());
//Press right (it should do nothing)
onView(withId(R.id.buttonRight)).perform(click());
//Press left twice (it should do nothing)
onView(withId(R.id.buttonLeft)).perform(click());
onView(withId(R.id.buttonLeft)).perform(click());
//Verify that the result contains "1"
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption1")));
try{Thread.sleep(2000);}catch(Exception e){}
//Clear the search for the next test
onView(withId(R.id.btnSnap2)).perform(click());
onView(withId(R.id.button)).perform(click());
}
@Test
public void TestFolders()
{
//The test assumes that 2 pictures have been taken already!!
//It also assumes the previous test has been run, so that the pictures are called Caption1 and Caption2.
//It also assumes that it's on the main screen of the photo gallery app.
try{Thread.sleep(1000);}catch(Exception e){}
//add picture called Caption1 to Folder 1
onView(withId(R.id.btnAddToFolder)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.textViewFolder1)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
//Now go to Folder 1
onView(withId(R.id.btnFolderView)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.textViewFolder1)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
//Press left (it should do nothing)
onView(withId(R.id.buttonLeft)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
//Press right twice (it should do nothing)
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
//Verify that Caption1 is in Folder1
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption1")));
try{Thread.sleep(1000);}catch(Exception e){}
}
@Test
public void TestLocationSearch()
{
//The test assumes that at least one picture containing location information has been taken already!!
//It also assumes the previous test has been run, so that the first picture to show up in the search will be Caption1.
// UI test for sprint 2. IL
// Testing Valid Equivalence Class, entering a range that's within 90 >= TopLeft.Lat >= BottomRight.Lat >= -90
// and -180 <= TopLeft.Long <= BottomRight.Long <= 180
//Press Search
onView(withId(R.id.btnSnap2)).perform(click());
//In the location search window Enter the desire search for upper bound latitude
onView(withId(R.id.search_fromLatitude)).perform(typeText("49.300000"), closeSoftKeyboard());
//In the location search window Enter the desire search for lower bound latitude
onView(withId(R.id.search_toLatitude)).perform(typeText("49.100000"), closeSoftKeyboard());
//In the location search window Enter the desire search for upper bound longitude
onView(withId(R.id.search_fromLongitude)).perform(typeText("-122.000000"), closeSoftKeyboard());
//In the location search window Enter the desire search for lower bound longitude
onView(withId(R.id.search_toLongitude)).perform(typeText("-124.000000"), closeSoftKeyboard());
//In the search window Press Search to go back to main activity
onView(withId(R.id.button)).perform(click());
// I can't verify the result because pictures on my specific phone has no location information, no matter what I tried.
// I enabled "save location" already
//Uncommented WM - works on my phone
//Verify that there is a result
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption1")));
try{Thread.sleep(1000);}catch(Exception e){}
//to Test InValid Equivalence Class: At least one of TopLeft.Lat, TopLeft.Long, BottomRight.Left, BottomRight.Long is null;
//Press Search
onView(withId(R.id.btnSnap2)).perform(click());
//---------------------------------The NULL -------------------------------//
onView(withId(R.id.search_fromLatitude)).perform(typeText(""), closeSoftKeyboard());
//In the location search window Enter the desire search for lower bound latitude
onView(withId(R.id.search_toLatitude)).perform(typeText("49.100000"), closeSoftKeyboard());
//In the location search window Enter the desire search for upper bound longitude
onView(withId(R.id.search_fromLongitude)).perform(typeText("-122.000000"), closeSoftKeyboard());
//In the location search window Enter the desire search for lower bound longitude
onView(withId(R.id.search_toLongitude)).perform(typeText("-124.000000"), closeSoftKeyboard());
//In the search window Press Search to go back to main activity
onView(withId(R.id.button)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
//Added WM - Verify that there is a result
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption1")));
onView(withId(R.id.buttonLeft)).perform(click());
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption2")));
//to Test InValid Equivalence Class: TopLeft.Lat < BottomRight.Lat; or TopLeft.Long > BottomRight.Long
//Press Search
onView(withId(R.id.btnSnap2)).perform(click());
//-------------------------The Top Lat should be greater, but a smaller value is entered--------//
onView(withId(R.id.search_fromLatitude)).perform(typeText("49.300000"), closeSoftKeyboard());
//-------------------------The lower Lat should be smaller, but a bigger value is entered--------//
onView(withId(R.id.search_toLatitude)).perform(typeText("55.100000"), closeSoftKeyboard());
//In the location search window Enter the desire search for upper bound longitude
onView(withId(R.id.search_fromLongitude)).perform(typeText("-122.000000"), closeSoftKeyboard());
//In the location search window Enter the desire search for lower bound longitude
onView(withId(R.id.search_toLongitude)).perform(typeText("-124.000000"), closeSoftKeyboard());
//In the search window Press Search to go back to main activity
onView(withId(R.id.button)).perform(click());
//Added WM - Verify that there is no result
onView(withId(R.id.editTextCaption)).check(matches(withText("No files found")));
try{Thread.sleep(1000);}catch(Exception e){}
}
//Note: this test is time sensitive. Must re-enter the dates below every time you run this test with a different
//set of pictures. WM
//Note 2: Must enter the dates such that the earlier picture (labelled "Caption1" above) is caught. WM
@Test
public void TestTimeSearch()
{
// Test for Valid Equivalence Class: MinDate <= StartDate <= EndDate <= MaxDate.
//Press Search
onView(withId(R.id.btnSnap2)).perform(click());
//In the Time search window Enter the desire search for StartDate in yyyyMMdd_hhmmss format
onView(withId(R.id.search_fromDate)).perform(typeText("20200418_170450"), closeSoftKeyboard());
//In the location search window Enter the desire search for lower bound latitude
onView(withId(R.id.search_toDate)).perform(typeText("20200418_172413"), closeSoftKeyboard());
//In the search window Press Search to go back to main activity
onView(withId(R.id.button)).perform(click());
//Verify that there is a result
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption1"))); // modified WM "valid")));
//Press left to cycle through the pictures matching search
onView(withId(R.id.buttonLeft)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.buttonLeft)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.buttonLeft)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.buttonLeft)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
// Test for InValid Equivalence Class: StartDate = null; EndDate = null; or EndDate < StartDate.
// If any of the Time search is Null, the app will display all the pictures.
//----------------------------- Test for StartDate = null--------------------------------
//Press Search
onView(withId(R.id.btnSnap2)).perform(click());
//------------------TEST FOR StartDATE NULL ------------------------------//
onView(withId(R.id.search_fromDate)).perform(typeText(""), closeSoftKeyboard());
//In the location search window Enter the desire search for lower bound latitude
onView(withId(R.id.search_toDate)).perform(typeText("20501212_010101"), closeSoftKeyboard());
//In the search window Press Search to go back to main activity
onView(withId(R.id.button)).perform(click());
//Press left to cycle through the pictures matching search
onView(withId(R.id.buttonLeft)).perform(click());
onView(withId(R.id.buttonLeft)).perform(click());
//onView(withId(R.id.buttonLeft)).perform(click()); //commented out WM
//onView(withId(R.id.buttonLeft)).perform(click()); //commented out WM
//added WM: at this point we should be on the later picture ("Caption2").
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption2")));
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
//added WM: at this point we should be on the earlier picture ("Caption1").
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption1")));
// --------------------------Test for EndDate = null----------------------------//
//Press Search
onView(withId(R.id.btnSnap2)).perform(click());
//In the Time search window Enter the desire search for StartDate in yyyyMMdd_hhmmss format
onView(withId(R.id.search_fromDate)).perform(typeText("20501212_010101"), closeSoftKeyboard());
//------------------TEST FOR EndDATE NULL ------------------------------//
onView(withId(R.id.search_toDate)).perform(typeText(""), closeSoftKeyboard());
//In the search window Press Search to go back to main activity
onView(withId(R.id.button)).perform(click());
//Press left to cycle through the pictures matching search
onView(withId(R.id.buttonLeft)).perform(click());
onView(withId(R.id.buttonLeft)).perform(click());
//onView(withId(R.id.buttonLeft)).perform(click()); //commented out WM
//onView(withId(R.id.buttonLeft)).perform(click()); //commented out WM
//added WM: at this point we should be on the later picture ("Caption2").
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption2")));
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
//added WM: at this point we should be on the earlier picture ("Caption1").
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption1")));
// --------------------------Test for EndDate < StartDate----------------------------//
//Press Search
onView(withId(R.id.btnSnap2)).perform(click());
//In the Time search window Enter the desire search for StartDate in yyyyMMdd_hhmmss format
onView(withId(R.id.search_fromDate)).perform(typeText("20200412_104601"), closeSoftKeyboard());
//---------------------- 10:44:04------------ smaller than 10:46:01 ---------------------//
onView(withId(R.id.search_toDate)).perform(typeText("20200412_104401"), closeSoftKeyboard());
//In the search window Press Search to go back to main activity
onView(withId(R.id.button)).perform(click());
/* commented out WM
//Press left to cycle through the pictures matching search
onView(withId(R.id.buttonLeft)).perform(click());
onView(withId(R.id.buttonLeft)).perform(click());
onView(withId(R.id.buttonLeft)).perform(click());
onView(withId(R.id.buttonLeft)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
onView(withId(R.id.buttonRight)).perform(click());
*/
//added WM: there should be no results
onView(withId(R.id.editTextCaption)).check(matches(withText("No files found")));
}
//The test fails because when the UI Test is installed, there is nothing in Folder 1,
//even though when the app is run (not as a UI Test), the face is in Folder 1.
//Test run manually works fine. WM
/*
@Test
public void TestFaceRecognition()
{
//The test assumes that 2 pictures with faces is already in the app
// The face of one of the picture needs to be fairly big proportional to the width of photo, bigger than 0.1 of the
// width of photo
//For another face of the other photo, the face width need to be smaller than 0.1 of the width of photo
//WM Modifications, april 18:
//The big face is the first picture taken (labelled as "Caption1" in the above tests),
//The small face is the second picture taken (labelled as "Caption2" in the above tests)
//Now go to Folder 1
onView(withId(R.id.btnFolderView)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.textViewFolder1)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
//Verify that the picture in folder 1 is the face that is bigger than 0.1 width of photo
onView(withId(R.id.editTextCaption)).check(matches(withText("Caption1"))); // modified WM "FaceWithin0.1")));
//Press left (it should do nothing)
onView(withId(R.id.buttonLeft)).perform(click());
}
*/
@Test
public void TestScan()
{
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.scanbtn)).perform(click());
}
@Test
public void TestShare() // testing the function of sharing photo to social media
{
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.btnShare)).perform(click());
}
@Test
public void zTestDelete() //tests run in alphabetical order, and this one must be last
{
//The test assumes that 2 pictures have been taken already!!
//and that it is on the main screen of the photo gallery app.
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.btnDelete)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.btnDelete)).perform(click());
try{Thread.sleep(1000);}catch(Exception e){}
onView(withId(R.id.editTextCaption)).check(matches(withText("No files found")));
try{Thread.sleep(2000);}catch(Exception e){}
}
}
| 20,013 | 0.66097 | 0.640684 | 398 | 49.28392 | 34.920403 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.540201 | false | false |
10
|
f26cc5d12779057788c8a02af21c42fc609cd72b
| 5,531,917,891,729 |
21891ebf452e51cc87982ab128a029e979236139
|
/addons/osio-addon/src/test/java/io/fabric8/launcher/osio/client/AuthPublicKeyProviderTest.java
|
a60ef2e0f2b57880df178c782fae9bcf027db6f1
|
[
"Apache-2.0"
] |
permissive
|
tinakurian/launcher-backend
|
https://github.com/tinakurian/launcher-backend
|
1f7d7825e088df97a447e78bba8962ee95cdc827
|
03d9743465c15fd426e21a8b0d44f50b33c76860
|
refs/heads/master
| 2020-03-22T17:14:10.825000 | 2018-10-30T21:43:16 | 2018-10-30T21:43:16 | 140,382,927 | 0 | 0 |
Apache-2.0
| true | 2019-01-29T00:32:01 | 2018-07-10T05:46:09 | 2018-10-31T15:05:44 | 2019-01-28T20:19:57 | 36,829 | 0 | 0 | 1 |
Java
| false | null |
package io.fabric8.launcher.osio.client;
import java.security.interfaces.RSAPublicKey;
import java.util.Optional;
import io.fabric8.launcher.base.http.HttpClient;
import io.fabric8.launcher.base.identity.RSAPublicKeyConverter;
import io.fabric8.launcher.base.test.hoverfly.LauncherPerTestHoverflyRule;
import io.fabric8.launcher.core.spi.PublicKeyProvider;
import io.specto.hoverfly.junit.rule.HoverflyRule;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import static io.fabric8.launcher.base.test.hoverfly.LauncherHoverflyEnvironment.createDefaultHoverflyEnvironment;
import static io.fabric8.launcher.base.test.hoverfly.LauncherHoverflyRuleConfigurer.createMultiTestHoverflyProxy;
import static io.fabric8.launcher.base.test.identity.TokenFixtures.KID;
import static io.fabric8.launcher.base.test.identity.TokenFixtures.STRIP_PUBLIC_KEY;
import static io.fabric8.launcher.base.test.identity.TokenFixtures.VALID_TOKEN;
import static io.fabric8.launcher.osio.client.OsioTests.LAUNCHER_OSIO_TOKEN;
import static io.fabric8.launcher.osio.client.OsioTests.getTestAuthorization;
import static org.assertj.core.api.Assertions.assertThat;
public class AuthPublicKeyProviderTest {
private static final HoverflyRule HOVERFLY_RULE = createMultiTestHoverflyProxy("auth.openshift.io|auth.prod-preview.openshift.io");
@ClassRule
public static final RuleChain RULE_CHAIN = RuleChain// After recording on a real environment against a real service,
// You should adapt the Hoverfly descriptors (.json) to make them work in simulation mode with the mock environment.
.outerRule(createDefaultHoverflyEnvironment(HOVERFLY_RULE)
.andForSimulationOnly(LAUNCHER_OSIO_TOKEN, VALID_TOKEN))
.around(HOVERFLY_RULE);
@Rule
public LauncherPerTestHoverflyRule hoverflyPerTestRule = new LauncherPerTestHoverflyRule(HOVERFLY_RULE);
@Test
public void should_receive_key_based_on_its_kid() {
// given
final PublicKeyProvider publicKeyProvider = new AuthPublicKeyProvider(getTestAuthorization(), HttpClient.create());
// when
final Optional<RSAPublicKey> publicKey = publicKeyProvider.getKey(KID);
// then
assertThat(publicKey).isPresent()
.get()
.isEqualTo(RSAPublicKeyConverter.fromString(STRIP_PUBLIC_KEY));
}
}
|
UTF-8
|
Java
| 2,434 |
java
|
AuthPublicKeyProviderTest.java
|
Java
|
[] | null |
[] |
package io.fabric8.launcher.osio.client;
import java.security.interfaces.RSAPublicKey;
import java.util.Optional;
import io.fabric8.launcher.base.http.HttpClient;
import io.fabric8.launcher.base.identity.RSAPublicKeyConverter;
import io.fabric8.launcher.base.test.hoverfly.LauncherPerTestHoverflyRule;
import io.fabric8.launcher.core.spi.PublicKeyProvider;
import io.specto.hoverfly.junit.rule.HoverflyRule;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import static io.fabric8.launcher.base.test.hoverfly.LauncherHoverflyEnvironment.createDefaultHoverflyEnvironment;
import static io.fabric8.launcher.base.test.hoverfly.LauncherHoverflyRuleConfigurer.createMultiTestHoverflyProxy;
import static io.fabric8.launcher.base.test.identity.TokenFixtures.KID;
import static io.fabric8.launcher.base.test.identity.TokenFixtures.STRIP_PUBLIC_KEY;
import static io.fabric8.launcher.base.test.identity.TokenFixtures.VALID_TOKEN;
import static io.fabric8.launcher.osio.client.OsioTests.LAUNCHER_OSIO_TOKEN;
import static io.fabric8.launcher.osio.client.OsioTests.getTestAuthorization;
import static org.assertj.core.api.Assertions.assertThat;
public class AuthPublicKeyProviderTest {
private static final HoverflyRule HOVERFLY_RULE = createMultiTestHoverflyProxy("auth.openshift.io|auth.prod-preview.openshift.io");
@ClassRule
public static final RuleChain RULE_CHAIN = RuleChain// After recording on a real environment against a real service,
// You should adapt the Hoverfly descriptors (.json) to make them work in simulation mode with the mock environment.
.outerRule(createDefaultHoverflyEnvironment(HOVERFLY_RULE)
.andForSimulationOnly(LAUNCHER_OSIO_TOKEN, VALID_TOKEN))
.around(HOVERFLY_RULE);
@Rule
public LauncherPerTestHoverflyRule hoverflyPerTestRule = new LauncherPerTestHoverflyRule(HOVERFLY_RULE);
@Test
public void should_receive_key_based_on_its_kid() {
// given
final PublicKeyProvider publicKeyProvider = new AuthPublicKeyProvider(getTestAuthorization(), HttpClient.create());
// when
final Optional<RSAPublicKey> publicKey = publicKeyProvider.getKey(KID);
// then
assertThat(publicKey).isPresent()
.get()
.isEqualTo(RSAPublicKeyConverter.fromString(STRIP_PUBLIC_KEY));
}
}
| 2,434 | 0.774445 | 0.769515 | 53 | 44.92453 | 40.329235 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.566038 | false | false |
10
|
2d9dab1f55b8fa5c8f1debce28d7341eede2cd98
| 3,753,801,483,765 |
951a2cebfb3b742a0b9da0dee787f4610505292c
|
/toq/Misc/JavaSrc/com/qualcomm/toq/base/connectionlistener/bluetooth/BTConnectionListener.java
|
8c62569754c4e93e1b1ae2d8bc967335f995ef05
|
[] |
no_license
|
marciallus/mytoqmanager
|
https://github.com/marciallus/mytoqmanager
|
eca30683508878b712e9c1c6642f39f34c2e257b
|
65fe1d54e8593900262d5b263d75feb646c015e6
|
refs/heads/master
| 2020-05-17T01:03:44.121000 | 2014-12-10T07:22:14 | 2014-12-10T07:22:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) fieldsfirst noctor space
package com.qualcomm.toq.base.connectionlistener.bluetooth;
import android.bluetooth.*;
import android.content.Context;
import android.content.SharedPreferences;
import android.telephony.TelephonyManager;
import com.qualcomm.toq.ToqApplication;
import com.qualcomm.toq.base.connectionlistener.IConnectionListener;
import com.qualcomm.toq.base.connectionmanager.IConnectionManager;
import com.qualcomm.toq.base.endpoint.IEndPoint;
import com.qualcomm.toq.base.utils.*;
import java.io.*;
import java.util.*;
public class BTConnectionListener
implements IConnectionListener
{
private class AcceptThread extends Thread
{
private BluetoothServerSocket mmServerSocket;
private BluetoothSocket serverSocket;
private volatile boolean stop;
final BTConnectionListener this$0;
private void closeSocket()
{
this;
JVM INSTR monitorenter ;
if (serverSocket != null)
{
Log.d("BTConnectionListener", "serverSocket: close() ");
serverSocket.close();
serverSocket = null;
}
_L1:
this;
JVM INSTR monitorexit ;
return;
Exception exception1;
exception1;
Log.e("BTConnectionListener", (new StringBuilder()).append("close() of serverSocket failed").append(exception1.toString()).toString());
goto _L1
Exception exception;
exception;
throw exception;
}
public void cancel()
{
Log.d("BTConnectionListener", "AcceptThread: cancel() ");
closeSocket();
closeServerSocket();
}
public void closeServerSocket()
{
this;
JVM INSTR monitorenter ;
if (mmServerSocket != null)
{
Log.d("BTConnectionListener", "mmServerSocket: close() ");
mmServerSocket.close();
mmServerSocket = null;
}
_L1:
this;
JVM INSTR monitorexit ;
return;
Exception exception1;
exception1;
Log.e("BTConnectionListener", (new StringBuilder()).append("close() of mmServerSocket failed ").append(exception1.toString()).toString());
exception1.printStackTrace();
goto _L1
Exception exception;
exception;
throw exception;
}
public void run()
{
Log.d("BTConnectionListener", (new StringBuilder()).append("AcceptThread: endpoint type = ").append(endPoint.getType()).toString());
setName("AcceptThread");
_L14:
if (!BluetoothAdapter.getDefaultAdapter().isEnabled() || mSPPState != 1 || stop)
break MISSING_BLOCK_LABEL_616;
Log.d("BTConnectionListener", (new StringBuilder()).append("Inside AcceptThread of device: ").append(com.qualcomm.toq.base.utils.Constants.EndPointEnum.values()[endPoint.getType()]).toString());
if (mmServerSocket != null) goto _L2; else goto _L1
_L1:
if (endPoint.getType() != 0) goto _L4; else goto _L3
_L3:
Log.printUsageLog("BTConnectionListener", "Listening to Socket connection for WD");
mmServerSocket = BluetoothAdapter.getDefaultAdapter().listenUsingRfcommWithServiceRecord("PHubCommServer", BTConnectionListener.SERVER_WD_UUID);
_L2:
if (mmServerSocket != null)
{
Utils.updateStatus("BTConnectionListener", "EPMessage:Waiting for incoming connection...", endPoint.getType(), 1, (byte)7);
serverSocket = mmServerSocket.accept();
Log.printUsageLog("BTConnectionListener", "A succssful connection estabished through Server Socket");
Utils.updateStatus("BTConnectionListener", "EPMessage:Accepted incoming connection...", endPoint.getType(), 1, (byte)7);
}
Log.d("BTConnectionListener", "AcceptThread: called: mmServerSocket.accept() completed");
_L11:
if (serverSocket == null) goto _L6; else goto _L5
_L5:
BTConnectionListener btconnectionlistener = BTConnectionListener.this;
btconnectionlistener;
JVM INSTR monitorenter ;
mSPPState;
JVM INSTR tableswitch 1 1: default 268
// 1 474;
goto _L7 _L8
_L7:
Log.e("BTConnectionListener", "closing SPP server socket as already in STATE_CONNECTED");
cancel();
_L6:
Log.d("BTConnectionListener", (new StringBuilder()).append("AcceptThread: End of while loop of device: ").append(com.qualcomm.toq.base.utils.Constants.EndPointEnum.values()[endPoint.getType()]).toString());
continue; /* Loop/switch isn't completed */
_L4:
if (endPoint.getType() != 1) goto _L10; else goto _L9
_L9:
Log.printUsageLog("BTConnectionListener", "Listening to Socket connection for Left EP");
mmServerSocket = BluetoothAdapter.getDefaultAdapter().listenUsingInsecureRfcommWithServiceRecord("EPLCommServer", BTConnectionListener.SERVER_EP_L_UUID);
goto _L2
Exception exception;
exception;
Log.e("BTConnectionListener", "AcceptThread: accept() failed", exception);
Log.printUsageLog("BTConnectionListener", (new StringBuilder()).append("AcceptThread: accept() failed ").append(exception.toString()).toString());
Utils.updateStatus("BTConnectionListener", "EPMessage:Exited from incoming connection...", endPoint.getType(), 1, (byte)7);
exception.printStackTrace();
cancel();
goto _L11
_L10:
if (endPoint.getType() != 2) goto _L2; else goto _L12
_L12:
Log.printUsageLog("BTConnectionListener", "Listening to Socket connection for Right EP");
mmServerSocket = BluetoothAdapter.getDefaultAdapter().listenUsingInsecureRfcommWithServiceRecord("EPRCommServer", BTConnectionListener.SERVER_EP_R_UUID);
goto _L2
_L8:
Log.d("BTConnectionListener", (new StringBuilder()).append("AcceptThread: SPP Server accepted the incoming connection... Incoming BT address: ").append(serverSocket.getRemoteDevice().getAddress()).append(" Associated Device Adress: ").append(endPoint.getAddress()).toString());
if (!serverSocket.getRemoteDevice().getAddress().equalsIgnoreCase(endPoint.getAddress()))
break MISSING_BLOCK_LABEL_602;
Log.d("BTConnectionListener", "AcceptThread: Incoming connection Success");
Log.printUsageLog("BTConnectionListener", "AcceptThread: Incoming connection Success");
Log.d("BTConnectionListener", "Initiate ConnectedThread by SPP Server");
connectionSuccess(serverSocket, serverSocket.getRemoteDevice());
goto _L6
Exception exception1;
exception1;
btconnectionlistener;
JVM INSTR monitorexit ;
throw exception1;
Log.e("BTConnectionListener", "AcceptThread: SPP server in connected state, but address didn't match!!!");
cancel();
goto _L6
if (mSPPState != 3)
{
Log.e("BTConnectionListener", (new StringBuilder()).append("End of AcceptThread and state = ").append(mSPPState).toString());
cancel();
}
return;
if (true) goto _L14; else goto _L13
_L13:
}
public void stopAcceptThread()
{
stop = true;
}
public AcceptThread()
{
this$0 = BTConnectionListener.this;
super();
mmServerSocket = null;
serverSocket = null;
stop = false;
Log.d("BTConnectionListener", (new StringBuilder()).append("Called AcceptThread constructor of device: ").append(com.qualcomm.toq.base.utils.Constants.EndPointEnum.values()[endPoint.getType()]).toString());
}
}
private class ConnectThread extends Thread
{
private final BluetoothDevice mmDevice;
private BluetoothSocket mmSocket;
final BTConnectionListener this$0;
public void cancel()
{
try
{
Log.d("BTConnectionListener", "ConnectThread cancel() called");
if (mmSocket != null)
mmSocket.close();
mmSocket = null;
return;
}
catch (Exception exception)
{
Log.e("BTConnectionListener", "close() of connect socket failed", exception);
}
}
public void run()
{
Log.i("BTConnectionListener", "BEGIN mConnectThread");
setName("ConnectThread");
Log.d("BTConnectionListener", (new StringBuilder()).append("End Point Type while Connect = ").append(endPoint.getType()).toString());
if (endPoint.getType() != 0) goto _L2; else goto _L1
_L1:
boolean flag;
flag = isWDDeviceAssociated(mmDevice.getAddress());
mmSocket = mmDevice.createRfcommSocketToServiceRecord(BTConnectionListener.CLIENT_WD_UUID);
_L4:
TelephonyManager telephonymanager;
telephonymanager = (TelephonyManager)ToqApplication.getAppContext().getSystemService("phone");
Log.d("BTConnectionListener", (new StringBuilder()).append("Call state value = ").append(telephonymanager.getCallState()).toString());
if (!flag)
break MISSING_BLOCK_LABEL_153;
if (telephonymanager.getCallState() != 2 && mmSocket != null)
break MISSING_BLOCK_LABEL_185;
if (endPoint.getType() != 1 && endPoint.getType() != 2)
break MISSING_BLOCK_LABEL_462;
Log.d("BTConnectionListener", "BT cancelDiscovery() called");
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
Log.d("BTConnectionListener", "BT Socket trying to connect");
Log.printUsageLog("BTConnectionListener", "BT Socket Trying to connect");
mmSocket.connect();
Log.d("BTConnectionListener", (new StringBuilder()).append("BT Socket connected = ").append(BTConnectionListener.this).toString());
Log.printUsageLog("BTConnectionListener", "BT Socket connected ");
synchronized (BTConnectionListener.this)
{
mConnectThread = null;
}
connectionSuccess(mmSocket, mmDevice);
return;
_L2:
Exception exception;
label0:
{
if (endPoint.getType() != 1)
break label0;
flag = isEPLeftDeviceAssociated(mmDevice.getAddress());
mmSocket = mmDevice.createInsecureRfcommSocketToServiceRecord(BTConnectionListener.CLIENT_EP_L_UUID);
}
if (true) goto _L4; else goto _L3
_L3:
int i;
try
{
i = endPoint.getType();
}
// Misplaced declaration of an exception variable
catch (Exception exception)
{
Log.e("BTConnectionListener", (new StringBuilder()).append("BTSocket Connect Failed: ").append(exception.toString()).toString());
Log.printUsageLog("BTConnectionListener", (new StringBuilder()).append("BTSocket Connect Failed: ").append(exception.toString()).toString());
exception.printStackTrace();
cancel();
connectionFailed();
return;
}
flag = false;
if (i != 2) goto _L4; else goto _L5
_L5:
flag = isEPRightDeviceAssociated(mmDevice.getAddress());
mmSocket = mmDevice.createInsecureRfcommSocketToServiceRecord(BTConnectionListener.CLIENT_EP_R_UUID);
goto _L4
Log.e("BTConnectionListener", "Not Associated: Device to connect is different from the associated Device or an Active call can be present");
cancel();
if (!isStopListenerCalled)
{
connectionFailed();
return;
}
Log.e("BTConnectionListener", "ConnectThread-- stopConnection already called, no need to set the state to failed. ");
return;
exception1;
btconnectionlistener;
JVM INSTR monitorexit ;
throw exception1;
}
public ConnectThread(BluetoothDevice bluetoothdevice)
{
this$0 = BTConnectionListener.this;
super();
mmSocket = null;
mmDevice = bluetoothdevice;
}
}
private class ConnectedThread extends Thread
{
private InputStream mmInStream;
private OutputStream mmOutStream;
private BluetoothSocket mmSocket;
private volatile boolean stop;
final BTConnectionListener this$0;
public void cancel()
{
try
{
Log.e("BTConnectionListener", "ConnectedThread cancel() called!");
closeInputStream();
closeOutputStream();
closeBTSocket();
return;
}
catch (Exception exception)
{
Log.e("BTConnectionListener", (new StringBuilder()).append("unable to close() socket during connection failure").append(exception.toString()).toString());
exception.printStackTrace();
return;
}
}
public void closeBTSocket()
{
this;
JVM INSTR monitorenter ;
if (mmSocket != null)
{
mmSocket.close();
mmSocket = null;
}
_L1:
this;
JVM INSTR monitorexit ;
return;
Exception exception1;
exception1;
exception1.printStackTrace();
goto _L1
Exception exception;
exception;
throw exception;
}
public void closeInputStream()
{
this;
JVM INSTR monitorenter ;
if (mmInStream != null)
{
mmInStream.close();
mmInStream = null;
}
_L1:
this;
JVM INSTR monitorexit ;
return;
Exception exception1;
exception1;
exception1.printStackTrace();
goto _L1
Exception exception;
exception;
throw exception;
}
public void closeOutputStream()
{
this;
JVM INSTR monitorenter ;
if (mmOutStream != null)
{
mmOutStream.close();
mmOutStream = null;
}
_L1:
this;
JVM INSTR monitorexit ;
return;
Exception exception1;
exception1;
exception1.printStackTrace();
goto _L1
Exception exception;
exception;
throw exception;
}
public void run()
{
Log.i("BTConnectionListener", "BEGIN mConnectedThread");
mResetConnectedThread = new ResetConnectedThread();
BTConnectionListener.isOPPSleepRequired = true;
Log.d("BTConnectionListener", (new StringBuilder()).append("End Point Type = ").append(endPoint.getType()).toString());
_L20:
if (stop) goto _L2; else goto _L1
_L1:
if (endPoint.getType() != 0) goto _L4; else goto _L3
_L3:
byte abyte10[];
byte abyte11[];
byte abyte12[];
int i3;
Log.d("BTConnectionListener", "Reading WD Device byte data");
abyte10 = new byte[6];
abyte11 = new byte[2];
abyte12 = new byte[2];
i3 = 0;
_L13:
if (i3 >= abyte10.length) goto _L6; else goto _L5
_L5:
int l5 = mmInStream.read(abyte10, i3, abyte10.length - i3);
if (l5 >= 0) goto _L7; else goto _L6
_L6:
if (i3 != abyte10.length)
{
Log.e("BTConnectionListener", (new StringBuilder()).append("Connected Thread first 6 bytes read failed!! bytes read = ").append(i3).append(" bytes").toString());
throw new IOException("ConnectedThread failed to read first 6 bytes");
}
goto _L8
Exception exception3;
exception3;
Log.printUsageLog("BTConnectionListener", (new StringBuilder()).append("BT Socket disconnected ").append(exception3.toString()).toString());
Log.e("BTConnectionListener", (new StringBuilder()).append("WD disconnected: ").append(exception3.toString()).toString());
exception3.printStackTrace();
BTConnectionListener.isOPPSleepRequired = false;
_L2:
int k3;
boolean flag;
int j4;
boolean flag1;
Log.printUsageLog("BTConnectionListener", "While loop exited BT Socket disconnected ");
Log.e("BTConnectionListener", "While loop exited WD disconnected: ");
byte abyte0[];
byte abyte1[];
byte abyte2[];
int i;
Exception exception1;
int j;
int k;
byte abyte3[];
int l;
byte abyte4[];
int i1;
int j1;
byte abyte5[];
byte abyte6[];
byte abyte7[];
int k1;
Exception exception2;
int l1;
int i2;
byte abyte8[];
int j2;
byte abyte9[];
int k2;
int l2;
int ai[];
int j3;
int l3;
int ai1[];
int i4;
int k4;
int l4;
int i5;
byte abyte13[];
byte abyte14[];
try
{
closeInputStream();
closeOutputStream();
closeBTSocket();
}
catch (Exception exception)
{
exception.printStackTrace();
Log.e("BTConnectionListener", (new StringBuilder()).append("ConnectedThread with Exception: ").append(exception).toString());
}
Log.d("BTConnectionListener", (new StringBuilder()).append("mSPPState = ").append(mSPPState).toString());
if (mSPPState == 0) goto _L10; else goto _L9
_L9:
if (isStopListenerCalled) goto _L12; else goto _L11
_L11:
connectionFailed();
_L10:
return;
_L7:
i3 += l5;
goto _L13
_L8:
if (mResetConnectedThread != null)
mResetConnectedThread.setContinueFlagEnabled(true);
Log.d("BTConnectionListener", (new StringBuilder()).append("WD src in listener:").append(abyte10[0]).toString());
Log.d("BTConnectionListener", (new StringBuilder()).append("WD dest in listener:").append(abyte10[1]).toString());
if (abyte10[0] < 0 || abyte10[1] < 0)
throw new IOException("src and dest value read are negative");
ai = Constants.SRC_ADDRESS;
j3 = ai.length;
k3 = 0;
_L36:
flag = false;
if (k3 >= j3) goto _L15; else goto _L14
_L14:
l3 = ai[k3];
if (abyte10[0] != l3) goto _L17; else goto _L16
_L16:
flag = true;
_L15:
ai1 = Constants.DEST_ADDRESS;
i4 = ai1.length;
j4 = 0;
_L37:
flag1 = false;
if (j4 >= i4) goto _L19; else goto _L18
_L18:
k4 = ai1[j4];
if (abyte10[1] != k4)
break MISSING_BLOCK_LABEL_1676;
flag1 = true;
goto _L19
_L34:
throw new IOException("src and dest value read are invalid");
_L35:
abyte11[0] = abyte10[2];
abyte11[1] = abyte10[3];
l4 = ByteUtils.convertBytestoNumber(abyte11);
Log.d("BTConnectionListener", (new StringBuilder()).append("WD sent payload length: ").append(l4).toString());
abyte12[0] = abyte10[4];
abyte12[1] = abyte10[5];
i5 = ByteUtils.convertBytestoNumber(abyte12);
Log.d("BTConnectionListener", (new StringBuilder()).append("WD transaction ID: ").append(i5).toString());
abyte13 = new byte[l4];
if (ProjectConfig.getProjectConfig() != null && !ProjectConfig.getProjectConfig().getAPKVariant().equalsIgnoreCase("release"))
startTimer();
break MISSING_BLOCK_LABEL_1682;
j5 = 0;
int j5;
int k5;
for (; j5 >= l4; j5 += k5)
break MISSING_BLOCK_LABEL_712;
k5 = mmInStream.read(abyte13, j5, l4 - j5);
if (k5 >= 0)
break MISSING_BLOCK_LABEL_1688;
Log.d("BTConnectionListener", (new StringBuilder()).append("Payload bytes read: ").append(j5).append(" bytes").toString());
if (ProjectConfig.getProjectConfig() != null && !ProjectConfig.getProjectConfig().getAPKVariant().equalsIgnoreCase("release"))
{
Log.d("BTConnectionListener", "stopTimer() called: isTimerRequired set to false");
stopTimer();
}
if (j5 == l4)
break MISSING_BLOCK_LABEL_846;
Log.e("BTConnectionListener", (new StringBuilder()).append("Connected Thread payload read failed!! bytes read = ").append(j5).append(" bytes").toString());
throw new IOException((new StringBuilder()).append("ConnectedThread failed to read payload ").append(l4).append(" bytes").toString());
abyte14 = new byte[l4 + abyte10.length];
System.arraycopy(abyte10, 0, abyte14, 0, abyte10.length);
System.arraycopy(abyte13, 0, abyte14, abyte10.length, abyte13.length);
read(abyte14);
goto _L20
_L4:
if (endPoint.getType() != 1) goto _L22; else goto _L21
_L21:
abyte5 = new byte[6];
abyte6 = new byte[2];
abyte7 = new byte[2];
k1 = 0;
_L26:
if (k1 >= abyte5.length) goto _L24; else goto _L23
_L23:
l2 = mmInStream.read(abyte5, k1, abyte5.length - k1);
if (l2 >= 0) goto _L25; else goto _L24
_L24:
if (mResetConnectedThread != null)
mResetConnectedThread.setContinueFlagEnabled(true);
Log.d("BTConnectionListener", (new StringBuilder()).append("EP-L src in listener:").append(abyte5[0]).toString());
Log.d("BTConnectionListener", (new StringBuilder()).append("EP-L dest in listener:").append(abyte5[1]).toString());
abyte6[0] = abyte5[2];
abyte6[1] = abyte5[3];
l1 = ByteUtils.convertBytestoNumber(abyte6);
Log.d("BTConnectionListener", (new StringBuilder()).append("EP-L sent payload length: ").append(l1).toString());
abyte7[0] = abyte5[4];
abyte7[1] = abyte5[5];
i2 = ByteUtils.convertBytestoNumber(abyte7);
Log.d("BTConnectionListener", (new StringBuilder()).append("EP-L transaction ID: ").append(i2).toString());
abyte8 = new byte[l1];
j2 = 0;
_L27:
if (j2 >= abyte8.length)
break MISSING_BLOCK_LABEL_1174;
k2 = mmInStream.read(abyte8, j2, abyte8.length - j2);
if (k2 >= 0)
break MISSING_BLOCK_LABEL_1250;
abyte9 = new byte[l1 + abyte5.length];
System.arraycopy(abyte5, 0, abyte9, 0, abyte5.length);
System.arraycopy(abyte8, 0, abyte9, abyte5.length, abyte8.length);
read(abyte9);
goto _L20
exception2;
Log.e("BTConnectionListener", "EP-L disconnected");
exception2.printStackTrace();
goto _L2
_L25:
k1 += l2;
goto _L26
j2 += k2;
goto _L27
_L22:
if (endPoint.getType() != 2) goto _L20; else goto _L28
_L28:
abyte0 = new byte[6];
abyte1 = new byte[2];
abyte2 = new byte[2];
i = 0;
_L32:
if (i >= abyte0.length) goto _L30; else goto _L29
_L29:
j1 = mmInStream.read(abyte0, i, abyte0.length - i);
if (j1 >= 0) goto _L31; else goto _L30
_L30:
if (mResetConnectedThread != null)
mResetConnectedThread.setContinueFlagEnabled(true);
Log.d("BTConnectionListener", (new StringBuilder()).append("EP-R src in listener:").append(abyte0[0]).toString());
Log.d("BTConnectionListener", (new StringBuilder()).append("EP-R dest in listener:").append(abyte0[1]).toString());
abyte1[0] = abyte0[2];
abyte1[1] = abyte0[3];
j = ByteUtils.convertBytestoNumber(abyte1);
Log.d("BTConnectionListener", (new StringBuilder()).append("EP-R sent payload length: ").append(j).toString());
abyte2[0] = abyte0[4];
abyte2[1] = abyte0[5];
k = ByteUtils.convertBytestoNumber(abyte2);
Log.d("BTConnectionListener", (new StringBuilder()).append("EP-R transaction ID: ").append(k).toString());
abyte3 = new byte[j];
l = 0;
_L33:
if (l >= abyte3.length)
break MISSING_BLOCK_LABEL_1533;
i1 = mmInStream.read(abyte3, l, abyte3.length - l);
if (i1 >= 0)
break MISSING_BLOCK_LABEL_1605;
abyte4 = new byte[j + abyte0.length];
System.arraycopy(abyte0, 0, abyte4, 0, abyte0.length);
System.arraycopy(abyte3, 0, abyte4, abyte0.length, abyte3.length);
read(abyte4);
goto _L20
exception1;
Log.e("BTConnectionListener", "EP-R disconnected");
exception1.printStackTrace();
goto _L2
_L31:
i += j1;
goto _L32
l += i1;
goto _L33
_L12:
Log.e("BTConnectionListener", " ConnectedThread--stopConnection already called, no need to set the state to failed. ");
return;
_L19:
if (flag && flag1) goto _L35; else goto _L34
_L17:
k3++;
goto _L36
j4++;
goto _L37
}
public void stopConnectedThread()
{
stop = true;
}
public void write(byte abyte0[])
{
if (abyte0 != null)
try
{
if (abyte0.length > 0 && mmOutStream != null)
{
mmOutStream.write(abyte0, 0, abyte0.length);
return;
}
}
catch (Exception exception)
{
exception.printStackTrace();
Log.e("BTConnectionListener", (new StringBuilder()).append("Exception during write: ").append(exception.toString()).toString());
return;
}
Log.e("BTConnectionListener", "Failed to Write buffer byte array data in mmOutStream due to error");
return;
}
public ConnectedThread(BluetoothDevice bluetoothdevice, BluetoothSocket bluetoothsocket)
{
this$0 = BTConnectionListener.this;
super();
mmSocket = null;
mmInStream = null;
mmOutStream = null;
stop = false;
Log.d("BTConnectionListener", "create ConnectedThread");
mmSocket = bluetoothsocket;
try
{
mmInStream = bluetoothsocket.getInputStream();
mmOutStream = bluetoothsocket.getOutputStream();
return;
}
catch (IOException ioexception)
{
ioexception.printStackTrace();
Log.e("BTConnectionListener", "ConnectedThread with IO Exception: e");
return;
}
catch (Exception exception)
{
exception.printStackTrace();
}
Log.e("BTConnectionListener", "Exception in ConnectedThread, temp sockets not created");
}
}
private class ResetConnectedThread extends Thread
{
private static final int RESET_DELAY = 10000;
private boolean continueFlagEnabled;
final BTConnectionListener this$0;
public void run()
{
super.run();
Log.d("BTConnectionListener", "ResetConnectedThread run() sleep for 10 seconds");
Log.d("BTConnectionListener", "[sleep] 10 seconds RESET_DELAY");
Thread.sleep(10000L);
Log.d("BTConnectionListener", (new StringBuilder()).append("Post 10 seonds delay continueFlagEnabled = ").append(continueFlagEnabled).toString());
if (!continueFlagEnabled && mConnectedThread != null)
synchronized (mConnectedThread)
{
Log.e("BTConnectionListener", "ResetConnectedThread stop the ConnectedThread");
Log.printUsageLog("BTConnectionListener", "Didn't receive Aloha Message: ResetConnectedThread stop the ConnectedThread");
mConnectedThread.stopConnectedThread();
mConnectedThread.cancel();
mConnectedThread = null;
}
_L2:
mResetConnectedThread = null;
return;
exception1;
connectedthread;
JVM INSTR monitorexit ;
try
{
throw exception1;
}
catch (Exception exception)
{
Log.e("BTConnectionListener", (new StringBuilder()).append("Exception in ResetConnectedThread: ").append(exception.toString()).toString());
}
if (true) goto _L2; else goto _L1
_L1:
}
public void setContinueFlagEnabled(boolean flag)
{
continueFlagEnabled = flag;
Log.d("BTConnectionListener", (new StringBuilder()).append("setContinueFlagEnabled called: ").append(flag).toString());
}
public ResetConnectedThread()
{
this$0 = BTConnectionListener.this;
super();
continueFlagEnabled = false;
Log.d("BTConnectionListener", "ResetConnectedThread Constructur");
start();
}
}
protected static final int BT_SPP_CONNECT_ATTEMPTS = 3;
private static final UUID CLIENT_EP_L_UUID = UUID.fromString("00000002-476D-42C4-BD11-9D377C45694C");
private static final UUID CLIENT_EP_R_UUID = UUID.fromString("00000003-476D-42C4-BD11-9D377C45694C");
private static final UUID CLIENT_WD_UUID = UUID.fromString("00000001-476D-42C4-BD11-9D377C45694C");
private static final UUID GENERIC_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final UUID SERVER_EP_L_UUID = UUID.fromString("00000002-476D-42C4-BD11-9D377C45694F");
private static final UUID SERVER_EP_R_UUID = UUID.fromString("00000003-476D-42C4-BD11-9D377C45694F");
private static final UUID SERVER_WD_UUID = UUID.fromString("00000001-476D-42C4-BD11-9D377C45694F");
private static final String TAG = "BTConnectionListener";
public static boolean isOPPSleepRequired = true;
private static boolean isTimerRequired = true;
private static Timer mTimer = null;
final int READ_DELAY = 15000;
protected int btConnectIteration;
private IConnectionManager connectionManager;
protected IEndPoint endPoint;
private boolean isStopListenerCalled;
private AcceptThread mAcceptThread;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private ResetConnectedThread mResetConnectedThread;
private volatile int mSPPState;
public BTConnectionListener(IEndPoint iendpoint, IConnectionManager iconnectionmanager)
{
isStopListenerCalled = false;
Log.i("BTConnectionListener", (new StringBuilder()).append("BTConnectionListener listener created = ").append(this).toString());
connectionManager = iconnectionmanager;
endPoint = iendpoint;
mSPPState = 0;
}
private void startTimer()
{
stopTimer();
if (mTimer == null)
{
mTimer = new Timer();
isTimerRequired = true;
Log.d("BTConnectionListener", "startTimer() called: Timer to scheduled for 15 seconds delay");
}
mTimer.schedule(new TimerTask() {
final BTConnectionListener this$0;
public void run()
{
if (BTConnectionListener.isTimerRequired)
{
stopTimer();
if (mConnectedThread != null)
{
synchronized (mConnectedThread)
{
Log.e("BTConnectionListener", "startTimer() run() called: mTimer to stop the ConnectedThread");
Log.printUsageLog("BTConnectionListener", "Didn't receive payload, mTimer to stop the ConnectedThread");
mConnectedThread.stopConnectedThread();
mConnectedThread.cancel();
mConnectedThread = null;
}
return;
}
}
break MISSING_BLOCK_LABEL_84;
exception;
connectedthread;
JVM INSTR monitorexit ;
throw exception;
}
{
this$0 = BTConnectionListener.this;
super();
}
}
, 15000L);
}
private void stopTimer()
{
isTimerRequired = false;
if (mTimer != null)
{
mTimer.cancel();
mTimer = null;
}
}
public void connect(String s)
{
Log.d("BTConnectionListener", (new StringBuilder()).append("connect() mSPPState = ").append(mSPPState).toString());
if (mSPPState != 3 && mSPPState != 2)
{
if (mConnectThread != null)
{
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null)
{
mConnectedThread.stopConnectedThread();
mConnectedThread.cancel();
mConnectedThread = null;
}
setState(2);
if (mAcceptThread != null)
{
mAcceptThread.stopAcceptThread();
mAcceptThread.cancel();
mAcceptThread = null;
}
mConnectThread = new ConnectThread(BluetoothAdapter.getDefaultAdapter().getRemoteDevice(s));
mConnectThread.start();
}
}
protected void connectionFailed()
{
Log.e("BTConnectionListener", "Connection Failed");
setState(4);
}
protected void connectionSuccess(BluetoothSocket bluetoothsocket, BluetoothDevice bluetoothdevice)
{
this;
JVM INSTR monitorenter ;
Log.d("BTConnectionListener", "connected");
if (mConnectThread != null)
{
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null)
{
mConnectedThread.stopConnectedThread();
mConnectedThread.cancel();
mConnectedThread = null;
}
setState(3);
if (mAcceptThread != null)
{
mAcceptThread.stopAcceptThread();
mAcceptThread.closeServerSocket();
mAcceptThread = null;
}
mConnectedThread = new ConnectedThread(bluetoothdevice, bluetoothsocket);
mConnectedThread.start();
this;
JVM INSTR monitorexit ;
return;
Exception exception;
exception;
throw exception;
}
public void disconnect()
{
if (mConnectedThread != null)
mConnectedThread.cancel();
}
public boolean isEPLeftDeviceAssociated(String s)
{
Log.i("BTConnectionListener", "isEPLeftDeviceAssociated");
if (ToqData.getInstance().getAssociatedDevicePrefs().contains("associated_ep_l_device_address") && !ToqData.getInstance().getAssociatedDevicePrefs().getString("associated_ep_l_device_address", "").equalsIgnoreCase(s))
{
Log.i("BTConnectionListener", "isDeviceAssociated EP Left false");
return false;
} else
{
Log.i("BTConnectionListener", "isDeviceAssociated EP Left true");
return true;
}
}
public boolean isEPRightDeviceAssociated(String s)
{
Log.i("BTConnectionListener", "isEPRightDeviceAssociated");
if (ToqData.getInstance().getAssociatedDevicePrefs().contains("associated_ep_r_device_address") && !ToqData.getInstance().getAssociatedDevicePrefs().getString("associated_ep_r_device_address", "").equalsIgnoreCase(s))
{
Log.i("BTConnectionListener", "isDeviceAssociated EP right false");
return false;
} else
{
Log.i("BTConnectionListener", "isDeviceAssociated EP right true");
return true;
}
}
public boolean isWDDeviceAssociated(String s)
{
Log.i("BTConnectionListener", "isWDDeviceAssociated");
if (ToqData.getInstance().getAssociatedDevicePrefs().contains("associated_wd_device_address") && !ToqData.getInstance().getAssociatedDevicePrefs().getString("associated_wd_device_address", "").equalsIgnoreCase(s))
{
Log.i("BTConnectionListener", "isDeviceAssociated WD false");
return false;
} else
{
Log.i("BTConnectionListener", "isDeviceAssociated WD true");
return true;
}
}
public void read(byte abyte0[])
{
connectionManager.receiveData(abyte0, endPoint);
}
protected void setState(int i)
{
this;
JVM INSTR monitorenter ;
Log.d("BTConnectionListener", (new StringBuilder()).append("setState(connlisten: ").append(this).append(", endpt: ").append(endPoint).append(", mSPPState: ").append(i).toString());
mSPPState = i;
if (endPoint == null) goto _L2; else goto _L1
_L1:
Log.printUsageLog("BTConnectionListener", (new StringBuilder()).append("setState() End Point Type = ").append(endPoint.getType()).append(" State = ").append(mSPPState).toString());
Log.d("BTConnectionListener", (new StringBuilder()).append("setState() End Point Type = ").append(endPoint.getType()).append(" State = ").append(mSPPState).toString());
connectionManager.connectionStateChange(endPoint, i);
if (endPoint.getType() != 0) goto _L4; else goto _L3
_L3:
if (mSPPState != 4 || !BluetoothAdapter.getDefaultAdapter().isEnabled()) goto _L6; else goto _L5
_L5:
if (btConnectIteration >= 3) goto _L8; else goto _L7
_L7:
Log.printUsageLog("BTConnectionListener", (new StringBuilder()).append("SPP retry interation: ").append(btConnectIteration).toString());
Log.e("BTConnectionListener", (new StringBuilder()).append("SPP retry interation: ").append(btConnectIteration).toString());
btConnectIteration = 1 + btConnectIteration;
Log.d("BTConnectionListener", "[sleep] 5 seconds");
wait(5000L);
if (!ToqData.getInstance().getAssociatedDevicePrefs().contains("associated_wd_device_address")) goto _L10; else goto _L9
_L9:
connect(endPoint.getAddress());
_L4:
this;
JVM INSTR monitorexit ;
return;
InterruptedException interruptedexception;
interruptedexception;
Log.e("BTConnectionListener", (new StringBuilder()).append("SPP retry interation: ").append(btConnectIteration).append(" interrupted!!!").toString());
goto _L4
Exception exception;
exception;
throw exception;
_L10:
Log.e("BTConnectionListener", "No associated WD details found to initiate a reconnect");
goto _L4
_L8:
if (ToqData.getInstance().getAssociatedDevicePrefs() == null || !ToqData.getInstance().getAssociatedDevicePrefs().contains("associated_wd_device_address")) goto _L4; else goto _L11
_L11:
Log.d("BTConnectionListener", "WD SPP server start");
startSPPServer();
goto _L4
_L12:
btConnectIteration = 0;
break; /* Loop/switch isn't completed */
_L2:
Log.e("BTConnectionListener", "endPoint is NULL in setState fuction");
break; /* Loop/switch isn't completed */
_L6:
if (i != 3 && i != 1) goto _L4; else goto _L12
}
public void setStopListenerCalled(boolean flag)
{
isStopListenerCalled = flag;
}
public void startSPPServer()
{
Log.d("BTConnectionListener", (new StringBuilder()).append("startSPPServer() mSPPState = ").append(mSPPState).append(" of device: ").append(com.qualcomm.toq.base.utils.Constants.EndPointEnum.values()[endPoint.getType()]).toString());
if (mSPPState == 4)
{
if (mConnectThread != null)
{
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null)
{
mConnectedThread.stopConnectedThread();
mConnectedThread.cancel();
mConnectedThread = null;
}
if (mAcceptThread != null)
{
mAcceptThread.stopAcceptThread();
mAcceptThread.cancel();
mAcceptThread = null;
}
setState(1);
mAcceptThread = new AcceptThread();
mAcceptThread.start();
}
}
public void stopConnectionListener()
{
Log.d("BTConnectionListener", "stopConnectionListener()");
if (mConnectThread != null)
mConnectThread.interrupt();
if (mConnectedThread != null)
mConnectedThread.interrupt();
if (mResetConnectedThread != null)
mResetConnectedThread.interrupt();
this;
JVM INSTR monitorenter ;
setState(0);
if (mConnectThread != null)
{
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null)
{
mConnectedThread.stopConnectedThread();
mConnectedThread.cancel();
mConnectedThread = null;
}
if (mAcceptThread != null)
{
mAcceptThread.stopAcceptThread();
mAcceptThread.cancel();
mAcceptThread = null;
}
this;
JVM INSTR monitorexit ;
return;
Exception exception;
exception;
this;
JVM INSTR monitorexit ;
throw exception;
}
public void write(byte abyte0[])
{
this;
JVM INSTR monitorenter ;
if (mSPPState == 3)
break MISSING_BLOCK_LABEL_13;
this;
JVM INSTR monitorexit ;
return;
ConnectedThread connectedthread = mConnectedThread;
this;
JVM INSTR monitorexit ;
if (connectedthread != null)
{
connectedthread.write(abyte0);
Log.d("BTConnectionListener", (new StringBuilder()).append("write of byte data done: size = ").append(abyte0.length).toString());
}
try
{
Thread.sleep(5L);
return;
}
catch (Exception exception1)
{
Log.e("BTConnectionListener", (new StringBuilder()).append("Exception occured during writing data ").append(exception1).toString());
}
return;
Exception exception;
exception;
this;
JVM INSTR monitorexit ;
throw exception;
}
public void writeFile(String s, String s1)
{
}
/*
static ResetConnectedThread access$1002(BTConnectionListener btconnectionlistener, ResetConnectedThread resetconnectedthread)
{
btconnectionlistener.mResetConnectedThread = resetconnectedthread;
return resetconnectedthread;
}
*/
/*
static ConnectThread access$802(BTConnectionListener btconnectionlistener, ConnectThread connectthread)
{
btconnectionlistener.mConnectThread = connectthread;
return connectthread;
}
*/
/*
static ConnectedThread access$902(BTConnectionListener btconnectionlistener, ConnectedThread connectedthread)
{
btconnectionlistener.mConnectedThread = connectedthread;
return connectedthread;
}
*/
}
|
UTF-8
|
Java
| 45,389 |
java
|
BTConnectionListener.java
|
Java
|
[
{
"context": "// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.kpdus.com/jad.html\n",
"end": 61,
"score": 0.9996756315231323,
"start": 45,
"tag": "NAME",
"value": "Pavel Kouznetsov"
}
] | null |
[] |
// Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) fieldsfirst noctor space
package com.qualcomm.toq.base.connectionlistener.bluetooth;
import android.bluetooth.*;
import android.content.Context;
import android.content.SharedPreferences;
import android.telephony.TelephonyManager;
import com.qualcomm.toq.ToqApplication;
import com.qualcomm.toq.base.connectionlistener.IConnectionListener;
import com.qualcomm.toq.base.connectionmanager.IConnectionManager;
import com.qualcomm.toq.base.endpoint.IEndPoint;
import com.qualcomm.toq.base.utils.*;
import java.io.*;
import java.util.*;
public class BTConnectionListener
implements IConnectionListener
{
private class AcceptThread extends Thread
{
private BluetoothServerSocket mmServerSocket;
private BluetoothSocket serverSocket;
private volatile boolean stop;
final BTConnectionListener this$0;
private void closeSocket()
{
this;
JVM INSTR monitorenter ;
if (serverSocket != null)
{
Log.d("BTConnectionListener", "serverSocket: close() ");
serverSocket.close();
serverSocket = null;
}
_L1:
this;
JVM INSTR monitorexit ;
return;
Exception exception1;
exception1;
Log.e("BTConnectionListener", (new StringBuilder()).append("close() of serverSocket failed").append(exception1.toString()).toString());
goto _L1
Exception exception;
exception;
throw exception;
}
public void cancel()
{
Log.d("BTConnectionListener", "AcceptThread: cancel() ");
closeSocket();
closeServerSocket();
}
public void closeServerSocket()
{
this;
JVM INSTR monitorenter ;
if (mmServerSocket != null)
{
Log.d("BTConnectionListener", "mmServerSocket: close() ");
mmServerSocket.close();
mmServerSocket = null;
}
_L1:
this;
JVM INSTR monitorexit ;
return;
Exception exception1;
exception1;
Log.e("BTConnectionListener", (new StringBuilder()).append("close() of mmServerSocket failed ").append(exception1.toString()).toString());
exception1.printStackTrace();
goto _L1
Exception exception;
exception;
throw exception;
}
public void run()
{
Log.d("BTConnectionListener", (new StringBuilder()).append("AcceptThread: endpoint type = ").append(endPoint.getType()).toString());
setName("AcceptThread");
_L14:
if (!BluetoothAdapter.getDefaultAdapter().isEnabled() || mSPPState != 1 || stop)
break MISSING_BLOCK_LABEL_616;
Log.d("BTConnectionListener", (new StringBuilder()).append("Inside AcceptThread of device: ").append(com.qualcomm.toq.base.utils.Constants.EndPointEnum.values()[endPoint.getType()]).toString());
if (mmServerSocket != null) goto _L2; else goto _L1
_L1:
if (endPoint.getType() != 0) goto _L4; else goto _L3
_L3:
Log.printUsageLog("BTConnectionListener", "Listening to Socket connection for WD");
mmServerSocket = BluetoothAdapter.getDefaultAdapter().listenUsingRfcommWithServiceRecord("PHubCommServer", BTConnectionListener.SERVER_WD_UUID);
_L2:
if (mmServerSocket != null)
{
Utils.updateStatus("BTConnectionListener", "EPMessage:Waiting for incoming connection...", endPoint.getType(), 1, (byte)7);
serverSocket = mmServerSocket.accept();
Log.printUsageLog("BTConnectionListener", "A succssful connection estabished through Server Socket");
Utils.updateStatus("BTConnectionListener", "EPMessage:Accepted incoming connection...", endPoint.getType(), 1, (byte)7);
}
Log.d("BTConnectionListener", "AcceptThread: called: mmServerSocket.accept() completed");
_L11:
if (serverSocket == null) goto _L6; else goto _L5
_L5:
BTConnectionListener btconnectionlistener = BTConnectionListener.this;
btconnectionlistener;
JVM INSTR monitorenter ;
mSPPState;
JVM INSTR tableswitch 1 1: default 268
// 1 474;
goto _L7 _L8
_L7:
Log.e("BTConnectionListener", "closing SPP server socket as already in STATE_CONNECTED");
cancel();
_L6:
Log.d("BTConnectionListener", (new StringBuilder()).append("AcceptThread: End of while loop of device: ").append(com.qualcomm.toq.base.utils.Constants.EndPointEnum.values()[endPoint.getType()]).toString());
continue; /* Loop/switch isn't completed */
_L4:
if (endPoint.getType() != 1) goto _L10; else goto _L9
_L9:
Log.printUsageLog("BTConnectionListener", "Listening to Socket connection for Left EP");
mmServerSocket = BluetoothAdapter.getDefaultAdapter().listenUsingInsecureRfcommWithServiceRecord("EPLCommServer", BTConnectionListener.SERVER_EP_L_UUID);
goto _L2
Exception exception;
exception;
Log.e("BTConnectionListener", "AcceptThread: accept() failed", exception);
Log.printUsageLog("BTConnectionListener", (new StringBuilder()).append("AcceptThread: accept() failed ").append(exception.toString()).toString());
Utils.updateStatus("BTConnectionListener", "EPMessage:Exited from incoming connection...", endPoint.getType(), 1, (byte)7);
exception.printStackTrace();
cancel();
goto _L11
_L10:
if (endPoint.getType() != 2) goto _L2; else goto _L12
_L12:
Log.printUsageLog("BTConnectionListener", "Listening to Socket connection for Right EP");
mmServerSocket = BluetoothAdapter.getDefaultAdapter().listenUsingInsecureRfcommWithServiceRecord("EPRCommServer", BTConnectionListener.SERVER_EP_R_UUID);
goto _L2
_L8:
Log.d("BTConnectionListener", (new StringBuilder()).append("AcceptThread: SPP Server accepted the incoming connection... Incoming BT address: ").append(serverSocket.getRemoteDevice().getAddress()).append(" Associated Device Adress: ").append(endPoint.getAddress()).toString());
if (!serverSocket.getRemoteDevice().getAddress().equalsIgnoreCase(endPoint.getAddress()))
break MISSING_BLOCK_LABEL_602;
Log.d("BTConnectionListener", "AcceptThread: Incoming connection Success");
Log.printUsageLog("BTConnectionListener", "AcceptThread: Incoming connection Success");
Log.d("BTConnectionListener", "Initiate ConnectedThread by SPP Server");
connectionSuccess(serverSocket, serverSocket.getRemoteDevice());
goto _L6
Exception exception1;
exception1;
btconnectionlistener;
JVM INSTR monitorexit ;
throw exception1;
Log.e("BTConnectionListener", "AcceptThread: SPP server in connected state, but address didn't match!!!");
cancel();
goto _L6
if (mSPPState != 3)
{
Log.e("BTConnectionListener", (new StringBuilder()).append("End of AcceptThread and state = ").append(mSPPState).toString());
cancel();
}
return;
if (true) goto _L14; else goto _L13
_L13:
}
public void stopAcceptThread()
{
stop = true;
}
public AcceptThread()
{
this$0 = BTConnectionListener.this;
super();
mmServerSocket = null;
serverSocket = null;
stop = false;
Log.d("BTConnectionListener", (new StringBuilder()).append("Called AcceptThread constructor of device: ").append(com.qualcomm.toq.base.utils.Constants.EndPointEnum.values()[endPoint.getType()]).toString());
}
}
private class ConnectThread extends Thread
{
private final BluetoothDevice mmDevice;
private BluetoothSocket mmSocket;
final BTConnectionListener this$0;
public void cancel()
{
try
{
Log.d("BTConnectionListener", "ConnectThread cancel() called");
if (mmSocket != null)
mmSocket.close();
mmSocket = null;
return;
}
catch (Exception exception)
{
Log.e("BTConnectionListener", "close() of connect socket failed", exception);
}
}
public void run()
{
Log.i("BTConnectionListener", "BEGIN mConnectThread");
setName("ConnectThread");
Log.d("BTConnectionListener", (new StringBuilder()).append("End Point Type while Connect = ").append(endPoint.getType()).toString());
if (endPoint.getType() != 0) goto _L2; else goto _L1
_L1:
boolean flag;
flag = isWDDeviceAssociated(mmDevice.getAddress());
mmSocket = mmDevice.createRfcommSocketToServiceRecord(BTConnectionListener.CLIENT_WD_UUID);
_L4:
TelephonyManager telephonymanager;
telephonymanager = (TelephonyManager)ToqApplication.getAppContext().getSystemService("phone");
Log.d("BTConnectionListener", (new StringBuilder()).append("Call state value = ").append(telephonymanager.getCallState()).toString());
if (!flag)
break MISSING_BLOCK_LABEL_153;
if (telephonymanager.getCallState() != 2 && mmSocket != null)
break MISSING_BLOCK_LABEL_185;
if (endPoint.getType() != 1 && endPoint.getType() != 2)
break MISSING_BLOCK_LABEL_462;
Log.d("BTConnectionListener", "BT cancelDiscovery() called");
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
Log.d("BTConnectionListener", "BT Socket trying to connect");
Log.printUsageLog("BTConnectionListener", "BT Socket Trying to connect");
mmSocket.connect();
Log.d("BTConnectionListener", (new StringBuilder()).append("BT Socket connected = ").append(BTConnectionListener.this).toString());
Log.printUsageLog("BTConnectionListener", "BT Socket connected ");
synchronized (BTConnectionListener.this)
{
mConnectThread = null;
}
connectionSuccess(mmSocket, mmDevice);
return;
_L2:
Exception exception;
label0:
{
if (endPoint.getType() != 1)
break label0;
flag = isEPLeftDeviceAssociated(mmDevice.getAddress());
mmSocket = mmDevice.createInsecureRfcommSocketToServiceRecord(BTConnectionListener.CLIENT_EP_L_UUID);
}
if (true) goto _L4; else goto _L3
_L3:
int i;
try
{
i = endPoint.getType();
}
// Misplaced declaration of an exception variable
catch (Exception exception)
{
Log.e("BTConnectionListener", (new StringBuilder()).append("BTSocket Connect Failed: ").append(exception.toString()).toString());
Log.printUsageLog("BTConnectionListener", (new StringBuilder()).append("BTSocket Connect Failed: ").append(exception.toString()).toString());
exception.printStackTrace();
cancel();
connectionFailed();
return;
}
flag = false;
if (i != 2) goto _L4; else goto _L5
_L5:
flag = isEPRightDeviceAssociated(mmDevice.getAddress());
mmSocket = mmDevice.createInsecureRfcommSocketToServiceRecord(BTConnectionListener.CLIENT_EP_R_UUID);
goto _L4
Log.e("BTConnectionListener", "Not Associated: Device to connect is different from the associated Device or an Active call can be present");
cancel();
if (!isStopListenerCalled)
{
connectionFailed();
return;
}
Log.e("BTConnectionListener", "ConnectThread-- stopConnection already called, no need to set the state to failed. ");
return;
exception1;
btconnectionlistener;
JVM INSTR monitorexit ;
throw exception1;
}
public ConnectThread(BluetoothDevice bluetoothdevice)
{
this$0 = BTConnectionListener.this;
super();
mmSocket = null;
mmDevice = bluetoothdevice;
}
}
private class ConnectedThread extends Thread
{
private InputStream mmInStream;
private OutputStream mmOutStream;
private BluetoothSocket mmSocket;
private volatile boolean stop;
final BTConnectionListener this$0;
public void cancel()
{
try
{
Log.e("BTConnectionListener", "ConnectedThread cancel() called!");
closeInputStream();
closeOutputStream();
closeBTSocket();
return;
}
catch (Exception exception)
{
Log.e("BTConnectionListener", (new StringBuilder()).append("unable to close() socket during connection failure").append(exception.toString()).toString());
exception.printStackTrace();
return;
}
}
public void closeBTSocket()
{
this;
JVM INSTR monitorenter ;
if (mmSocket != null)
{
mmSocket.close();
mmSocket = null;
}
_L1:
this;
JVM INSTR monitorexit ;
return;
Exception exception1;
exception1;
exception1.printStackTrace();
goto _L1
Exception exception;
exception;
throw exception;
}
public void closeInputStream()
{
this;
JVM INSTR monitorenter ;
if (mmInStream != null)
{
mmInStream.close();
mmInStream = null;
}
_L1:
this;
JVM INSTR monitorexit ;
return;
Exception exception1;
exception1;
exception1.printStackTrace();
goto _L1
Exception exception;
exception;
throw exception;
}
public void closeOutputStream()
{
this;
JVM INSTR monitorenter ;
if (mmOutStream != null)
{
mmOutStream.close();
mmOutStream = null;
}
_L1:
this;
JVM INSTR monitorexit ;
return;
Exception exception1;
exception1;
exception1.printStackTrace();
goto _L1
Exception exception;
exception;
throw exception;
}
public void run()
{
Log.i("BTConnectionListener", "BEGIN mConnectedThread");
mResetConnectedThread = new ResetConnectedThread();
BTConnectionListener.isOPPSleepRequired = true;
Log.d("BTConnectionListener", (new StringBuilder()).append("End Point Type = ").append(endPoint.getType()).toString());
_L20:
if (stop) goto _L2; else goto _L1
_L1:
if (endPoint.getType() != 0) goto _L4; else goto _L3
_L3:
byte abyte10[];
byte abyte11[];
byte abyte12[];
int i3;
Log.d("BTConnectionListener", "Reading WD Device byte data");
abyte10 = new byte[6];
abyte11 = new byte[2];
abyte12 = new byte[2];
i3 = 0;
_L13:
if (i3 >= abyte10.length) goto _L6; else goto _L5
_L5:
int l5 = mmInStream.read(abyte10, i3, abyte10.length - i3);
if (l5 >= 0) goto _L7; else goto _L6
_L6:
if (i3 != abyte10.length)
{
Log.e("BTConnectionListener", (new StringBuilder()).append("Connected Thread first 6 bytes read failed!! bytes read = ").append(i3).append(" bytes").toString());
throw new IOException("ConnectedThread failed to read first 6 bytes");
}
goto _L8
Exception exception3;
exception3;
Log.printUsageLog("BTConnectionListener", (new StringBuilder()).append("BT Socket disconnected ").append(exception3.toString()).toString());
Log.e("BTConnectionListener", (new StringBuilder()).append("WD disconnected: ").append(exception3.toString()).toString());
exception3.printStackTrace();
BTConnectionListener.isOPPSleepRequired = false;
_L2:
int k3;
boolean flag;
int j4;
boolean flag1;
Log.printUsageLog("BTConnectionListener", "While loop exited BT Socket disconnected ");
Log.e("BTConnectionListener", "While loop exited WD disconnected: ");
byte abyte0[];
byte abyte1[];
byte abyte2[];
int i;
Exception exception1;
int j;
int k;
byte abyte3[];
int l;
byte abyte4[];
int i1;
int j1;
byte abyte5[];
byte abyte6[];
byte abyte7[];
int k1;
Exception exception2;
int l1;
int i2;
byte abyte8[];
int j2;
byte abyte9[];
int k2;
int l2;
int ai[];
int j3;
int l3;
int ai1[];
int i4;
int k4;
int l4;
int i5;
byte abyte13[];
byte abyte14[];
try
{
closeInputStream();
closeOutputStream();
closeBTSocket();
}
catch (Exception exception)
{
exception.printStackTrace();
Log.e("BTConnectionListener", (new StringBuilder()).append("ConnectedThread with Exception: ").append(exception).toString());
}
Log.d("BTConnectionListener", (new StringBuilder()).append("mSPPState = ").append(mSPPState).toString());
if (mSPPState == 0) goto _L10; else goto _L9
_L9:
if (isStopListenerCalled) goto _L12; else goto _L11
_L11:
connectionFailed();
_L10:
return;
_L7:
i3 += l5;
goto _L13
_L8:
if (mResetConnectedThread != null)
mResetConnectedThread.setContinueFlagEnabled(true);
Log.d("BTConnectionListener", (new StringBuilder()).append("WD src in listener:").append(abyte10[0]).toString());
Log.d("BTConnectionListener", (new StringBuilder()).append("WD dest in listener:").append(abyte10[1]).toString());
if (abyte10[0] < 0 || abyte10[1] < 0)
throw new IOException("src and dest value read are negative");
ai = Constants.SRC_ADDRESS;
j3 = ai.length;
k3 = 0;
_L36:
flag = false;
if (k3 >= j3) goto _L15; else goto _L14
_L14:
l3 = ai[k3];
if (abyte10[0] != l3) goto _L17; else goto _L16
_L16:
flag = true;
_L15:
ai1 = Constants.DEST_ADDRESS;
i4 = ai1.length;
j4 = 0;
_L37:
flag1 = false;
if (j4 >= i4) goto _L19; else goto _L18
_L18:
k4 = ai1[j4];
if (abyte10[1] != k4)
break MISSING_BLOCK_LABEL_1676;
flag1 = true;
goto _L19
_L34:
throw new IOException("src and dest value read are invalid");
_L35:
abyte11[0] = abyte10[2];
abyte11[1] = abyte10[3];
l4 = ByteUtils.convertBytestoNumber(abyte11);
Log.d("BTConnectionListener", (new StringBuilder()).append("WD sent payload length: ").append(l4).toString());
abyte12[0] = abyte10[4];
abyte12[1] = abyte10[5];
i5 = ByteUtils.convertBytestoNumber(abyte12);
Log.d("BTConnectionListener", (new StringBuilder()).append("WD transaction ID: ").append(i5).toString());
abyte13 = new byte[l4];
if (ProjectConfig.getProjectConfig() != null && !ProjectConfig.getProjectConfig().getAPKVariant().equalsIgnoreCase("release"))
startTimer();
break MISSING_BLOCK_LABEL_1682;
j5 = 0;
int j5;
int k5;
for (; j5 >= l4; j5 += k5)
break MISSING_BLOCK_LABEL_712;
k5 = mmInStream.read(abyte13, j5, l4 - j5);
if (k5 >= 0)
break MISSING_BLOCK_LABEL_1688;
Log.d("BTConnectionListener", (new StringBuilder()).append("Payload bytes read: ").append(j5).append(" bytes").toString());
if (ProjectConfig.getProjectConfig() != null && !ProjectConfig.getProjectConfig().getAPKVariant().equalsIgnoreCase("release"))
{
Log.d("BTConnectionListener", "stopTimer() called: isTimerRequired set to false");
stopTimer();
}
if (j5 == l4)
break MISSING_BLOCK_LABEL_846;
Log.e("BTConnectionListener", (new StringBuilder()).append("Connected Thread payload read failed!! bytes read = ").append(j5).append(" bytes").toString());
throw new IOException((new StringBuilder()).append("ConnectedThread failed to read payload ").append(l4).append(" bytes").toString());
abyte14 = new byte[l4 + abyte10.length];
System.arraycopy(abyte10, 0, abyte14, 0, abyte10.length);
System.arraycopy(abyte13, 0, abyte14, abyte10.length, abyte13.length);
read(abyte14);
goto _L20
_L4:
if (endPoint.getType() != 1) goto _L22; else goto _L21
_L21:
abyte5 = new byte[6];
abyte6 = new byte[2];
abyte7 = new byte[2];
k1 = 0;
_L26:
if (k1 >= abyte5.length) goto _L24; else goto _L23
_L23:
l2 = mmInStream.read(abyte5, k1, abyte5.length - k1);
if (l2 >= 0) goto _L25; else goto _L24
_L24:
if (mResetConnectedThread != null)
mResetConnectedThread.setContinueFlagEnabled(true);
Log.d("BTConnectionListener", (new StringBuilder()).append("EP-L src in listener:").append(abyte5[0]).toString());
Log.d("BTConnectionListener", (new StringBuilder()).append("EP-L dest in listener:").append(abyte5[1]).toString());
abyte6[0] = abyte5[2];
abyte6[1] = abyte5[3];
l1 = ByteUtils.convertBytestoNumber(abyte6);
Log.d("BTConnectionListener", (new StringBuilder()).append("EP-L sent payload length: ").append(l1).toString());
abyte7[0] = abyte5[4];
abyte7[1] = abyte5[5];
i2 = ByteUtils.convertBytestoNumber(abyte7);
Log.d("BTConnectionListener", (new StringBuilder()).append("EP-L transaction ID: ").append(i2).toString());
abyte8 = new byte[l1];
j2 = 0;
_L27:
if (j2 >= abyte8.length)
break MISSING_BLOCK_LABEL_1174;
k2 = mmInStream.read(abyte8, j2, abyte8.length - j2);
if (k2 >= 0)
break MISSING_BLOCK_LABEL_1250;
abyte9 = new byte[l1 + abyte5.length];
System.arraycopy(abyte5, 0, abyte9, 0, abyte5.length);
System.arraycopy(abyte8, 0, abyte9, abyte5.length, abyte8.length);
read(abyte9);
goto _L20
exception2;
Log.e("BTConnectionListener", "EP-L disconnected");
exception2.printStackTrace();
goto _L2
_L25:
k1 += l2;
goto _L26
j2 += k2;
goto _L27
_L22:
if (endPoint.getType() != 2) goto _L20; else goto _L28
_L28:
abyte0 = new byte[6];
abyte1 = new byte[2];
abyte2 = new byte[2];
i = 0;
_L32:
if (i >= abyte0.length) goto _L30; else goto _L29
_L29:
j1 = mmInStream.read(abyte0, i, abyte0.length - i);
if (j1 >= 0) goto _L31; else goto _L30
_L30:
if (mResetConnectedThread != null)
mResetConnectedThread.setContinueFlagEnabled(true);
Log.d("BTConnectionListener", (new StringBuilder()).append("EP-R src in listener:").append(abyte0[0]).toString());
Log.d("BTConnectionListener", (new StringBuilder()).append("EP-R dest in listener:").append(abyte0[1]).toString());
abyte1[0] = abyte0[2];
abyte1[1] = abyte0[3];
j = ByteUtils.convertBytestoNumber(abyte1);
Log.d("BTConnectionListener", (new StringBuilder()).append("EP-R sent payload length: ").append(j).toString());
abyte2[0] = abyte0[4];
abyte2[1] = abyte0[5];
k = ByteUtils.convertBytestoNumber(abyte2);
Log.d("BTConnectionListener", (new StringBuilder()).append("EP-R transaction ID: ").append(k).toString());
abyte3 = new byte[j];
l = 0;
_L33:
if (l >= abyte3.length)
break MISSING_BLOCK_LABEL_1533;
i1 = mmInStream.read(abyte3, l, abyte3.length - l);
if (i1 >= 0)
break MISSING_BLOCK_LABEL_1605;
abyte4 = new byte[j + abyte0.length];
System.arraycopy(abyte0, 0, abyte4, 0, abyte0.length);
System.arraycopy(abyte3, 0, abyte4, abyte0.length, abyte3.length);
read(abyte4);
goto _L20
exception1;
Log.e("BTConnectionListener", "EP-R disconnected");
exception1.printStackTrace();
goto _L2
_L31:
i += j1;
goto _L32
l += i1;
goto _L33
_L12:
Log.e("BTConnectionListener", " ConnectedThread--stopConnection already called, no need to set the state to failed. ");
return;
_L19:
if (flag && flag1) goto _L35; else goto _L34
_L17:
k3++;
goto _L36
j4++;
goto _L37
}
public void stopConnectedThread()
{
stop = true;
}
public void write(byte abyte0[])
{
if (abyte0 != null)
try
{
if (abyte0.length > 0 && mmOutStream != null)
{
mmOutStream.write(abyte0, 0, abyte0.length);
return;
}
}
catch (Exception exception)
{
exception.printStackTrace();
Log.e("BTConnectionListener", (new StringBuilder()).append("Exception during write: ").append(exception.toString()).toString());
return;
}
Log.e("BTConnectionListener", "Failed to Write buffer byte array data in mmOutStream due to error");
return;
}
public ConnectedThread(BluetoothDevice bluetoothdevice, BluetoothSocket bluetoothsocket)
{
this$0 = BTConnectionListener.this;
super();
mmSocket = null;
mmInStream = null;
mmOutStream = null;
stop = false;
Log.d("BTConnectionListener", "create ConnectedThread");
mmSocket = bluetoothsocket;
try
{
mmInStream = bluetoothsocket.getInputStream();
mmOutStream = bluetoothsocket.getOutputStream();
return;
}
catch (IOException ioexception)
{
ioexception.printStackTrace();
Log.e("BTConnectionListener", "ConnectedThread with IO Exception: e");
return;
}
catch (Exception exception)
{
exception.printStackTrace();
}
Log.e("BTConnectionListener", "Exception in ConnectedThread, temp sockets not created");
}
}
private class ResetConnectedThread extends Thread
{
private static final int RESET_DELAY = 10000;
private boolean continueFlagEnabled;
final BTConnectionListener this$0;
public void run()
{
super.run();
Log.d("BTConnectionListener", "ResetConnectedThread run() sleep for 10 seconds");
Log.d("BTConnectionListener", "[sleep] 10 seconds RESET_DELAY");
Thread.sleep(10000L);
Log.d("BTConnectionListener", (new StringBuilder()).append("Post 10 seonds delay continueFlagEnabled = ").append(continueFlagEnabled).toString());
if (!continueFlagEnabled && mConnectedThread != null)
synchronized (mConnectedThread)
{
Log.e("BTConnectionListener", "ResetConnectedThread stop the ConnectedThread");
Log.printUsageLog("BTConnectionListener", "Didn't receive Aloha Message: ResetConnectedThread stop the ConnectedThread");
mConnectedThread.stopConnectedThread();
mConnectedThread.cancel();
mConnectedThread = null;
}
_L2:
mResetConnectedThread = null;
return;
exception1;
connectedthread;
JVM INSTR monitorexit ;
try
{
throw exception1;
}
catch (Exception exception)
{
Log.e("BTConnectionListener", (new StringBuilder()).append("Exception in ResetConnectedThread: ").append(exception.toString()).toString());
}
if (true) goto _L2; else goto _L1
_L1:
}
public void setContinueFlagEnabled(boolean flag)
{
continueFlagEnabled = flag;
Log.d("BTConnectionListener", (new StringBuilder()).append("setContinueFlagEnabled called: ").append(flag).toString());
}
public ResetConnectedThread()
{
this$0 = BTConnectionListener.this;
super();
continueFlagEnabled = false;
Log.d("BTConnectionListener", "ResetConnectedThread Constructur");
start();
}
}
protected static final int BT_SPP_CONNECT_ATTEMPTS = 3;
private static final UUID CLIENT_EP_L_UUID = UUID.fromString("00000002-476D-42C4-BD11-9D377C45694C");
private static final UUID CLIENT_EP_R_UUID = UUID.fromString("00000003-476D-42C4-BD11-9D377C45694C");
private static final UUID CLIENT_WD_UUID = UUID.fromString("00000001-476D-42C4-BD11-9D377C45694C");
private static final UUID GENERIC_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final UUID SERVER_EP_L_UUID = UUID.fromString("00000002-476D-42C4-BD11-9D377C45694F");
private static final UUID SERVER_EP_R_UUID = UUID.fromString("00000003-476D-42C4-BD11-9D377C45694F");
private static final UUID SERVER_WD_UUID = UUID.fromString("00000001-476D-42C4-BD11-9D377C45694F");
private static final String TAG = "BTConnectionListener";
public static boolean isOPPSleepRequired = true;
private static boolean isTimerRequired = true;
private static Timer mTimer = null;
final int READ_DELAY = 15000;
protected int btConnectIteration;
private IConnectionManager connectionManager;
protected IEndPoint endPoint;
private boolean isStopListenerCalled;
private AcceptThread mAcceptThread;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private ResetConnectedThread mResetConnectedThread;
private volatile int mSPPState;
public BTConnectionListener(IEndPoint iendpoint, IConnectionManager iconnectionmanager)
{
isStopListenerCalled = false;
Log.i("BTConnectionListener", (new StringBuilder()).append("BTConnectionListener listener created = ").append(this).toString());
connectionManager = iconnectionmanager;
endPoint = iendpoint;
mSPPState = 0;
}
private void startTimer()
{
stopTimer();
if (mTimer == null)
{
mTimer = new Timer();
isTimerRequired = true;
Log.d("BTConnectionListener", "startTimer() called: Timer to scheduled for 15 seconds delay");
}
mTimer.schedule(new TimerTask() {
final BTConnectionListener this$0;
public void run()
{
if (BTConnectionListener.isTimerRequired)
{
stopTimer();
if (mConnectedThread != null)
{
synchronized (mConnectedThread)
{
Log.e("BTConnectionListener", "startTimer() run() called: mTimer to stop the ConnectedThread");
Log.printUsageLog("BTConnectionListener", "Didn't receive payload, mTimer to stop the ConnectedThread");
mConnectedThread.stopConnectedThread();
mConnectedThread.cancel();
mConnectedThread = null;
}
return;
}
}
break MISSING_BLOCK_LABEL_84;
exception;
connectedthread;
JVM INSTR monitorexit ;
throw exception;
}
{
this$0 = BTConnectionListener.this;
super();
}
}
, 15000L);
}
private void stopTimer()
{
isTimerRequired = false;
if (mTimer != null)
{
mTimer.cancel();
mTimer = null;
}
}
public void connect(String s)
{
Log.d("BTConnectionListener", (new StringBuilder()).append("connect() mSPPState = ").append(mSPPState).toString());
if (mSPPState != 3 && mSPPState != 2)
{
if (mConnectThread != null)
{
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null)
{
mConnectedThread.stopConnectedThread();
mConnectedThread.cancel();
mConnectedThread = null;
}
setState(2);
if (mAcceptThread != null)
{
mAcceptThread.stopAcceptThread();
mAcceptThread.cancel();
mAcceptThread = null;
}
mConnectThread = new ConnectThread(BluetoothAdapter.getDefaultAdapter().getRemoteDevice(s));
mConnectThread.start();
}
}
protected void connectionFailed()
{
Log.e("BTConnectionListener", "Connection Failed");
setState(4);
}
protected void connectionSuccess(BluetoothSocket bluetoothsocket, BluetoothDevice bluetoothdevice)
{
this;
JVM INSTR monitorenter ;
Log.d("BTConnectionListener", "connected");
if (mConnectThread != null)
{
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null)
{
mConnectedThread.stopConnectedThread();
mConnectedThread.cancel();
mConnectedThread = null;
}
setState(3);
if (mAcceptThread != null)
{
mAcceptThread.stopAcceptThread();
mAcceptThread.closeServerSocket();
mAcceptThread = null;
}
mConnectedThread = new ConnectedThread(bluetoothdevice, bluetoothsocket);
mConnectedThread.start();
this;
JVM INSTR monitorexit ;
return;
Exception exception;
exception;
throw exception;
}
public void disconnect()
{
if (mConnectedThread != null)
mConnectedThread.cancel();
}
public boolean isEPLeftDeviceAssociated(String s)
{
Log.i("BTConnectionListener", "isEPLeftDeviceAssociated");
if (ToqData.getInstance().getAssociatedDevicePrefs().contains("associated_ep_l_device_address") && !ToqData.getInstance().getAssociatedDevicePrefs().getString("associated_ep_l_device_address", "").equalsIgnoreCase(s))
{
Log.i("BTConnectionListener", "isDeviceAssociated EP Left false");
return false;
} else
{
Log.i("BTConnectionListener", "isDeviceAssociated EP Left true");
return true;
}
}
public boolean isEPRightDeviceAssociated(String s)
{
Log.i("BTConnectionListener", "isEPRightDeviceAssociated");
if (ToqData.getInstance().getAssociatedDevicePrefs().contains("associated_ep_r_device_address") && !ToqData.getInstance().getAssociatedDevicePrefs().getString("associated_ep_r_device_address", "").equalsIgnoreCase(s))
{
Log.i("BTConnectionListener", "isDeviceAssociated EP right false");
return false;
} else
{
Log.i("BTConnectionListener", "isDeviceAssociated EP right true");
return true;
}
}
public boolean isWDDeviceAssociated(String s)
{
Log.i("BTConnectionListener", "isWDDeviceAssociated");
if (ToqData.getInstance().getAssociatedDevicePrefs().contains("associated_wd_device_address") && !ToqData.getInstance().getAssociatedDevicePrefs().getString("associated_wd_device_address", "").equalsIgnoreCase(s))
{
Log.i("BTConnectionListener", "isDeviceAssociated WD false");
return false;
} else
{
Log.i("BTConnectionListener", "isDeviceAssociated WD true");
return true;
}
}
public void read(byte abyte0[])
{
connectionManager.receiveData(abyte0, endPoint);
}
protected void setState(int i)
{
this;
JVM INSTR monitorenter ;
Log.d("BTConnectionListener", (new StringBuilder()).append("setState(connlisten: ").append(this).append(", endpt: ").append(endPoint).append(", mSPPState: ").append(i).toString());
mSPPState = i;
if (endPoint == null) goto _L2; else goto _L1
_L1:
Log.printUsageLog("BTConnectionListener", (new StringBuilder()).append("setState() End Point Type = ").append(endPoint.getType()).append(" State = ").append(mSPPState).toString());
Log.d("BTConnectionListener", (new StringBuilder()).append("setState() End Point Type = ").append(endPoint.getType()).append(" State = ").append(mSPPState).toString());
connectionManager.connectionStateChange(endPoint, i);
if (endPoint.getType() != 0) goto _L4; else goto _L3
_L3:
if (mSPPState != 4 || !BluetoothAdapter.getDefaultAdapter().isEnabled()) goto _L6; else goto _L5
_L5:
if (btConnectIteration >= 3) goto _L8; else goto _L7
_L7:
Log.printUsageLog("BTConnectionListener", (new StringBuilder()).append("SPP retry interation: ").append(btConnectIteration).toString());
Log.e("BTConnectionListener", (new StringBuilder()).append("SPP retry interation: ").append(btConnectIteration).toString());
btConnectIteration = 1 + btConnectIteration;
Log.d("BTConnectionListener", "[sleep] 5 seconds");
wait(5000L);
if (!ToqData.getInstance().getAssociatedDevicePrefs().contains("associated_wd_device_address")) goto _L10; else goto _L9
_L9:
connect(endPoint.getAddress());
_L4:
this;
JVM INSTR monitorexit ;
return;
InterruptedException interruptedexception;
interruptedexception;
Log.e("BTConnectionListener", (new StringBuilder()).append("SPP retry interation: ").append(btConnectIteration).append(" interrupted!!!").toString());
goto _L4
Exception exception;
exception;
throw exception;
_L10:
Log.e("BTConnectionListener", "No associated WD details found to initiate a reconnect");
goto _L4
_L8:
if (ToqData.getInstance().getAssociatedDevicePrefs() == null || !ToqData.getInstance().getAssociatedDevicePrefs().contains("associated_wd_device_address")) goto _L4; else goto _L11
_L11:
Log.d("BTConnectionListener", "WD SPP server start");
startSPPServer();
goto _L4
_L12:
btConnectIteration = 0;
break; /* Loop/switch isn't completed */
_L2:
Log.e("BTConnectionListener", "endPoint is NULL in setState fuction");
break; /* Loop/switch isn't completed */
_L6:
if (i != 3 && i != 1) goto _L4; else goto _L12
}
public void setStopListenerCalled(boolean flag)
{
isStopListenerCalled = flag;
}
public void startSPPServer()
{
Log.d("BTConnectionListener", (new StringBuilder()).append("startSPPServer() mSPPState = ").append(mSPPState).append(" of device: ").append(com.qualcomm.toq.base.utils.Constants.EndPointEnum.values()[endPoint.getType()]).toString());
if (mSPPState == 4)
{
if (mConnectThread != null)
{
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null)
{
mConnectedThread.stopConnectedThread();
mConnectedThread.cancel();
mConnectedThread = null;
}
if (mAcceptThread != null)
{
mAcceptThread.stopAcceptThread();
mAcceptThread.cancel();
mAcceptThread = null;
}
setState(1);
mAcceptThread = new AcceptThread();
mAcceptThread.start();
}
}
public void stopConnectionListener()
{
Log.d("BTConnectionListener", "stopConnectionListener()");
if (mConnectThread != null)
mConnectThread.interrupt();
if (mConnectedThread != null)
mConnectedThread.interrupt();
if (mResetConnectedThread != null)
mResetConnectedThread.interrupt();
this;
JVM INSTR monitorenter ;
setState(0);
if (mConnectThread != null)
{
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null)
{
mConnectedThread.stopConnectedThread();
mConnectedThread.cancel();
mConnectedThread = null;
}
if (mAcceptThread != null)
{
mAcceptThread.stopAcceptThread();
mAcceptThread.cancel();
mAcceptThread = null;
}
this;
JVM INSTR monitorexit ;
return;
Exception exception;
exception;
this;
JVM INSTR monitorexit ;
throw exception;
}
public void write(byte abyte0[])
{
this;
JVM INSTR monitorenter ;
if (mSPPState == 3)
break MISSING_BLOCK_LABEL_13;
this;
JVM INSTR monitorexit ;
return;
ConnectedThread connectedthread = mConnectedThread;
this;
JVM INSTR monitorexit ;
if (connectedthread != null)
{
connectedthread.write(abyte0);
Log.d("BTConnectionListener", (new StringBuilder()).append("write of byte data done: size = ").append(abyte0.length).toString());
}
try
{
Thread.sleep(5L);
return;
}
catch (Exception exception1)
{
Log.e("BTConnectionListener", (new StringBuilder()).append("Exception occured during writing data ").append(exception1).toString());
}
return;
Exception exception;
exception;
this;
JVM INSTR monitorexit ;
throw exception;
}
public void writeFile(String s, String s1)
{
}
/*
static ResetConnectedThread access$1002(BTConnectionListener btconnectionlistener, ResetConnectedThread resetconnectedthread)
{
btconnectionlistener.mResetConnectedThread = resetconnectedthread;
return resetconnectedthread;
}
*/
/*
static ConnectThread access$802(BTConnectionListener btconnectionlistener, ConnectThread connectthread)
{
btconnectionlistener.mConnectThread = connectthread;
return connectthread;
}
*/
/*
static ConnectedThread access$902(BTConnectionListener btconnectionlistener, ConnectedThread connectedthread)
{
btconnectionlistener.mConnectedThread = connectedthread;
return connectedthread;
}
*/
}
| 45,379 | 0.567516 | 0.546212 | 1,199 | 36.855713 | 37.969372 | 289 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.724771 | false | false |
10
|
474500761ffc7c58d34a168e69d0ea96d8298442
| 21,010,980,018,073 |
eb7682c8b4e301b8ee92628b797c7a2bba0de979
|
/src/main/java/com/example/pro/sys/dao/SysFuncInfoDao.java
|
00de2a6a1f12ff6eba60ad8c0d8de6fd64382a09
|
[] |
no_license
|
l-bk/pro
|
https://github.com/l-bk/pro
|
aa986490b5311897e6e70251a9edcfe24f4dcc1a
|
df92b75813cdb7ee22397c5a3012816e5917e11f
|
refs/heads/master
| 2020-04-13T19:03:17.311000 | 2018-12-28T09:23:19 | 2018-12-28T09:23:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.pro.sys.dao;
import com.example.pro.sys.entity.SysFuncInfo;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
public interface SysFuncInfoDao {
public List<SysFuncInfo> getList();
}
|
UTF-8
|
Java
| 285 |
java
|
SysFuncInfoDao.java
|
Java
|
[] | null |
[] |
package com.example.pro.sys.dao;
import com.example.pro.sys.entity.SysFuncInfo;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
public interface SysFuncInfoDao {
public List<SysFuncInfo> getList();
}
| 285 | 0.8 | 0.8 | 12 | 22.75 | 19.170834 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
10
|
f0c1af6480294027974125c938c98a7986e22501
| 3,384,434,262,059 |
2b6af8c01b4a5be1b59c67e4e177714106c570eb
|
/Quiz/src/main/java/com/devoteam/dls/service/CacheService.java
|
e78c9660d87d11844cecce94651b909019d2fb1b
|
[] |
no_license
|
iamjoydevdas/Quiz-Sample
|
https://github.com/iamjoydevdas/Quiz-Sample
|
ef266488db2184dec625c4544ef467430b500580
|
7e8958c346bc59623b7d69a632b0231719069f0b
|
refs/heads/master
| 2020-03-26T04:12:29.010000 | 2018-10-12T15:13:25 | 2018-10-12T15:13:25 | 144,492,414 | 0 | 0 | null | false | 2018-10-12T15:13:26 | 2018-08-12T18:47:51 | 2018-10-11T21:28:15 | 2018-10-12T15:13:26 | 79,494 | 0 | 0 | 0 |
CSS
| false | null |
package com.devoteam.dls.service;
import java.util.List;
import com.devoteam.dls.dao.Receiver;
import com.devoteam.dls.dao.Sender;
import com.devoteam.dls.domain.OnlineQuizzers;
import com.devoteam.dls.domain.OnlineStatus;
import com.devoteam.dls.domain.Quizzer;
public interface CacheService {
void setQuizzer(OnlineQuizzers quizzer);
List<OnlineQuizzers> getQuizzers();
void removeQuizzer();
void removeQuizzer(String userId);
void setPushCache(Sender sender, Receiver receiver);
Sender getPushCache(String receiverId);
void updateOnlineStatus(String userId, OnlineStatus status);
}
|
UTF-8
|
Java
| 595 |
java
|
CacheService.java
|
Java
|
[] | null |
[] |
package com.devoteam.dls.service;
import java.util.List;
import com.devoteam.dls.dao.Receiver;
import com.devoteam.dls.dao.Sender;
import com.devoteam.dls.domain.OnlineQuizzers;
import com.devoteam.dls.domain.OnlineStatus;
import com.devoteam.dls.domain.Quizzer;
public interface CacheService {
void setQuizzer(OnlineQuizzers quizzer);
List<OnlineQuizzers> getQuizzers();
void removeQuizzer();
void removeQuizzer(String userId);
void setPushCache(Sender sender, Receiver receiver);
Sender getPushCache(String receiverId);
void updateOnlineStatus(String userId, OnlineStatus status);
}
| 595 | 0.813445 | 0.813445 | 19 | 30.31579 | 17.853357 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.210526 | false | false |
7
|
b1e8f6aa59ded11df9e90ec15d7b7bbdb869d477
| 15,530,601,774,069 |
ae1ace5b6c38594105cfb2ba53b2a012cddc2ebf
|
/src/prover/Prover.java
|
b7f6f83639202d2090f1b5c98c168fe686a2076e
|
[] |
no_license
|
JorgeFerreira93/TP-VF
|
https://github.com/JorgeFerreira93/TP-VF
|
2e34ebd0c148b0338c2dea09dc019027fda7c1ce
|
b5698780afdf1b5f7632b6637c014bfd6992b504
|
refs/heads/master
| 2020-04-16T01:52:04.337000 | 2016-09-12T12:13:31 | 2016-09-12T12:13:31 | 60,902,190 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package prover;
import com.microsoft.z3.*;
import operator.*;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Classe que dado um conjunto de condições retorna o seu resultado.
*
* @author jorge
*/
public class Prover {
private ArrayList<Exp> condicoes;
public Prover(ArrayList<Exp> condicoes){
this.condicoes = condicoes;
}
/**
* Método que retorna o conjunto de resultados da prova de cada condição de verificação
*
* @return Conjunto de resultados.
* */
public ArrayList<Result> parse(){
HashMap<String, String> cfg = new HashMap<String, String>();
cfg.put("model", "true");
cfg.put("proof", "true");
Context ctx = new Context(cfg);
ArrayList<Result> results = new ArrayList<>();
for(Exp e : this.condicoes){
BoolExpr b = (BoolExpr) resExp(e, ctx);
Solver solver = ctx.mkSolver();
solver.add(ctx.mkNot(b));
Status q = solver.check();
switch (q){
case SATISFIABLE:
results.add(new Result(q, e, b, solver.getModel().toString()));
break;
case UNSATISFIABLE:
results.add(new Result(q, e, b, solver.getProof().toString()));
break;
}
}
return results;
}
/**
* Método que constrói uma expressão Z3 para ser validada
*
* @param ctx Contexto
* @param e Condição de verificação
* @return Expressão a ser verificada.
* */
private Expr resExp(Exp e, Context ctx){
Operador expressao = (Operador) e;
Expr left = null;
Expr right = null;
if(expressao.getLeft() != null){
if(expressao.getLeft() instanceof Int){
left = ctx.mkNumeral(((Int) expressao.getLeft()).getN(), ctx.getIntSort());
}
else if(expressao.getLeft() instanceof Id){
left = ctx.mkIntConst(((Id) expressao.getLeft()).getName());
}
else{
left = resExp(expressao.getLeft(), ctx);
}
}
if(expressao.getRight() instanceof Int){
right = ctx.mkNumeral(((Int) expressao.getRight()).getN(), ctx.getIntSort());
}
else if(expressao.getRight() instanceof Id){
right = ctx.mkIntConst(((Id) expressao.getRight()).getName());
}
else{
right = resExp(expressao.getRight(), ctx);
}
Expr b = null;
switch (expressao.getOp()){
case "+":
b = ctx.mkAdd((ArithExpr) left, (ArithExpr) right);
return b;
case "-":
b = ctx.mkSub((ArithExpr) left, (ArithExpr) right);
return b;
case "*":
b = ctx.mkMul((ArithExpr) left, (ArithExpr) right);
return b;
case "/":
b = ctx.mkDiv((ArithExpr) left, (ArithExpr) right);
return b;
case ">":
b = ctx.mkGt((ArithExpr) left, (ArithExpr) right);
return b;
case ">=":
b = ctx.mkGe((ArithExpr) left, (ArithExpr) right);
return b;
case "<":
b = ctx.mkLt((ArithExpr) left, (ArithExpr) right);
return b;
case "<=":
b = ctx.mkLe((ArithExpr) left, (ArithExpr) right);
return b;
case "&&":
b = ctx.mkAnd((BoolExpr) left, (BoolExpr) right);
return b;
case "||":
b = ctx.mkOr((BoolExpr) left, (BoolExpr) right);
return b;
case "=>":
b = ctx.mkImplies((BoolExpr) left, (BoolExpr) right);
return b;
case "!":
b = ctx.mkNot((BoolExpr) right);
return b;
case "==":
b = ctx.mkEq(left, right);
return b;
case "<=>":
b = ctx.mkEq((BoolExpr) left, (BoolExpr) right);
return b;
}
return null;
}
}
|
UTF-8
|
Java
| 4,243 |
java
|
Prover.java
|
Java
|
[
{
"context": "e condições retorna o seu resultado.\n *\n * @author jorge\n */\npublic class Prover {\n\n private ArrayList<",
"end": 211,
"score": 0.9076505899429321,
"start": 206,
"tag": "USERNAME",
"value": "jorge"
}
] | null |
[] |
package prover;
import com.microsoft.z3.*;
import operator.*;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Classe que dado um conjunto de condições retorna o seu resultado.
*
* @author jorge
*/
public class Prover {
private ArrayList<Exp> condicoes;
public Prover(ArrayList<Exp> condicoes){
this.condicoes = condicoes;
}
/**
* Método que retorna o conjunto de resultados da prova de cada condição de verificação
*
* @return Conjunto de resultados.
* */
public ArrayList<Result> parse(){
HashMap<String, String> cfg = new HashMap<String, String>();
cfg.put("model", "true");
cfg.put("proof", "true");
Context ctx = new Context(cfg);
ArrayList<Result> results = new ArrayList<>();
for(Exp e : this.condicoes){
BoolExpr b = (BoolExpr) resExp(e, ctx);
Solver solver = ctx.mkSolver();
solver.add(ctx.mkNot(b));
Status q = solver.check();
switch (q){
case SATISFIABLE:
results.add(new Result(q, e, b, solver.getModel().toString()));
break;
case UNSATISFIABLE:
results.add(new Result(q, e, b, solver.getProof().toString()));
break;
}
}
return results;
}
/**
* Método que constrói uma expressão Z3 para ser validada
*
* @param ctx Contexto
* @param e Condição de verificação
* @return Expressão a ser verificada.
* */
private Expr resExp(Exp e, Context ctx){
Operador expressao = (Operador) e;
Expr left = null;
Expr right = null;
if(expressao.getLeft() != null){
if(expressao.getLeft() instanceof Int){
left = ctx.mkNumeral(((Int) expressao.getLeft()).getN(), ctx.getIntSort());
}
else if(expressao.getLeft() instanceof Id){
left = ctx.mkIntConst(((Id) expressao.getLeft()).getName());
}
else{
left = resExp(expressao.getLeft(), ctx);
}
}
if(expressao.getRight() instanceof Int){
right = ctx.mkNumeral(((Int) expressao.getRight()).getN(), ctx.getIntSort());
}
else if(expressao.getRight() instanceof Id){
right = ctx.mkIntConst(((Id) expressao.getRight()).getName());
}
else{
right = resExp(expressao.getRight(), ctx);
}
Expr b = null;
switch (expressao.getOp()){
case "+":
b = ctx.mkAdd((ArithExpr) left, (ArithExpr) right);
return b;
case "-":
b = ctx.mkSub((ArithExpr) left, (ArithExpr) right);
return b;
case "*":
b = ctx.mkMul((ArithExpr) left, (ArithExpr) right);
return b;
case "/":
b = ctx.mkDiv((ArithExpr) left, (ArithExpr) right);
return b;
case ">":
b = ctx.mkGt((ArithExpr) left, (ArithExpr) right);
return b;
case ">=":
b = ctx.mkGe((ArithExpr) left, (ArithExpr) right);
return b;
case "<":
b = ctx.mkLt((ArithExpr) left, (ArithExpr) right);
return b;
case "<=":
b = ctx.mkLe((ArithExpr) left, (ArithExpr) right);
return b;
case "&&":
b = ctx.mkAnd((BoolExpr) left, (BoolExpr) right);
return b;
case "||":
b = ctx.mkOr((BoolExpr) left, (BoolExpr) right);
return b;
case "=>":
b = ctx.mkImplies((BoolExpr) left, (BoolExpr) right);
return b;
case "!":
b = ctx.mkNot((BoolExpr) right);
return b;
case "==":
b = ctx.mkEq(left, right);
return b;
case "<=>":
b = ctx.mkEq((BoolExpr) left, (BoolExpr) right);
return b;
}
return null;
}
}
| 4,243 | 0.481079 | 0.480605 | 158 | 25.759493 | 24.059639 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.575949 | false | false |
7
|
d598dd3d17bfb2d10d31539c24e5278fae9ca57a
| 979,252,580,520 |
f99c3a5c7034480fc5525ebeee314afb4a0d8e52
|
/src/main/java/com/netcracker/crm/datagenerator/impl/HistorySetter.java
|
0e016784cb48507a0177591851a764cc3383fd97
|
[] |
no_license
|
ncProjectRoot/nc-crm
|
https://github.com/ncProjectRoot/nc-crm
|
1ce2283b4948527169053ca3e13f8913f5ecdd15
|
ba76e9147c2a7aaefb89d4186cea783449bdd7ca
|
refs/heads/master
| 2021-01-19T16:26:07.157000 | 2017-05-31T11:56:34 | 2017-05-31T11:56:34 | 88,263,363 | 0 | 5 | null | false | 2017-05-29T21:46:19 | 2017-04-14T11:48:29 | 2017-04-24T14:45:41 | 2017-05-29T21:46:19 | 1,390 | 0 | 3 | 1 |
Java
| null | null |
package com.netcracker.crm.datagenerator.impl;
import com.netcracker.crm.dao.HistoryDao;
import com.netcracker.crm.datagenerator.AbstractSetter;
import com.netcracker.crm.domain.model.*;
import com.netcracker.crm.domain.real.RealHistory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
/**
* Created by Pasha on 16.05.2017.
*/
@Service
public class HistorySetter extends AbstractSetter<History> {
private List<Order> orders;
private List<Complaint> complaints;
private List<Product> products;
private final HistoryDao historyDao;
@Autowired
public HistorySetter(HistoryDao historyDao) {
this.historyDao = historyDao;
}
@Override
public List<History> generate(int numbers) {
generateOrderHistory();
generateComplaintsHistory();
generateProductHistory();
return null;
}
@Override
public History generateObject() {
return new RealHistory();
}
private void generateOrderHistory() {
for (Order order : orders) {
orderCycle(order);
}
}
private void generateComplaintsHistory() {
for (Complaint complaint : complaints) {
complaintCycle(complaint);
}
}
private void generateProductHistory() {
for (Product product : products) {
productCycle(product);
}
}
private void orderCycle(Order order) {
int days = LocalDateTime.now().getDayOfYear() - order.getDate().getDayOfYear();
LocalDateTime buffer = order.getDate();
for (int i = 0; i < 3; i++) {
OrderStatus orderStatus = OrderStatus.values()[i];
History history = generateObject();
history.setOrder(order);
history.setNewStatus(orderStatus);
setOrderDescHistory(history);
history.setDateChangeStatus(buffer);
historyDao.create(history);
if (order.getStatus() == orderStatus) {
break;
}
days = getRand(days);
buffer = LocalDateTime.now().minusDays(days);
}
if (order.getStatus() == OrderStatus.PAUSED || order.getStatus() == OrderStatus.DISABLED) {
endCycle(order, days, buffer);
} else if (order.getStatus() == OrderStatus.ACTIVE && Math.random() > 0.7) {
endActiveAllCycle(order, days);
} else if (order.getStatus() == OrderStatus.REQUEST_TO_RESUME) {
endRequestPauseCycle(order, buffer);
days = getRand(days);
endPauseCycle(order, LocalDateTime.now().minusDays(days));
days = getRand(days);
endResumeCycle(order, LocalDateTime.now().minusDays(days));
} else if (order.getStatus() == OrderStatus.REQUEST_TO_PAUSE) {
endRequestPauseCycle(order, buffer);
} else if (order.getStatus() == OrderStatus.REQUEST_TO_DISABLE) {
endRequestDisableCycle(order, buffer);
}
}
private void endActiveAllCycle(Order order, int days) {
days = getRand(days);
endRequestPauseCycle(order, LocalDateTime.now().minusDays(days));
days = getRand(days);
endPauseCycle(order, LocalDateTime.now().minusDays(days));
days = getRand(days);
endResumeCycle(order, LocalDateTime.now().minusDays(days));
days = getRand(days);
endActivateCycle(order, LocalDateTime.now().minusDays(days));
}
private void endResumeCycle(Order order, LocalDateTime buffer) {
History history = generateObject();
history.setOrder(order);
history.setNewStatus(OrderStatus.REQUEST_TO_RESUME);
setOrderDescHistory(history);
history.setDateChangeStatus(buffer);
historyDao.create(history);
}
private void endActivateCycle(Order order, LocalDateTime buffer) {
History history = generateObject();
history.setOrder(order);
history.setNewStatus(OrderStatus.ACTIVE);
setOrderDescHistory(history, OrderStatus.REQUEST_TO_RESUME);
history.setDateChangeStatus(buffer);
historyDao.create(history);
}
private void endPauseCycle(Order order, LocalDateTime buffer) {
History history = generateObject();
history.setOrder(order);
history.setNewStatus(OrderStatus.PAUSED);
setOrderDescHistory(history);
history.setDateChangeStatus(buffer);
historyDao.create(history);
}
private void endRequestPauseCycle(Order order, LocalDateTime buffer) {
History history = generateObject();
history.setOrder(order);
history.setNewStatus(OrderStatus.REQUEST_TO_PAUSE);
setOrderDescHistory(history);
history.setDateChangeStatus(buffer);
historyDao.create(history);
}
private void endRequestDisableCycle(Order order, LocalDateTime buffer) {
History history = generateObject();
history.setOrder(order);
history.setNewStatus(OrderStatus.REQUEST_TO_DISABLE);
setOrderDescHistory(history);
history.setDateChangeStatus(buffer);
historyDao.create(history);
}
private void endCycle(Order order, int days, LocalDateTime buffer) {
History history = generateObject();
history.setOrder(order);
setEndCycleStatus(order, history);
setOrderDescHistory(history);
history.setDateChangeStatus(buffer);
historyDao.create(history);
days = getRand(days);
buffer = LocalDateTime.now().minusDays(days);
history = generateObject();
history.setOrder(order);
history.setNewStatus(order.getStatus());
setOrderDescHistory(history);
history.setDateChangeStatus(buffer);
historyDao.create(history);
}
private void setEndCycleStatus(Order order, History history) {
if (order.getStatus() == OrderStatus.PAUSED) {
history.setNewStatus(OrderStatus.REQUEST_TO_PAUSE);
} else if (order.getStatus() == OrderStatus.DISABLED) {
history.setNewStatus(OrderStatus.REQUEST_TO_DISABLE);
}
}
private void complaintCycle(Complaint complaint) {
int days = LocalDateTime.now().getDayOfYear() - complaint.getDate().getDayOfYear();
LocalDateTime buffer = complaint.getDate();
for (ComplaintStatus complaintStatus : ComplaintStatus.values()) {
History history = generateObject();
history.setComplaint(complaint);
history.setNewStatus(complaintStatus);
setComplaintDescHistory(history);
history.setDateChangeStatus(buffer);
historyDao.create(history);
if (complaint.getStatus() == complaintStatus) {
break;
}
days = getRand(days);
buffer = LocalDateTime.now().minusDays(days);
}
}
private void productCycle(Product product) {
int days = getRand(365);
LocalDateTime buffer = LocalDateTime.now().minusDays(days);
for (ProductStatus productStatus : ProductStatus.values()) {
History history = generateObject();
history.setProduct(product);
history.setNewStatus(productStatus);
setProductDescHistory(history);
history.setDateChangeStatus(buffer);
historyDao.create(history);
if (product.getStatus() == productStatus) {
break;
}
days = getRand(days);
buffer = LocalDateTime.now().minusDays(days);
}
}
private int getRand(int index) {
if (index <= 0) {
return 0;
}
while (true) {
int rand = random.nextInt(index);
if (rand >= 0) {
return rand;
}
}
}
public void setOrders(List<Order> orders) {
this.orders = orders;
}
public void setComplaints(List<Complaint> complaints) {
this.complaints = complaints;
}
public void setProducts(List<Product> products) {
this.products = products;
}
private void setOrderDescHistory(History history) {
setOrderDescHistory(history, null);
}
private void setOrderDescHistory(History history, OrderStatus oldStatus) {
switch ((OrderStatus) history.getNewStatus()) {
case NEW:
history.setDescChangeStatus(getNewDesc());
break;
case PROCESSING:
history.setDescChangeStatus(getProcessingDesc(history.getOrder().getCsr().getId()));
break;
case ACTIVE:
if (oldStatus != null && oldStatus == OrderStatus.REQUEST_TO_RESUME) {
history.setDescChangeStatus(getResumeDesc(history.getOrder().getCsr().getId()));
} else {
history.setDescChangeStatus(getActivateDesc(history.getOrder().getCsr().getId()));
}
break;
case REQUEST_TO_PAUSE:
history.setDescChangeStatus(getRequestPauseDesc());
break;
case REQUEST_TO_RESUME:
history.setDescChangeStatus(getRequestResumeDesc());
break;
case REQUEST_TO_DISABLE:
history.setDescChangeStatus(getRequestDisableDesc());
break;
case PAUSED:
history.setDescChangeStatus(getPausedDesc(history.getOrder().getCsr().getId()));
break;
case DISABLED:
history.setDescChangeStatus(getDisabledDesc(history.getOrder().getCsr().getId()));
break;
}
}
private void setComplaintDescHistory(History history) {
switch ((ComplaintStatus) history.getNewStatus()) {
case OPEN:
history.setDescChangeStatus(getComplOpenDesc());
break;
case SOLVING:
history.setDescChangeStatus(getComplSolvingDesc());
break;
case CLOSED:
history.setDescChangeStatus(getComplClosedDesc());
break;
}
}
private void setProductDescHistory(History history) {
switch ((ProductStatus) history.getNewStatus()) {
case PLANNED:
history.setDescChangeStatus(getProductPlanedDesc());
break;
case ACTUAL:
history.setDescChangeStatus(getProductActualDesc());
break;
case OUTDATED:
history.setDescChangeStatus(getProductOutdatedDesc());
break;
}
}
private String getProductPlanedDesc(){
return "Product is successful create";
}
private String getProductActualDesc(){
return "Product is successful move in actual status";
}
private String getProductOutdatedDesc(){
return "Product already not actual after then product be outdated";
}
private String getComplOpenDesc() {
return "Complaint is successful open";
}
private String getComplSolvingDesc() {
return "Complaint have solving condition";
}
private String getComplClosedDesc() {
return "Complaint is successful solved and closed";
}
private String getNewDesc() {
return "Order successful create";
}
private String getProcessingDesc(Long csrId) {
return "Csr with id : " + csrId + " is successful accepted this order";
}
private String getActivateDesc(Long csrId) {
return "Csr with id : " + csrId + " after successfully done work for connect service, csr activated this order";
}
private String getRequestPauseDesc() {
return "Request to pause is successful send";
}
private String getRequestResumeDesc() {
return "Request to resume is successful send";
}
private String getRequestDisableDesc() {
return "Request to pause is successful send";
}
private String getPausedDesc(Long csrId) {
return "Csr with id : " + csrId + " is successful paused this order";
}
private String getResumeDesc(Long csrId) {
return "Csr with id : " + csrId + " is successful resume this order";
}
private String getDisabledDesc(Long csrId) {
return "Csr with id : " + csrId + " is successful disabled this order";
}
}
|
UTF-8
|
Java
| 12,511 |
java
|
HistorySetter.java
|
Java
|
[
{
"context": "ateTime;\nimport java.util.List;\n\n/**\n * Created by Pasha on 16.05.2017.\n */\n@Service\npublic class HistoryS",
"end": 429,
"score": 0.9969298243522644,
"start": 424,
"tag": "NAME",
"value": "Pasha"
}
] | null |
[] |
package com.netcracker.crm.datagenerator.impl;
import com.netcracker.crm.dao.HistoryDao;
import com.netcracker.crm.datagenerator.AbstractSetter;
import com.netcracker.crm.domain.model.*;
import com.netcracker.crm.domain.real.RealHistory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
/**
* Created by Pasha on 16.05.2017.
*/
@Service
public class HistorySetter extends AbstractSetter<History> {
private List<Order> orders;
private List<Complaint> complaints;
private List<Product> products;
private final HistoryDao historyDao;
@Autowired
public HistorySetter(HistoryDao historyDao) {
this.historyDao = historyDao;
}
@Override
public List<History> generate(int numbers) {
generateOrderHistory();
generateComplaintsHistory();
generateProductHistory();
return null;
}
@Override
public History generateObject() {
return new RealHistory();
}
private void generateOrderHistory() {
for (Order order : orders) {
orderCycle(order);
}
}
private void generateComplaintsHistory() {
for (Complaint complaint : complaints) {
complaintCycle(complaint);
}
}
private void generateProductHistory() {
for (Product product : products) {
productCycle(product);
}
}
private void orderCycle(Order order) {
int days = LocalDateTime.now().getDayOfYear() - order.getDate().getDayOfYear();
LocalDateTime buffer = order.getDate();
for (int i = 0; i < 3; i++) {
OrderStatus orderStatus = OrderStatus.values()[i];
History history = generateObject();
history.setOrder(order);
history.setNewStatus(orderStatus);
setOrderDescHistory(history);
history.setDateChangeStatus(buffer);
historyDao.create(history);
if (order.getStatus() == orderStatus) {
break;
}
days = getRand(days);
buffer = LocalDateTime.now().minusDays(days);
}
if (order.getStatus() == OrderStatus.PAUSED || order.getStatus() == OrderStatus.DISABLED) {
endCycle(order, days, buffer);
} else if (order.getStatus() == OrderStatus.ACTIVE && Math.random() > 0.7) {
endActiveAllCycle(order, days);
} else if (order.getStatus() == OrderStatus.REQUEST_TO_RESUME) {
endRequestPauseCycle(order, buffer);
days = getRand(days);
endPauseCycle(order, LocalDateTime.now().minusDays(days));
days = getRand(days);
endResumeCycle(order, LocalDateTime.now().minusDays(days));
} else if (order.getStatus() == OrderStatus.REQUEST_TO_PAUSE) {
endRequestPauseCycle(order, buffer);
} else if (order.getStatus() == OrderStatus.REQUEST_TO_DISABLE) {
endRequestDisableCycle(order, buffer);
}
}
private void endActiveAllCycle(Order order, int days) {
days = getRand(days);
endRequestPauseCycle(order, LocalDateTime.now().minusDays(days));
days = getRand(days);
endPauseCycle(order, LocalDateTime.now().minusDays(days));
days = getRand(days);
endResumeCycle(order, LocalDateTime.now().minusDays(days));
days = getRand(days);
endActivateCycle(order, LocalDateTime.now().minusDays(days));
}
private void endResumeCycle(Order order, LocalDateTime buffer) {
History history = generateObject();
history.setOrder(order);
history.setNewStatus(OrderStatus.REQUEST_TO_RESUME);
setOrderDescHistory(history);
history.setDateChangeStatus(buffer);
historyDao.create(history);
}
private void endActivateCycle(Order order, LocalDateTime buffer) {
History history = generateObject();
history.setOrder(order);
history.setNewStatus(OrderStatus.ACTIVE);
setOrderDescHistory(history, OrderStatus.REQUEST_TO_RESUME);
history.setDateChangeStatus(buffer);
historyDao.create(history);
}
private void endPauseCycle(Order order, LocalDateTime buffer) {
History history = generateObject();
history.setOrder(order);
history.setNewStatus(OrderStatus.PAUSED);
setOrderDescHistory(history);
history.setDateChangeStatus(buffer);
historyDao.create(history);
}
private void endRequestPauseCycle(Order order, LocalDateTime buffer) {
History history = generateObject();
history.setOrder(order);
history.setNewStatus(OrderStatus.REQUEST_TO_PAUSE);
setOrderDescHistory(history);
history.setDateChangeStatus(buffer);
historyDao.create(history);
}
private void endRequestDisableCycle(Order order, LocalDateTime buffer) {
History history = generateObject();
history.setOrder(order);
history.setNewStatus(OrderStatus.REQUEST_TO_DISABLE);
setOrderDescHistory(history);
history.setDateChangeStatus(buffer);
historyDao.create(history);
}
private void endCycle(Order order, int days, LocalDateTime buffer) {
History history = generateObject();
history.setOrder(order);
setEndCycleStatus(order, history);
setOrderDescHistory(history);
history.setDateChangeStatus(buffer);
historyDao.create(history);
days = getRand(days);
buffer = LocalDateTime.now().minusDays(days);
history = generateObject();
history.setOrder(order);
history.setNewStatus(order.getStatus());
setOrderDescHistory(history);
history.setDateChangeStatus(buffer);
historyDao.create(history);
}
private void setEndCycleStatus(Order order, History history) {
if (order.getStatus() == OrderStatus.PAUSED) {
history.setNewStatus(OrderStatus.REQUEST_TO_PAUSE);
} else if (order.getStatus() == OrderStatus.DISABLED) {
history.setNewStatus(OrderStatus.REQUEST_TO_DISABLE);
}
}
private void complaintCycle(Complaint complaint) {
int days = LocalDateTime.now().getDayOfYear() - complaint.getDate().getDayOfYear();
LocalDateTime buffer = complaint.getDate();
for (ComplaintStatus complaintStatus : ComplaintStatus.values()) {
History history = generateObject();
history.setComplaint(complaint);
history.setNewStatus(complaintStatus);
setComplaintDescHistory(history);
history.setDateChangeStatus(buffer);
historyDao.create(history);
if (complaint.getStatus() == complaintStatus) {
break;
}
days = getRand(days);
buffer = LocalDateTime.now().minusDays(days);
}
}
private void productCycle(Product product) {
int days = getRand(365);
LocalDateTime buffer = LocalDateTime.now().minusDays(days);
for (ProductStatus productStatus : ProductStatus.values()) {
History history = generateObject();
history.setProduct(product);
history.setNewStatus(productStatus);
setProductDescHistory(history);
history.setDateChangeStatus(buffer);
historyDao.create(history);
if (product.getStatus() == productStatus) {
break;
}
days = getRand(days);
buffer = LocalDateTime.now().minusDays(days);
}
}
private int getRand(int index) {
if (index <= 0) {
return 0;
}
while (true) {
int rand = random.nextInt(index);
if (rand >= 0) {
return rand;
}
}
}
public void setOrders(List<Order> orders) {
this.orders = orders;
}
public void setComplaints(List<Complaint> complaints) {
this.complaints = complaints;
}
public void setProducts(List<Product> products) {
this.products = products;
}
private void setOrderDescHistory(History history) {
setOrderDescHistory(history, null);
}
private void setOrderDescHistory(History history, OrderStatus oldStatus) {
switch ((OrderStatus) history.getNewStatus()) {
case NEW:
history.setDescChangeStatus(getNewDesc());
break;
case PROCESSING:
history.setDescChangeStatus(getProcessingDesc(history.getOrder().getCsr().getId()));
break;
case ACTIVE:
if (oldStatus != null && oldStatus == OrderStatus.REQUEST_TO_RESUME) {
history.setDescChangeStatus(getResumeDesc(history.getOrder().getCsr().getId()));
} else {
history.setDescChangeStatus(getActivateDesc(history.getOrder().getCsr().getId()));
}
break;
case REQUEST_TO_PAUSE:
history.setDescChangeStatus(getRequestPauseDesc());
break;
case REQUEST_TO_RESUME:
history.setDescChangeStatus(getRequestResumeDesc());
break;
case REQUEST_TO_DISABLE:
history.setDescChangeStatus(getRequestDisableDesc());
break;
case PAUSED:
history.setDescChangeStatus(getPausedDesc(history.getOrder().getCsr().getId()));
break;
case DISABLED:
history.setDescChangeStatus(getDisabledDesc(history.getOrder().getCsr().getId()));
break;
}
}
private void setComplaintDescHistory(History history) {
switch ((ComplaintStatus) history.getNewStatus()) {
case OPEN:
history.setDescChangeStatus(getComplOpenDesc());
break;
case SOLVING:
history.setDescChangeStatus(getComplSolvingDesc());
break;
case CLOSED:
history.setDescChangeStatus(getComplClosedDesc());
break;
}
}
private void setProductDescHistory(History history) {
switch ((ProductStatus) history.getNewStatus()) {
case PLANNED:
history.setDescChangeStatus(getProductPlanedDesc());
break;
case ACTUAL:
history.setDescChangeStatus(getProductActualDesc());
break;
case OUTDATED:
history.setDescChangeStatus(getProductOutdatedDesc());
break;
}
}
private String getProductPlanedDesc(){
return "Product is successful create";
}
private String getProductActualDesc(){
return "Product is successful move in actual status";
}
private String getProductOutdatedDesc(){
return "Product already not actual after then product be outdated";
}
private String getComplOpenDesc() {
return "Complaint is successful open";
}
private String getComplSolvingDesc() {
return "Complaint have solving condition";
}
private String getComplClosedDesc() {
return "Complaint is successful solved and closed";
}
private String getNewDesc() {
return "Order successful create";
}
private String getProcessingDesc(Long csrId) {
return "Csr with id : " + csrId + " is successful accepted this order";
}
private String getActivateDesc(Long csrId) {
return "Csr with id : " + csrId + " after successfully done work for connect service, csr activated this order";
}
private String getRequestPauseDesc() {
return "Request to pause is successful send";
}
private String getRequestResumeDesc() {
return "Request to resume is successful send";
}
private String getRequestDisableDesc() {
return "Request to pause is successful send";
}
private String getPausedDesc(Long csrId) {
return "Csr with id : " + csrId + " is successful paused this order";
}
private String getResumeDesc(Long csrId) {
return "Csr with id : " + csrId + " is successful resume this order";
}
private String getDisabledDesc(Long csrId) {
return "Csr with id : " + csrId + " is successful disabled this order";
}
}
| 12,511 | 0.619215 | 0.617776 | 363 | 33.465565 | 25.181015 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.550964 | false | false |
7
|
61c0ef0aa60a8f26d40e4d214355b3d0019698c5
| 24,627,342,510,160 |
3aba32972405be7ea7c99f1a3c54220b53f12ee9
|
/jk_service/src/main/java/top.greathead.jk.service/impl/ExportServiceImpl.java
|
28ac0046c8b893b36ac942f62329f0d9bfa83e6d
|
[] |
no_license
|
YiYi666/jk_parent
|
https://github.com/YiYi666/jk_parent
|
04130904556bf481f91f4e0a34bc9045f3ed5ae5
|
a3d5140128cb772064812e235e1b7b9f9da756ce
|
refs/heads/master
| 2021-09-04T00:44:34.402000 | 2018-01-12T09:37:10 | 2018-01-12T09:37:10 | 114,776,137 | 1 | 0 | null | false | 2018-01-12T09:37:11 | 2017-12-19T14:40:48 | 2017-12-19T14:53:08 | 2018-01-12T09:37:11 | 2,182 | 0 | 0 | 0 |
Java
| false | null |
package top.greathead.jk.service.impl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.greathead.jk.dao.BaseDao;
import top.greathead.jk.entity.*;
import top.greathead.jk.service.ExportService;
import top.greathead.jk.utils.Pagination;
import top.greathead.jk.utils.SysConstant;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Set;
@Service
@Transactional
public class ExportServiceImpl implements ExportService {
@Autowired
private BaseDao<Export,String> exportDao;
@Autowired
private BaseDao<Contract,String> contractDao;
@Autowired
private BaseDao<ExportProduct,String> exportProductDao;
@Override
@Transactional(readOnly = true)
public Pagination findByPage(Pagination page) {
return exportDao.pageByHql("from Export order by inputDate desc" ,page.getPageNo(),page.getPageSize());
}
@Override
@Transactional(readOnly = true)
public List<Export> findAll() {
return exportDao.getListByHQL("from Export");
}
@Override
public void insert(Export model) {
String ids = model.getId();
String[] contractIds = ids.split(", ");
model.setId(null);
Long state = 0L;
model.setState(state);
model.setInputDate(new Date());
model.setCreateTime(new Date());
model.setContractIds(ids);
User user = (User) ServletActionContext.getRequest().getSession().getAttribute(SysConstant.C_USER);
model.setCreateBy(user.getId());
model.setCreateDept(user.getDept().getId());
String customerContract="";
for(String contractId:contractIds){
Contract contract = contractDao.get(Contract.class, contractId);
contract.setState(2L);
Set<ContractProduct> contractProducts = contract.getContractProducts();
// Set<ExportProduct> exportProducts = model.getExportProducts();
customerContract = customerContract +" " + contract.getContractNo();
for(ContractProduct contractProduct:contractProducts){
try {
ExportProduct exportProduct = new ExportProduct();
BeanUtils.copyProperties(exportProduct,contractProduct);
exportProduct.setId(null);
model.getExportProducts().add(exportProduct);
Set<ExtCproduct> extCproducts = contractProduct.getExtCproducts();
//Set<ExtEproduct> extEproducts = exportProduct.getExtEproducts();
for(ExtCproduct extCproduct:extCproducts){
try {
ExtEproduct extEproduct = new ExtEproduct();
BeanUtils.copyProperties(extEproduct,extCproduct);
extEproduct.setId(null);
exportProduct.getExtEproducts().add(extEproduct);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
contractDao.update(contract);
}
}
model.setCustomerContract(customerContract);
exportDao.save(model);
}
/* @Override
public void update(Export model, String[] mr_id, String[] mr_changed, String[] mr_orderNo,
String[] mr_cnumber, String[] mr_grossWeight, String[] mr_netWeight, String[] mr_sizeLength,
String[] mr_sizeWidth, String[] mr_sizeHeight, String[] mr_exPrice, String[] mr_tax) {
for(int i=0; i<mr_changed.length; i++){
if(!mr_changed[i].isEmpty()){
ExportProduct exportProduct = exportProductDao.get(ExportProduct.class, mr_id[i]);
exportProduct.setCnumber(toLong(mr_cnumber[i]));
exportProduct.setGrossWeight(toLong(mr_grossWeight[i]));
exportProduct.setNetWeight(toLong(mr_netWeight[i]));
exportProduct.setSizeLength(toLong(mr_sizeLength[i]));
exportProduct.setSizeWidth(toLong(mr_sizeWidth[i]));
exportProduct.setSizeHeight(toLong(mr_sizeHeight[i]));
exportProduct.setExPrice(toLong(mr_exPrice[i]));
exportProduct.setTax(toLong(mr_tax[i]));
exportProductDao.update(exportProduct);
}
}
Export export = exportDao.get(Export.class, model.getId());
model.setExportProducts(export.getExportProducts());
exportDao.evict(export);
model.setState(export.getState());
exportDao.update(model);
}*/
@Override
public void update(Export model) {
Export export = exportDao.get(Export.class, model.getId());
model.setExportProducts(export.getExportProducts());
exportDao.evict(export);
model.setState(export.getState());
/*User user = (User) ServletActionContext.getRequest().getSession().getAttribute(SysConstant.C_USER);
model.setUpdateBy(user.getId());
model.setUpdateTime(new Date());*/
exportDao.update(model);
}
private Long toLong (String data){
return data.isEmpty()? null : Long.valueOf(data);
}
@Override
@Transactional(readOnly = true)
public Export findById(String id) {
return exportDao.get(Export.class,id);
}
@Override
public void delete(String[] ids) {
for (String id : ids) {
exportDao.deleteById(Export.class,id);
}
}
@Override
public void updateState(Export model,Long exportState) {
Export export = exportDao.get(Export.class, model.getId());
exportDao.evict(export);
Export ex = exportDao.get(Export.class, model.getId());
ex.setState(exportState);
/*String contractIds = export.getContractIds();
if(contractIds!=null){
String[] Ids = contractIds.split(", ");
for(String contractId : Ids){
Contract contract = contractDao.get(Contract.class, contractId);
contract.setState(contractState);
contractDao.update(contract);//
}
}*/
// exportDao.evict(model);
exportDao.update(ex);
}
@Override
public Pagination findByPage(Pagination page, Long state) {
return exportDao.pageByHql("from Export where state = ?" ,page.getPageNo(),page.getPageSize() , state);
}
@Override
public List<ExportProduct> fingExportProductByExportId(String id) {
return exportProductDao.getListByHQL("from ExportProduct where export.id = ?",id);
}
@Override
public void updateEP(ExportProduct ep) {
ExportProduct exportProduct = exportProductDao.get(ExportProduct.class, ep.getId());
exportProduct.setCnumber(ep.getCnumber());
exportProduct.setGrossWeight(ep.getGrossWeight());
exportProduct.setNetWeight(ep.getNetWeight());
exportProduct.setSizeLength(ep.getSizeLength());
exportProduct.setSizeWidth(ep.getSizeWidth());
exportProduct.setSizeHeight(ep.getSizeHeight());
exportProduct.setExPrice(ep.getExPrice());
exportProduct.setTax(ep.getTax());
exportProductDao.update(exportProduct);
}
}
|
UTF-8
|
Java
| 7,884 |
java
|
ExportServiceImpl.java
|
Java
|
[] | null |
[] |
package top.greathead.jk.service.impl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.greathead.jk.dao.BaseDao;
import top.greathead.jk.entity.*;
import top.greathead.jk.service.ExportService;
import top.greathead.jk.utils.Pagination;
import top.greathead.jk.utils.SysConstant;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Set;
@Service
@Transactional
public class ExportServiceImpl implements ExportService {
@Autowired
private BaseDao<Export,String> exportDao;
@Autowired
private BaseDao<Contract,String> contractDao;
@Autowired
private BaseDao<ExportProduct,String> exportProductDao;
@Override
@Transactional(readOnly = true)
public Pagination findByPage(Pagination page) {
return exportDao.pageByHql("from Export order by inputDate desc" ,page.getPageNo(),page.getPageSize());
}
@Override
@Transactional(readOnly = true)
public List<Export> findAll() {
return exportDao.getListByHQL("from Export");
}
@Override
public void insert(Export model) {
String ids = model.getId();
String[] contractIds = ids.split(", ");
model.setId(null);
Long state = 0L;
model.setState(state);
model.setInputDate(new Date());
model.setCreateTime(new Date());
model.setContractIds(ids);
User user = (User) ServletActionContext.getRequest().getSession().getAttribute(SysConstant.C_USER);
model.setCreateBy(user.getId());
model.setCreateDept(user.getDept().getId());
String customerContract="";
for(String contractId:contractIds){
Contract contract = contractDao.get(Contract.class, contractId);
contract.setState(2L);
Set<ContractProduct> contractProducts = contract.getContractProducts();
// Set<ExportProduct> exportProducts = model.getExportProducts();
customerContract = customerContract +" " + contract.getContractNo();
for(ContractProduct contractProduct:contractProducts){
try {
ExportProduct exportProduct = new ExportProduct();
BeanUtils.copyProperties(exportProduct,contractProduct);
exportProduct.setId(null);
model.getExportProducts().add(exportProduct);
Set<ExtCproduct> extCproducts = contractProduct.getExtCproducts();
//Set<ExtEproduct> extEproducts = exportProduct.getExtEproducts();
for(ExtCproduct extCproduct:extCproducts){
try {
ExtEproduct extEproduct = new ExtEproduct();
BeanUtils.copyProperties(extEproduct,extCproduct);
extEproduct.setId(null);
exportProduct.getExtEproducts().add(extEproduct);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
contractDao.update(contract);
}
}
model.setCustomerContract(customerContract);
exportDao.save(model);
}
/* @Override
public void update(Export model, String[] mr_id, String[] mr_changed, String[] mr_orderNo,
String[] mr_cnumber, String[] mr_grossWeight, String[] mr_netWeight, String[] mr_sizeLength,
String[] mr_sizeWidth, String[] mr_sizeHeight, String[] mr_exPrice, String[] mr_tax) {
for(int i=0; i<mr_changed.length; i++){
if(!mr_changed[i].isEmpty()){
ExportProduct exportProduct = exportProductDao.get(ExportProduct.class, mr_id[i]);
exportProduct.setCnumber(toLong(mr_cnumber[i]));
exportProduct.setGrossWeight(toLong(mr_grossWeight[i]));
exportProduct.setNetWeight(toLong(mr_netWeight[i]));
exportProduct.setSizeLength(toLong(mr_sizeLength[i]));
exportProduct.setSizeWidth(toLong(mr_sizeWidth[i]));
exportProduct.setSizeHeight(toLong(mr_sizeHeight[i]));
exportProduct.setExPrice(toLong(mr_exPrice[i]));
exportProduct.setTax(toLong(mr_tax[i]));
exportProductDao.update(exportProduct);
}
}
Export export = exportDao.get(Export.class, model.getId());
model.setExportProducts(export.getExportProducts());
exportDao.evict(export);
model.setState(export.getState());
exportDao.update(model);
}*/
@Override
public void update(Export model) {
Export export = exportDao.get(Export.class, model.getId());
model.setExportProducts(export.getExportProducts());
exportDao.evict(export);
model.setState(export.getState());
/*User user = (User) ServletActionContext.getRequest().getSession().getAttribute(SysConstant.C_USER);
model.setUpdateBy(user.getId());
model.setUpdateTime(new Date());*/
exportDao.update(model);
}
private Long toLong (String data){
return data.isEmpty()? null : Long.valueOf(data);
}
@Override
@Transactional(readOnly = true)
public Export findById(String id) {
return exportDao.get(Export.class,id);
}
@Override
public void delete(String[] ids) {
for (String id : ids) {
exportDao.deleteById(Export.class,id);
}
}
@Override
public void updateState(Export model,Long exportState) {
Export export = exportDao.get(Export.class, model.getId());
exportDao.evict(export);
Export ex = exportDao.get(Export.class, model.getId());
ex.setState(exportState);
/*String contractIds = export.getContractIds();
if(contractIds!=null){
String[] Ids = contractIds.split(", ");
for(String contractId : Ids){
Contract contract = contractDao.get(Contract.class, contractId);
contract.setState(contractState);
contractDao.update(contract);//
}
}*/
// exportDao.evict(model);
exportDao.update(ex);
}
@Override
public Pagination findByPage(Pagination page, Long state) {
return exportDao.pageByHql("from Export where state = ?" ,page.getPageNo(),page.getPageSize() , state);
}
@Override
public List<ExportProduct> fingExportProductByExportId(String id) {
return exportProductDao.getListByHQL("from ExportProduct where export.id = ?",id);
}
@Override
public void updateEP(ExportProduct ep) {
ExportProduct exportProduct = exportProductDao.get(ExportProduct.class, ep.getId());
exportProduct.setCnumber(ep.getCnumber());
exportProduct.setGrossWeight(ep.getGrossWeight());
exportProduct.setNetWeight(ep.getNetWeight());
exportProduct.setSizeLength(ep.getSizeLength());
exportProduct.setSizeWidth(ep.getSizeWidth());
exportProduct.setSizeHeight(ep.getSizeHeight());
exportProduct.setExPrice(ep.getExPrice());
exportProduct.setTax(ep.getTax());
exportProductDao.update(exportProduct);
}
}
| 7,884 | 0.624302 | 0.623795 | 201 | 38.223881 | 28.214788 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.701493 | false | false |
7
|
8d0db6edfefbcec02aab5ce95167ff7c3c625d1a
| 11,063,835,760,055 |
ab7bb384447e7937a413da10d0806506d8f6ec4e
|
/workout/src/com/mschmidt/android/workout/activity/AddRestActivity.java
|
86a63557269255b92c20bd1b3c53f52896725bc5
|
[] |
no_license
|
mschmidt18/steves-workout
|
https://github.com/mschmidt18/steves-workout
|
69e463a111df5f3f658a27353c2eb2e214232a72
|
93fe9b213eaaf8570db68469423c062541c30f0d
|
refs/heads/master
| 2021-01-01T19:20:54.275000 | 2012-02-05T21:51:09 | 2012-02-05T21:51:09 | 3,330,710 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mschmidt.android.workout.activity;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.mschmidt.android.workout.IWorkoutComponent;
import com.mschmidt.android.workout.R;
import com.mschmidt.android.workout.Rest;
import com.mschmidt.android.workout.WorkoutSession;
public class AddRestActivity extends Activity {
public static final String TAG = "AddRestActivity";
private Button addRestButton;
private Button cancelButton;
private EditText minutes;
private EditText seconds;
private Integer editingItem = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_rest);
addRestButton = (Button) findViewById(R.id.addButton);
cancelButton = (Button) findViewById(R.id.cancelButton);
minutes = (EditText) findViewById(R.id.minutesText);
seconds = (EditText) findViewById(R.id.secondsText);
Bundle editBundle = getIntent().getExtras();
if (editBundle != null) {
int itemToEdit = editBundle.getInt("edit");
if (itemToEdit > 0
&& itemToEdit <= WorkoutSession.getInstance()
.getWorkoutItems().size()) {
editingItem = itemToEdit - 1;
IWorkoutComponent iItem = WorkoutSession.getInstance()
.getWorkoutItems().get(editingItem);
if (iItem instanceof Rest) {
minutes.setText(Integer.toString(((Rest) iItem)
.getMinutes()));
seconds.setText(Integer.toString(((Rest) iItem)
.getSeconds()));
}
}
}
addRestButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "addRestButton clicked");
Editable sMins = minutes.getText();
Editable sSecs = seconds.getText();
int iMins = Integer.parseInt(sMins.toString());
int iSecs = Integer.parseInt(sSecs.toString());
if (editingItem == null) {
Rest rest = new Rest();
rest.setMinutes(iMins);
rest.setSeconds(iSecs);
WorkoutSession.getInstance().addWorkoutItem(rest);
} else {
Rest rest = (Rest) WorkoutSession.getInstance()
.getWorkoutItems().get(editingItem);
rest.setMinutes(iMins);
rest.setSeconds(iSecs);
}
finish();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "cancelButton clicked");
finish();
}
});
}
}
|
UTF-8
|
Java
| 2,581 |
java
|
AddRestActivity.java
|
Java
|
[] | null |
[] |
package com.mschmidt.android.workout.activity;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.mschmidt.android.workout.IWorkoutComponent;
import com.mschmidt.android.workout.R;
import com.mschmidt.android.workout.Rest;
import com.mschmidt.android.workout.WorkoutSession;
public class AddRestActivity extends Activity {
public static final String TAG = "AddRestActivity";
private Button addRestButton;
private Button cancelButton;
private EditText minutes;
private EditText seconds;
private Integer editingItem = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_rest);
addRestButton = (Button) findViewById(R.id.addButton);
cancelButton = (Button) findViewById(R.id.cancelButton);
minutes = (EditText) findViewById(R.id.minutesText);
seconds = (EditText) findViewById(R.id.secondsText);
Bundle editBundle = getIntent().getExtras();
if (editBundle != null) {
int itemToEdit = editBundle.getInt("edit");
if (itemToEdit > 0
&& itemToEdit <= WorkoutSession.getInstance()
.getWorkoutItems().size()) {
editingItem = itemToEdit - 1;
IWorkoutComponent iItem = WorkoutSession.getInstance()
.getWorkoutItems().get(editingItem);
if (iItem instanceof Rest) {
minutes.setText(Integer.toString(((Rest) iItem)
.getMinutes()));
seconds.setText(Integer.toString(((Rest) iItem)
.getSeconds()));
}
}
}
addRestButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "addRestButton clicked");
Editable sMins = minutes.getText();
Editable sSecs = seconds.getText();
int iMins = Integer.parseInt(sMins.toString());
int iSecs = Integer.parseInt(sSecs.toString());
if (editingItem == null) {
Rest rest = new Rest();
rest.setMinutes(iMins);
rest.setSeconds(iSecs);
WorkoutSession.getInstance().addWorkoutItem(rest);
} else {
Rest rest = (Rest) WorkoutSession.getInstance()
.getWorkoutItems().get(editingItem);
rest.setMinutes(iMins);
rest.setSeconds(iSecs);
}
finish();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "cancelButton clicked");
finish();
}
});
}
}
| 2,581 | 0.688493 | 0.687718 | 86 | 28.011627 | 19.541544 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.895349 | false | false |
7
|
f2c67bb6ef91220a030f0aa7892c6254b28d6650
| 11,063,835,761,946 |
e8e48a96f2aba9040f4f55ab61efaab1a9eb6a23
|
/Leetcode/437-path-sum-iii/Solution.java
|
40350dd4e16ed0465f71cc918d453d81bb17e04f
|
[] |
no_license
|
arnabs542/algorithmic-problems
|
https://github.com/arnabs542/algorithmic-problems
|
67342172c2035d9ffb2ee2bf0f1901e651dcce12
|
5d19d2e9cddc20e8a6949ac38fe6fb73dfc81bf4
|
refs/heads/master
| 2021-12-14T05:41:50.177000 | 2017-04-15T07:42:41 | 2017-04-15T07:42:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go
downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
Return 3. The paths that sum to 8 are:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int count;
public int pathSumCnt(TreeNode root, int curSum, int sum) {
if(root == null)
return 0;
curSum += root.val;
int r = (sum == curSum ? 1 : 0);
int left = pathSumCnt(root.left, curSum, sum);
int right = pathSumCnt(root.right, curSum, sum);
return left + right + r;
}
public void pathSumHelper(TreeNode root, int sum){
if(root == null)
return;
count += pathSumCnt(root, 0, sum);
pathSumHelper(root.left, sum);
pathSumHelper(root.right, sum);
}
public int pathSum(TreeNode root, int sum){
count = 0;
pathSumHelper(root, sum);
return count;
}
}
// O(n^2)
class Solution2 {
int total = 0;
public int hasPathSum(TreeNode node, int sum) {
if(node == null)
return 0;
int cnt = 0;
if(sum == node.val)
cnt++;
cnt += hasPathSum(node.left, sum - node.val);
cnt += hasPathSum(node.right, sum - node.val);
return cnt;
}
public void getPathSum(TreeNode node, int sum) {
if(node == null)
return;
total += hasPathSum(node, sum);
getPathSum(node.left, sum);
getPathSum(node.right, sum);
}
public int pathSum(TreeNode root, int sum) {
total = 0;
getPathSum(root, sum);
return total;
}
}
// Alternative
// Time complexity: O(n)
// Space Complexity: O(height)
class Solution3 {
public int pathSumHelper(TreeNode root, int target, int curSum, Map<Integer, Integer> map) {
if(root == null)
return 0;
curSum += root.val;
int sum = curSum - target;
int npaths = map.getOrDefault(sum, 0);
if(curSum == target)
npaths++;
map.put(curSum, map.getOrDefault(curSum, 0) + 1);
npaths += pathSumHelper(root.left, target, curSum, map);
npaths += pathSumHelper(root.right, target, curSum, map);
// decrement path Count
map.put(curSum, map.get(curSum) - 1);
if(map.get(curSum) == 0)
map.remove(curSum);
return npaths;
}
public int pathSum(TreeNode root, int sum) {
// <Number, Count>
Map<Integer, Integer> map = new HashMap<>();
return pathSumHelper(root, sum, 0, map);
}
}
// Count the prefix sum
class Solution4 {
public int cntPathSum(TreeNode node, int sum, int target, Map<Integer, Integer> map){
if(node == null)
return 0;
int cnt = 0;
sum += node.val;
cnt += map.getOrDefault(sum - target, 0);
map.put(sum, map.getOrDefault(sum, 0) + 1);
cnt += cntPathSum(node.left, sum, target, map);
cnt += cntPathSum(node.right, sum, target, map);
map.put(sum, map.get(sum) - 1);
return cnt;
}
public int pathSum(TreeNode root, int sum) {
// <Number, Count>
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
return cntPathSum(root, 0, sum, map);
}
}
|
UTF-8
|
Java
| 3,946 |
java
|
Solution.java
|
Java
|
[] | null |
[] |
/*
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go
downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
Return 3. The paths that sum to 8 are:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int count;
public int pathSumCnt(TreeNode root, int curSum, int sum) {
if(root == null)
return 0;
curSum += root.val;
int r = (sum == curSum ? 1 : 0);
int left = pathSumCnt(root.left, curSum, sum);
int right = pathSumCnt(root.right, curSum, sum);
return left + right + r;
}
public void pathSumHelper(TreeNode root, int sum){
if(root == null)
return;
count += pathSumCnt(root, 0, sum);
pathSumHelper(root.left, sum);
pathSumHelper(root.right, sum);
}
public int pathSum(TreeNode root, int sum){
count = 0;
pathSumHelper(root, sum);
return count;
}
}
// O(n^2)
class Solution2 {
int total = 0;
public int hasPathSum(TreeNode node, int sum) {
if(node == null)
return 0;
int cnt = 0;
if(sum == node.val)
cnt++;
cnt += hasPathSum(node.left, sum - node.val);
cnt += hasPathSum(node.right, sum - node.val);
return cnt;
}
public void getPathSum(TreeNode node, int sum) {
if(node == null)
return;
total += hasPathSum(node, sum);
getPathSum(node.left, sum);
getPathSum(node.right, sum);
}
public int pathSum(TreeNode root, int sum) {
total = 0;
getPathSum(root, sum);
return total;
}
}
// Alternative
// Time complexity: O(n)
// Space Complexity: O(height)
class Solution3 {
public int pathSumHelper(TreeNode root, int target, int curSum, Map<Integer, Integer> map) {
if(root == null)
return 0;
curSum += root.val;
int sum = curSum - target;
int npaths = map.getOrDefault(sum, 0);
if(curSum == target)
npaths++;
map.put(curSum, map.getOrDefault(curSum, 0) + 1);
npaths += pathSumHelper(root.left, target, curSum, map);
npaths += pathSumHelper(root.right, target, curSum, map);
// decrement path Count
map.put(curSum, map.get(curSum) - 1);
if(map.get(curSum) == 0)
map.remove(curSum);
return npaths;
}
public int pathSum(TreeNode root, int sum) {
// <Number, Count>
Map<Integer, Integer> map = new HashMap<>();
return pathSumHelper(root, sum, 0, map);
}
}
// Count the prefix sum
class Solution4 {
public int cntPathSum(TreeNode node, int sum, int target, Map<Integer, Integer> map){
if(node == null)
return 0;
int cnt = 0;
sum += node.val;
cnt += map.getOrDefault(sum - target, 0);
map.put(sum, map.getOrDefault(sum, 0) + 1);
cnt += cntPathSum(node.left, sum, target, map);
cnt += cntPathSum(node.right, sum, target, map);
map.put(sum, map.get(sum) - 1);
return cnt;
}
public int pathSum(TreeNode root, int sum) {
// <Number, Count>
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
return cntPathSum(root, 0, sum, map);
}
}
| 3,946 | 0.545362 | 0.524328 | 153 | 24.79085 | 21.482218 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.895425 | false | false |
7
|
a6085927ec2cffd59b6d492d6b18392afc6cc692
| 16,595,753,666,629 |
14770f49eb96598933faa34a38b1d065f960a682
|
/src/main/java/springBootService/models/Token.java
|
e3855d937b22538271bb8ee850254366ba9446dc
|
[] |
no_license
|
PlanidinR/SpringBootService
|
https://github.com/PlanidinR/SpringBootService
|
71f802b635012ea1e4b1b21115e17f21971c026d
|
dedd2b2b807dabd95d4ed70d60f59fabe9ee4c24
|
refs/heads/master
| 2021-07-05T06:48:29.265000 | 2020-12-10T20:03:00 | 2020-12-10T20:03:00 | 212,337,837 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package springBootService.models;
import java.util.Objects;
/**
* @author Planidin Roman
* @version v1.0
*/
public class Token {
private Integer id;
private String value;
private String user_login;
private User user;
public Token (){}
public Token( String value, String user_login) {
this.value = value;
this.user_login = user_login;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public void setUser(User user) {
this.user = user;
}
public String getUser_login() {
return user_login;
}
public void setUser_login(String user_login) {
this.user_login= user_login;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Token token = (Token) o;
return Objects.equals(getId(), token.getId()) &&
Objects.equals(getValue(), token.getValue()) &&
Objects.equals(getUser_login(), token.getUser_login()) &&
Objects.equals(user, token.user);
}
@Override
public int hashCode() {
return Objects.hash(getId(), getValue(), getUser_login(), user);
}
@Override
public String toString() {
return "Token{" +
"id=" + id +
", value='" + value + '\'' +
", user_id=" + user_login +
", user=" + user +
'}';
}
}
|
UTF-8
|
Java
| 1,683 |
java
|
Token.java
|
Java
|
[
{
"context": "models;\n\nimport java.util.Objects;\n\n/**\n * @author Planidin Roman\n * @version v1.0\n */\n\npublic class Token {\n pr",
"end": 91,
"score": 0.999833881855011,
"start": 77,
"tag": "NAME",
"value": "Planidin Roman"
}
] | null |
[] |
package springBootService.models;
import java.util.Objects;
/**
* @author <NAME>
* @version v1.0
*/
public class Token {
private Integer id;
private String value;
private String user_login;
private User user;
public Token (){}
public Token( String value, String user_login) {
this.value = value;
this.user_login = user_login;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public void setUser(User user) {
this.user = user;
}
public String getUser_login() {
return user_login;
}
public void setUser_login(String user_login) {
this.user_login= user_login;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Token token = (Token) o;
return Objects.equals(getId(), token.getId()) &&
Objects.equals(getValue(), token.getValue()) &&
Objects.equals(getUser_login(), token.getUser_login()) &&
Objects.equals(user, token.user);
}
@Override
public int hashCode() {
return Objects.hash(getId(), getValue(), getUser_login(), user);
}
@Override
public String toString() {
return "Token{" +
"id=" + id +
", value='" + value + '\'' +
", user_id=" + user_login +
", user=" + user +
'}';
}
}
| 1,675 | 0.536542 | 0.535354 | 64 | 25.296875 | 18.138081 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.53125 | false | false |
7
|
35dafd9365076addd141f1cec37fe61f78deb52a
| 9,552,007,271,516 |
600ad8e01092d1f1219e36c4b417618c3231205e
|
/modules/quality-check/src/main/java/net/sf/qualitycheck/exception/IllegalInstanceOfArgumentException.java
|
d0c14d5e374c1ea721eae1a3ecf018af90bfee27
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
arouel/quality-check
|
https://github.com/arouel/quality-check
|
23b85d7286c633dc3e5d0f9abce0c441400c2e98
|
a75c32c39434ddb1f89bece57acae0536724c15a
|
refs/heads/master
| 2023-07-09T00:46:13.987000 | 2015-12-09T11:35:23 | 2015-12-09T11:35:23 | 5,590,873 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*******************************************************************************
* Copyright 2013 André Rouél and Dominik Seichter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package net.sf.qualitycheck.exception;
import javax.annotation.Nullable;
/**
* Thrown to indicate that a method has been passed with a reference of an unexpected type.
*
* @author André Rouél
* @author Dominik Seichter
*/
public class IllegalInstanceOfArgumentException extends RuntimeException {
private static final long serialVersionUID = -1886931952915327794L;
/**
* Default message to indicate that a given argument must is a member of an unexpected type
*/
protected static final String DEFAULT_MESSAGE = "The passed argument is a member of an unexpected type.";
/**
* Message to indicate that a given argument with must is a member of an unexpected type (with current and expected
* type information)
*/
protected static final String MESSAGE_WITH_TYPES = "The passed argument is a member of an unexpected type (expected type: %s, actual: %s).";
/**
* Message to indicate that a given argument with <em>name</em> must is a member of an unexpected type (with current
* and expected type information)
*/
protected static final String MESSAGE_WITH_NAME_AND_TYPES = "The passed argument '%s' is a member of an unexpected type (expected type: %s, actual: %s).";
/**
* Placeholder for not set types to format a message human readable
*/
protected static final String NO_TYPE_PLACEHOLDER = "(not set)";
/**
* Determines the message to be used, depending on the passed argument name. If if the given argument name is
* {@code null} or empty {@code DEFAULT_MESSAGE} will be returned, otherwise a formatted {@code MESSAGE_WITH_NAME}
* with the passed name.
*
* @param argumentName
* the name of the passed argument
* @param expectedType
* the expected class of the given argument
* @param actualType
* the actual class of the given argument
* @return {@code MESSAGE_WITH_TYPES} if the given argument name is {@code null} or empty, otherwise a formatted
* {@code MESSAGE_WITH_NAME}
*/
private static String determineMessage(@Nullable final String argumentName, @Nullable final Class<?> expectedType,
@Nullable final Class<?> actualType) {
return argumentName != null && !argumentName.isEmpty() ? format(argumentName, expectedType, actualType) : format(expectedType,
actualType);
}
/**
* Returns the formatted string {@link IllegalInstanceOfArgumentException#MESSAGE_WITH_TYPES} with the given types.
*
* @param expectedType
* the expected class of the given argument
* @param actualType
* the actual class of the given argument
* @return a formatted string of message with the given argument name
*/
private static String format(@Nullable final Class<?> expectedType, @Nullable final Class<?> actualType) {
final String expected = expectedType != null ? expectedType.getName() : NO_TYPE_PLACEHOLDER;
final String actual = actualType != null ? actualType.getName() : NO_TYPE_PLACEHOLDER;
return String.format(MESSAGE_WITH_TYPES, expected, actual);
}
/**
* Returns the formatted string {@link IllegalInstanceOfArgumentException#MESSAGE_WITH_NAME_AND_TYPES} with the
* given {@code argumentName}.
*
* @param argumentName
* the name of the passed argument
* @param expectedType
* the expected class of the given argument
* @param actualType
* the actual class of the given argument
* @return a formatted string of message with the given argument name
*/
private static String format(@Nullable final String argumentName, @Nullable final Class<?> expectedType,
@Nullable final Class<?> actualType) {
final String expected = expectedType != null ? expectedType.getName() : NO_TYPE_PLACEHOLDER;
final String actual = actualType != null ? actualType.getName() : NO_TYPE_PLACEHOLDER;
return String.format(MESSAGE_WITH_NAME_AND_TYPES, argumentName, expected, actual);
}
/**
* Constructs an {@code IllegalInstanceOfArgumentException} with the default message
* {@link IllegalInstanceOfArgumentException#DEFAULT_MESSAGE}.
*/
public IllegalInstanceOfArgumentException() {
super(DEFAULT_MESSAGE);
}
/**
* Constructs an {@code IllegalInstanceOfArgumentException} with the message
* {@link IllegalInstanceOfArgumentException#MESSAGE_WITH_NAME_AND_TYPES} including the given name of the argument
* as string representation.
*
* @param argumentName
* the name of the passed argument
* @param expectedType
* the expected class of the given argument
* @param actualType
* the actual class of the given argument
*/
public IllegalInstanceOfArgumentException(@Nullable final String argumentName, @Nullable final Class<?> expectedType,
@Nullable final Class<?> actualType) {
super(determineMessage(argumentName, expectedType, actualType));
}
/**
* Constructs a new exception with the default message {@link IllegalInstanceOfArgumentException#DEFAULT_MESSAGE}.
*
* @param cause
* the cause (which is saved for later retrieval by the {@link Throwable#getCause()} method). (A
* {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.)
*/
public IllegalInstanceOfArgumentException(@Nullable final Throwable cause) {
super(DEFAULT_MESSAGE, cause);
}
}
|
UTF-8
|
Java
| 6,086 |
java
|
IllegalInstanceOfArgumentException.java
|
Java
|
[
{
"context": "********************************\n * Copyright 2013 André Rouél and Dominik Seichter\n * \n * Licensed under the Ap",
"end": 110,
"score": 0.999869167804718,
"start": 99,
"tag": "NAME",
"value": "André Rouél"
},
{
"context": "****************\n * Copyright 2013 André Rouél and Dominik Seichter\n * \n * Licensed under the Apache License, Version",
"end": 131,
"score": 0.9998621940612793,
"start": 115,
"tag": "NAME",
"value": "Dominik Seichter"
},
{
"context": " a reference of an unexpected type.\n * \n * @author André Rouél\n * @author Dominik Seichter\n */\npublic class Ille",
"end": 969,
"score": 0.9998682141304016,
"start": 958,
"tag": "NAME",
"value": "André Rouél"
},
{
"context": "pected type.\n * \n * @author André Rouél\n * @author Dominik Seichter\n */\npublic class IllegalInstanceOfArgumentExcepti",
"end": 997,
"score": 0.9998578429222107,
"start": 981,
"tag": "NAME",
"value": "Dominik Seichter"
}
] | null |
[] |
/*******************************************************************************
* Copyright 2013 <NAME> and <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package net.sf.qualitycheck.exception;
import javax.annotation.Nullable;
/**
* Thrown to indicate that a method has been passed with a reference of an unexpected type.
*
* @author <NAME>
* @author <NAME>
*/
public class IllegalInstanceOfArgumentException extends RuntimeException {
private static final long serialVersionUID = -1886931952915327794L;
/**
* Default message to indicate that a given argument must is a member of an unexpected type
*/
protected static final String DEFAULT_MESSAGE = "The passed argument is a member of an unexpected type.";
/**
* Message to indicate that a given argument with must is a member of an unexpected type (with current and expected
* type information)
*/
protected static final String MESSAGE_WITH_TYPES = "The passed argument is a member of an unexpected type (expected type: %s, actual: %s).";
/**
* Message to indicate that a given argument with <em>name</em> must is a member of an unexpected type (with current
* and expected type information)
*/
protected static final String MESSAGE_WITH_NAME_AND_TYPES = "The passed argument '%s' is a member of an unexpected type (expected type: %s, actual: %s).";
/**
* Placeholder for not set types to format a message human readable
*/
protected static final String NO_TYPE_PLACEHOLDER = "(not set)";
/**
* Determines the message to be used, depending on the passed argument name. If if the given argument name is
* {@code null} or empty {@code DEFAULT_MESSAGE} will be returned, otherwise a formatted {@code MESSAGE_WITH_NAME}
* with the passed name.
*
* @param argumentName
* the name of the passed argument
* @param expectedType
* the expected class of the given argument
* @param actualType
* the actual class of the given argument
* @return {@code MESSAGE_WITH_TYPES} if the given argument name is {@code null} or empty, otherwise a formatted
* {@code MESSAGE_WITH_NAME}
*/
private static String determineMessage(@Nullable final String argumentName, @Nullable final Class<?> expectedType,
@Nullable final Class<?> actualType) {
return argumentName != null && !argumentName.isEmpty() ? format(argumentName, expectedType, actualType) : format(expectedType,
actualType);
}
/**
* Returns the formatted string {@link IllegalInstanceOfArgumentException#MESSAGE_WITH_TYPES} with the given types.
*
* @param expectedType
* the expected class of the given argument
* @param actualType
* the actual class of the given argument
* @return a formatted string of message with the given argument name
*/
private static String format(@Nullable final Class<?> expectedType, @Nullable final Class<?> actualType) {
final String expected = expectedType != null ? expectedType.getName() : NO_TYPE_PLACEHOLDER;
final String actual = actualType != null ? actualType.getName() : NO_TYPE_PLACEHOLDER;
return String.format(MESSAGE_WITH_TYPES, expected, actual);
}
/**
* Returns the formatted string {@link IllegalInstanceOfArgumentException#MESSAGE_WITH_NAME_AND_TYPES} with the
* given {@code argumentName}.
*
* @param argumentName
* the name of the passed argument
* @param expectedType
* the expected class of the given argument
* @param actualType
* the actual class of the given argument
* @return a formatted string of message with the given argument name
*/
private static String format(@Nullable final String argumentName, @Nullable final Class<?> expectedType,
@Nullable final Class<?> actualType) {
final String expected = expectedType != null ? expectedType.getName() : NO_TYPE_PLACEHOLDER;
final String actual = actualType != null ? actualType.getName() : NO_TYPE_PLACEHOLDER;
return String.format(MESSAGE_WITH_NAME_AND_TYPES, argumentName, expected, actual);
}
/**
* Constructs an {@code IllegalInstanceOfArgumentException} with the default message
* {@link IllegalInstanceOfArgumentException#DEFAULT_MESSAGE}.
*/
public IllegalInstanceOfArgumentException() {
super(DEFAULT_MESSAGE);
}
/**
* Constructs an {@code IllegalInstanceOfArgumentException} with the message
* {@link IllegalInstanceOfArgumentException#MESSAGE_WITH_NAME_AND_TYPES} including the given name of the argument
* as string representation.
*
* @param argumentName
* the name of the passed argument
* @param expectedType
* the expected class of the given argument
* @param actualType
* the actual class of the given argument
*/
public IllegalInstanceOfArgumentException(@Nullable final String argumentName, @Nullable final Class<?> expectedType,
@Nullable final Class<?> actualType) {
super(determineMessage(argumentName, expectedType, actualType));
}
/**
* Constructs a new exception with the default message {@link IllegalInstanceOfArgumentException#DEFAULT_MESSAGE}.
*
* @param cause
* the cause (which is saved for later retrieval by the {@link Throwable#getCause()} method). (A
* {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.)
*/
public IllegalInstanceOfArgumentException(@Nullable final Throwable cause) {
super(DEFAULT_MESSAGE, cause);
}
}
| 6,052 | 0.705196 | 0.700756 | 142 | 41.830986 | 40.509602 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.183099 | false | false |
7
|
bfa282eb6c45f6bb24b4abfbdfe83209de8b6ff9
| 15,032,385,587,515 |
3133a87e9eb50026df6c7dd94c97f83a89dff729
|
/Algorithms/src/com/practise/hackerearth/Factorial.java
|
ffd427a7c2d67d7bef180c402ad76c7e73ea7037
|
[] |
no_license
|
rishuatgithub/Algorithms
|
https://github.com/rishuatgithub/Algorithms
|
d7fa6117d13d77b35321da9d877e416647e59801
|
295671045468998c2e4c4855324eb0520cf0b883
|
refs/heads/master
| 2021-12-28T22:18:01.263000 | 2021-12-21T13:46:11 | 2021-12-21T13:46:11 | 42,785,294 | 0 | 0 | null | false | 2021-12-21T13:46:03 | 2015-09-19T18:43:14 | 2018-04-27T23:37:40 | 2021-12-21T13:46:02 | 30 | 0 | 0 | 1 |
Java
| false | false |
package com.practise.hackerearth;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Factorial {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int N = Integer.parseInt(line);
int fact=1;
for(int i=1; i<=N; i++) {
fact *= i;
}
System.out.println(fact);
}
}
|
UTF-8
|
Java
| 558 |
java
|
Factorial.java
|
Java
|
[] | null |
[] |
package com.practise.hackerearth;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Factorial {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int N = Integer.parseInt(line);
int fact=1;
for(int i=1; i<=N; i++) {
fact *= i;
}
System.out.println(fact);
}
}
| 558 | 0.625448 | 0.621864 | 25 | 21.32 | 19.529915 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.76 | false | false |
7
|
7a0105d27f896ffc1772ea9b562dfb401a54dabc
| 7,473,243,141,669 |
7112ce5c2a3f9ab9f36c7c8cf94c2ef627ac7813
|
/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/SimplePingTest.java
|
8745b2771e09be37a628baa1cba2b57f8138a880
|
[] |
no_license
|
Aedificatores8581/relic-recovery
|
https://github.com/Aedificatores8581/relic-recovery
|
be2fab873bdfef808926a173a87430defa72c426
|
5d6bfca50a29df86849ee31b251ae1d437119baf
|
refs/heads/master
| 2022-01-16T13:29:18.573000 | 2019-07-24T15:31:46 | 2019-07-24T15:31:46 | 95,800,731 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
/**
* Conjured into existence by The Saminator on 03-05-2018.
*/
@Autonomous(name = "Simple Ping Test (config 'ps')", group = "succ")
@Disabled
public class SimplePingTest extends OpMode {
private PingSensor distance;
@Override
public void init() {
distance = new PingSensor(hardwareMap.analogInput.get("ps"));
}
@Override
public void loop() {
telemetry.addData("Distance (LY)", distance.getDistanceInLightyears());
}
}
|
UTF-8
|
Java
| 681 |
java
|
SimplePingTest.java
|
Java
|
[
{
"context": ".opmode.OpMode;\n\n/**\n * Conjured into existence by The Saminator on 03-05-2018.\n */\n@Autonomous(name = \"Simple Pin",
"end": 260,
"score": 0.5715964436531067,
"start": 247,
"tag": "NAME",
"value": "The Saminator"
}
] | null |
[] |
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
/**
* Conjured into existence by <NAME> on 03-05-2018.
*/
@Autonomous(name = "Simple Ping Test (config 'ps')", group = "succ")
@Disabled
public class SimplePingTest extends OpMode {
private PingSensor distance;
@Override
public void init() {
distance = new PingSensor(hardwareMap.analogInput.get("ps"));
}
@Override
public void loop() {
telemetry.addData("Distance (LY)", distance.getDistanceInLightyears());
}
}
| 674 | 0.720999 | 0.709251 | 24 | 27.375 | 26.253273 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false |
7
|
99f25fa5889de4b053de479ed00ddd07536f90e9
| 29,016,799,093,201 |
72b6943ba2b177764c7cc587e6040817f63f4e4c
|
/AtomCore/src/sg/atom/stage/SelectManager.java
|
60ea60dcc00c94604cff9941c234f0a5be46799a
|
[
"BSD-3-Clause"
] |
permissive
|
cckmit/atom-game-framework
|
https://github.com/cckmit/atom-game-framework
|
cb7dbb6445eb648de73ed7e948b8362ee348d370
|
4a5d01e4c739346c8adaa79ee397646e50b979b8
|
refs/heads/master
| 2023-03-16T09:55:23.570000 | 2014-04-18T09:04:02 | 2014-04-18T09:04:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package sg.atom.stage;
import sg.atom.world.WorldManager;
import com.jme3.asset.AssetManager;
import com.jme3.collision.CollisionResult;
import com.jme3.collision.CollisionResults;
import com.jme3.input.InputManager;
import com.jme3.input.event.MouseButtonEvent;
import com.jme3.input.event.MouseMotionEvent;
import com.jme3.math.Ray;
import com.jme3.math.Vector3f;
import com.jme3.renderer.Camera;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import java.util.ArrayList;
import java.util.logging.Logger;
import sg.atom.entity.EntityManager;
import sg.atom.entity.SpatialEntity;
import sg.atom.entity.SpatialEntityControl;
import sg.atom.logic.input.AtomRawInputManager;
import sg.atom.stage.select.EntitySelectCondition;
import sg.atom.stage.select.HoverFunction;
import sg.atom.stage.select.SelectFunction;
import sg.atom.stage.select.SelectListener;
import sg.atom.stage.select.SpatialSelectControl;
import sg.atom.stage.select.condition.EmptyEntitySelectCondition;
import sg.atom.ui.GameGUIManager;
import sg.atom.world.spatial.SceneGraphUtils;
/**
@author atomix
*/
/**
* This class
* <code>SelectManager</code> manages the select actions of the game<br> In fact
* is pretty generic for custom mechanic to hook in!<br> <br> <p>
* <b>SelectListener</b> via Obsever pattern: like Event Listener in Swing<br>
* You should register your listener by registerSelectListener.<br> The
* listeners will be called when an Object (
* <code>Spatial</code> or
* <code>Entity</code>) is Selected/Deselected.<br>
*
* This class also hold a list of selected objects for you to check.<br> </p>
* <p><br> <b>Function</b> You can also drive the SelectManager by set the
* function for it by
* <code>setFunction(String functionName)</code> <ul><li>SingleSelect</li></ul>
* </p>
*
* <b>SelectFunction</b> has a SelectCondition and determine a SelectShape,
* which will be represent by a SelectUI. By default , RectangleSelectShape is
* made of 2 points, top-left and bottom-down. In other case PolySelectShape
* points will be added to the shape each time the user click in SelectMode.<br>
*
* <b>SelectCondition</b> The select method is defined by an interface
* SelectCondition <br>
*
* If the current selectCondition of the SelectManager is meet, selectEvent will
* be trigger and spreaded<br>
*
* <b>SelectUI</b> is used to represent to select area or shape in the screen,
* like rectangle or circle.<br>
*
* <b>SelectManager</b> will automaticly work when Mouse moved and click
* arcording to the current Function:<br> <ul><li>SingleSelect</li></ul>
*/
public class SelectManager {
protected static final Logger logger = Logger.getLogger(SelectManager.class.getName());
public static enum SelectOperationType {
Normal, Add, Substract, Union
}
protected SelectOperationType selectOperationType = SelectOperationType.Normal;
protected AssetManager assetManager;
protected StageManager stageManager;
protected InputManager inputManager;
protected WorldManager worldManager;
protected GameGUIManager gameGUIManager;
protected EntityManager entityManager;
/**
* the current selection of the game
*/
protected ArrayList< SpatialEntity> currentSelection;
protected ArrayList<SelectListener> listeners = new ArrayList<SelectListener>();
protected boolean trackHover = false;
private EntitySelectCondition entitySelectCondition;
private SelectFunction currentSelectFunction;
private HoverFunction hoverFunction;
private CollisionResults currentResults;
private CollisionResults currentHoverResults;
private boolean enable = false;
public SelectManager(GameGUIManager gameGUIManager, StageManager stageManager, WorldManager worldManager) {
this.gameGUIManager = gameGUIManager;
this.stageManager = stageManager;
this.inputManager = stageManager.getApp().getInputManager();
currentSelection = new ArrayList< SpatialEntity>(100);
this.hoverFunction = new HoverFunction(this);
}
/**
* the first initilazation of the Manager
*/
public void init() {
this.entityManager = this.stageManager.getEntityManager();
this.worldManager = this.stageManager.getWorldManager();
this.assetManager = this.worldManager.getAssetManager();
entitySelectCondition = new EmptyEntitySelectCondition();
}
public void setRootNode() {
}
public void processSelectFunction() {
Node shootables = worldManager.getWorldNode();
currentResults = this.doShoot(stageManager.getCamera(), shootables);
}
public void processHoverFunction() {
Node shootables = worldManager.getWorldNode();
currentHoverResults = this.doShoot(stageManager.getCamera(), shootables);
}
public void setupInputListener() {
System.out.println("Select Input setup!");
inputManager.addRawInputListener(new AtomRawInputManager() {
@Override
public void onMouseMotionEvent(MouseMotionEvent evt) {
mouseMove(evt);
}
@Override
public void onMouseButtonEvent(MouseButtonEvent evt) {
mouseButton(evt);
}
});
}
public void mouseMove(MouseMotionEvent evt) {
if (enable) {
if (currentSelectFunction != null) {
currentSelectFunction.mouseMove(evt);
}
if (trackHover) {
if (this.hoverFunction != null) {
processHoverFunction();
this.hoverFunction.funcHover();
}
}
}
}
public void mouseButton(MouseButtonEvent evt) {
if (enable) {
if (currentSelectFunction != null) {
currentSelectFunction.mouseButton(evt);
}
}
}
public SpatialEntityControl findSpatialEntityControl(CollisionResults results) {
if (results.size() > 0) {
CollisionResult closest = results.getClosestCollision();
Geometry geo = closest.getGeometry();
// check SpatialEntityControl
Spatial selectableSpatial = SceneGraphUtils.travelUpFindControl(geo, SpatialEntityControl.class);
if (selectableSpatial == null) {
funcDeselectAll();
return null;
} else {
SpatialEntityControl spatialEntityControl = selectableSpatial.getControl(SpatialEntityControl.class);
return spatialEntityControl;
}
}
return null;
}
public CollisionResults doShoot(Camera cam, Node shootables) {
//System.out.println(" DO SHOOT !");
Vector3f origin = cam.getWorldCoordinates(inputManager.getCursorPosition(), 0.0f);
Vector3f direction = cam.getWorldCoordinates(inputManager.getCursorPosition(), 0.3f);
direction.subtractLocal(origin).normalizeLocal();
// shoot and check the shoot ray collision
Ray ray = new Ray(origin, direction);
CollisionResults results = new CollisionResults();
shootables.collideWith(ray, results);
return results;
}
/**
* This function drive the default deselect All mechanic <ol> <li>Set
* selected to False in all
* <code>SpatialSelectControl</code></li> <li>Call the select listeners</li>
* </ol>
*/
protected void funcDeselectAll() {
if (!currentSelection.isEmpty()) {
for (SpatialEntity entity : currentSelection) {
Spatial sp = entity.getSpatial();
SpatialSelectControl entityControl = sp.getControl(SpatialSelectControl.class);
entityControl.setSelected(false);
for (SelectListener sl : listeners) {
sl.deselected(entity);
}
}
for (SelectListener sl : listeners) {
sl.deselectMulti(currentSelection);
}
currentSelection.clear();
}
}
public ArrayList<SpatialEntity> getCurrentSelection() {
return currentSelection;
}
public <T extends SpatialEntity> ArrayList<T> getCurrentSelection(Class<T> clazz) {
ArrayList<T> result = new ArrayList<T>();
for (SpatialEntity se : currentSelection) {
result.add((T) se);
}
return result;
}
public void registerSelectListener(SelectListener listener1) {
listeners.add(listener1);
}
public void deselectAll() {
funcDeselectAll();
}
public CollisionResults getCurrentResults() {
return currentResults;
}
public CollisionResults getCurrentHoverResults() {
return currentHoverResults;
}
public void setSelectFunction(SelectFunction selectFunc) {
this.currentSelectFunction = selectFunc;
}
public StageManager getStageManager() {
return stageManager;
}
public EntityManager getEntityManager() {
return entityManager;
}
public EntitySelectCondition getEntitySelectCondition() {
return entitySelectCondition;
}
public SelectFunction getCurrentSelectFunction() {
return currentSelectFunction;
}
public ArrayList<SelectListener> getListeners() {
return listeners;
}
public GameGUIManager getGameGUIManager() {
return gameGUIManager;
}
public void setEntitySelectCondition(EntitySelectCondition entitySelectCondition) {
this.entitySelectCondition = entitySelectCondition;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public boolean isTrackHover() {
return trackHover;
}
public void setTrackHover(boolean trackHover) {
this.trackHover = trackHover;
}
public void setHoverFunction(HoverFunction hoverFunction) {
this.hoverFunction = hoverFunction;
}
public HoverFunction getHoverFunction() {
return hoverFunction;
}
public SelectOperationType getSelectOperationType() {
return selectOperationType;
}
public void setSelectOperationType(SelectOperationType selectOperationType) {
this.selectOperationType = selectOperationType;
}
}
|
UTF-8
|
Java
| 10,403 |
java
|
SelectManager.java
|
Java
|
[
{
"context": "g.atom.world.spatial.SceneGraphUtils;\n\n/**\n@author atomix\n */\n/**\n * This class\n * <code>SelectManager</cod",
"end": 1117,
"score": 0.9996368885040283,
"start": 1111,
"tag": "USERNAME",
"value": "atomix"
}
] | null |
[] |
package sg.atom.stage;
import sg.atom.world.WorldManager;
import com.jme3.asset.AssetManager;
import com.jme3.collision.CollisionResult;
import com.jme3.collision.CollisionResults;
import com.jme3.input.InputManager;
import com.jme3.input.event.MouseButtonEvent;
import com.jme3.input.event.MouseMotionEvent;
import com.jme3.math.Ray;
import com.jme3.math.Vector3f;
import com.jme3.renderer.Camera;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import java.util.ArrayList;
import java.util.logging.Logger;
import sg.atom.entity.EntityManager;
import sg.atom.entity.SpatialEntity;
import sg.atom.entity.SpatialEntityControl;
import sg.atom.logic.input.AtomRawInputManager;
import sg.atom.stage.select.EntitySelectCondition;
import sg.atom.stage.select.HoverFunction;
import sg.atom.stage.select.SelectFunction;
import sg.atom.stage.select.SelectListener;
import sg.atom.stage.select.SpatialSelectControl;
import sg.atom.stage.select.condition.EmptyEntitySelectCondition;
import sg.atom.ui.GameGUIManager;
import sg.atom.world.spatial.SceneGraphUtils;
/**
@author atomix
*/
/**
* This class
* <code>SelectManager</code> manages the select actions of the game<br> In fact
* is pretty generic for custom mechanic to hook in!<br> <br> <p>
* <b>SelectListener</b> via Obsever pattern: like Event Listener in Swing<br>
* You should register your listener by registerSelectListener.<br> The
* listeners will be called when an Object (
* <code>Spatial</code> or
* <code>Entity</code>) is Selected/Deselected.<br>
*
* This class also hold a list of selected objects for you to check.<br> </p>
* <p><br> <b>Function</b> You can also drive the SelectManager by set the
* function for it by
* <code>setFunction(String functionName)</code> <ul><li>SingleSelect</li></ul>
* </p>
*
* <b>SelectFunction</b> has a SelectCondition and determine a SelectShape,
* which will be represent by a SelectUI. By default , RectangleSelectShape is
* made of 2 points, top-left and bottom-down. In other case PolySelectShape
* points will be added to the shape each time the user click in SelectMode.<br>
*
* <b>SelectCondition</b> The select method is defined by an interface
* SelectCondition <br>
*
* If the current selectCondition of the SelectManager is meet, selectEvent will
* be trigger and spreaded<br>
*
* <b>SelectUI</b> is used to represent to select area or shape in the screen,
* like rectangle or circle.<br>
*
* <b>SelectManager</b> will automaticly work when Mouse moved and click
* arcording to the current Function:<br> <ul><li>SingleSelect</li></ul>
*/
public class SelectManager {
protected static final Logger logger = Logger.getLogger(SelectManager.class.getName());
public static enum SelectOperationType {
Normal, Add, Substract, Union
}
protected SelectOperationType selectOperationType = SelectOperationType.Normal;
protected AssetManager assetManager;
protected StageManager stageManager;
protected InputManager inputManager;
protected WorldManager worldManager;
protected GameGUIManager gameGUIManager;
protected EntityManager entityManager;
/**
* the current selection of the game
*/
protected ArrayList< SpatialEntity> currentSelection;
protected ArrayList<SelectListener> listeners = new ArrayList<SelectListener>();
protected boolean trackHover = false;
private EntitySelectCondition entitySelectCondition;
private SelectFunction currentSelectFunction;
private HoverFunction hoverFunction;
private CollisionResults currentResults;
private CollisionResults currentHoverResults;
private boolean enable = false;
public SelectManager(GameGUIManager gameGUIManager, StageManager stageManager, WorldManager worldManager) {
this.gameGUIManager = gameGUIManager;
this.stageManager = stageManager;
this.inputManager = stageManager.getApp().getInputManager();
currentSelection = new ArrayList< SpatialEntity>(100);
this.hoverFunction = new HoverFunction(this);
}
/**
* the first initilazation of the Manager
*/
public void init() {
this.entityManager = this.stageManager.getEntityManager();
this.worldManager = this.stageManager.getWorldManager();
this.assetManager = this.worldManager.getAssetManager();
entitySelectCondition = new EmptyEntitySelectCondition();
}
public void setRootNode() {
}
public void processSelectFunction() {
Node shootables = worldManager.getWorldNode();
currentResults = this.doShoot(stageManager.getCamera(), shootables);
}
public void processHoverFunction() {
Node shootables = worldManager.getWorldNode();
currentHoverResults = this.doShoot(stageManager.getCamera(), shootables);
}
public void setupInputListener() {
System.out.println("Select Input setup!");
inputManager.addRawInputListener(new AtomRawInputManager() {
@Override
public void onMouseMotionEvent(MouseMotionEvent evt) {
mouseMove(evt);
}
@Override
public void onMouseButtonEvent(MouseButtonEvent evt) {
mouseButton(evt);
}
});
}
public void mouseMove(MouseMotionEvent evt) {
if (enable) {
if (currentSelectFunction != null) {
currentSelectFunction.mouseMove(evt);
}
if (trackHover) {
if (this.hoverFunction != null) {
processHoverFunction();
this.hoverFunction.funcHover();
}
}
}
}
public void mouseButton(MouseButtonEvent evt) {
if (enable) {
if (currentSelectFunction != null) {
currentSelectFunction.mouseButton(evt);
}
}
}
public SpatialEntityControl findSpatialEntityControl(CollisionResults results) {
if (results.size() > 0) {
CollisionResult closest = results.getClosestCollision();
Geometry geo = closest.getGeometry();
// check SpatialEntityControl
Spatial selectableSpatial = SceneGraphUtils.travelUpFindControl(geo, SpatialEntityControl.class);
if (selectableSpatial == null) {
funcDeselectAll();
return null;
} else {
SpatialEntityControl spatialEntityControl = selectableSpatial.getControl(SpatialEntityControl.class);
return spatialEntityControl;
}
}
return null;
}
public CollisionResults doShoot(Camera cam, Node shootables) {
//System.out.println(" DO SHOOT !");
Vector3f origin = cam.getWorldCoordinates(inputManager.getCursorPosition(), 0.0f);
Vector3f direction = cam.getWorldCoordinates(inputManager.getCursorPosition(), 0.3f);
direction.subtractLocal(origin).normalizeLocal();
// shoot and check the shoot ray collision
Ray ray = new Ray(origin, direction);
CollisionResults results = new CollisionResults();
shootables.collideWith(ray, results);
return results;
}
/**
* This function drive the default deselect All mechanic <ol> <li>Set
* selected to False in all
* <code>SpatialSelectControl</code></li> <li>Call the select listeners</li>
* </ol>
*/
protected void funcDeselectAll() {
if (!currentSelection.isEmpty()) {
for (SpatialEntity entity : currentSelection) {
Spatial sp = entity.getSpatial();
SpatialSelectControl entityControl = sp.getControl(SpatialSelectControl.class);
entityControl.setSelected(false);
for (SelectListener sl : listeners) {
sl.deselected(entity);
}
}
for (SelectListener sl : listeners) {
sl.deselectMulti(currentSelection);
}
currentSelection.clear();
}
}
public ArrayList<SpatialEntity> getCurrentSelection() {
return currentSelection;
}
public <T extends SpatialEntity> ArrayList<T> getCurrentSelection(Class<T> clazz) {
ArrayList<T> result = new ArrayList<T>();
for (SpatialEntity se : currentSelection) {
result.add((T) se);
}
return result;
}
public void registerSelectListener(SelectListener listener1) {
listeners.add(listener1);
}
public void deselectAll() {
funcDeselectAll();
}
public CollisionResults getCurrentResults() {
return currentResults;
}
public CollisionResults getCurrentHoverResults() {
return currentHoverResults;
}
public void setSelectFunction(SelectFunction selectFunc) {
this.currentSelectFunction = selectFunc;
}
public StageManager getStageManager() {
return stageManager;
}
public EntityManager getEntityManager() {
return entityManager;
}
public EntitySelectCondition getEntitySelectCondition() {
return entitySelectCondition;
}
public SelectFunction getCurrentSelectFunction() {
return currentSelectFunction;
}
public ArrayList<SelectListener> getListeners() {
return listeners;
}
public GameGUIManager getGameGUIManager() {
return gameGUIManager;
}
public void setEntitySelectCondition(EntitySelectCondition entitySelectCondition) {
this.entitySelectCondition = entitySelectCondition;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public boolean isTrackHover() {
return trackHover;
}
public void setTrackHover(boolean trackHover) {
this.trackHover = trackHover;
}
public void setHoverFunction(HoverFunction hoverFunction) {
this.hoverFunction = hoverFunction;
}
public HoverFunction getHoverFunction() {
return hoverFunction;
}
public SelectOperationType getSelectOperationType() {
return selectOperationType;
}
public void setSelectOperationType(SelectOperationType selectOperationType) {
this.selectOperationType = selectOperationType;
}
}
| 10,403 | 0.679131 | 0.676632 | 314 | 32.130573 | 26.797165 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.414013 | false | false |
7
|
bbf54ffb877d8de4360b9b5a3295b54882bc40ce
| 28,776,280,930,014 |
9a34b100ca5ce6fbd4873c0bfaacf73177183d5e
|
/src/main/java/ioprintwriter/talentshow/ResultCalculator.java
|
6a09770c0e26311a1b149a0027d13095ee42ef12
|
[] |
no_license
|
kondasg/training-solutions
|
https://github.com/kondasg/training-solutions
|
862a4704bd782a3cf7fdf4f07ec65228ed28ff8d
|
337e96453eb50f628ce664aead00169317d99635
|
refs/heads/master
| 2023-04-30T03:11:28.852000 | 2021-05-14T16:24:54 | 2021-05-14T16:24:54 | 308,166,095 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ioprintwriter.talentshow;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class ResultCalculator {
private final List<Production> productions = new ArrayList<>();
private final List<Vote> votes = new ArrayList<>();
public List<Production> getProductions() {
return productions;
}
public List<Vote> getVotes() {
return votes;
}
public void readTalents(Path talentsFile) {
try (BufferedReader reader = Files.newBufferedReader(talentsFile)) {
String line;
while ((line = reader.readLine()) != null) {
String[] splittedLine = line.split(" ");
productions.add(new Production(Integer.parseInt(splittedLine[0]), splittedLine[1]));
}
} catch (IOException e) {
throw new IllegalStateException("Can't read " + talentsFile.toString() + " file", e);
}
}
public void calculateVotes(Path votesFile) {
try (BufferedReader reader = Files.newBufferedReader(votesFile)) {
String line;
while ((line = reader.readLine()) != null) {
int id = Integer.parseInt(line);
addVote(id);
}
} catch (IOException e) {
throw new IllegalStateException("Can't read " + votesFile + " file", e);
}
}
public void writeResultToFile(Path resultFile) {
try (PrintWriter writer = new PrintWriter(new BufferedWriter(Files.newBufferedWriter(resultFile)))) {
for (Production production: productions) {
writer.println(production.getId() + " " + production.getName() + " " + getVote(production.getId()));
}
writer.print(maxVote());
} catch (IOException e) {
throw new IllegalStateException("Can't write " + resultFile + " file", e);
}
}
private void addVote(int id) {
for (Vote vote: votes) {
if (vote.getId() == id) {
vote.incNum();
return;
}
}
votes.add(new Vote(id, 1));
}
private String maxVote() {
int max = votes.get(0).getNumber();
int id = votes.get(0).getId();
for (Vote vote: votes) {
if (max < vote.getNumber()) {
id = vote.getId();
max = vote.getNumber();
}
}
for (Production production: productions) {
if (production.getId() == id) {
return "Winner: " + production.getName();
}
}
throw new IllegalArgumentException("Nincs nyertes");
}
private int getVote(int id) {
for (Vote vote: votes) {
if (vote.getId() == id) {
return vote.getNumber();
}
}
throw new IllegalArgumentException("Nincs ilyen produkció");
}
}
|
UTF-8
|
Java
| 3,059 |
java
|
ResultCalculator.java
|
Java
|
[] | null |
[] |
package ioprintwriter.talentshow;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class ResultCalculator {
private final List<Production> productions = new ArrayList<>();
private final List<Vote> votes = new ArrayList<>();
public List<Production> getProductions() {
return productions;
}
public List<Vote> getVotes() {
return votes;
}
public void readTalents(Path talentsFile) {
try (BufferedReader reader = Files.newBufferedReader(talentsFile)) {
String line;
while ((line = reader.readLine()) != null) {
String[] splittedLine = line.split(" ");
productions.add(new Production(Integer.parseInt(splittedLine[0]), splittedLine[1]));
}
} catch (IOException e) {
throw new IllegalStateException("Can't read " + talentsFile.toString() + " file", e);
}
}
public void calculateVotes(Path votesFile) {
try (BufferedReader reader = Files.newBufferedReader(votesFile)) {
String line;
while ((line = reader.readLine()) != null) {
int id = Integer.parseInt(line);
addVote(id);
}
} catch (IOException e) {
throw new IllegalStateException("Can't read " + votesFile + " file", e);
}
}
public void writeResultToFile(Path resultFile) {
try (PrintWriter writer = new PrintWriter(new BufferedWriter(Files.newBufferedWriter(resultFile)))) {
for (Production production: productions) {
writer.println(production.getId() + " " + production.getName() + " " + getVote(production.getId()));
}
writer.print(maxVote());
} catch (IOException e) {
throw new IllegalStateException("Can't write " + resultFile + " file", e);
}
}
private void addVote(int id) {
for (Vote vote: votes) {
if (vote.getId() == id) {
vote.incNum();
return;
}
}
votes.add(new Vote(id, 1));
}
private String maxVote() {
int max = votes.get(0).getNumber();
int id = votes.get(0).getId();
for (Vote vote: votes) {
if (max < vote.getNumber()) {
id = vote.getId();
max = vote.getNumber();
}
}
for (Production production: productions) {
if (production.getId() == id) {
return "Winner: " + production.getName();
}
}
throw new IllegalArgumentException("Nincs nyertes");
}
private int getVote(int id) {
for (Vote vote: votes) {
if (vote.getId() == id) {
return vote.getNumber();
}
}
throw new IllegalArgumentException("Nincs ilyen produkció");
}
}
| 3,059 | 0.559189 | 0.557554 | 95 | 31.189474 | 26.1362 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.421053 | false | false |
7
|
8695b36405cba2139ec12ec0563bf8c24c7d22dd
| 1,941,325,286,450 |
64e22313b567d1b9e4cf0cb9c428c5929f176348
|
/2018-02/2018-02-14/leetcode34.java
|
4fa6b02c2049446fc00107d913dc01b78f77a717
|
[] |
no_license
|
pwxcoo/accept
|
https://github.com/pwxcoo/accept
|
e6f9b1cf1d42cbd3b8f557205146404c2481bf89
|
075ac957e7fbf9542a3d00188589626654c0201d
|
refs/heads/master
| 2021-09-28T15:04:07.987000 | 2021-09-27T17:28:18 | 2021-09-27T17:28:18 | 112,719,098 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* date: 2018-02-14
* author: pwxcoo
* complexity: T = O(log(n)), S = O(1)
* describe: 二分查找。找出下限和上限。
*/
class Solution {
public int[] searchRange(int[] nums, int target) {
int len = nums.length;
int[] res = {-1, -1};
if(len == 0) return res;
int low = 0, high = len - 1;
while(low < high)
{
int mid = (low + high) / 2;
if(nums[mid] < target) low = mid + 1;
else high = mid;
}
if(nums[low] != target) return res;
res[0] = low;
low = 0; high = len - 1;
while(low < high)
{
int mid = (low + high) / 2;
if(nums[mid] < target || (nums[mid] == target && nums[mid + 1] == target)) low = mid + 1;
else high = mid;
}
res[1] = high;
return res;
}
}
|
UTF-8
|
Java
| 948 |
java
|
leetcode34.java
|
Java
|
[
{
"context": "/**\n * date: 2018-02-14\n * author: pwxcoo\n * complexity: T = O(log(n)), S = O(1)\n * describ",
"end": 41,
"score": 0.9994974732398987,
"start": 35,
"tag": "USERNAME",
"value": "pwxcoo"
}
] | null |
[] |
/**
* date: 2018-02-14
* author: pwxcoo
* complexity: T = O(log(n)), S = O(1)
* describe: 二分查找。找出下限和上限。
*/
class Solution {
public int[] searchRange(int[] nums, int target) {
int len = nums.length;
int[] res = {-1, -1};
if(len == 0) return res;
int low = 0, high = len - 1;
while(low < high)
{
int mid = (low + high) / 2;
if(nums[mid] < target) low = mid + 1;
else high = mid;
}
if(nums[low] != target) return res;
res[0] = low;
low = 0; high = len - 1;
while(low < high)
{
int mid = (low + high) / 2;
if(nums[mid] < target || (nums[mid] == target && nums[mid + 1] == target)) low = mid + 1;
else high = mid;
}
res[1] = high;
return res;
}
}
| 948 | 0.401302 | 0.376356 | 40 | 22.075001 | 18.826029 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.55 | false | false |
7
|
a5c93a3f87ef938b756c8e4b21127504a4670a4a
| 25,426,206,456,873 |
919b2816ce09a52d95d91843ef69083f4313b9db
|
/group/DeviceGroupUtils.java
|
cbab0b0d4e8fd9cebd2f4e558e4bbe7e1e4d3d41
|
[] |
no_license
|
Walidib/sitewhere
|
https://github.com/Walidib/sitewhere
|
f6d582df20a6e670ebfb1ed849fdc9c38942c80d
|
985e87c3cf14b31d887b6f21c3118ca596d879c7
|
refs/heads/main
| 2023-08-27T04:25:55.699000 | 2021-09-20T01:46:08 | 2021-09-20T01:46:08 | 408,276,797 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright (c) SiteWhere, LLC. All rights reserved. http://www.sitewhere.com
*
* The software in this package is published under the terms of the CPAL v1.0
* license, a copy of which has been included with this distribution in the
* LICENSE.txt file.
*/
package com.sitewhere.device.group;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.sitewhere.SiteWhere;
import com.sitewhere.rest.model.search.SearchCriteria;
import com.sitewhere.spi.SiteWhereException;
import com.sitewhere.spi.device.IDevice;
import com.sitewhere.spi.device.group.IDeviceGroup;
import com.sitewhere.spi.device.group.IDeviceGroupElement;
import com.sitewhere.spi.search.ISearchCriteria;
import com.sitewhere.spi.search.ISearchResults;
import com.sitewhere.spi.search.device.IDeviceSearchCriteria;
import com.sitewhere.spi.tenant.ITenant;
/**
* Utility methods for maniupulating device groups.
*
* @author Derek
*/
public class DeviceGroupUtils {
/**
* Get devices in a group that match the given criteria.
*
* @param groupToken
* @param criteria
* @return
* @throws SiteWhereException
*/
public static List<IDevice> getDevicesInGroup(String groupToken, IDeviceSearchCriteria criteria, ITenant tenant)
throws SiteWhereException {
Collection<IDevice> devices = getDevicesInGroup(groupToken, tenant);
List<IDevice> matches = new ArrayList<IDevice>();
for (IDevice device : devices) {
// Handle filter by specification.
if (criteria.getSpecificationToken() != null) {
if (!device.getSpecificationToken().equals(criteria.getSpecificationToken())) {
continue;
}
}
// Handle filter by site.
if (criteria.getSiteToken() != null) {
if (!device.getSiteToken().equals(criteria.getSiteToken())) {
continue;
}
}
// Handle exclude assigned.
if (criteria.isExcludeAssigned() && (device.getAssignmentToken() != null)) {
continue;
}
if ((criteria.getStartDate() != null) && (device.getCreatedDate().before(criteria.getStartDate()))) {
continue;
}
if ((criteria.getEndDate() != null) && (device.getCreatedDate().after(criteria.getEndDate()))) {
continue;
}
matches.add(device);
}
return matches;
}
/**
* Get the list of unique devices in a group. (Recurses into subgroups and
* removes duplicates)
*
* @param groupToken
* @return
* @throws SiteWhereException
*/
public static Collection<IDevice> getDevicesInGroup(String groupToken, ITenant tenant) throws SiteWhereException {
Map<String, IDevice> devices = new HashMap<String, IDevice>();
ISearchResults<IDeviceGroupElement> elements = SiteWhere.getServer().getDeviceManagement(tenant)
.listDeviceGroupElements(groupToken, SearchCriteria.ALL);
for (IDeviceGroupElement element : elements.getResults()) {
switch (element.getType()) {
case Device: {
devices.put(element.getElementId(), SiteWhere.getServer().getDeviceManagement(tenant)
.getDeviceByHardwareId(element.getElementId()));
break;
}
case Group: {
Collection<IDevice> subDevices = getDevicesInGroup(element.getElementId(), tenant);
for (IDevice subDevice : subDevices) {
devices.put(subDevice.getHardwareId(), subDevice);
}
break;
}
}
}
return devices.values();
}
/**
* Gets devices in all groups that have the given role. Duplicates are
* removed.
*
* @param groupRole
* @param criteria
* @return
* @throws SiteWhereException
*/
public static Collection<IDevice> getDevicesInGroupsWithRole(String groupRole, IDeviceSearchCriteria criteria,
ITenant tenant) throws SiteWhereException {
Map<String, IDevice> devices = new HashMap<String, IDevice>();
ISearchCriteria groupCriteria = new SearchCriteria(1, 0);
ISearchResults<IDeviceGroup> groups = SiteWhere.getServer().getDeviceManagement(tenant)
.listDeviceGroupsWithRole(groupRole, false, groupCriteria);
for (IDeviceGroup group : groups.getResults()) {
List<IDevice> groupDevices = getDevicesInGroup(group.getToken(), criteria, tenant);
for (IDevice groupDevice : groupDevices) {
devices.put(groupDevice.getHardwareId(), groupDevice);
}
}
return devices.values();
}
}
|
UTF-8
|
Java
| 4,339 |
java
|
DeviceGroupUtils.java
|
Java
|
[
{
"context": "ds for maniupulating device groups.\n * \n * @author Derek\n */\npublic class DeviceGroupUtils {\n\n /**\n ",
"end": 991,
"score": 0.999620258808136,
"start": 986,
"tag": "NAME",
"value": "Derek"
}
] | null |
[] |
/*
* Copyright (c) SiteWhere, LLC. All rights reserved. http://www.sitewhere.com
*
* The software in this package is published under the terms of the CPAL v1.0
* license, a copy of which has been included with this distribution in the
* LICENSE.txt file.
*/
package com.sitewhere.device.group;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.sitewhere.SiteWhere;
import com.sitewhere.rest.model.search.SearchCriteria;
import com.sitewhere.spi.SiteWhereException;
import com.sitewhere.spi.device.IDevice;
import com.sitewhere.spi.device.group.IDeviceGroup;
import com.sitewhere.spi.device.group.IDeviceGroupElement;
import com.sitewhere.spi.search.ISearchCriteria;
import com.sitewhere.spi.search.ISearchResults;
import com.sitewhere.spi.search.device.IDeviceSearchCriteria;
import com.sitewhere.spi.tenant.ITenant;
/**
* Utility methods for maniupulating device groups.
*
* @author Derek
*/
public class DeviceGroupUtils {
/**
* Get devices in a group that match the given criteria.
*
* @param groupToken
* @param criteria
* @return
* @throws SiteWhereException
*/
public static List<IDevice> getDevicesInGroup(String groupToken, IDeviceSearchCriteria criteria, ITenant tenant)
throws SiteWhereException {
Collection<IDevice> devices = getDevicesInGroup(groupToken, tenant);
List<IDevice> matches = new ArrayList<IDevice>();
for (IDevice device : devices) {
// Handle filter by specification.
if (criteria.getSpecificationToken() != null) {
if (!device.getSpecificationToken().equals(criteria.getSpecificationToken())) {
continue;
}
}
// Handle filter by site.
if (criteria.getSiteToken() != null) {
if (!device.getSiteToken().equals(criteria.getSiteToken())) {
continue;
}
}
// Handle exclude assigned.
if (criteria.isExcludeAssigned() && (device.getAssignmentToken() != null)) {
continue;
}
if ((criteria.getStartDate() != null) && (device.getCreatedDate().before(criteria.getStartDate()))) {
continue;
}
if ((criteria.getEndDate() != null) && (device.getCreatedDate().after(criteria.getEndDate()))) {
continue;
}
matches.add(device);
}
return matches;
}
/**
* Get the list of unique devices in a group. (Recurses into subgroups and
* removes duplicates)
*
* @param groupToken
* @return
* @throws SiteWhereException
*/
public static Collection<IDevice> getDevicesInGroup(String groupToken, ITenant tenant) throws SiteWhereException {
Map<String, IDevice> devices = new HashMap<String, IDevice>();
ISearchResults<IDeviceGroupElement> elements = SiteWhere.getServer().getDeviceManagement(tenant)
.listDeviceGroupElements(groupToken, SearchCriteria.ALL);
for (IDeviceGroupElement element : elements.getResults()) {
switch (element.getType()) {
case Device: {
devices.put(element.getElementId(), SiteWhere.getServer().getDeviceManagement(tenant)
.getDeviceByHardwareId(element.getElementId()));
break;
}
case Group: {
Collection<IDevice> subDevices = getDevicesInGroup(element.getElementId(), tenant);
for (IDevice subDevice : subDevices) {
devices.put(subDevice.getHardwareId(), subDevice);
}
break;
}
}
}
return devices.values();
}
/**
* Gets devices in all groups that have the given role. Duplicates are
* removed.
*
* @param groupRole
* @param criteria
* @return
* @throws SiteWhereException
*/
public static Collection<IDevice> getDevicesInGroupsWithRole(String groupRole, IDeviceSearchCriteria criteria,
ITenant tenant) throws SiteWhereException {
Map<String, IDevice> devices = new HashMap<String, IDevice>();
ISearchCriteria groupCriteria = new SearchCriteria(1, 0);
ISearchResults<IDeviceGroup> groups = SiteWhere.getServer().getDeviceManagement(tenant)
.listDeviceGroupsWithRole(groupRole, false, groupCriteria);
for (IDeviceGroup group : groups.getResults()) {
List<IDevice> groupDevices = getDevicesInGroup(group.getToken(), criteria, tenant);
for (IDevice groupDevice : groupDevices) {
devices.put(groupDevice.getHardwareId(), groupDevice);
}
}
return devices.values();
}
}
| 4,339 | 0.713298 | 0.712376 | 131 | 32.129772 | 30.001883 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.091603 | false | false |
7
|
7012685a82cdd55a22caa3e94c423751a2b37a73
| 28,278,064,740,534 |
8af1164bac943cef64e41bae312223c3c0e38114
|
/results-java/realm--realm-java/6892df6eed75e81c361a60c7e7b723c056ced124/after/TableDataOperationsTest.java
|
7458130b040383f4c1f229f45a6bb6bfefaf6216
|
[] |
no_license
|
fracz/refactor-extractor
|
https://github.com/fracz/refactor-extractor
|
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
|
dd5e82bfcc376e74a99e18c2bf54c95676914272
|
refs/heads/master
| 2021-01-19T06:50:08.211000 | 2018-11-30T13:00:57 | 2018-11-30T13:00:57 | 87,353,478 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.tightdb.typed;
import static org.testng.AssertJUnit.assertEquals;
import java.util.Date;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.tightdb.test.TestEmployeeQuery;
import com.tightdb.test.TestEmployeeRow;
import com.tightdb.test.TestEmployeeTable;
import com.tightdb.test.TestEmployeeView;
import com.tightdb.test.TestPhoneTable;
import com.tightdb.typed.AbstractTableOrView;
@Test
public class TableDataOperationsTest extends AbstractDataOperationsTest {
private TestEmployeeTable employees;
@Override
protected AbstractTableOrView<TestEmployeeRow, TestEmployeeView, TestEmployeeQuery> getEmployees() {
return employees;
}
@BeforeMethod
public void init() {
employees = new TestEmployeeTable();
employees.add(NAME0, "Doe", 10000, true, new byte[] { 1, 2, 3 }, new Date(), "extra", null);
employees.add(NAME2, "B. Good", 10000, true, new byte[] { 1, 2, 3 }, new Date(), true, null);
employees.insert(1, NAME1, "Mihajlovski", 30000, false, new byte[] { 4, 5 }, new Date(), 1234, null);
Object[][] phones = { { "home", "123-123" }, { "mobile", "456-456" } };
employees.add(NAME3, "Bond", 150000, true, new byte[] { 0 }, new Date(), "x", phones);
}
private void setAndTestValue(long val) {
employees.at(1).setSalary(val);
assertEquals(val, employees.at(1).getSalary());
}
@Test
public void shouldStoreValues() {
setAndTestValue(Integer.MAX_VALUE);
setAndTestValue(Integer.MIN_VALUE);
setAndTestValue(Long.MAX_VALUE);
setAndTestValue(Long.MIN_VALUE);
}
@Test
public void shouldConstructSubtableInline() {
TestPhoneTable phones = employees.last().getPhones();
assertEquals(2, phones.size());
assertEquals("home", phones.at(0).type.get());
assertEquals("123-123", phones.at(0).number.get());
assertEquals("mobile", phones.at(1).getType());
assertEquals("456-456", phones.at(1).getNumber());
}
}
|
UTF-8
|
Java
| 1,918 |
java
|
TableDataOperationsTest.java
|
Java
|
[
{
"context": "new TestEmployeeTable();\n\n\t\temployees.add(NAME0, \"Doe\", 10000, true, new byte[] { 1, 2, 3 }, new Date()",
"end": 802,
"score": 0.9996250867843628,
"start": 799,
"tag": "NAME",
"value": "Doe"
},
{
"context": "w Date(), \"extra\", null);\n\t\temployees.add(NAME2, \"B. Good\", 10000, true, new byte[] { 1, 2, 3 }, new Date()",
"end": 901,
"score": 0.9997806549072266,
"start": 894,
"tag": "NAME",
"value": "B. Good"
},
{
"context": "ate(), true, null);\n\t\temployees.insert(1, NAME1, \"Mihajlovski\", 30000, false, new byte[] { 4, 5 }, new Date(), ",
"end": 1007,
"score": 0.9992938041687012,
"start": 996,
"tag": "NAME",
"value": "Mihajlovski"
},
{
"context": " \"mobile\", \"456-456\" } };\n\t\temployees.add(NAME3, \"Bond\", 150000, true, new byte[] { 0 }, new Date(), \"x\"",
"end": 1173,
"score": 0.9997530579566956,
"start": 1169,
"tag": "NAME",
"value": "Bond"
}
] | null |
[] |
package com.tightdb.typed;
import static org.testng.AssertJUnit.assertEquals;
import java.util.Date;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.tightdb.test.TestEmployeeQuery;
import com.tightdb.test.TestEmployeeRow;
import com.tightdb.test.TestEmployeeTable;
import com.tightdb.test.TestEmployeeView;
import com.tightdb.test.TestPhoneTable;
import com.tightdb.typed.AbstractTableOrView;
@Test
public class TableDataOperationsTest extends AbstractDataOperationsTest {
private TestEmployeeTable employees;
@Override
protected AbstractTableOrView<TestEmployeeRow, TestEmployeeView, TestEmployeeQuery> getEmployees() {
return employees;
}
@BeforeMethod
public void init() {
employees = new TestEmployeeTable();
employees.add(NAME0, "Doe", 10000, true, new byte[] { 1, 2, 3 }, new Date(), "extra", null);
employees.add(NAME2, "<NAME>", 10000, true, new byte[] { 1, 2, 3 }, new Date(), true, null);
employees.insert(1, NAME1, "Mihajlovski", 30000, false, new byte[] { 4, 5 }, new Date(), 1234, null);
Object[][] phones = { { "home", "123-123" }, { "mobile", "456-456" } };
employees.add(NAME3, "Bond", 150000, true, new byte[] { 0 }, new Date(), "x", phones);
}
private void setAndTestValue(long val) {
employees.at(1).setSalary(val);
assertEquals(val, employees.at(1).getSalary());
}
@Test
public void shouldStoreValues() {
setAndTestValue(Integer.MAX_VALUE);
setAndTestValue(Integer.MIN_VALUE);
setAndTestValue(Long.MAX_VALUE);
setAndTestValue(Long.MIN_VALUE);
}
@Test
public void shouldConstructSubtableInline() {
TestPhoneTable phones = employees.last().getPhones();
assertEquals(2, phones.size());
assertEquals("home", phones.at(0).type.get());
assertEquals("123-123", phones.at(0).number.get());
assertEquals("mobile", phones.at(1).getType());
assertEquals("456-456", phones.at(1).getNumber());
}
}
| 1,917 | 0.724192 | 0.687696 | 65 | 28.523077 | 28.591074 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.984615 | false | false |
7
|
c7c5dcfbd13efe78b481afaf873effd450c7e736
| 1,047,972,044,283 |
ebc3d87b953c5daab66b71981097d2d5492dc455
|
/shared/src/main/java/shared/model/EventType.java
|
a43f3e3d5bd523022ee4ff4cb5ebc153b3605122
|
[] |
no_license
|
griffinbholt/FamilyMapClient
|
https://github.com/griffinbholt/FamilyMapClient
|
fc70f2d4bfa5689891c43fb6c5991640de08e0cf
|
20560902f4e7fe02159680199d02fd73a52cb08f
|
refs/heads/master
| 2022-04-18T08:50:48.054000 | 2020-04-09T06:41:38 | 2020-04-09T06:41:38 | 253,123,665 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package shared.model;
import java.io.Serializable;
import java.util.Objects;
/**
* A class to manage the eventType field of {@link ServerEvent} objects
* @author griffinbholt
*/
@SuppressWarnings("StaticVariableOfConcreteClass")
public class EventType implements Comparable<EventType>, Serializable {
/**
* A default <code>EventType</code> object for birth events
*/
public static final EventType BIRTH = new EventType("BIRTH");
/**
* A default <code>EventType</code> object for marriage events
*/
public static final EventType MARRIAGE = new EventType("MARRIAGE");
/**
* A default <code>EventType</code> object for death events
*/
public static final EventType DEATH = new EventType("DEATH");
/**
* The name of the event (acc. to the input passed to the <code>generate</code> method)
*/
private String eventName;
/**
* Generates an <code>EventType</code> object from the given event name.
* @param name Input name of the event
* @return An <code>EventType</code> object with the input event name
*/
public static EventType generate(String name) {
return new EventType(name);
}
private EventType(String name) {
this.eventName = name;
}
/**
* Tests if the input <code>EventType</code> is equal to the current instance
* @param o Input <code>Object</code> to be tested for equality with the current <code>EventType</code> instance
* @return true, if the two authorization tokens are the same; false, if otherwise
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EventType)) return false;
EventType eventType = (EventType) o;
return getEventName().equals(eventType.getEventName());
}
/**
* Generates the hashcode of the <code>EventType</code> object
* @return The hashcode
*/
@Override
public int hashCode() {
return Objects.hash(getEventName());
}
// Getter
public String getEventName() {
return (null != this.eventName) ? this.eventName : this.toString();
}
// Setter
public void setEventName(String name) {
this.eventName = name;
}
@Override
public int compareTo(EventType o) {
return this.eventName.compareTo(o.eventName);
}
}
|
UTF-8
|
Java
| 2,383 |
java
|
EventType.java
|
Java
|
[
{
"context": "pe field of {@link ServerEvent} objects\n * @author griffinbholt\n */\n@SuppressWarnings(\"StaticVariableOfConcreteCl",
"end": 178,
"score": 0.9993273615837097,
"start": 166,
"tag": "USERNAME",
"value": "griffinbholt"
}
] | null |
[] |
package shared.model;
import java.io.Serializable;
import java.util.Objects;
/**
* A class to manage the eventType field of {@link ServerEvent} objects
* @author griffinbholt
*/
@SuppressWarnings("StaticVariableOfConcreteClass")
public class EventType implements Comparable<EventType>, Serializable {
/**
* A default <code>EventType</code> object for birth events
*/
public static final EventType BIRTH = new EventType("BIRTH");
/**
* A default <code>EventType</code> object for marriage events
*/
public static final EventType MARRIAGE = new EventType("MARRIAGE");
/**
* A default <code>EventType</code> object for death events
*/
public static final EventType DEATH = new EventType("DEATH");
/**
* The name of the event (acc. to the input passed to the <code>generate</code> method)
*/
private String eventName;
/**
* Generates an <code>EventType</code> object from the given event name.
* @param name Input name of the event
* @return An <code>EventType</code> object with the input event name
*/
public static EventType generate(String name) {
return new EventType(name);
}
private EventType(String name) {
this.eventName = name;
}
/**
* Tests if the input <code>EventType</code> is equal to the current instance
* @param o Input <code>Object</code> to be tested for equality with the current <code>EventType</code> instance
* @return true, if the two authorization tokens are the same; false, if otherwise
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EventType)) return false;
EventType eventType = (EventType) o;
return getEventName().equals(eventType.getEventName());
}
/**
* Generates the hashcode of the <code>EventType</code> object
* @return The hashcode
*/
@Override
public int hashCode() {
return Objects.hash(getEventName());
}
// Getter
public String getEventName() {
return (null != this.eventName) ? this.eventName : this.toString();
}
// Setter
public void setEventName(String name) {
this.eventName = name;
}
@Override
public int compareTo(EventType o) {
return this.eventName.compareTo(o.eventName);
}
}
| 2,383 | 0.647923 | 0.647923 | 81 | 28.419754 | 28.390514 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.259259 | false | false |
7
|
efbc5b45cf685d4f2d30fe9565cec5ce5ba342f6
| 12,506,944,769,733 |
5a0bfac7ad00c079fe8e0bdf1482f4271c46eeab
|
/app/src/main/wechat6.5.3/com/tencent/mm/plugin/webview/c/b.java
|
3f86e7f20ebc7b8816d233ee6ddf890ef546b5ef
|
[] |
no_license
|
newtonker/wechat6.5.3
|
https://github.com/newtonker/wechat6.5.3
|
8af53a870a752bb9e3c92ec92a63c1252cb81c10
|
637a69732afa3a936afc9f4679994b79a9222680
|
refs/heads/master
| 2020-04-16T03:32:32.230000 | 2017-06-15T09:54:10 | 2017-06-15T09:54:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.tencent.mm.plugin.webview.c;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import com.tencent.mm.a.g;
import com.tencent.mm.e.a.id;
import com.tencent.mm.e.a.nr;
import com.tencent.mm.model.ak;
import com.tencent.mm.model.m;
import com.tencent.mm.modelbiz.BizInfo;
import com.tencent.mm.modelsearch.h;
import com.tencent.mm.modelsearch.i;
import com.tencent.mm.modelsearch.l;
import com.tencent.mm.modelsearch.s;
import com.tencent.mm.modelsfs.FileOp;
import com.tencent.mm.plugin.webview.ui.tools.jsapi.j;
import com.tencent.mm.protocal.GeneralControlWrapper;
import com.tencent.mm.protocal.JsapiPermissionWrapper;
import com.tencent.mm.protocal.c.ahk;
import com.tencent.mm.protocal.c.aib;
import com.tencent.mm.protocal.c.ajn;
import com.tencent.mm.protocal.c.ajo;
import com.tencent.mm.protocal.c.ajr;
import com.tencent.mm.protocal.c.aqn;
import com.tencent.mm.protocal.c.azr;
import com.tencent.mm.protocal.c.bcy;
import com.tencent.mm.protocal.c.mc;
import com.tencent.mm.sdk.platformtools.aa;
import com.tencent.mm.sdk.platformtools.be;
import com.tencent.mm.sdk.platformtools.v;
import com.tencent.mm.storage.RegionCodeDecoder;
import com.tencent.mm.u.n;
import com.tencent.mm.v.k;
import com.tencent.tmassistantsdk.storage.table.DownloadSettingTable.Columns;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public final class b implements com.tencent.mm.sdk.h.g.a, com.tencent.mm.v.e {
public com.tencent.mm.sdk.c.c dHB = new com.tencent.mm.sdk.c.c<id>(this) {
final /* synthetic */ b ldu;
{
this.ldu = r2;
this.nhz = id.class.getName().hashCode();
}
private boolean a(id idVar) {
ajr com_tencent_mm_protocal_c_ajr = idVar.bif.bib;
if (com_tencent_mm_protocal_c_ajr != null && com.tencent.mm.ai.b.d(com_tencent_mm_protocal_c_ajr)) {
switch (idVar.bif.action) {
case 0:
case 1:
for (Integer intValue : this.ldu.ldn) {
j.tl(intValue.intValue()).bu(com_tencent_mm_protocal_c_ajr.mJW, 1);
}
break;
case 2:
case 3:
case 4:
for (Integer intValue2 : this.ldu.ldn) {
j.tl(intValue2.intValue()).bu(com_tencent_mm_protocal_c_ajr.mJW, 0);
}
break;
}
}
return false;
}
};
public com.tencent.mm.sdk.c.c jeg = new com.tencent.mm.sdk.c.c<nr>(this) {
final /* synthetic */ b ldu;
{
this.ldu = r2;
this.nhz = nr.class.getName().hashCode();
}
private boolean a(nr nrVar) {
if ((nrVar instanceof nr) && nrVar.boK.aYt == 2) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "Download callback %s", new Object[]{nrVar.boK.mediaId});
if (this.ldu.ldk.containsKey(nrVar.boK.mediaId)) {
synchronized (this.ldu.ldk) {
int intValue = ((Integer) this.ldu.ldm.get(nrVar.boK.mediaId)).intValue();
HashSet hashSet = (HashSet) this.ldu.ldk.get(nrVar.boK.mediaId);
JSONArray jSONArray = new JSONArray();
Iterator it = hashSet.iterator();
while (it.hasNext()) {
String str = (String) it.next();
String str2 = "weixin://fts/sns?path=" + nrVar.boK.path;
JSONObject jSONObject = new JSONObject();
try {
jSONObject.put("id", str);
jSONObject.put("src", str2);
} catch (JSONException e) {
}
jSONArray.put(jSONObject);
}
j.tl(intValue).FG(jSONArray.toString());
this.ldu.ldk.remove(nrVar.boK.mediaId);
}
}
}
return false;
}
};
private HashMap<String, HashSet<String>> ldj;
HashMap<String, HashSet<String>> ldk;
private HashMap<String, Integer> ldl;
HashMap<String, Integer> ldm;
public Set<Integer> ldn;
private HashMap<String, b> ldo;
private s ldp;
private LinkedList<bcy> ldq = new LinkedList();
public e ldr = new e(this);
public List<ajr> lds;
int ldt;
private class a implements Runnable {
public String data;
final /* synthetic */ b ldu;
public boolean ldv;
private a(b bVar) {
this.ldu = bVar;
}
public final void run() {
Object arrayList = new ArrayList();
try {
JSONArray jSONArray = new JSONArray(this.data);
for (int i = 0; i < jSONArray.length(); i++) {
azr ko = com.tencent.mm.modelsns.d.ko(jSONArray.getString(i));
ak.yW();
ajr a = com.tencent.mm.ai.b.a(com.tencent.mm.model.c.xq(), ko, 9);
if (a != null) {
arrayList.add(a);
}
}
if (!this.ldv || this.ldu.lds == null) {
this.ldu.lds = arrayList;
} else {
this.ldu.lds.addAll(arrayList);
}
} catch (Throwable e) {
v.a("MicroMsg.FTS.FTSWebViewLogic", e, "", new Object[0]);
}
}
}
private class b {
String bfi;
String bkJ;
final /* synthetic */ b ldu;
long ldw;
long ldx;
int scene;
int type;
private b(b bVar) {
this.ldu = bVar;
}
}
private class c {
public String bCj;
public String bkC;
public int bkI;
public String bpB;
public String cID;
public String hUf;
public mc hVh;
public String ldA;
final /* synthetic */ b ldu;
public int ldy;
public boolean ldz;
public int position;
public int scene;
public String username;
private c(b bVar) {
this.ldu = bVar;
}
}
private class d {
public int bBZ;
public String bCj;
public String bCk;
public String bCl;
public String bLc;
public String bkC;
public String cID;
public String cJg;
public int ldB;
final /* synthetic */ b ldu;
public int scene;
public String username;
private d(b bVar) {
this.ldu = bVar;
}
}
public class e {
public boolean aWL;
public String bkC;
public int iHC;
public boolean ldC = true;
public boolean ldD;
final /* synthetic */ b ldu;
public int scene;
public e(b bVar) {
this.ldu = bVar;
}
}
public b() {
v.i("MicroMsg.FTS.FTSWebViewLogic", "create FTSWebViewLogic");
this.ldj = new HashMap();
this.ldk = new HashMap();
this.ldl = new HashMap();
this.ldm = new HashMap();
this.ldo = new HashMap();
this.ldn = Collections.synchronizedSet(new HashSet());
com.tencent.mm.sdk.c.a.nhr.e(this.jeg);
com.tencent.mm.sdk.c.a.nhr.e(this.dHB);
n.Bo().c(this);
}
public final boolean F(Map<String, Object> map) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "getTeachSearchData: %s", new Object[]{map});
int c = c.c(map, "scene", 0);
int c2 = c.c(map, Columns.TYPE, 0);
int c3 = c.c(map, "requestType", 0);
int n = be.n(map.get("webview_instance_id"), -1);
String cM;
if (c3 == 0) {
b bVar;
bhZ();
cM = cM(c, c2);
if (this.ldo.get(cM) == null) {
bVar = new b();
ahk com_tencent_mm_protocal_c_ahk = new ahk();
ak.yW();
File file = new File(com.tencent.mm.model.c.wV(), cM(c, c2));
byte[] c4 = com.tencent.mm.a.e.c(file.getAbsolutePath(), 0, (int) file.length());
if (c4 != null) {
try {
com_tencent_mm_protocal_c_ahk.az(c4);
bVar.scene = com_tencent_mm_protocal_c_ahk.scene;
bVar.bfi = com_tencent_mm_protocal_c_ahk.min;
bVar.ldw = com_tencent_mm_protocal_c_ahk.mGW;
bVar.ldx = com_tencent_mm_protocal_c_ahk.mGX;
bVar.bkJ = com_tencent_mm_protocal_c_ahk.miU;
bVar.type = com_tencent_mm_protocal_c_ahk.efm;
v.i("MicroMsg.FTS.FTSWebViewLogic", "load bizCacheFile %s %d", new Object[]{file.getAbsolutePath(), Integer.valueOf(c4.length)});
} catch (IOException e) {
}
}
this.ldo.put(cM, bVar);
}
bVar = (b) this.ldo.get(cM);
if (!be.kS(bVar.bfi)) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "getTeachSearchData, webviewID = %d", new Object[]{Integer.valueOf(n)});
j.tl(n).b(c3, bVar.bfi, 1);
}
Object obj = (be.kS(bVar.bfi) || (System.currentTimeMillis() / 1000) - bVar.ldx > bVar.ldw) ? null : 1;
if (obj != null) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "hit the cache: %d %d %d %d", new Object[]{Integer.valueOf(bVar.scene), Long.valueOf(bVar.ldw), Long.valueOf(bVar.ldx), Integer.valueOf(bVar.type)});
l.a(bVar.scene, 0, bVar.bkJ, bVar.type, 1, "");
return false;
}
ak.vy().a(1048, this);
v.i("MicroMsg.FTS.FTSWebViewLogic", "getTeachSearchData, webviewID = %d", new Object[]{Integer.valueOf(n)});
this.ldp = new s(c, c2, h.cVT, n);
ak.vy().a(this.ldp, 0);
} else {
ajo Ik = i.Ik();
try {
JSONObject jSONObject = new JSONObject();
JSONArray jSONArray = new JSONArray();
JSONObject jSONObject2 = new JSONObject();
JSONArray jSONArray2 = new JSONArray();
for (c = Ik.eeu.size() - 1; c >= 0; c--) {
JSONObject jSONObject3 = new JSONObject();
ajn com_tencent_mm_protocal_c_ajn = (ajn) Ik.eeu.get(c);
if (m.eC(com_tencent_mm_protocal_c_ajn.mdw)) {
BizInfo hw = com.tencent.mm.modelbiz.e.hw(com_tencent_mm_protocal_c_ajn.mdw);
if (hw != null) {
jSONObject3.put("avatarUrl", hw.field_brandIconURL);
jSONObject3.put("userName", hw.field_username);
jSONObject3.put("nickName", com.tencent.mm.model.l.er(hw.field_username));
jSONArray2.put(jSONObject3);
}
}
}
jSONObject2.put("items", jSONArray2);
jSONObject2.put(Columns.TYPE, 5);
jSONObject2.put("title", "");
jSONArray.put(jSONObject2);
jSONObject.put("data", jSONArray);
v.d("MicroMsg.FTS.FTSWebViewLogic", "getTeachSearchData returnString=%s", new Object[]{jSONObject.toString()});
j.tl(n).b(1, cM, 1);
} catch (Throwable e2) {
v.a("MicroMsg.FTS.FTSWebViewLogic", e2, "gen mostSearchBizContactList error", new Object[0]);
}
}
return false;
}
public final void bhZ() {
if (this.ldp != null) {
ak.vy().b(1048, this);
ak.vy().c(this.ldp);
this.ldp = null;
}
}
public final boolean a(Map<String, Object> map, com.tencent.mm.plugin.webview.ui.tools.jsapi.i iVar) {
Bundle bundle = null;
this.ldr.ldD = true;
boolean b = c.b(map, "isTeachPage", false);
boolean b2 = c.b(map, "isMoreButton", false);
if (!(c.c(map, "isFeedBack", 0) == 1)) {
int c = c.c(map, Columns.TYPE, 0);
int c2 = c.c(map, "opType", 0);
String str;
if (c2 <= 0) {
Intent intent;
if (!b2) {
str = (String) map.get("url");
v.i("MicroMsg.FTS.FTSWebViewLogic", "doStartSearchItemDetailPage: type=%d link=%s", new Object[]{Integer.valueOf(c), str});
switch (c) {
case 1:
a(K(map), false);
break;
case 2:
case 4:
case 16:
v.i("MicroMsg.FTS.FTSWebViewLogic", "jump url = %s", new Object[]{c.n(map, "jumpUrl")});
if (iVar != null) {
bundle = iVar.blC();
}
com.tencent.mm.plugin.webview.e.e.biZ();
b(str, bundle);
break;
case 8:
c.n(map, "snsid");
str = c.n(map, "objectXmlDesc");
String n = c.n(map, "userName");
boolean b3 = c.b(map, "fromMusicItem", false);
com.tencent.mm.plugin.webview.e.e.biZ();
azr ko = com.tencent.mm.modelsns.d.ko(str);
intent = new Intent();
intent.putExtra("INTENT_TALKER", n);
intent.putExtra("INTENT_SNSID", new BigInteger(ko.gID).longValue());
intent.putExtra("SNS_FROM_MUSIC_ITEM", b3);
try {
intent.putExtra("INTENT_SNS_TIMELINEOBJECT", ko.toByteArray());
} catch (IOException e) {
}
com.tencent.mm.ay.c.b(aa.getContext(), "sns", ".ui.SnsCommentDetailUI", intent);
break;
case JsApiStopRecordVoice.CTRL_INDEX /*32*/:
d dVar = new d();
dVar.username = c.n(map, "userName");
dVar.cID = c.n(map, "nickName");
dVar.bLc = c.n(map, "alias");
dVar.bCj = c.n(map, "signature");
dVar.bBZ = c.c(map, "sex", 0);
dVar.cJg = c.n(map, "country");
dVar.bCl = c.n(map, "city");
dVar.bCk = c.n(map, "province");
dVar.ldB = c.c(map, "snsFlag", 0);
String n2 = c.n(map, "query");
if (be.kS(n2)) {
dVar.scene = 3;
} else {
if (Character.isDigit(n2.charAt(0))) {
c2 = 15;
} else {
c2 = 3;
}
dVar.scene = c2;
if (dVar.scene == 15) {
if ("mobile".equals(c.n(map, "matchType"))) {
dVar.bkC = n2;
} else {
dVar.scene = 1;
}
}
}
Intent intent2 = new Intent();
intent2.putExtra("Contact_User", dVar.username);
intent2.putExtra("Contact_Nick", dVar.cID);
intent2.putExtra("Contact_Alias", dVar.bLc);
intent2.putExtra("Contact_Sex", dVar.bBZ);
intent2.putExtra("Contact_Scene", dVar.scene);
intent2.putExtra("Contact_KHideExpose", true);
intent2.putExtra("Contact_RegionCode", RegionCodeDecoder.Y(dVar.cJg, dVar.bCk, dVar.bCl));
intent2.putExtra("Contact_Signature", dVar.bCj);
intent2.putExtra("Contact_KSnsIFlag", dVar.ldB);
intent2.putExtra("Contact_full_Mobile_MD5", dVar.bkC);
com.tencent.mm.ay.c.b(aa.getContext(), "profile", ".ui.ContactInfoUI", intent2);
break;
default:
break;
}
}
str = c.n(map, "query");
int c3 = c.c(map, "scene", 0);
String n3 = c.n(map, "searchId");
intent = new Intent();
intent.putExtra("hardcode_jspermission", JsapiPermissionWrapper.lWt);
intent.putExtra("hardcode_general_ctrl", GeneralControlWrapper.lWq);
intent.putExtra("neverGetA8Key", true);
intent.putExtra("key_load_js_without_delay", true);
intent.putExtra("ftsQuery", str);
intent.putExtra("ftsType", c);
Map a = h.a(c3, false, c);
a.put("query", str);
a.put("searchId", n3);
intent.putExtra("rawUrl", h.l(a));
com.tencent.mm.ay.c.b(aa.getContext(), "webview", ".ui.tools.fts.FTSSearchTabWebViewUI", intent);
} else {
switch (c2) {
case 2:
a(K(map), b);
break;
case 3:
c K = K(map);
if (!m.eC(K.username)) {
a(K, b);
break;
}
i.jF(K.username);
Intent intent3 = new Intent();
intent3.putExtra("Chat_User", K.username);
intent3.putExtra("finish_direct", true);
intent3.putExtra("key_temp_session_show_type", 0);
com.tencent.mm.ay.c.a(aa.getContext(), ".ui.chatting.ChattingUI", intent3);
break;
case 4:
str = c.n(map, "jumpUrl");
if (iVar != null) {
bundle = iVar.blC();
}
com.tencent.mm.plugin.webview.e.e.biZ();
b(str, bundle);
break;
default:
break;
}
}
}
Bundle blC;
n3 = c.n(map, "jumpUrl");
if (iVar != null) {
blC = iVar.blC();
} else {
blC = null;
}
com.tencent.mm.plugin.webview.e.e.biZ();
b(n3, blC);
return false;
}
public final boolean G(Map<String, Object> map) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "reportSearchRealTimeReport: %s", new Object[]{map.toString()});
aqn com_tencent_mm_protocal_c_aqn = new aqn();
com_tencent_mm_protocal_c_aqn.mPT = c.n(map, "logString");
ak.vy().a(1134, this);
ak.vy().a(new e(com_tencent_mm_protocal_c_aqn), 0);
return false;
}
private static void b(String str, Bundle bundle) {
Intent intent = new Intent();
intent.putExtra("rawUrl", str);
if (!(bundle == null || be.kS(str))) {
String str2 = bundle.getString("publishIdPrefix", "gs") + "_" + g.m(str.getBytes());
intent.putExtra("prePublishId", str2);
intent.putExtra("KPublisherId", str2);
}
com.tencent.mm.ay.c.b(aa.getContext(), "webview", ".ui.tools.WebViewUI", intent);
}
private static void a(c cVar, boolean z) {
int i;
if (cVar.bkI == 2) {
i = 89;
} else if (z) {
i = 85;
} else if (cVar.scene != 3 && cVar.scene != 16) {
i = 39;
} else if (cVar.ldz) {
i = 88;
} else {
i = 87;
}
i.jF(cVar.username);
Intent intent = new Intent();
intent.putExtra("Contact_User", cVar.username);
intent.putExtra("Contact_Nick", cVar.cID);
intent.putExtra("Contact_BrandIconURL", cVar.hUf);
intent.putExtra("Contact_Signature", cVar.bCj);
intent.putExtra("Contact_VUser_Info_Flag", cVar.ldy);
intent.putExtra("Contact_Scene", i);
if (cVar.hVh != null) {
try {
intent.putExtra("Contact_customInfo", cVar.hVh.toByteArray());
} catch (IOException e) {
}
}
Bundle bundle = new Bundle();
bundle.putString("Contact_Ext_Args_Search_Id", cVar.bpB);
bundle.putString("Contact_Ext_Args_Query_String", cVar.bkC);
bundle.putInt("Contact_Scene", i);
bundle.putInt("Contact_Ext_Args_Index", cVar.position);
bundle.putString("Contact_Ext_Extra_Params", cVar.ldA);
intent.putExtra("Contact_Ext_Args", bundle);
com.tencent.mm.ay.c.b(aa.getContext(), "profile", ".ui.ContactInfoUI", intent);
}
public static int b(Map<String, Object> map, Map<String, Object> map2) {
try {
JSONArray jSONArray = new JSONArray(c.n(map, "data"));
JSONArray jSONArray2 = new JSONArray();
for (int i = 0; i < jSONArray.length(); i++) {
JSONObject jSONObject = jSONArray.getJSONObject(i);
String string = jSONObject.getString("id");
String string2 = jSONObject.getString("userName");
String er = com.tencent.mm.model.l.er(string2);
JSONObject jSONObject2 = new JSONObject();
jSONObject2.put("id", string);
jSONObject2.put("userName", string2);
jSONObject2.put("displayName", er);
jSONArray2.put(jSONObject2);
}
map2.put("ret", Integer.valueOf(0));
map2.put("data", jSONArray2.toString());
} catch (JSONException e) {
}
return 0;
}
public static boolean H(Map<String, Object> map) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "getSearchImageList");
String n = c.n(map, "data");
int n2 = be.n(map.get("webview_instance_id"), -1);
try {
JSONArray jSONArray = new JSONArray(n);
JSONArray jSONArray2 = new JSONArray();
for (int i = 0; i < jSONArray.length(); i++) {
JSONObject jSONObject = jSONArray.getJSONObject(i);
JSONObject jSONObject2 = new JSONObject();
String string = jSONObject.getString("id");
String string2 = jSONObject.getString("imageUrl");
jSONObject2.put("id", string);
jSONObject2.put("src", string2);
jSONArray2.put(jSONObject2);
}
j.tl(n2).FG(jSONArray2.toString());
} catch (JSONException e) {
}
return false;
}
public final boolean I(Map<String, Object> map) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "getSearchAvatarList");
String n = c.n(map, "data");
int n2 = be.n(map.get("webview_instance_id"), -1);
try {
JSONArray jSONArray = new JSONArray(n);
JSONArray jSONArray2 = new JSONArray();
int i = 0;
Object obj = null;
while (i < jSONArray.length()) {
JSONObject jSONObject = jSONArray.getJSONObject(i);
String string = jSONObject.getString("id");
String string2 = jSONObject.getString("userName");
int i2 = jSONObject.getInt(Columns.TYPE);
Object string3 = jSONObject.getString("imageUrl");
String string4 = jSONObject.getString("bigImageUrl");
switch (i2) {
case 1:
case 4:
case 64:
break;
case JsApiStopRecordVoice.CTRL_INDEX /*32*/:
com.tencent.mm.u.h hVar = new com.tencent.mm.u.h();
hVar.username = string2;
hVar.cyD = string4;
hVar.cyC = string3;
hVar.bkU = -1;
hVar.bBY = 3;
hVar.aP(true);
n.Bo().a(hVar);
break;
}
n.AX();
n = com.tencent.mm.u.d.s(string2, false);
if (FileOp.aR(n)) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "avatar file exist %s", new Object[]{n});
string3 = "weixin://fts/avatar?path=" + n;
} else {
v.i("MicroMsg.FTS.FTSWebViewLogic", "avatar file not exist %s", new Object[]{n});
this.ldl.put(string2, Integer.valueOf(n2));
HashSet hashSet = (HashSet) this.ldj.get(string2);
if (hashSet == null) {
hashSet = new HashSet();
}
hashSet.add(string);
this.ldj.put(string2, hashSet);
com.tencent.mm.pluginsdk.ui.a.b.box().bg(string2);
string3 = obj;
}
if (string3 != null) {
JSONObject jSONObject2 = new JSONObject();
jSONObject2.put("id", string);
jSONObject2.put("src", string3);
jSONArray2.put(jSONObject2);
string3 = null;
}
i++;
obj = string3;
}
if (jSONArray2.length() > 0) {
j.tl(n2).FG(jSONArray2.toString());
}
} catch (JSONException e) {
}
return false;
}
public final boolean J(Map<String, Object> map) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "getSearchSnsImageList");
String n = c.n(map, "data");
int n2 = be.n(map.get("webview_instance_id"), -1);
try {
JSONArray jSONArray = new JSONArray(n);
JSONArray jSONArray2 = new JSONArray();
Object obj = null;
int i = 0;
while (i < jSONArray.length()) {
Object obj2;
JSONObject jSONObject = jSONArray.getJSONObject(i);
String string = jSONObject.getString("id");
String string2 = jSONObject.getString("objectXmlDesc");
int i2 = jSONObject.getInt("index");
azr ko = com.tencent.mm.modelsns.d.ko(string2);
if (ko.mWq.mom.size() > i2) {
aib com_tencent_mm_protocal_c_aib = (aib) ko.mWq.mom.get(i2);
nr nrVar = new nr();
nrVar.boK.aYt = 3;
nrVar.boK.mediaId = com_tencent_mm_protocal_c_aib.gID;
com.tencent.mm.sdk.c.a.nhr.z(nrVar);
v.i("MicroMsg.FTS.FTSWebViewLogic", "generatePath: %s", new Object[]{nrVar.boK.path});
if (FileOp.aR(nrVar.boK.path)) {
obj2 = "weixin://fts/sns?path=" + nrVar.boK.path;
} else {
synchronized (this.ldk) {
HashSet hashSet;
if (this.ldk.containsKey(com_tencent_mm_protocal_c_aib.gID)) {
hashSet = (HashSet) this.ldk.get(com_tencent_mm_protocal_c_aib.gID);
} else {
hashSet = new HashSet();
}
hashSet.add(string);
this.ldk.put(com_tencent_mm_protocal_c_aib.gID, hashSet);
this.ldm.put(com_tencent_mm_protocal_c_aib.gID, Integer.valueOf(n2));
}
nrVar = new nr();
nrVar.boK.aYt = 1;
nrVar.boK.boL = com_tencent_mm_protocal_c_aib;
com.tencent.mm.sdk.c.a.nhr.z(nrVar);
obj2 = obj;
}
if (obj2 != null) {
JSONObject jSONObject2 = new JSONObject();
jSONObject2.put("id", string);
jSONObject2.put("src", obj2);
jSONArray2.put(jSONObject2);
obj2 = null;
}
} else {
obj2 = obj;
}
i++;
obj = obj2;
}
if (jSONArray2.length() > 0) {
j.tl(n2).FG(jSONArray2.toString());
}
} catch (JSONException e) {
}
return false;
}
public final void a(int i, int i2, String str, k kVar) {
if (kVar instanceof s) {
ak.vy().b(1048, this);
if (i == 0 && i2 == 0) {
s sVar = (s) kVar;
b bVar = new b();
bVar.scene = sVar.scene;
bVar.ldw = (long) sVar.cWR.mHb;
bVar.bfi = sVar.cWR.min;
bVar.ldx = System.currentTimeMillis() / 1000;
bVar.bkJ = sVar.cWR.mzu;
bVar.type = sVar.cWS;
String cM = cM(bVar.scene, bVar.type);
if (!be.kS(bVar.bfi)) {
j.tl(sVar.bkE).b(0, bVar.bfi, 0);
v.i("MicroMsg.FTS.FTSWebViewLogic", "onTeachSearchDataReady, %s", new Object[]{bVar.bfi});
}
this.ldo.put(cM, bVar);
if (bVar.ldw == 0) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "delete biz cache %d %d", new Object[]{Integer.valueOf(bVar.scene), Integer.valueOf(bVar.type)});
ak.yW();
new File(com.tencent.mm.model.c.wV(), cM(r0, r2)).delete();
} else {
ahk com_tencent_mm_protocal_c_ahk = new ahk();
com_tencent_mm_protocal_c_ahk.scene = bVar.scene;
com_tencent_mm_protocal_c_ahk.min = bVar.bfi;
com_tencent_mm_protocal_c_ahk.mGW = bVar.ldw;
com_tencent_mm_protocal_c_ahk.mGX = bVar.ldx;
com_tencent_mm_protocal_c_ahk.miU = bVar.bkJ;
com_tencent_mm_protocal_c_ahk.efm = bVar.type;
byte[] bArr = null;
try {
bArr = com_tencent_mm_protocal_c_ahk.toByteArray();
} catch (IOException e) {
}
if (bArr != null) {
ak.yW();
File file = new File(com.tencent.mm.model.c.wV(), "FTS_BizCacheObj" + bVar.scene);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (file.exists()) {
file.delete();
}
com.tencent.mm.a.e.b(file.getAbsolutePath(), bArr, bArr.length);
v.i("MicroMsg.FTS.FTSWebViewLogic", "save bizCacheFile %s %d", new Object[]{file.getAbsolutePath(), Integer.valueOf(bArr.length)});
} else {
v.i("MicroMsg.FTS.FTSWebViewLogic", "save bizCacheFile fail");
}
}
l.a(bVar.scene, 1, bVar.bkJ, bVar.type, 1, "");
}
} else if (kVar instanceof e) {
ak.vy().b(1134, this);
}
}
private c K(Map<String, Object> map) {
c cVar = new c();
cVar.username = c.n(map, "userName");
cVar.cID = c.n(map, "nickName");
cVar.hUf = c.n(map, "headHDImgUrl");
cVar.ldy = c.c(map, "verifyFlag", 0);
cVar.bCj = c.n(map, "signature");
cVar.scene = c.c(map, "scene", 0);
cVar.bkI = c.c(map, "sceneActionType", 1);
cVar.hVh = new mc();
cVar.hVh.cHq = c.c(map, "brandFlag", 0);
cVar.hVh.cHt = c.n(map, "iconUrl");
cVar.hVh.cHs = c.n(map, "brandInfo");
cVar.hVh.cHr = c.n(map, "externalInfo");
cVar.bpB = c.n(map, "searchId");
cVar.bkC = c.n(map, "query");
cVar.position = c.c(map, "position", 0);
cVar.ldz = c.b(map, "isCurrentDetailPage", false);
cVar.ldA = c.n(map, "extraParams");
return cVar;
}
public final void a(String str, com.tencent.mm.sdk.h.i iVar) {
if (iVar != null && iVar.obj != null) {
synchronized (this.ldj) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "event %s,eventData %s", new Object[]{str, iVar.toString()});
String obj = iVar.obj.toString();
if (this.ldj.containsKey(obj) && this.ldl.containsKey(obj)) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "notify avatar changed %s", new Object[]{obj});
int intValue = ((Integer) this.ldl.get(obj)).intValue();
HashSet hashSet = (HashSet) this.ldj.get(obj);
JSONArray jSONArray = new JSONArray();
Iterator it = hashSet.iterator();
while (it.hasNext()) {
String str2 = (String) it.next();
n.AX();
String str3 = "weixin://fts/avatar?path=" + com.tencent.mm.u.d.s(obj, false);
JSONObject jSONObject = new JSONObject();
try {
jSONObject.put("id", str2);
jSONObject.put("src", str3);
} catch (JSONException e) {
}
jSONArray.put(jSONObject);
}
j.tl(intValue).FG(jSONArray.toString());
this.ldj.remove(obj);
this.ldl.remove(obj);
}
}
}
}
private static String cM(int i, int i2) {
return "FTS_BizCacheObj" + i + "-" + i2;
}
public static boolean L(Map<String, Object> map) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "setSearchInputWord %s", new Object[]{map});
String n = c.n(map, "word");
boolean b = c.b(map, "isInputChange", false);
String n2 = c.n(map, "custom");
String n3 = c.n(map, "tagList");
com.tencent.mm.plugin.webview.ui.tools.jsapi.i tl = j.tl(be.n(map.get("webview_instance_id"), -1));
Bundle bundle = new Bundle();
bundle.putString("fts_key_new_query", n);
bundle.putString("fts_key_custom_query", n2);
bundle.putBoolean("fts_key_need_keyboard", b);
bundle.putString("fts_key_tag_list", n3);
try {
if (tl.leB != null) {
tl.leB.g(22, bundle);
}
} catch (RemoteException e) {
v.w("MicroMsg.MsgHandler", "onFTSSearchQueryChange exception" + e.getMessage());
}
return false;
}
}
|
UTF-8
|
Java
| 36,173 |
java
|
b.java
|
Java
|
[
{
"context": "\n String n = c.n(map, \"userName\");\n boolean b3 = c.b(m",
"end": 13968,
"score": 0.9726217985153198,
"start": 13960,
"tag": "USERNAME",
"value": "userName"
},
{
"context": " dVar.username = c.n(map, \"userName\");\n dVar.cID = c.n(map",
"end": 15008,
"score": 0.9989401698112488,
"start": 15000,
"tag": "USERNAME",
"value": "userName"
},
{
"context": ".mm.u.h();\n hVar.username = string2;\n hVar.cyD = string4;\n ",
"end": 25176,
"score": 0.505851149559021,
"start": 25170,
"tag": "USERNAME",
"value": "string"
},
{
"context": "cVar = new c();\n cVar.username = c.n(map, \"userName\");\n cVar.cID = c.n(map, \"nickName\");\n ",
"end": 32834,
"score": 0.9995704293251038,
"start": 32826,
"tag": "USERNAME",
"value": "userName"
}
] | null |
[] |
package com.tencent.mm.plugin.webview.c;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import com.tencent.mm.a.g;
import com.tencent.mm.e.a.id;
import com.tencent.mm.e.a.nr;
import com.tencent.mm.model.ak;
import com.tencent.mm.model.m;
import com.tencent.mm.modelbiz.BizInfo;
import com.tencent.mm.modelsearch.h;
import com.tencent.mm.modelsearch.i;
import com.tencent.mm.modelsearch.l;
import com.tencent.mm.modelsearch.s;
import com.tencent.mm.modelsfs.FileOp;
import com.tencent.mm.plugin.webview.ui.tools.jsapi.j;
import com.tencent.mm.protocal.GeneralControlWrapper;
import com.tencent.mm.protocal.JsapiPermissionWrapper;
import com.tencent.mm.protocal.c.ahk;
import com.tencent.mm.protocal.c.aib;
import com.tencent.mm.protocal.c.ajn;
import com.tencent.mm.protocal.c.ajo;
import com.tencent.mm.protocal.c.ajr;
import com.tencent.mm.protocal.c.aqn;
import com.tencent.mm.protocal.c.azr;
import com.tencent.mm.protocal.c.bcy;
import com.tencent.mm.protocal.c.mc;
import com.tencent.mm.sdk.platformtools.aa;
import com.tencent.mm.sdk.platformtools.be;
import com.tencent.mm.sdk.platformtools.v;
import com.tencent.mm.storage.RegionCodeDecoder;
import com.tencent.mm.u.n;
import com.tencent.mm.v.k;
import com.tencent.tmassistantsdk.storage.table.DownloadSettingTable.Columns;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public final class b implements com.tencent.mm.sdk.h.g.a, com.tencent.mm.v.e {
public com.tencent.mm.sdk.c.c dHB = new com.tencent.mm.sdk.c.c<id>(this) {
final /* synthetic */ b ldu;
{
this.ldu = r2;
this.nhz = id.class.getName().hashCode();
}
private boolean a(id idVar) {
ajr com_tencent_mm_protocal_c_ajr = idVar.bif.bib;
if (com_tencent_mm_protocal_c_ajr != null && com.tencent.mm.ai.b.d(com_tencent_mm_protocal_c_ajr)) {
switch (idVar.bif.action) {
case 0:
case 1:
for (Integer intValue : this.ldu.ldn) {
j.tl(intValue.intValue()).bu(com_tencent_mm_protocal_c_ajr.mJW, 1);
}
break;
case 2:
case 3:
case 4:
for (Integer intValue2 : this.ldu.ldn) {
j.tl(intValue2.intValue()).bu(com_tencent_mm_protocal_c_ajr.mJW, 0);
}
break;
}
}
return false;
}
};
public com.tencent.mm.sdk.c.c jeg = new com.tencent.mm.sdk.c.c<nr>(this) {
final /* synthetic */ b ldu;
{
this.ldu = r2;
this.nhz = nr.class.getName().hashCode();
}
private boolean a(nr nrVar) {
if ((nrVar instanceof nr) && nrVar.boK.aYt == 2) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "Download callback %s", new Object[]{nrVar.boK.mediaId});
if (this.ldu.ldk.containsKey(nrVar.boK.mediaId)) {
synchronized (this.ldu.ldk) {
int intValue = ((Integer) this.ldu.ldm.get(nrVar.boK.mediaId)).intValue();
HashSet hashSet = (HashSet) this.ldu.ldk.get(nrVar.boK.mediaId);
JSONArray jSONArray = new JSONArray();
Iterator it = hashSet.iterator();
while (it.hasNext()) {
String str = (String) it.next();
String str2 = "weixin://fts/sns?path=" + nrVar.boK.path;
JSONObject jSONObject = new JSONObject();
try {
jSONObject.put("id", str);
jSONObject.put("src", str2);
} catch (JSONException e) {
}
jSONArray.put(jSONObject);
}
j.tl(intValue).FG(jSONArray.toString());
this.ldu.ldk.remove(nrVar.boK.mediaId);
}
}
}
return false;
}
};
private HashMap<String, HashSet<String>> ldj;
HashMap<String, HashSet<String>> ldk;
private HashMap<String, Integer> ldl;
HashMap<String, Integer> ldm;
public Set<Integer> ldn;
private HashMap<String, b> ldo;
private s ldp;
private LinkedList<bcy> ldq = new LinkedList();
public e ldr = new e(this);
public List<ajr> lds;
int ldt;
private class a implements Runnable {
public String data;
final /* synthetic */ b ldu;
public boolean ldv;
private a(b bVar) {
this.ldu = bVar;
}
public final void run() {
Object arrayList = new ArrayList();
try {
JSONArray jSONArray = new JSONArray(this.data);
for (int i = 0; i < jSONArray.length(); i++) {
azr ko = com.tencent.mm.modelsns.d.ko(jSONArray.getString(i));
ak.yW();
ajr a = com.tencent.mm.ai.b.a(com.tencent.mm.model.c.xq(), ko, 9);
if (a != null) {
arrayList.add(a);
}
}
if (!this.ldv || this.ldu.lds == null) {
this.ldu.lds = arrayList;
} else {
this.ldu.lds.addAll(arrayList);
}
} catch (Throwable e) {
v.a("MicroMsg.FTS.FTSWebViewLogic", e, "", new Object[0]);
}
}
}
private class b {
String bfi;
String bkJ;
final /* synthetic */ b ldu;
long ldw;
long ldx;
int scene;
int type;
private b(b bVar) {
this.ldu = bVar;
}
}
private class c {
public String bCj;
public String bkC;
public int bkI;
public String bpB;
public String cID;
public String hUf;
public mc hVh;
public String ldA;
final /* synthetic */ b ldu;
public int ldy;
public boolean ldz;
public int position;
public int scene;
public String username;
private c(b bVar) {
this.ldu = bVar;
}
}
private class d {
public int bBZ;
public String bCj;
public String bCk;
public String bCl;
public String bLc;
public String bkC;
public String cID;
public String cJg;
public int ldB;
final /* synthetic */ b ldu;
public int scene;
public String username;
private d(b bVar) {
this.ldu = bVar;
}
}
public class e {
public boolean aWL;
public String bkC;
public int iHC;
public boolean ldC = true;
public boolean ldD;
final /* synthetic */ b ldu;
public int scene;
public e(b bVar) {
this.ldu = bVar;
}
}
public b() {
v.i("MicroMsg.FTS.FTSWebViewLogic", "create FTSWebViewLogic");
this.ldj = new HashMap();
this.ldk = new HashMap();
this.ldl = new HashMap();
this.ldm = new HashMap();
this.ldo = new HashMap();
this.ldn = Collections.synchronizedSet(new HashSet());
com.tencent.mm.sdk.c.a.nhr.e(this.jeg);
com.tencent.mm.sdk.c.a.nhr.e(this.dHB);
n.Bo().c(this);
}
public final boolean F(Map<String, Object> map) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "getTeachSearchData: %s", new Object[]{map});
int c = c.c(map, "scene", 0);
int c2 = c.c(map, Columns.TYPE, 0);
int c3 = c.c(map, "requestType", 0);
int n = be.n(map.get("webview_instance_id"), -1);
String cM;
if (c3 == 0) {
b bVar;
bhZ();
cM = cM(c, c2);
if (this.ldo.get(cM) == null) {
bVar = new b();
ahk com_tencent_mm_protocal_c_ahk = new ahk();
ak.yW();
File file = new File(com.tencent.mm.model.c.wV(), cM(c, c2));
byte[] c4 = com.tencent.mm.a.e.c(file.getAbsolutePath(), 0, (int) file.length());
if (c4 != null) {
try {
com_tencent_mm_protocal_c_ahk.az(c4);
bVar.scene = com_tencent_mm_protocal_c_ahk.scene;
bVar.bfi = com_tencent_mm_protocal_c_ahk.min;
bVar.ldw = com_tencent_mm_protocal_c_ahk.mGW;
bVar.ldx = com_tencent_mm_protocal_c_ahk.mGX;
bVar.bkJ = com_tencent_mm_protocal_c_ahk.miU;
bVar.type = com_tencent_mm_protocal_c_ahk.efm;
v.i("MicroMsg.FTS.FTSWebViewLogic", "load bizCacheFile %s %d", new Object[]{file.getAbsolutePath(), Integer.valueOf(c4.length)});
} catch (IOException e) {
}
}
this.ldo.put(cM, bVar);
}
bVar = (b) this.ldo.get(cM);
if (!be.kS(bVar.bfi)) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "getTeachSearchData, webviewID = %d", new Object[]{Integer.valueOf(n)});
j.tl(n).b(c3, bVar.bfi, 1);
}
Object obj = (be.kS(bVar.bfi) || (System.currentTimeMillis() / 1000) - bVar.ldx > bVar.ldw) ? null : 1;
if (obj != null) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "hit the cache: %d %d %d %d", new Object[]{Integer.valueOf(bVar.scene), Long.valueOf(bVar.ldw), Long.valueOf(bVar.ldx), Integer.valueOf(bVar.type)});
l.a(bVar.scene, 0, bVar.bkJ, bVar.type, 1, "");
return false;
}
ak.vy().a(1048, this);
v.i("MicroMsg.FTS.FTSWebViewLogic", "getTeachSearchData, webviewID = %d", new Object[]{Integer.valueOf(n)});
this.ldp = new s(c, c2, h.cVT, n);
ak.vy().a(this.ldp, 0);
} else {
ajo Ik = i.Ik();
try {
JSONObject jSONObject = new JSONObject();
JSONArray jSONArray = new JSONArray();
JSONObject jSONObject2 = new JSONObject();
JSONArray jSONArray2 = new JSONArray();
for (c = Ik.eeu.size() - 1; c >= 0; c--) {
JSONObject jSONObject3 = new JSONObject();
ajn com_tencent_mm_protocal_c_ajn = (ajn) Ik.eeu.get(c);
if (m.eC(com_tencent_mm_protocal_c_ajn.mdw)) {
BizInfo hw = com.tencent.mm.modelbiz.e.hw(com_tencent_mm_protocal_c_ajn.mdw);
if (hw != null) {
jSONObject3.put("avatarUrl", hw.field_brandIconURL);
jSONObject3.put("userName", hw.field_username);
jSONObject3.put("nickName", com.tencent.mm.model.l.er(hw.field_username));
jSONArray2.put(jSONObject3);
}
}
}
jSONObject2.put("items", jSONArray2);
jSONObject2.put(Columns.TYPE, 5);
jSONObject2.put("title", "");
jSONArray.put(jSONObject2);
jSONObject.put("data", jSONArray);
v.d("MicroMsg.FTS.FTSWebViewLogic", "getTeachSearchData returnString=%s", new Object[]{jSONObject.toString()});
j.tl(n).b(1, cM, 1);
} catch (Throwable e2) {
v.a("MicroMsg.FTS.FTSWebViewLogic", e2, "gen mostSearchBizContactList error", new Object[0]);
}
}
return false;
}
public final void bhZ() {
if (this.ldp != null) {
ak.vy().b(1048, this);
ak.vy().c(this.ldp);
this.ldp = null;
}
}
public final boolean a(Map<String, Object> map, com.tencent.mm.plugin.webview.ui.tools.jsapi.i iVar) {
Bundle bundle = null;
this.ldr.ldD = true;
boolean b = c.b(map, "isTeachPage", false);
boolean b2 = c.b(map, "isMoreButton", false);
if (!(c.c(map, "isFeedBack", 0) == 1)) {
int c = c.c(map, Columns.TYPE, 0);
int c2 = c.c(map, "opType", 0);
String str;
if (c2 <= 0) {
Intent intent;
if (!b2) {
str = (String) map.get("url");
v.i("MicroMsg.FTS.FTSWebViewLogic", "doStartSearchItemDetailPage: type=%d link=%s", new Object[]{Integer.valueOf(c), str});
switch (c) {
case 1:
a(K(map), false);
break;
case 2:
case 4:
case 16:
v.i("MicroMsg.FTS.FTSWebViewLogic", "jump url = %s", new Object[]{c.n(map, "jumpUrl")});
if (iVar != null) {
bundle = iVar.blC();
}
com.tencent.mm.plugin.webview.e.e.biZ();
b(str, bundle);
break;
case 8:
c.n(map, "snsid");
str = c.n(map, "objectXmlDesc");
String n = c.n(map, "userName");
boolean b3 = c.b(map, "fromMusicItem", false);
com.tencent.mm.plugin.webview.e.e.biZ();
azr ko = com.tencent.mm.modelsns.d.ko(str);
intent = new Intent();
intent.putExtra("INTENT_TALKER", n);
intent.putExtra("INTENT_SNSID", new BigInteger(ko.gID).longValue());
intent.putExtra("SNS_FROM_MUSIC_ITEM", b3);
try {
intent.putExtra("INTENT_SNS_TIMELINEOBJECT", ko.toByteArray());
} catch (IOException e) {
}
com.tencent.mm.ay.c.b(aa.getContext(), "sns", ".ui.SnsCommentDetailUI", intent);
break;
case JsApiStopRecordVoice.CTRL_INDEX /*32*/:
d dVar = new d();
dVar.username = c.n(map, "userName");
dVar.cID = c.n(map, "nickName");
dVar.bLc = c.n(map, "alias");
dVar.bCj = c.n(map, "signature");
dVar.bBZ = c.c(map, "sex", 0);
dVar.cJg = c.n(map, "country");
dVar.bCl = c.n(map, "city");
dVar.bCk = c.n(map, "province");
dVar.ldB = c.c(map, "snsFlag", 0);
String n2 = c.n(map, "query");
if (be.kS(n2)) {
dVar.scene = 3;
} else {
if (Character.isDigit(n2.charAt(0))) {
c2 = 15;
} else {
c2 = 3;
}
dVar.scene = c2;
if (dVar.scene == 15) {
if ("mobile".equals(c.n(map, "matchType"))) {
dVar.bkC = n2;
} else {
dVar.scene = 1;
}
}
}
Intent intent2 = new Intent();
intent2.putExtra("Contact_User", dVar.username);
intent2.putExtra("Contact_Nick", dVar.cID);
intent2.putExtra("Contact_Alias", dVar.bLc);
intent2.putExtra("Contact_Sex", dVar.bBZ);
intent2.putExtra("Contact_Scene", dVar.scene);
intent2.putExtra("Contact_KHideExpose", true);
intent2.putExtra("Contact_RegionCode", RegionCodeDecoder.Y(dVar.cJg, dVar.bCk, dVar.bCl));
intent2.putExtra("Contact_Signature", dVar.bCj);
intent2.putExtra("Contact_KSnsIFlag", dVar.ldB);
intent2.putExtra("Contact_full_Mobile_MD5", dVar.bkC);
com.tencent.mm.ay.c.b(aa.getContext(), "profile", ".ui.ContactInfoUI", intent2);
break;
default:
break;
}
}
str = c.n(map, "query");
int c3 = c.c(map, "scene", 0);
String n3 = c.n(map, "searchId");
intent = new Intent();
intent.putExtra("hardcode_jspermission", JsapiPermissionWrapper.lWt);
intent.putExtra("hardcode_general_ctrl", GeneralControlWrapper.lWq);
intent.putExtra("neverGetA8Key", true);
intent.putExtra("key_load_js_without_delay", true);
intent.putExtra("ftsQuery", str);
intent.putExtra("ftsType", c);
Map a = h.a(c3, false, c);
a.put("query", str);
a.put("searchId", n3);
intent.putExtra("rawUrl", h.l(a));
com.tencent.mm.ay.c.b(aa.getContext(), "webview", ".ui.tools.fts.FTSSearchTabWebViewUI", intent);
} else {
switch (c2) {
case 2:
a(K(map), b);
break;
case 3:
c K = K(map);
if (!m.eC(K.username)) {
a(K, b);
break;
}
i.jF(K.username);
Intent intent3 = new Intent();
intent3.putExtra("Chat_User", K.username);
intent3.putExtra("finish_direct", true);
intent3.putExtra("key_temp_session_show_type", 0);
com.tencent.mm.ay.c.a(aa.getContext(), ".ui.chatting.ChattingUI", intent3);
break;
case 4:
str = c.n(map, "jumpUrl");
if (iVar != null) {
bundle = iVar.blC();
}
com.tencent.mm.plugin.webview.e.e.biZ();
b(str, bundle);
break;
default:
break;
}
}
}
Bundle blC;
n3 = c.n(map, "jumpUrl");
if (iVar != null) {
blC = iVar.blC();
} else {
blC = null;
}
com.tencent.mm.plugin.webview.e.e.biZ();
b(n3, blC);
return false;
}
public final boolean G(Map<String, Object> map) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "reportSearchRealTimeReport: %s", new Object[]{map.toString()});
aqn com_tencent_mm_protocal_c_aqn = new aqn();
com_tencent_mm_protocal_c_aqn.mPT = c.n(map, "logString");
ak.vy().a(1134, this);
ak.vy().a(new e(com_tencent_mm_protocal_c_aqn), 0);
return false;
}
private static void b(String str, Bundle bundle) {
Intent intent = new Intent();
intent.putExtra("rawUrl", str);
if (!(bundle == null || be.kS(str))) {
String str2 = bundle.getString("publishIdPrefix", "gs") + "_" + g.m(str.getBytes());
intent.putExtra("prePublishId", str2);
intent.putExtra("KPublisherId", str2);
}
com.tencent.mm.ay.c.b(aa.getContext(), "webview", ".ui.tools.WebViewUI", intent);
}
private static void a(c cVar, boolean z) {
int i;
if (cVar.bkI == 2) {
i = 89;
} else if (z) {
i = 85;
} else if (cVar.scene != 3 && cVar.scene != 16) {
i = 39;
} else if (cVar.ldz) {
i = 88;
} else {
i = 87;
}
i.jF(cVar.username);
Intent intent = new Intent();
intent.putExtra("Contact_User", cVar.username);
intent.putExtra("Contact_Nick", cVar.cID);
intent.putExtra("Contact_BrandIconURL", cVar.hUf);
intent.putExtra("Contact_Signature", cVar.bCj);
intent.putExtra("Contact_VUser_Info_Flag", cVar.ldy);
intent.putExtra("Contact_Scene", i);
if (cVar.hVh != null) {
try {
intent.putExtra("Contact_customInfo", cVar.hVh.toByteArray());
} catch (IOException e) {
}
}
Bundle bundle = new Bundle();
bundle.putString("Contact_Ext_Args_Search_Id", cVar.bpB);
bundle.putString("Contact_Ext_Args_Query_String", cVar.bkC);
bundle.putInt("Contact_Scene", i);
bundle.putInt("Contact_Ext_Args_Index", cVar.position);
bundle.putString("Contact_Ext_Extra_Params", cVar.ldA);
intent.putExtra("Contact_Ext_Args", bundle);
com.tencent.mm.ay.c.b(aa.getContext(), "profile", ".ui.ContactInfoUI", intent);
}
public static int b(Map<String, Object> map, Map<String, Object> map2) {
try {
JSONArray jSONArray = new JSONArray(c.n(map, "data"));
JSONArray jSONArray2 = new JSONArray();
for (int i = 0; i < jSONArray.length(); i++) {
JSONObject jSONObject = jSONArray.getJSONObject(i);
String string = jSONObject.getString("id");
String string2 = jSONObject.getString("userName");
String er = com.tencent.mm.model.l.er(string2);
JSONObject jSONObject2 = new JSONObject();
jSONObject2.put("id", string);
jSONObject2.put("userName", string2);
jSONObject2.put("displayName", er);
jSONArray2.put(jSONObject2);
}
map2.put("ret", Integer.valueOf(0));
map2.put("data", jSONArray2.toString());
} catch (JSONException e) {
}
return 0;
}
public static boolean H(Map<String, Object> map) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "getSearchImageList");
String n = c.n(map, "data");
int n2 = be.n(map.get("webview_instance_id"), -1);
try {
JSONArray jSONArray = new JSONArray(n);
JSONArray jSONArray2 = new JSONArray();
for (int i = 0; i < jSONArray.length(); i++) {
JSONObject jSONObject = jSONArray.getJSONObject(i);
JSONObject jSONObject2 = new JSONObject();
String string = jSONObject.getString("id");
String string2 = jSONObject.getString("imageUrl");
jSONObject2.put("id", string);
jSONObject2.put("src", string2);
jSONArray2.put(jSONObject2);
}
j.tl(n2).FG(jSONArray2.toString());
} catch (JSONException e) {
}
return false;
}
public final boolean I(Map<String, Object> map) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "getSearchAvatarList");
String n = c.n(map, "data");
int n2 = be.n(map.get("webview_instance_id"), -1);
try {
JSONArray jSONArray = new JSONArray(n);
JSONArray jSONArray2 = new JSONArray();
int i = 0;
Object obj = null;
while (i < jSONArray.length()) {
JSONObject jSONObject = jSONArray.getJSONObject(i);
String string = jSONObject.getString("id");
String string2 = jSONObject.getString("userName");
int i2 = jSONObject.getInt(Columns.TYPE);
Object string3 = jSONObject.getString("imageUrl");
String string4 = jSONObject.getString("bigImageUrl");
switch (i2) {
case 1:
case 4:
case 64:
break;
case JsApiStopRecordVoice.CTRL_INDEX /*32*/:
com.tencent.mm.u.h hVar = new com.tencent.mm.u.h();
hVar.username = string2;
hVar.cyD = string4;
hVar.cyC = string3;
hVar.bkU = -1;
hVar.bBY = 3;
hVar.aP(true);
n.Bo().a(hVar);
break;
}
n.AX();
n = com.tencent.mm.u.d.s(string2, false);
if (FileOp.aR(n)) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "avatar file exist %s", new Object[]{n});
string3 = "weixin://fts/avatar?path=" + n;
} else {
v.i("MicroMsg.FTS.FTSWebViewLogic", "avatar file not exist %s", new Object[]{n});
this.ldl.put(string2, Integer.valueOf(n2));
HashSet hashSet = (HashSet) this.ldj.get(string2);
if (hashSet == null) {
hashSet = new HashSet();
}
hashSet.add(string);
this.ldj.put(string2, hashSet);
com.tencent.mm.pluginsdk.ui.a.b.box().bg(string2);
string3 = obj;
}
if (string3 != null) {
JSONObject jSONObject2 = new JSONObject();
jSONObject2.put("id", string);
jSONObject2.put("src", string3);
jSONArray2.put(jSONObject2);
string3 = null;
}
i++;
obj = string3;
}
if (jSONArray2.length() > 0) {
j.tl(n2).FG(jSONArray2.toString());
}
} catch (JSONException e) {
}
return false;
}
public final boolean J(Map<String, Object> map) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "getSearchSnsImageList");
String n = c.n(map, "data");
int n2 = be.n(map.get("webview_instance_id"), -1);
try {
JSONArray jSONArray = new JSONArray(n);
JSONArray jSONArray2 = new JSONArray();
Object obj = null;
int i = 0;
while (i < jSONArray.length()) {
Object obj2;
JSONObject jSONObject = jSONArray.getJSONObject(i);
String string = jSONObject.getString("id");
String string2 = jSONObject.getString("objectXmlDesc");
int i2 = jSONObject.getInt("index");
azr ko = com.tencent.mm.modelsns.d.ko(string2);
if (ko.mWq.mom.size() > i2) {
aib com_tencent_mm_protocal_c_aib = (aib) ko.mWq.mom.get(i2);
nr nrVar = new nr();
nrVar.boK.aYt = 3;
nrVar.boK.mediaId = com_tencent_mm_protocal_c_aib.gID;
com.tencent.mm.sdk.c.a.nhr.z(nrVar);
v.i("MicroMsg.FTS.FTSWebViewLogic", "generatePath: %s", new Object[]{nrVar.boK.path});
if (FileOp.aR(nrVar.boK.path)) {
obj2 = "weixin://fts/sns?path=" + nrVar.boK.path;
} else {
synchronized (this.ldk) {
HashSet hashSet;
if (this.ldk.containsKey(com_tencent_mm_protocal_c_aib.gID)) {
hashSet = (HashSet) this.ldk.get(com_tencent_mm_protocal_c_aib.gID);
} else {
hashSet = new HashSet();
}
hashSet.add(string);
this.ldk.put(com_tencent_mm_protocal_c_aib.gID, hashSet);
this.ldm.put(com_tencent_mm_protocal_c_aib.gID, Integer.valueOf(n2));
}
nrVar = new nr();
nrVar.boK.aYt = 1;
nrVar.boK.boL = com_tencent_mm_protocal_c_aib;
com.tencent.mm.sdk.c.a.nhr.z(nrVar);
obj2 = obj;
}
if (obj2 != null) {
JSONObject jSONObject2 = new JSONObject();
jSONObject2.put("id", string);
jSONObject2.put("src", obj2);
jSONArray2.put(jSONObject2);
obj2 = null;
}
} else {
obj2 = obj;
}
i++;
obj = obj2;
}
if (jSONArray2.length() > 0) {
j.tl(n2).FG(jSONArray2.toString());
}
} catch (JSONException e) {
}
return false;
}
public final void a(int i, int i2, String str, k kVar) {
if (kVar instanceof s) {
ak.vy().b(1048, this);
if (i == 0 && i2 == 0) {
s sVar = (s) kVar;
b bVar = new b();
bVar.scene = sVar.scene;
bVar.ldw = (long) sVar.cWR.mHb;
bVar.bfi = sVar.cWR.min;
bVar.ldx = System.currentTimeMillis() / 1000;
bVar.bkJ = sVar.cWR.mzu;
bVar.type = sVar.cWS;
String cM = cM(bVar.scene, bVar.type);
if (!be.kS(bVar.bfi)) {
j.tl(sVar.bkE).b(0, bVar.bfi, 0);
v.i("MicroMsg.FTS.FTSWebViewLogic", "onTeachSearchDataReady, %s", new Object[]{bVar.bfi});
}
this.ldo.put(cM, bVar);
if (bVar.ldw == 0) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "delete biz cache %d %d", new Object[]{Integer.valueOf(bVar.scene), Integer.valueOf(bVar.type)});
ak.yW();
new File(com.tencent.mm.model.c.wV(), cM(r0, r2)).delete();
} else {
ahk com_tencent_mm_protocal_c_ahk = new ahk();
com_tencent_mm_protocal_c_ahk.scene = bVar.scene;
com_tencent_mm_protocal_c_ahk.min = bVar.bfi;
com_tencent_mm_protocal_c_ahk.mGW = bVar.ldw;
com_tencent_mm_protocal_c_ahk.mGX = bVar.ldx;
com_tencent_mm_protocal_c_ahk.miU = bVar.bkJ;
com_tencent_mm_protocal_c_ahk.efm = bVar.type;
byte[] bArr = null;
try {
bArr = com_tencent_mm_protocal_c_ahk.toByteArray();
} catch (IOException e) {
}
if (bArr != null) {
ak.yW();
File file = new File(com.tencent.mm.model.c.wV(), "FTS_BizCacheObj" + bVar.scene);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (file.exists()) {
file.delete();
}
com.tencent.mm.a.e.b(file.getAbsolutePath(), bArr, bArr.length);
v.i("MicroMsg.FTS.FTSWebViewLogic", "save bizCacheFile %s %d", new Object[]{file.getAbsolutePath(), Integer.valueOf(bArr.length)});
} else {
v.i("MicroMsg.FTS.FTSWebViewLogic", "save bizCacheFile fail");
}
}
l.a(bVar.scene, 1, bVar.bkJ, bVar.type, 1, "");
}
} else if (kVar instanceof e) {
ak.vy().b(1134, this);
}
}
private c K(Map<String, Object> map) {
c cVar = new c();
cVar.username = c.n(map, "userName");
cVar.cID = c.n(map, "nickName");
cVar.hUf = c.n(map, "headHDImgUrl");
cVar.ldy = c.c(map, "verifyFlag", 0);
cVar.bCj = c.n(map, "signature");
cVar.scene = c.c(map, "scene", 0);
cVar.bkI = c.c(map, "sceneActionType", 1);
cVar.hVh = new mc();
cVar.hVh.cHq = c.c(map, "brandFlag", 0);
cVar.hVh.cHt = c.n(map, "iconUrl");
cVar.hVh.cHs = c.n(map, "brandInfo");
cVar.hVh.cHr = c.n(map, "externalInfo");
cVar.bpB = c.n(map, "searchId");
cVar.bkC = c.n(map, "query");
cVar.position = c.c(map, "position", 0);
cVar.ldz = c.b(map, "isCurrentDetailPage", false);
cVar.ldA = c.n(map, "extraParams");
return cVar;
}
public final void a(String str, com.tencent.mm.sdk.h.i iVar) {
if (iVar != null && iVar.obj != null) {
synchronized (this.ldj) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "event %s,eventData %s", new Object[]{str, iVar.toString()});
String obj = iVar.obj.toString();
if (this.ldj.containsKey(obj) && this.ldl.containsKey(obj)) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "notify avatar changed %s", new Object[]{obj});
int intValue = ((Integer) this.ldl.get(obj)).intValue();
HashSet hashSet = (HashSet) this.ldj.get(obj);
JSONArray jSONArray = new JSONArray();
Iterator it = hashSet.iterator();
while (it.hasNext()) {
String str2 = (String) it.next();
n.AX();
String str3 = "weixin://fts/avatar?path=" + com.tencent.mm.u.d.s(obj, false);
JSONObject jSONObject = new JSONObject();
try {
jSONObject.put("id", str2);
jSONObject.put("src", str3);
} catch (JSONException e) {
}
jSONArray.put(jSONObject);
}
j.tl(intValue).FG(jSONArray.toString());
this.ldj.remove(obj);
this.ldl.remove(obj);
}
}
}
}
private static String cM(int i, int i2) {
return "FTS_BizCacheObj" + i + "-" + i2;
}
public static boolean L(Map<String, Object> map) {
v.i("MicroMsg.FTS.FTSWebViewLogic", "setSearchInputWord %s", new Object[]{map});
String n = c.n(map, "word");
boolean b = c.b(map, "isInputChange", false);
String n2 = c.n(map, "custom");
String n3 = c.n(map, "tagList");
com.tencent.mm.plugin.webview.ui.tools.jsapi.i tl = j.tl(be.n(map.get("webview_instance_id"), -1));
Bundle bundle = new Bundle();
bundle.putString("fts_key_new_query", n);
bundle.putString("fts_key_custom_query", n2);
bundle.putBoolean("fts_key_need_keyboard", b);
bundle.putString("fts_key_tag_list", n3);
try {
if (tl.leB != null) {
tl.leB.g(22, bundle);
}
} catch (RemoteException e) {
v.w("MicroMsg.MsgHandler", "onFTSSearchQueryChange exception" + e.getMessage());
}
return false;
}
}
| 36,173 | 0.465152 | 0.456802 | 849 | 41.60424 | 25.940336 | 201 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.025913 | false | false |
7
|
428dce7f1e4201361187633c5241133b2d702d6a
| 1,580,548,027,668 |
614435b298084c9eb9a5d01af716154f4e9a7019
|
/voguemovies/app/src/main/java/com/anshulvyas/android/voguemovies/data/MoviesRepository.java
|
c5f88f49b2cc102f740c3554116417a6c0d905ad
|
[
"Apache-2.0"
] |
permissive
|
av-7/vogue-movies
|
https://github.com/av-7/vogue-movies
|
60a7f0f4c431a4f6b8ebae6a8198c30859bec3bd
|
bd21fb5dfb9a80244a27a206160f5a553b190ae8
|
refs/heads/master
| 2018-10-14T16:48:28.985000 | 2018-07-28T21:47:54 | 2018-07-28T21:47:54 | 136,954,999 | 0 | 0 |
Apache-2.0
| false | 2018-07-27T00:01:19 | 2018-06-11T16:49:07 | 2018-07-23T23:36:08 | 2018-07-27T00:01:18 | 57,352 | 0 | 0 | 0 |
Java
| false | null |
package com.anshulvyas.android.voguemovies.data;
import android.app.Application;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.util.Log;
import com.anshulvyas.android.voguemovies.AppExecutors;
import com.anshulvyas.android.voguemovies.data.model.Movie;
import com.anshulvyas.android.voguemovies.data.model.MovieReviews;
import com.anshulvyas.android.voguemovies.data.model.MovieReviewsResponse;
import com.anshulvyas.android.voguemovies.data.model.MovieVideos;
import com.anshulvyas.android.voguemovies.data.model.MovieVideosResponse;
import com.anshulvyas.android.voguemovies.data.model.MoviesResponse;
import com.anshulvyas.android.voguemovies.data.source.local.FavoriteMoviesDao;
import com.anshulvyas.android.voguemovies.data.source.local.FavoriteMoviesDatabase;
import com.anshulvyas.android.voguemovies.data.source.remote.MoviesApiClient;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Movies Repository, provides abstraction to the data layer
*/
public class MoviesRepository {
private static final String LOG_TAG = MoviesRepository.class.getSimpleName();
private static MoviesRepository mMoviesRepositoryInstance = null;
private final MoviesApiClient mMoviesApiClient;
private final FavoriteMoviesDao mFavoriteMoviesDao;
public static MoviesRepository getInstance(Application application) {
if (mMoviesRepositoryInstance == null) {
mMoviesRepositoryInstance = new MoviesRepository(application);
}
return mMoviesRepositoryInstance;
}
private MoviesRepository(Application application) {
FavoriteMoviesDatabase database = FavoriteMoviesDatabase.getInstance(application);
mFavoriteMoviesDao = database.favoriteMoviesDao();
mMoviesApiClient = MoviesApiClient.getInstance();
}
/**
* Fetches the Popular Movies data from the MoviesApiService
*
* @return List<Movie>
*/
public LiveData<List<Movie>> getPopularMoviesLiveData() {
final MutableLiveData<List<Movie>> popularMoviesMutableLiveData = new MutableLiveData<>();
mMoviesApiClient.getMoviesApiHandler().getPopularMovies().enqueue(new Callback<MoviesResponse>() {
@Override
public void onResponse(Call<MoviesResponse> call, Response<MoviesResponse> response) {
popularMoviesMutableLiveData.setValue(fetchPopularMovies(response));
Log.d(LOG_TAG, popularMoviesMutableLiveData.toString());
}
@Override
public void onFailure(Call<MoviesResponse> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});
return popularMoviesMutableLiveData;
}
private List<Movie> fetchPopularMovies(Response<MoviesResponse> popularMoviesResponse) {
List<Movie> popularMovies = new ArrayList<>();
if (popularMoviesResponse.body() != null && popularMoviesResponse.body().getResults() != null) {
popularMovies = popularMoviesResponse.body().getResults();
}
return popularMovies;
}
/**
* Fetches the Top-Rated Movies data from the MoviesApiService
*
* @return List<Movie>
*/
public LiveData<List<Movie>> getTopRatedMoviesLiveData() {
final MutableLiveData<List<Movie>> topRatedMoviesMutableLiveData = new MutableLiveData<>();
mMoviesApiClient.getMoviesApiHandler().getTopRatedMovies().enqueue(new Callback<MoviesResponse>() {
@Override
public void onResponse(Call<MoviesResponse> call, Response<MoviesResponse> response) {
topRatedMoviesMutableLiveData.setValue(fetchTopRatedMovies(response));
Log.d(LOG_TAG, topRatedMoviesMutableLiveData.toString());
}
@Override
public void onFailure(Call<MoviesResponse> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});
return topRatedMoviesMutableLiveData;
}
private List<Movie> fetchTopRatedMovies(Response<MoviesResponse> topRatedMoviesResponse) {
List<Movie> topRatedMovies = new ArrayList<>();
if (topRatedMoviesResponse.body() != null && topRatedMoviesResponse.body().getResults() != null) {
topRatedMovies = topRatedMoviesResponse.body().getResults();
}
return topRatedMovies;
}
public LiveData<List<MovieVideos>> getVideosFromMovieId (int movieId) {
final MutableLiveData<List<MovieVideos>> movieVideosMutableLiveData = new MutableLiveData<>();
mMoviesApiClient.getMoviesApiHandler().getVideosFromMovieId(movieId).enqueue(new Callback<MovieVideosResponse>() {
@Override
public void onResponse(Call<MovieVideosResponse> call, Response<MovieVideosResponse> response) {
movieVideosMutableLiveData.setValue(fetchMovieVideos(response));
Log.d(LOG_TAG, movieVideosMutableLiveData.toString());
}
@Override
public void onFailure(Call<MovieVideosResponse> call, Throwable t) {
Log.d(LOG_TAG, t.toString());
}
});
return movieVideosMutableLiveData;
}
private List<MovieVideos> fetchMovieVideos(Response<MovieVideosResponse> movieVideosResponse) {
List<MovieVideos> movieVideosList = new ArrayList<>();
if (movieVideosResponse.body() != null && movieVideosResponse.body().getResults() != null) {
movieVideosList = movieVideosResponse.body().getResults();
}
return movieVideosList;
}
public LiveData<List<MovieReviews>> getReviewsFromMovieId (int movieId) {
final MutableLiveData<List<MovieReviews>> movieReviewsMutableLiveData = new MutableLiveData<>();
mMoviesApiClient.getMoviesApiHandler().getReviewsFromMovieId(movieId).enqueue(new Callback<MovieReviewsResponse>() {
@Override
public void onResponse(Call<MovieReviewsResponse> call, Response<MovieReviewsResponse> response) {
movieReviewsMutableLiveData.setValue(fetchMovieReviews(response));
Log.d(LOG_TAG, movieReviewsMutableLiveData.toString());
}
@Override
public void onFailure(Call<MovieReviewsResponse> call, Throwable t) {
Log.d(LOG_TAG, t.toString());
}
});
return movieReviewsMutableLiveData;
}
private List<MovieReviews> fetchMovieReviews (Response<MovieReviewsResponse> movieReviewsResponse) {
List<MovieReviews> movieReviewsList = new ArrayList<>();
if (movieReviewsResponse.body() != null && movieReviewsResponse.body().getResults() != null) {
movieReviewsList = movieReviewsResponse.body().getResults();
}
return movieReviewsList;
}
public LiveData<List<Movie>> getFavoriteMoviesLiveData() {
return mFavoriteMoviesDao.getFavoriteMovies();
}
public LiveData<Movie> getFavoriteMovieById (int movieId) {
return mFavoriteMoviesDao.getMovieById(movieId);
}
public void toggleFavoriteMovie (Movie movie) {
AppExecutors.getInstance().diskIO().execute(() -> {
boolean isFavorite = mFavoriteMoviesDao.isFavoriteMovie(movie.getMovieId());
if (isFavorite) {
deleteFavoriteMovie(movie);
} else {
insertFavoriteMovie(movie);
}
});
}
private void insertFavoriteMovie (Movie movie) {
AppExecutors.getInstance().diskIO().execute(() -> mFavoriteMoviesDao.insertMovie(movie));
}
private void deleteFavoriteMovie (Movie movie) {
AppExecutors.getInstance().diskIO().execute(() -> mFavoriteMoviesDao.deleteMovie(movie));
}
}
|
UTF-8
|
Java
| 7,906 |
java
|
MoviesRepository.java
|
Java
|
[] | null |
[] |
package com.anshulvyas.android.voguemovies.data;
import android.app.Application;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.util.Log;
import com.anshulvyas.android.voguemovies.AppExecutors;
import com.anshulvyas.android.voguemovies.data.model.Movie;
import com.anshulvyas.android.voguemovies.data.model.MovieReviews;
import com.anshulvyas.android.voguemovies.data.model.MovieReviewsResponse;
import com.anshulvyas.android.voguemovies.data.model.MovieVideos;
import com.anshulvyas.android.voguemovies.data.model.MovieVideosResponse;
import com.anshulvyas.android.voguemovies.data.model.MoviesResponse;
import com.anshulvyas.android.voguemovies.data.source.local.FavoriteMoviesDao;
import com.anshulvyas.android.voguemovies.data.source.local.FavoriteMoviesDatabase;
import com.anshulvyas.android.voguemovies.data.source.remote.MoviesApiClient;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Movies Repository, provides abstraction to the data layer
*/
public class MoviesRepository {
private static final String LOG_TAG = MoviesRepository.class.getSimpleName();
private static MoviesRepository mMoviesRepositoryInstance = null;
private final MoviesApiClient mMoviesApiClient;
private final FavoriteMoviesDao mFavoriteMoviesDao;
public static MoviesRepository getInstance(Application application) {
if (mMoviesRepositoryInstance == null) {
mMoviesRepositoryInstance = new MoviesRepository(application);
}
return mMoviesRepositoryInstance;
}
private MoviesRepository(Application application) {
FavoriteMoviesDatabase database = FavoriteMoviesDatabase.getInstance(application);
mFavoriteMoviesDao = database.favoriteMoviesDao();
mMoviesApiClient = MoviesApiClient.getInstance();
}
/**
* Fetches the Popular Movies data from the MoviesApiService
*
* @return List<Movie>
*/
public LiveData<List<Movie>> getPopularMoviesLiveData() {
final MutableLiveData<List<Movie>> popularMoviesMutableLiveData = new MutableLiveData<>();
mMoviesApiClient.getMoviesApiHandler().getPopularMovies().enqueue(new Callback<MoviesResponse>() {
@Override
public void onResponse(Call<MoviesResponse> call, Response<MoviesResponse> response) {
popularMoviesMutableLiveData.setValue(fetchPopularMovies(response));
Log.d(LOG_TAG, popularMoviesMutableLiveData.toString());
}
@Override
public void onFailure(Call<MoviesResponse> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});
return popularMoviesMutableLiveData;
}
private List<Movie> fetchPopularMovies(Response<MoviesResponse> popularMoviesResponse) {
List<Movie> popularMovies = new ArrayList<>();
if (popularMoviesResponse.body() != null && popularMoviesResponse.body().getResults() != null) {
popularMovies = popularMoviesResponse.body().getResults();
}
return popularMovies;
}
/**
* Fetches the Top-Rated Movies data from the MoviesApiService
*
* @return List<Movie>
*/
public LiveData<List<Movie>> getTopRatedMoviesLiveData() {
final MutableLiveData<List<Movie>> topRatedMoviesMutableLiveData = new MutableLiveData<>();
mMoviesApiClient.getMoviesApiHandler().getTopRatedMovies().enqueue(new Callback<MoviesResponse>() {
@Override
public void onResponse(Call<MoviesResponse> call, Response<MoviesResponse> response) {
topRatedMoviesMutableLiveData.setValue(fetchTopRatedMovies(response));
Log.d(LOG_TAG, topRatedMoviesMutableLiveData.toString());
}
@Override
public void onFailure(Call<MoviesResponse> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});
return topRatedMoviesMutableLiveData;
}
private List<Movie> fetchTopRatedMovies(Response<MoviesResponse> topRatedMoviesResponse) {
List<Movie> topRatedMovies = new ArrayList<>();
if (topRatedMoviesResponse.body() != null && topRatedMoviesResponse.body().getResults() != null) {
topRatedMovies = topRatedMoviesResponse.body().getResults();
}
return topRatedMovies;
}
public LiveData<List<MovieVideos>> getVideosFromMovieId (int movieId) {
final MutableLiveData<List<MovieVideos>> movieVideosMutableLiveData = new MutableLiveData<>();
mMoviesApiClient.getMoviesApiHandler().getVideosFromMovieId(movieId).enqueue(new Callback<MovieVideosResponse>() {
@Override
public void onResponse(Call<MovieVideosResponse> call, Response<MovieVideosResponse> response) {
movieVideosMutableLiveData.setValue(fetchMovieVideos(response));
Log.d(LOG_TAG, movieVideosMutableLiveData.toString());
}
@Override
public void onFailure(Call<MovieVideosResponse> call, Throwable t) {
Log.d(LOG_TAG, t.toString());
}
});
return movieVideosMutableLiveData;
}
private List<MovieVideos> fetchMovieVideos(Response<MovieVideosResponse> movieVideosResponse) {
List<MovieVideos> movieVideosList = new ArrayList<>();
if (movieVideosResponse.body() != null && movieVideosResponse.body().getResults() != null) {
movieVideosList = movieVideosResponse.body().getResults();
}
return movieVideosList;
}
public LiveData<List<MovieReviews>> getReviewsFromMovieId (int movieId) {
final MutableLiveData<List<MovieReviews>> movieReviewsMutableLiveData = new MutableLiveData<>();
mMoviesApiClient.getMoviesApiHandler().getReviewsFromMovieId(movieId).enqueue(new Callback<MovieReviewsResponse>() {
@Override
public void onResponse(Call<MovieReviewsResponse> call, Response<MovieReviewsResponse> response) {
movieReviewsMutableLiveData.setValue(fetchMovieReviews(response));
Log.d(LOG_TAG, movieReviewsMutableLiveData.toString());
}
@Override
public void onFailure(Call<MovieReviewsResponse> call, Throwable t) {
Log.d(LOG_TAG, t.toString());
}
});
return movieReviewsMutableLiveData;
}
private List<MovieReviews> fetchMovieReviews (Response<MovieReviewsResponse> movieReviewsResponse) {
List<MovieReviews> movieReviewsList = new ArrayList<>();
if (movieReviewsResponse.body() != null && movieReviewsResponse.body().getResults() != null) {
movieReviewsList = movieReviewsResponse.body().getResults();
}
return movieReviewsList;
}
public LiveData<List<Movie>> getFavoriteMoviesLiveData() {
return mFavoriteMoviesDao.getFavoriteMovies();
}
public LiveData<Movie> getFavoriteMovieById (int movieId) {
return mFavoriteMoviesDao.getMovieById(movieId);
}
public void toggleFavoriteMovie (Movie movie) {
AppExecutors.getInstance().diskIO().execute(() -> {
boolean isFavorite = mFavoriteMoviesDao.isFavoriteMovie(movie.getMovieId());
if (isFavorite) {
deleteFavoriteMovie(movie);
} else {
insertFavoriteMovie(movie);
}
});
}
private void insertFavoriteMovie (Movie movie) {
AppExecutors.getInstance().diskIO().execute(() -> mFavoriteMoviesDao.insertMovie(movie));
}
private void deleteFavoriteMovie (Movie movie) {
AppExecutors.getInstance().diskIO().execute(() -> mFavoriteMoviesDao.deleteMovie(movie));
}
}
| 7,906 | 0.689097 | 0.688717 | 199 | 38.728642 | 35.62714 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.452261 | false | false |
7
|
6096b35bd0c58e7b11ab05ed19e9e504cf067e00
| 29,987,461,724,021 |
b5e234d941697acd1784cad05d4135f01117c289
|
/Project2/src/ChartBuilder.java
|
8eb94f53f7836495471c79f73124db91aacc0bb9
|
[] |
no_license
|
ksdorsett/Project2
|
https://github.com/ksdorsett/Project2
|
4f04ca575d9c4c4b76f7615f6ff4c5bc7bd1b011
|
47748fcee5bfef60854b7aaf157b0628af5497af
|
refs/heads/master
| 2021-01-24T11:36:10.192000 | 2016-11-03T14:48:25 | 2016-11-03T14:48:25 | 70,212,627 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
//Kevin Dorsett
//Project 1
//Software Engineering
import java.util.Scanner;
import csci348.drawings.SimpleDrawing;
/**
*
* @author kdorsett
*/
public class ChartBuilder{
static void drawLineOutside(Board board){
if(board.getSize().getWidth()+20<=SimpleDrawing.MAX_WIDTH){
board.addShape(new Line((int)board.getSize().getWidth()+10, 0, (int)board.getSize().getWidth()+10, (int)board.getSize().getHeight()));
System.out.println("Line drawn outside frame from ("+((int)board.getSize().getWidth()+10)+", 0) to "+((int)board.getSize().getWidth()+10)+", "+(int)board.getSize().getHeight()+").");
}else if(board.getSize().getHeight()+20<=SimpleDrawing.MAX_HEIGHT){
board.addShape(new Line(0,(int)board.getSize().getHeight()+10, (int)board.getSize().getWidth(), (int)board.getSize().getHeight()+10));
System.out.println("Line drawn outside frame from (0, "+((int)board.getSize().getHeight()+10)+") to ("+(int)board.getSize().getWidth()+", "+((int)board.getSize().getHeight()+10)+").");
}else{
System.out.println("Cannot draw line outside screen, screen is too big.");
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
while(true){
System.out.println("What size window would you like? Type a width and height...");
int WIDTH=scan.nextInt();
int HEIGHT=scan.nextInt();
if (WIDTH>SimpleDrawing.MAX_WIDTH){
System.out.println("Width cannot be greater than "+SimpleDrawing.MAX_WIDTH);
}
if (HEIGHT>SimpleDrawing.MAX_HEIGHT){
System.out.println("Height cannot be greater than "+SimpleDrawing.MAX_HEIGHT);
}
if (!(WIDTH>SimpleDrawing.MAX_WIDTH)&&!(HEIGHT>SimpleDrawing.MAX_HEIGHT)){
Board testBoard=new Board(WIDTH,HEIGHT);
drawLineOutside(testBoard);
System.out.println("Click on the tools to draw shapes. \n"
+ "Most shapes are drawn by clicking two locations. \n"
+ "Parallelograms are drawn by clicking three.\n"
+ "When no tool is selected left click to delete the top shape at a point\n"
+ "or right click to delete all shapes at a point.\n"
+ "Type a foreground and background color then press enter to change the colors.\n"
+ "Type stop to stop changing colors.");
while(true){
String foreground=scan.next();
if (foreground.equals("stop")){break;}
String background=scan.next();
if (background.equals("stop")){break;}
testBoard.changeColors(foreground,background);
}
System.out.println("No longer changing colors.");
scan.close();
break;
}
}
}
}
|
UTF-8
|
Java
| 2,727 |
java
|
ChartBuilder.java
|
Java
|
[
{
"context": "//Kevin Dorsett\n//Project 1\n//Software Engineering\n\nimport java.u",
"end": 15,
"score": 0.9998905062675476,
"start": 2,
"tag": "NAME",
"value": "Kevin Dorsett"
},
{
"context": "csci348.drawings.SimpleDrawing;\n\n/**\n *\n * @author kdorsett\n */\n\n\npublic class ChartBuilder{\n\tstatic void dra",
"end": 145,
"score": 0.9995762705802917,
"start": 137,
"tag": "USERNAME",
"value": "kdorsett"
}
] | null |
[] |
//<NAME>
//Project 1
//Software Engineering
import java.util.Scanner;
import csci348.drawings.SimpleDrawing;
/**
*
* @author kdorsett
*/
public class ChartBuilder{
static void drawLineOutside(Board board){
if(board.getSize().getWidth()+20<=SimpleDrawing.MAX_WIDTH){
board.addShape(new Line((int)board.getSize().getWidth()+10, 0, (int)board.getSize().getWidth()+10, (int)board.getSize().getHeight()));
System.out.println("Line drawn outside frame from ("+((int)board.getSize().getWidth()+10)+", 0) to "+((int)board.getSize().getWidth()+10)+", "+(int)board.getSize().getHeight()+").");
}else if(board.getSize().getHeight()+20<=SimpleDrawing.MAX_HEIGHT){
board.addShape(new Line(0,(int)board.getSize().getHeight()+10, (int)board.getSize().getWidth(), (int)board.getSize().getHeight()+10));
System.out.println("Line drawn outside frame from (0, "+((int)board.getSize().getHeight()+10)+") to ("+(int)board.getSize().getWidth()+", "+((int)board.getSize().getHeight()+10)+").");
}else{
System.out.println("Cannot draw line outside screen, screen is too big.");
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
while(true){
System.out.println("What size window would you like? Type a width and height...");
int WIDTH=scan.nextInt();
int HEIGHT=scan.nextInt();
if (WIDTH>SimpleDrawing.MAX_WIDTH){
System.out.println("Width cannot be greater than "+SimpleDrawing.MAX_WIDTH);
}
if (HEIGHT>SimpleDrawing.MAX_HEIGHT){
System.out.println("Height cannot be greater than "+SimpleDrawing.MAX_HEIGHT);
}
if (!(WIDTH>SimpleDrawing.MAX_WIDTH)&&!(HEIGHT>SimpleDrawing.MAX_HEIGHT)){
Board testBoard=new Board(WIDTH,HEIGHT);
drawLineOutside(testBoard);
System.out.println("Click on the tools to draw shapes. \n"
+ "Most shapes are drawn by clicking two locations. \n"
+ "Parallelograms are drawn by clicking three.\n"
+ "When no tool is selected left click to delete the top shape at a point\n"
+ "or right click to delete all shapes at a point.\n"
+ "Type a foreground and background color then press enter to change the colors.\n"
+ "Type stop to stop changing colors.");
while(true){
String foreground=scan.next();
if (foreground.equals("stop")){break;}
String background=scan.next();
if (background.equals("stop")){break;}
testBoard.changeColors(foreground,background);
}
System.out.println("No longer changing colors.");
scan.close();
break;
}
}
}
}
| 2,720 | 0.645765 | 0.635497 | 67 | 39.716419 | 41.208538 | 187 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.686567 | false | false |
7
|
0352c1c1ed56e6f3357b8c90f6a97e487a38d1d9
| 11,605,001,647,532 |
95c49f466673952b465e19a5ee3ae6eff76bee00
|
/src/main/java/com/zhihu/android/videox/api/model/Statement.java
|
b1fd9f729fb469b853eb764c7547ca50a2c8af49
|
[] |
no_license
|
Phantoms007/zhihuAPK
|
https://github.com/Phantoms007/zhihuAPK
|
58889c399ae56b16a9160a5f48b807e02c87797e
|
dcdbd103436a187f9c8b4be8f71bdf7813b6d201
|
refs/heads/main
| 2023-01-24T01:34:18.716000 | 2020-11-25T17:14:55 | 2020-11-25T17:14:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.zhihu.android.videox.api.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.fasterxml.jackson.p518a.JsonProperty;
import com.secneo.apkwrapper.C6969H;
import kotlin.Metadata;
import kotlin.p2243e.p2245b.C32569u;
import kotlin.p2243e.p2245b.DefaultConstructorMarker;
@Metadata
/* compiled from: Statement.kt */
public final class Statement implements Parcelable {
public static final Parcelable.Creator<Statement> CREATOR = new Statement$Companion$CREATOR$1();
public static final Companion Companion = new Companion(null);
private LivePeople author;
private int campType;
private String content;
private Integer contentType;
/* renamed from: id */
private String f96614id;
private Boolean isVoted;
private Integer replyState;
private Integer type;
private long voteCount;
public Statement() {
this(null, null, null, null, null, null, null, 0, 0, 511, null);
}
public static /* synthetic */ Statement copy$default(Statement statement, LivePeople livePeople, String str, Integer num, String str2, Boolean bool, Integer num2, Integer num3, long j, int i, int i2, Object obj) {
return statement.copy((i2 & 1) != 0 ? statement.author : livePeople, (i2 & 2) != 0 ? statement.content : str, (i2 & 4) != 0 ? statement.contentType : num, (i2 & 8) != 0 ? statement.f96614id : str2, (i2 & 16) != 0 ? statement.isVoted : bool, (i2 & 32) != 0 ? statement.replyState : num2, (i2 & 64) != 0 ? statement.type : num3, (i2 & 128) != 0 ? statement.voteCount : j, (i2 & 256) != 0 ? statement.campType : i);
}
public final LivePeople component1() {
return this.author;
}
public final String component2() {
return this.content;
}
public final Integer component3() {
return this.contentType;
}
public final String component4() {
return this.f96614id;
}
public final Boolean component5() {
return this.isVoted;
}
public final Integer component6() {
return this.replyState;
}
public final Integer component7() {
return this.type;
}
public final long component8() {
return this.voteCount;
}
public final int component9() {
return this.campType;
}
public final Statement copy(@JsonProperty(mo29184a = "author") LivePeople livePeople, @JsonProperty(mo29184a = "content") String str, @JsonProperty(mo29184a = "content_type") Integer num, @JsonProperty(mo29184a = "id") String str2, @JsonProperty(mo29184a = "is_voted") Boolean bool, @JsonProperty(mo29184a = "reply_state") Integer num2, @JsonProperty(mo29184a = "type") Integer num3, @JsonProperty(mo29184a = "vote_count") long j, @JsonProperty(mo29184a = "camp_type") int i) {
return new Statement(livePeople, str, num, str2, bool, num2, num3, j, i);
}
public int describeContents() {
return 0;
}
public boolean equals(Object obj) {
if (this != obj) {
if (obj instanceof Statement) {
Statement statement = (Statement) obj;
if (C32569u.m150517a(this.author, statement.author) && C32569u.m150517a((Object) this.content, (Object) statement.content) && C32569u.m150517a(this.contentType, statement.contentType) && C32569u.m150517a((Object) this.f96614id, (Object) statement.f96614id) && C32569u.m150517a(this.isVoted, statement.isVoted) && C32569u.m150517a(this.replyState, statement.replyState) && C32569u.m150517a(this.type, statement.type)) {
if (this.voteCount == statement.voteCount) {
if (this.campType == statement.campType) {
return true;
}
}
}
}
return false;
}
return true;
}
public int hashCode() {
LivePeople livePeople = this.author;
int i = 0;
int hashCode = (livePeople != null ? livePeople.hashCode() : 0) * 31;
String str = this.content;
int hashCode2 = (hashCode + (str != null ? str.hashCode() : 0)) * 31;
Integer num = this.contentType;
int hashCode3 = (hashCode2 + (num != null ? num.hashCode() : 0)) * 31;
String str2 = this.f96614id;
int hashCode4 = (hashCode3 + (str2 != null ? str2.hashCode() : 0)) * 31;
Boolean bool = this.isVoted;
int hashCode5 = (hashCode4 + (bool != null ? bool.hashCode() : 0)) * 31;
Integer num2 = this.replyState;
int hashCode6 = (hashCode5 + (num2 != null ? num2.hashCode() : 0)) * 31;
Integer num3 = this.type;
if (num3 != null) {
i = num3.hashCode();
}
long j = this.voteCount;
return ((((hashCode6 + i) * 31) + ((int) (j ^ (j >>> 32)))) * 31) + this.campType;
}
public String toString() {
return C6969H.m41409d("G5A97D40EBA3DAE27F246915DE6EDCCC534") + this.author + C6969H.m41409d("G25C3D615B124AE27F253") + this.content + C6969H.m41409d("G25C3D615B124AE27F23A8958F7B8") + this.contentType + C6969H.m41409d("G25C3DC1EE2") + this.f96614id + C6969H.m41409d("G25C3DC09893FBF2CE253") + this.isVoted + C6969H.m41409d("G25C3C71FAF3CB21AF20F844DAF") + this.replyState + C6969H.m41409d("G25C3C103AF35F6") + this.type + C6969H.m41409d("G25C3C315AB358826F3008415") + this.voteCount + C6969H.m41409d("G25C3D61BB2209F30F60BCD") + this.campType + ")";
}
public Statement(@JsonProperty(mo29184a = "author") LivePeople livePeople, @JsonProperty(mo29184a = "content") String str, @JsonProperty(mo29184a = "content_type") Integer num, @JsonProperty(mo29184a = "id") String str2, @JsonProperty(mo29184a = "is_voted") Boolean bool, @JsonProperty(mo29184a = "reply_state") Integer num2, @JsonProperty(mo29184a = "type") Integer num3, @JsonProperty(mo29184a = "vote_count") long j, @JsonProperty(mo29184a = "camp_type") int i) {
this.author = livePeople;
this.content = str;
this.contentType = num;
this.f96614id = str2;
this.isVoted = bool;
this.replyState = num2;
this.type = num3;
this.voteCount = j;
this.campType = i;
}
/* JADX INFO: this call moved to the top of the method (can break code semantics) */
public /* synthetic */ Statement(LivePeople livePeople, String str, Integer num, String str2, Boolean bool, Integer num2, Integer num3, long j, int i, int i2, DefaultConstructorMarker pVar) {
this((i2 & 1) != 0 ? null : livePeople, (i2 & 2) != 0 ? null : str, (i2 & 4) != 0 ? null : num, (i2 & 8) != 0 ? null : str2, (i2 & 16) != 0 ? null : bool, (i2 & 32) != 0 ? null : num2, (i2 & 64) != 0 ? null : num3, (i2 & 128) != 0 ? 0 : j, (i2 & 256) != 0 ? 0 : i);
}
public final LivePeople getAuthor() {
return this.author;
}
public final void setAuthor(LivePeople livePeople) {
this.author = livePeople;
}
public final String getContent() {
return this.content;
}
public final void setContent(String str) {
this.content = str;
}
public final Integer getContentType() {
return this.contentType;
}
public final void setContentType(Integer num) {
this.contentType = num;
}
public final String getId() {
return this.f96614id;
}
public final void setId(String str) {
this.f96614id = str;
}
public final Boolean isVoted() {
return this.isVoted;
}
public final void setVoted(Boolean bool) {
this.isVoted = bool;
}
public final Integer getReplyState() {
return this.replyState;
}
public final void setReplyState(Integer num) {
this.replyState = num;
}
public final Integer getType() {
return this.type;
}
public final void setType(Integer num) {
this.type = num;
}
public final long getVoteCount() {
return this.voteCount;
}
public final void setVoteCount(long j) {
this.voteCount = j;
}
public final int getCampType() {
return this.campType;
}
public final void setCampType(int i) {
this.campType = i;
}
/* JADX INFO: this call moved to the top of the method (can break code semantics) */
public Statement(Parcel parcel) {
this((LivePeople) parcel.readParcelable(LivePeople.class.getClassLoader()), parcel.readString(), (Integer) parcel.readValue(Integer.TYPE.getClassLoader()), parcel.readString(), (Boolean) parcel.readValue(Boolean.TYPE.getClassLoader()), (Integer) parcel.readValue(Integer.TYPE.getClassLoader()), (Integer) parcel.readValue(Integer.TYPE.getClassLoader()), parcel.readLong(), parcel.readInt());
C32569u.m150519b(parcel, C6969H.m41409d("G7A8CC008BC35"));
}
public void writeToParcel(Parcel parcel, int i) {
C32569u.m150519b(parcel, "dest");
parcel.writeParcelable(this.author, 0);
parcel.writeString(this.content);
parcel.writeValue(this.contentType);
parcel.writeString(this.f96614id);
parcel.writeValue(this.isVoted);
parcel.writeValue(this.replyState);
parcel.writeValue(this.type);
parcel.writeLong(this.voteCount);
parcel.writeInt(this.campType);
}
@Metadata
/* compiled from: Statement.kt */
public static final class Companion {
private Companion() {
}
public /* synthetic */ Companion(DefaultConstructorMarker pVar) {
this();
}
}
}
|
UTF-8
|
Java
| 9,518 |
java
|
Statement.java
|
Java
|
[] | null |
[] |
package com.zhihu.android.videox.api.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.fasterxml.jackson.p518a.JsonProperty;
import com.secneo.apkwrapper.C6969H;
import kotlin.Metadata;
import kotlin.p2243e.p2245b.C32569u;
import kotlin.p2243e.p2245b.DefaultConstructorMarker;
@Metadata
/* compiled from: Statement.kt */
public final class Statement implements Parcelable {
public static final Parcelable.Creator<Statement> CREATOR = new Statement$Companion$CREATOR$1();
public static final Companion Companion = new Companion(null);
private LivePeople author;
private int campType;
private String content;
private Integer contentType;
/* renamed from: id */
private String f96614id;
private Boolean isVoted;
private Integer replyState;
private Integer type;
private long voteCount;
public Statement() {
this(null, null, null, null, null, null, null, 0, 0, 511, null);
}
public static /* synthetic */ Statement copy$default(Statement statement, LivePeople livePeople, String str, Integer num, String str2, Boolean bool, Integer num2, Integer num3, long j, int i, int i2, Object obj) {
return statement.copy((i2 & 1) != 0 ? statement.author : livePeople, (i2 & 2) != 0 ? statement.content : str, (i2 & 4) != 0 ? statement.contentType : num, (i2 & 8) != 0 ? statement.f96614id : str2, (i2 & 16) != 0 ? statement.isVoted : bool, (i2 & 32) != 0 ? statement.replyState : num2, (i2 & 64) != 0 ? statement.type : num3, (i2 & 128) != 0 ? statement.voteCount : j, (i2 & 256) != 0 ? statement.campType : i);
}
public final LivePeople component1() {
return this.author;
}
public final String component2() {
return this.content;
}
public final Integer component3() {
return this.contentType;
}
public final String component4() {
return this.f96614id;
}
public final Boolean component5() {
return this.isVoted;
}
public final Integer component6() {
return this.replyState;
}
public final Integer component7() {
return this.type;
}
public final long component8() {
return this.voteCount;
}
public final int component9() {
return this.campType;
}
public final Statement copy(@JsonProperty(mo29184a = "author") LivePeople livePeople, @JsonProperty(mo29184a = "content") String str, @JsonProperty(mo29184a = "content_type") Integer num, @JsonProperty(mo29184a = "id") String str2, @JsonProperty(mo29184a = "is_voted") Boolean bool, @JsonProperty(mo29184a = "reply_state") Integer num2, @JsonProperty(mo29184a = "type") Integer num3, @JsonProperty(mo29184a = "vote_count") long j, @JsonProperty(mo29184a = "camp_type") int i) {
return new Statement(livePeople, str, num, str2, bool, num2, num3, j, i);
}
public int describeContents() {
return 0;
}
public boolean equals(Object obj) {
if (this != obj) {
if (obj instanceof Statement) {
Statement statement = (Statement) obj;
if (C32569u.m150517a(this.author, statement.author) && C32569u.m150517a((Object) this.content, (Object) statement.content) && C32569u.m150517a(this.contentType, statement.contentType) && C32569u.m150517a((Object) this.f96614id, (Object) statement.f96614id) && C32569u.m150517a(this.isVoted, statement.isVoted) && C32569u.m150517a(this.replyState, statement.replyState) && C32569u.m150517a(this.type, statement.type)) {
if (this.voteCount == statement.voteCount) {
if (this.campType == statement.campType) {
return true;
}
}
}
}
return false;
}
return true;
}
public int hashCode() {
LivePeople livePeople = this.author;
int i = 0;
int hashCode = (livePeople != null ? livePeople.hashCode() : 0) * 31;
String str = this.content;
int hashCode2 = (hashCode + (str != null ? str.hashCode() : 0)) * 31;
Integer num = this.contentType;
int hashCode3 = (hashCode2 + (num != null ? num.hashCode() : 0)) * 31;
String str2 = this.f96614id;
int hashCode4 = (hashCode3 + (str2 != null ? str2.hashCode() : 0)) * 31;
Boolean bool = this.isVoted;
int hashCode5 = (hashCode4 + (bool != null ? bool.hashCode() : 0)) * 31;
Integer num2 = this.replyState;
int hashCode6 = (hashCode5 + (num2 != null ? num2.hashCode() : 0)) * 31;
Integer num3 = this.type;
if (num3 != null) {
i = num3.hashCode();
}
long j = this.voteCount;
return ((((hashCode6 + i) * 31) + ((int) (j ^ (j >>> 32)))) * 31) + this.campType;
}
public String toString() {
return C6969H.m41409d("G5A97D40EBA3DAE27F246915DE6EDCCC534") + this.author + C6969H.m41409d("G25C3D615B124AE27F253") + this.content + C6969H.m41409d("G25C3D615B124AE27F23A8958F7B8") + this.contentType + C6969H.m41409d("G25C3DC1EE2") + this.f96614id + C6969H.m41409d("G25C3DC09893FBF2CE253") + this.isVoted + C6969H.m41409d("G25C3C71FAF3CB21AF20F844DAF") + this.replyState + C6969H.m41409d("G25C3C103AF35F6") + this.type + C6969H.m41409d("G25C3C315AB358826F3008415") + this.voteCount + C6969H.m41409d("G25C3D61BB2209F30F60BCD") + this.campType + ")";
}
public Statement(@JsonProperty(mo29184a = "author") LivePeople livePeople, @JsonProperty(mo29184a = "content") String str, @JsonProperty(mo29184a = "content_type") Integer num, @JsonProperty(mo29184a = "id") String str2, @JsonProperty(mo29184a = "is_voted") Boolean bool, @JsonProperty(mo29184a = "reply_state") Integer num2, @JsonProperty(mo29184a = "type") Integer num3, @JsonProperty(mo29184a = "vote_count") long j, @JsonProperty(mo29184a = "camp_type") int i) {
this.author = livePeople;
this.content = str;
this.contentType = num;
this.f96614id = str2;
this.isVoted = bool;
this.replyState = num2;
this.type = num3;
this.voteCount = j;
this.campType = i;
}
/* JADX INFO: this call moved to the top of the method (can break code semantics) */
public /* synthetic */ Statement(LivePeople livePeople, String str, Integer num, String str2, Boolean bool, Integer num2, Integer num3, long j, int i, int i2, DefaultConstructorMarker pVar) {
this((i2 & 1) != 0 ? null : livePeople, (i2 & 2) != 0 ? null : str, (i2 & 4) != 0 ? null : num, (i2 & 8) != 0 ? null : str2, (i2 & 16) != 0 ? null : bool, (i2 & 32) != 0 ? null : num2, (i2 & 64) != 0 ? null : num3, (i2 & 128) != 0 ? 0 : j, (i2 & 256) != 0 ? 0 : i);
}
public final LivePeople getAuthor() {
return this.author;
}
public final void setAuthor(LivePeople livePeople) {
this.author = livePeople;
}
public final String getContent() {
return this.content;
}
public final void setContent(String str) {
this.content = str;
}
public final Integer getContentType() {
return this.contentType;
}
public final void setContentType(Integer num) {
this.contentType = num;
}
public final String getId() {
return this.f96614id;
}
public final void setId(String str) {
this.f96614id = str;
}
public final Boolean isVoted() {
return this.isVoted;
}
public final void setVoted(Boolean bool) {
this.isVoted = bool;
}
public final Integer getReplyState() {
return this.replyState;
}
public final void setReplyState(Integer num) {
this.replyState = num;
}
public final Integer getType() {
return this.type;
}
public final void setType(Integer num) {
this.type = num;
}
public final long getVoteCount() {
return this.voteCount;
}
public final void setVoteCount(long j) {
this.voteCount = j;
}
public final int getCampType() {
return this.campType;
}
public final void setCampType(int i) {
this.campType = i;
}
/* JADX INFO: this call moved to the top of the method (can break code semantics) */
public Statement(Parcel parcel) {
this((LivePeople) parcel.readParcelable(LivePeople.class.getClassLoader()), parcel.readString(), (Integer) parcel.readValue(Integer.TYPE.getClassLoader()), parcel.readString(), (Boolean) parcel.readValue(Boolean.TYPE.getClassLoader()), (Integer) parcel.readValue(Integer.TYPE.getClassLoader()), (Integer) parcel.readValue(Integer.TYPE.getClassLoader()), parcel.readLong(), parcel.readInt());
C32569u.m150519b(parcel, C6969H.m41409d("G7A8CC008BC35"));
}
public void writeToParcel(Parcel parcel, int i) {
C32569u.m150519b(parcel, "dest");
parcel.writeParcelable(this.author, 0);
parcel.writeString(this.content);
parcel.writeValue(this.contentType);
parcel.writeString(this.f96614id);
parcel.writeValue(this.isVoted);
parcel.writeValue(this.replyState);
parcel.writeValue(this.type);
parcel.writeLong(this.voteCount);
parcel.writeInt(this.campType);
}
@Metadata
/* compiled from: Statement.kt */
public static final class Companion {
private Companion() {
}
public /* synthetic */ Companion(DefaultConstructorMarker pVar) {
this();
}
}
}
| 9,518 | 0.634167 | 0.566085 | 241 | 38.493774 | 74.787949 | 557 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.767635 | false | false |
7
|
f38feb141688016a27b61abf9c010295bc23e62c
| 7,980,049,240,481 |
4cfda4f1b4d7703e1b460359012082c158103476
|
/miliconvert/xsmt/branches/xsmt-1.0.0/org.miliconvert.xsmt.editor/src/org/miliconvert/xsmt/editor/parts/LinkElementEditPart.java
|
8c9c6026c897cf71c8eaf7e661a43ad20d7ed2fa
|
[] |
no_license
|
opensourcejavadeveloper/military_xml_project_miliconvert
|
https://github.com/opensourcejavadeveloper/military_xml_project_miliconvert
|
e62dee54499fdb8abaa76a9d44ed97ace19dc887
|
bb0276970c243ec3acc07fd4b255673d6d7dd080
|
refs/heads/master
| 2022-01-10T18:11:39.021000 | 2018-08-20T12:45:02 | 2018-08-20T12:45:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/* ***** BEGIN LICENSE BLOCK *****
* Version: GPL 2.0
*
* The contents of this file are subject to the GNU General Public
* License Version 2 or later (the "GPL").
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Initial Developer of the Original Code is
* BT Global Services / Etat français Ministre de la Défense
*
* ***** END LICENSE BLOCK ***** */
package org.miliconvert.xsmt.editor.parts;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.Connection;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.PolygonDecoration;
import org.eclipse.draw2d.PolylineConnection;
import org.eclipse.draw2d.RoutingAnimator;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.editparts.AbstractConnectionEditPart;
import org.miliconvert.xsmt.editor.model.LinkElement;
import org.miliconvert.xsmt.editor.policies.LinkEditPolicy;
import org.miliconvert.xsmt.editor.policies.LinkEndpointEditPolicy;
public class LinkElementEditPart extends AbstractConnectionEditPart implements
PropertyChangeListener {
public LinkElementEditPart() {
super();
}
public void activate() {
super.activate();
getLinkElement().addPropertyChangeListener(this);
}
public void activateFigure() {
super.activateFigure();
getFigure().addPropertyChangeListener(
Connection.PROPERTY_CONNECTION_ROUTER, this);
}
@Override
protected void createEditPolicies() {
installEditPolicy(EditPolicy.CONNECTION_ENDPOINTS_ROLE,
new LinkEndpointEditPolicy());
installEditPolicy(EditPolicy.CONNECTION_ROLE, new LinkEditPolicy());
}
@Override
protected IFigure createFigure() {
PolylineConnection pc = new PolylineConnection();
pc.addRoutingListener(RoutingAnimator.getDefault());
PolygonDecoration arrow = new PolygonDecoration();
arrow.setTemplate(PolygonDecoration.TRIANGLE_TIP);
arrow.setScale(5, 2.5);
pc.setTargetDecoration(arrow);
System.out.println("link figure created"); //$NON-NLS-1$
return pc;
}
public void deactivate() {
getLinkElement().removePropertyChangeListener(this);
super.deactivate();
}
public void deactivateFigure() {
getFigure().removePropertyChangeListener(
Connection.PROPERTY_CONNECTION_ROUTER, this);
super.deactivateFigure();
}
protected LinkElement getLinkElement() {
return (LinkElement) getModel();
}
public void propertyChange(PropertyChangeEvent event) {
System.out.println("leep:propertyChange(" + event.getPropertyName() //$NON-NLS-1$
+ ")"); //$NON-NLS-1$
refreshVisuals();
}
@Override
protected void refreshVisuals() {
getFigure().setForegroundColor(ColorConstants.red);
}
}
|
UTF-8
|
Java
| 2,892 |
java
|
LinkElementEditPart.java
|
Java
|
[] | null |
[] |
/* ***** BEGIN LICENSE BLOCK *****
* Version: GPL 2.0
*
* The contents of this file are subject to the GNU General Public
* License Version 2 or later (the "GPL").
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Initial Developer of the Original Code is
* BT Global Services / Etat français Ministre de la Défense
*
* ***** END LICENSE BLOCK ***** */
package org.miliconvert.xsmt.editor.parts;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.Connection;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.PolygonDecoration;
import org.eclipse.draw2d.PolylineConnection;
import org.eclipse.draw2d.RoutingAnimator;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.editparts.AbstractConnectionEditPart;
import org.miliconvert.xsmt.editor.model.LinkElement;
import org.miliconvert.xsmt.editor.policies.LinkEditPolicy;
import org.miliconvert.xsmt.editor.policies.LinkEndpointEditPolicy;
public class LinkElementEditPart extends AbstractConnectionEditPart implements
PropertyChangeListener {
public LinkElementEditPart() {
super();
}
public void activate() {
super.activate();
getLinkElement().addPropertyChangeListener(this);
}
public void activateFigure() {
super.activateFigure();
getFigure().addPropertyChangeListener(
Connection.PROPERTY_CONNECTION_ROUTER, this);
}
@Override
protected void createEditPolicies() {
installEditPolicy(EditPolicy.CONNECTION_ENDPOINTS_ROLE,
new LinkEndpointEditPolicy());
installEditPolicy(EditPolicy.CONNECTION_ROLE, new LinkEditPolicy());
}
@Override
protected IFigure createFigure() {
PolylineConnection pc = new PolylineConnection();
pc.addRoutingListener(RoutingAnimator.getDefault());
PolygonDecoration arrow = new PolygonDecoration();
arrow.setTemplate(PolygonDecoration.TRIANGLE_TIP);
arrow.setScale(5, 2.5);
pc.setTargetDecoration(arrow);
System.out.println("link figure created"); //$NON-NLS-1$
return pc;
}
public void deactivate() {
getLinkElement().removePropertyChangeListener(this);
super.deactivate();
}
public void deactivateFigure() {
getFigure().removePropertyChangeListener(
Connection.PROPERTY_CONNECTION_ROUTER, this);
super.deactivateFigure();
}
protected LinkElement getLinkElement() {
return (LinkElement) getModel();
}
public void propertyChange(PropertyChangeEvent event) {
System.out.println("leep:propertyChange(" + event.getPropertyName() //$NON-NLS-1$
+ ")"); //$NON-NLS-1$
refreshVisuals();
}
@Override
protected void refreshVisuals() {
getFigure().setForegroundColor(ColorConstants.red);
}
}
| 2,892 | 0.764706 | 0.759516 | 98 | 28.489796 | 23.939653 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.336735 | false | false |
7
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.